xref: /freebsd/tests/sys/opencrypto/cryptodev.py (revision f4b37ed0f8b307b1f3f0f630ca725d68f1dff30d)
1#!/usr/bin/env python
2#
3# Copyright (c) 2014 The FreeBSD Foundation
4# Copyright 2014 John-Mark Gurney
5# All rights reserved.
6#
7# This software was developed by John-Mark Gurney under
8# the sponsorship from the FreeBSD Foundation.
9# Redistribution and use in source and binary forms, with or without
10# modification, are permitted provided that the following conditions
11# are met:
12# 1.  Redistributions of source code must retain the above copyright
13#     notice, this list of conditions and the following disclaimer.
14# 2.  Redistributions in binary form must reproduce the above copyright
15#     notice, this list of conditions and the following disclaimer in the
16#     documentation and/or other materials provided with the distribution.
17#
18# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28# SUCH DAMAGE.
29#
30# $FreeBSD$
31#
32
33import array
34import dpkt
35from fcntl import ioctl
36import os
37import signal
38from struct import pack as _pack
39
40from cryptodevh import *
41
42__all__ = [ 'Crypto', 'MismatchError', ]
43
44class FindOp(dpkt.Packet):
45	__byte_order__ = '@'
46	__hdr__ = ( ('crid', 'i', 0),
47		('name', '32s', 0),
48	)
49
50class SessionOp(dpkt.Packet):
51	__byte_order__ = '@'
52	__hdr__ = ( ('cipher', 'I', 0),
53		('mac', 'I', 0),
54		('keylen', 'I', 0),
55		('key', 'P', 0),
56		('mackeylen', 'i', 0),
57		('mackey', 'P', 0),
58		('ses', 'I', 0),
59	)
60
61class SessionOp2(dpkt.Packet):
62	__byte_order__ = '@'
63	__hdr__ = ( ('cipher', 'I', 0),
64		('mac', 'I', 0),
65		('keylen', 'I', 0),
66		('key', 'P', 0),
67		('mackeylen', 'i', 0),
68		('mackey', 'P', 0),
69		('ses', 'I', 0),
70		('crid', 'i', 0),
71		('pad0', 'i', 0),
72		('pad1', 'i', 0),
73		('pad2', 'i', 0),
74		('pad3', 'i', 0),
75	)
76
77class CryptOp(dpkt.Packet):
78	__byte_order__ = '@'
79	__hdr__ = ( ('ses', 'I', 0),
80		('op', 'H', 0),
81		('flags', 'H', 0),
82		('len', 'I', 0),
83		('src', 'P', 0),
84		('dst', 'P', 0),
85		('mac', 'P', 0),
86		('iv', 'P', 0),
87	)
88
89class CryptAEAD(dpkt.Packet):
90	__byte_order__ = '@'
91	__hdr__ = (
92		('ses',		'I', 0),
93		('op',		'H', 0),
94		('flags',	'H', 0),
95		('len',		'I', 0),
96		('aadlen',	'I', 0),
97		('ivlen',	'I', 0),
98		('src',		'P', 0),
99		('dst',		'P', 0),
100		('aad',		'P', 0),
101		('tag',		'P', 0),
102		('iv',		'P', 0),
103	)
104
105# h2py.py can't handle multiarg macros
106CRIOGET = 3221513060
107CIOCGSESSION = 3224396645
108CIOCGSESSION2 = 3225445226
109CIOCFSESSION = 2147771238
110CIOCCRYPT = 3224396647
111CIOCKEY = 3230688104
112CIOCASYMFEAT = 1074029417
113CIOCKEY2 = 3230688107
114CIOCFINDDEV = 3223610220
115CIOCCRYPTAEAD = 3225445229
116
117def _getdev():
118	fd = os.open('/dev/crypto', os.O_RDWR)
119	buf = array.array('I', [0])
120	ioctl(fd, CRIOGET, buf, 1)
121	os.close(fd)
122
123	return buf[0]
124
125_cryptodev = _getdev()
126
127def _findop(crid, name):
128	fop = FindOp()
129	fop.crid = crid
130	fop.name = name
131	s = array.array('B', fop.pack_hdr())
132	ioctl(_cryptodev, CIOCFINDDEV, s, 1)
133	fop.unpack(s)
134
135	try:
136		idx = fop.name.index('\x00')
137		name = fop.name[:idx]
138	except ValueError:
139		name = fop.name
140
141	return fop.crid, name
142
143class Crypto:
144	@staticmethod
145	def findcrid(name):
146		return _findop(-1, name)[0]
147
148	@staticmethod
149	def getcridname(crid):
150		return _findop(crid, '')[1]
151
152	def __init__(self, cipher=0, key=None, mac=0, mackey=None,
153	    crid=CRYPTOCAP_F_SOFTWARE | CRYPTOCAP_F_HARDWARE):
154		self._ses = None
155		ses = SessionOp2()
156		ses.cipher = cipher
157		ses.mac = mac
158
159		if key is not None:
160			ses.keylen = len(key)
161			k = array.array('B', key)
162			ses.key = k.buffer_info()[0]
163		else:
164			self.key = None
165
166		if mackey is not None:
167			ses.mackeylen = len(mackey)
168			mk = array.array('B', mackey)
169			ses.mackey = mk.buffer_info()[0]
170			self._maclen = 16	# parameterize?
171		else:
172			self._maclen = None
173
174		if not cipher and not mac:
175			raise ValueError('one of cipher or mac MUST be specified.')
176		ses.crid = CRYPTOCAP_F_SOFTWARE | CRYPTOCAP_F_HARDWARE
177		#ses.crid = CRYPTOCAP_F_HARDWARE
178		#ses.crid = CRYPTOCAP_F_SOFTWARE
179		#ses.crid = 0
180		#print `ses`
181		s = array.array('B', ses.pack_hdr())
182		#print `s`
183		ioctl(_cryptodev, CIOCGSESSION2, s, 1)
184		ses.unpack(s)
185
186		self._ses = ses.ses
187
188	def __del__(self):
189		if self._ses is None:
190			return
191
192		try:
193			ioctl(_cryptodev, CIOCFSESSION, _pack('I', self._ses))
194		except TypeError:
195			pass
196		self._ses = None
197
198	def _doop(self, op, src, iv):
199		cop = CryptOp()
200		cop.ses = self._ses
201		cop.op = op
202		cop.flags = 0
203		cop.len = len(src)
204		s = array.array('B', src)
205		cop.src = cop.dst = s.buffer_info()[0]
206		if self._maclen is not None:
207			m = array.array('B', [0] * self._maclen)
208			cop.mac = m.buffer_info()[0]
209		ivbuf = array.array('B', iv)
210		cop.iv = ivbuf.buffer_info()[0]
211
212		#print 'cop:', `cop`
213		ioctl(_cryptodev, CIOCCRYPT, str(cop))
214
215		s = s.tostring()
216		if self._maclen is not None:
217			return s, m.tostring()
218
219		return s
220
221	def _doaead(self, op, src, aad, iv, tag=None):
222		caead = CryptAEAD()
223		caead.ses = self._ses
224		caead.op = op
225		caead.flags = CRD_F_IV_EXPLICIT
226		caead.flags = 0
227		caead.len = len(src)
228		s = array.array('B', src)
229		caead.src = caead.dst = s.buffer_info()[0]
230		caead.aadlen = len(aad)
231		saad = array.array('B', aad)
232		caead.aad = saad.buffer_info()[0]
233
234		if self._maclen is None:
235			raise ValueError('must have a tag length')
236
237		if tag is None:
238			tag = array.array('B', [0] * self._maclen)
239		else:
240			assert len(tag) == self._maclen, `len(tag), self._maclen`
241			tag = array.array('B', tag)
242
243		caead.tag = tag.buffer_info()[0]
244
245		ivbuf = array.array('B', iv)
246		caead.ivlen = len(iv)
247		caead.iv = ivbuf.buffer_info()[0]
248
249		ioctl(_cryptodev, CIOCCRYPTAEAD, str(caead))
250
251		s = s.tostring()
252
253		return s, tag.tostring()
254
255	def perftest(self, op, size, timeo=3):
256		import random
257		import time
258
259		inp = array.array('B', (random.randint(0, 255) for x in xrange(size)))
260		out = array.array('B', inp)
261
262		# prep ioctl
263		cop = CryptOp()
264		cop.ses = self._ses
265		cop.op = op
266		cop.flags = 0
267		cop.len = len(inp)
268		s = array.array('B', inp)
269		cop.src = s.buffer_info()[0]
270		cop.dst = out.buffer_info()[0]
271		if self._maclen is not None:
272			m = array.array('B', [0] * self._maclen)
273			cop.mac = m.buffer_info()[0]
274		ivbuf = array.array('B', (random.randint(0, 255) for x in xrange(16)))
275		cop.iv = ivbuf.buffer_info()[0]
276
277		exit = [ False ]
278		def alarmhandle(a, b, exit=exit):
279			exit[0] = True
280
281		oldalarm = signal.signal(signal.SIGALRM, alarmhandle)
282		signal.alarm(timeo)
283
284		start = time.time()
285		reps = 0
286		while not exit[0]:
287			ioctl(_cryptodev, CIOCCRYPT, str(cop))
288			reps += 1
289
290		end = time.time()
291
292		signal.signal(signal.SIGALRM, oldalarm)
293
294		print 'time:', end - start
295		print 'perf MB/sec:', (reps * size) / (end - start) / 1024 / 1024
296
297	def encrypt(self, data, iv, aad=None):
298		if aad is None:
299			return self._doop(COP_ENCRYPT, data, iv)
300		else:
301			return self._doaead(COP_ENCRYPT, data, aad,
302			    iv)
303
304	def decrypt(self, data, iv, aad=None, tag=None):
305		if aad is None:
306			return self._doop(COP_DECRYPT, data, iv)
307		else:
308			return self._doaead(COP_DECRYPT, data, aad,
309			    iv, tag=tag)
310
311class MismatchError(Exception):
312	pass
313
314class KATParser:
315	def __init__(self, fname, fields):
316		self.fp = open(fname)
317		self.fields = set(fields)
318		self._pending = None
319
320	def __iter__(self):
321		while True:
322			didread = False
323			if self._pending is not None:
324				i = self._pending
325				self._pending = None
326			else:
327				i = self.fp.readline()
328				didread = True
329
330			if didread and not i:
331				return
332
333			if (i and i[0] == '#') or not i.strip():
334				continue
335			if i[0] == '[':
336				yield i[1:].split(']', 1)[0], self.fielditer()
337			else:
338				raise ValueError('unknown line: %s' % `i`)
339
340	def eatblanks(self):
341		while True:
342			line = self.fp.readline()
343			if line == '':
344				break
345
346			line = line.strip()
347			if line:
348				break
349
350		return line
351
352	def fielditer(self):
353		while True:
354			values = {}
355
356			line = self.eatblanks()
357			if not line or line[0] == '[':
358				self._pending = line
359				return
360
361			while True:
362				try:
363					f, v = line.split(' =')
364				except:
365					if line == 'FAIL':
366						f, v = 'FAIL', ''
367					else:
368						print 'line:', `line`
369						raise
370				v = v.strip()
371
372				if f in values:
373					raise ValueError('already present: %s' % `f`)
374				values[f] = v
375				line = self.fp.readline().strip()
376				if not line:
377					break
378
379			# we should have everything
380			remain = self.fields.copy() - set(values.keys())
381			# XXX - special case GCM decrypt
382			if remain and not ('FAIL' in values and 'PT' in remain):
383					raise ValueError('not all fields found: %s' % `remain`)
384
385			yield values
386
387def _spdechex(s):
388	return ''.join(s.split()).decode('hex')
389
390if __name__ == '__main__':
391	if True:
392		try:
393			crid = Crypto.findcrid('aesni0')
394			print 'aesni:', crid
395		except IOError:
396			print 'aesni0 not found'
397
398		for i in xrange(10):
399			try:
400				name = Crypto.getcridname(i)
401				print '%2d: %s' % (i, `name`)
402			except IOError:
403				pass
404	elif False:
405		kp = KATParser('/usr/home/jmg/aesni.testing/format tweak value input - data unit seq no/XTSGenAES128.rsp', [ 'COUNT', 'DataUnitLen', 'Key', 'DataUnitSeqNumber', 'PT', 'CT' ])
406		for mode, ni in kp:
407			print `i`, `ni`
408			for j in ni:
409				print `j`
410	elif False:
411		key = _spdechex('c939cc13397c1d37de6ae0e1cb7c423c')
412		iv = _spdechex('00000000000000000000000000000001')
413		pt = _spdechex('ab3cabed693a32946055524052afe3c9cb49664f09fc8b7da824d924006b7496353b8c1657c5dec564d8f38d7432e1de35aae9d95590e66278d4acce883e51abaf94977fcd3679660109a92bf7b2973ccd547f065ec6cee4cb4a72a5e9f45e615d920d76cb34cba482467b3e21422a7242e7d931330c0fbf465c3a3a46fae943029fd899626dda542750a1eee253df323c6ef1573f1c8c156613e2ea0a6cdbf2ae9701020be2d6a83ecb7f3f9d8e')
414		#pt = _spdechex('00000000000000000000000000000000')
415		ct = _spdechex('f42c33853ecc5ce2949865fdb83de3bff1089e9360c94f830baebfaff72836ab5236f77212f1e7396c8c54ac73d81986375a6e9e299cfeca5ba051ed25e8d1affa5beaf6c1d2b45e90802408f2ced21663497e906de5f29341e5e52ddfea5363d628b3eb7806835e17bae051b3a6da3f8e2941fe44384eac17a9d298d2c331ca8320c775b5d53263a5e905059d891b21dede2d8110fd427c7bd5a9a274ddb47b1945ee79522203b6e297d0e399ef')
416
417		c = Crypto(CRYPTO_AES_ICM, key)
418		enc = c.encrypt(pt, iv)
419
420		print 'enc:', enc.encode('hex')
421		print ' ct:', ct.encode('hex')
422
423		assert ct == enc
424
425		dec = c.decrypt(ct, iv)
426
427		print 'dec:', dec.encode('hex')
428		print ' pt:', pt.encode('hex')
429
430		assert pt == dec
431	elif False:
432		key = _spdechex('c939cc13397c1d37de6ae0e1cb7c423c')
433		iv = _spdechex('00000000000000000000000000000001')
434		pt = _spdechex('ab3cabed693a32946055524052afe3c9cb49664f09fc8b7da824d924006b7496353b8c1657c5dec564d8f38d7432e1de35aae9d95590e66278d4acce883e51abaf94977fcd3679660109a92bf7b2973ccd547f065ec6cee4cb4a72a5e9f45e615d920d76cb34cba482467b3e21422a7242e7d931330c0fbf465c3a3a46fae943029fd899626dda542750a1eee253df323c6ef1573f1c8c156613e2ea0a6cdbf2ae9701020be2d6a83ecb7f3f9d8e0a3f')
435		#pt = _spdechex('00000000000000000000000000000000')
436		ct = _spdechex('f42c33853ecc5ce2949865fdb83de3bff1089e9360c94f830baebfaff72836ab5236f77212f1e7396c8c54ac73d81986375a6e9e299cfeca5ba051ed25e8d1affa5beaf6c1d2b45e90802408f2ced21663497e906de5f29341e5e52ddfea5363d628b3eb7806835e17bae051b3a6da3f8e2941fe44384eac17a9d298d2c331ca8320c775b5d53263a5e905059d891b21dede2d8110fd427c7bd5a9a274ddb47b1945ee79522203b6e297d0e399ef3768')
437
438		c = Crypto(CRYPTO_AES_ICM, key)
439		enc = c.encrypt(pt, iv)
440
441		print 'enc:', enc.encode('hex')
442		print ' ct:', ct.encode('hex')
443
444		assert ct == enc
445
446		dec = c.decrypt(ct, iv)
447
448		print 'dec:', dec.encode('hex')
449		print ' pt:', pt.encode('hex')
450
451		assert pt == dec
452	elif False:
453		key = _spdechex('c939cc13397c1d37de6ae0e1cb7c423c')
454		iv = _spdechex('6eba2716ec0bd6fa5cdef5e6d3a795bc')
455		pt = _spdechex('ab3cabed693a32946055524052afe3c9cb49664f09fc8b7da824d924006b7496353b8c1657c5dec564d8f38d7432e1de35aae9d95590e66278d4acce883e51abaf94977fcd3679660109a92bf7b2973ccd547f065ec6cee4cb4a72a5e9f45e615d920d76cb34cba482467b3e21422a7242e7d931330c0fbf465c3a3a46fae943029fd899626dda542750a1eee253df323c6ef1573f1c8c156613e2ea0a6cdbf2ae9701020be2d6a83ecb7f3f9d8e0a3f')
456		ct = _spdechex('f1f81f12e72e992dbdc304032705dc75dc3e4180eff8ee4819906af6aee876d5b00b7c36d282a445ce3620327be481e8e53a8e5a8e5ca9abfeb2281be88d12ffa8f46d958d8224738c1f7eea48bda03edbf9adeb900985f4fa25648b406d13a886c25e70cfdecdde0ad0f2991420eb48a61c64fd797237cf2798c2675b9bb744360b0a3f329ac53bbceb4e3e7456e6514f1a9d2f06c236c31d0f080b79c15dce1096357416602520daa098b17d1af427')
457		c = Crypto(CRYPTO_AES_CBC, key)
458
459		enc = c.encrypt(pt, iv)
460
461		print 'enc:', enc.encode('hex')
462		print ' ct:', ct.encode('hex')
463
464		assert ct == enc
465
466		dec = c.decrypt(ct, iv)
467
468		print 'dec:', dec.encode('hex')
469		print ' pt:', pt.encode('hex')
470
471		assert pt == dec
472	elif False:
473		key = _spdechex('c939cc13397c1d37de6ae0e1cb7c423c')
474		iv = _spdechex('b3d8cc017cbb89b39e0f67e2')
475		pt = _spdechex('c3b3c41f113a31b73d9a5cd4321030')
476		aad = _spdechex('24825602bd12a984e0092d3e448eda5f')
477		ct = _spdechex('93fe7d9e9bfd10348a5606e5cafa7354')
478		ct = _spdechex('93fe7d9e9bfd10348a5606e5cafa73')
479		tag = _spdechex('0032a1dc85f1c9786925a2e71d8272dd')
480		tag = _spdechex('8d11a0929cb3fbe1fef01a4a38d5f8ea')
481
482		c = Crypto(CRYPTO_AES_NIST_GCM_16, key,
483		    mac=CRYPTO_AES_128_NIST_GMAC, mackey=key)
484
485		enc, enctag = c.encrypt(pt, iv, aad=aad)
486
487		print 'enc:', enc.encode('hex')
488		print ' ct:', ct.encode('hex')
489
490		assert enc == ct
491
492		print 'etg:', enctag.encode('hex')
493		print 'tag:', tag.encode('hex')
494		assert enctag == tag
495
496		# Make sure we get EBADMSG
497		#enctag = enctag[:-1] + 'a'
498		dec, dectag = c.decrypt(ct, iv, aad=aad, tag=enctag)
499
500		print 'dec:', dec.encode('hex')
501		print ' pt:', pt.encode('hex')
502
503		assert dec == pt
504
505		print 'dtg:', dectag.encode('hex')
506		print 'tag:', tag.encode('hex')
507
508		assert dectag == tag
509	elif False:
510		key = _spdechex('c939cc13397c1d37de6ae0e1cb7c423c')
511		iv = _spdechex('b3d8cc017cbb89b39e0f67e2')
512		key = key + iv[:4]
513		iv = iv[4:]
514		pt = _spdechex('c3b3c41f113a31b73d9a5cd432103069')
515		aad = _spdechex('24825602bd12a984e0092d3e448eda5f')
516		ct = _spdechex('93fe7d9e9bfd10348a5606e5cafa7354')
517		tag = _spdechex('0032a1dc85f1c9786925a2e71d8272dd')
518
519		c = Crypto(CRYPTO_AES_GCM_16, key, mac=CRYPTO_AES_128_GMAC, mackey=key)
520
521		enc, enctag = c.encrypt(pt, iv, aad=aad)
522
523		print 'enc:', enc.encode('hex')
524		print ' ct:', ct.encode('hex')
525
526		assert enc == ct
527
528		print 'etg:', enctag.encode('hex')
529		print 'tag:', tag.encode('hex')
530		assert enctag == tag
531	elif False:
532		for i in xrange(100000):
533			c = Crypto(CRYPTO_AES_XTS, '1bbfeadf539daedcae33ced497343f3ca1f2474ad932b903997d44707db41382'.decode('hex'))
534			data = '52a42bca4e9425a25bbc8c8bf6129dec'.decode('hex')
535			ct = '517e602becd066b65fa4f4f56ddfe240'.decode('hex')
536			iv = _pack('QQ', 71, 0)
537
538			enc = c.encrypt(data, iv)
539			assert enc == ct
540	elif True:
541		c = Crypto(CRYPTO_AES_XTS, '1bbfeadf539daedcae33ced497343f3ca1f2474ad932b903997d44707db41382'.decode('hex'))
542		data = '52a42bca4e9425a25bbc8c8bf6129dec'.decode('hex')
543		ct = '517e602becd066b65fa4f4f56ddfe240'.decode('hex')
544		iv = _pack('QQ', 71, 0)
545
546		enc = c.encrypt(data, iv)
547		assert enc == ct
548
549		dec = c.decrypt(enc, iv)
550		assert dec == data
551
552		#c.perftest(COP_ENCRYPT, 192*1024, reps=30000)
553
554	else:
555		key = '1bbfeadf539daedcae33ced497343f3ca1f2474ad932b903997d44707db41382'.decode('hex')
556		print 'XTS %d testing:' % (len(key) * 8)
557		c = Crypto(CRYPTO_AES_XTS, key)
558		for i in [ 8192, 192*1024]:
559			print 'block size: %d' % i
560			c.perftest(COP_ENCRYPT, i)
561			c.perftest(COP_DECRYPT, i)
562