1 #!/usr/local/bin/python2
3 # Copyright (c) 2014 The FreeBSD Foundation
4 # Copyright 2014 John-Mark Gurney
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
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.
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
33 from __future__ import print_function
36 from fcntl import ioctl
40 from struct import pack as _pack
45 from cryptodevh import *
47 __all__ = [ 'Crypto', 'MismatchError', ]
49 class FindOp(dpkt.Packet):
56 class SessionOp(dpkt.Packet):
63 ('mackeylen', 'i', 0),
68 class SessionOp2(dpkt.Packet):
75 ('mackeylen', 'i', 0),
85 class CryptOp(dpkt.Packet):
98 class CryptAEAD(dpkt.Packet):
114 # h2py.py can't handle multiarg macros
116 CIOCGSESSION = 3224396645
117 CIOCGSESSION2 = 3225445226
118 CIOCFSESSION = 2147771238
119 CIOCCRYPT = 3224396647
121 CIOCASYMFEAT = 1074029417
122 CIOCKEY2 = 3230688107
123 CIOCFINDDEV = 3223610220
124 CIOCCRYPTAEAD = 3225445229
127 buf = array.array('I', [0])
128 fd = os.open('/dev/crypto', os.O_RDWR)
130 ioctl(fd, CRIOGET, buf, 1)
136 _cryptodev = _getdev()
138 def _findop(crid, name):
142 s = array.array('B', fop.pack_hdr())
143 ioctl(_cryptodev, CIOCFINDDEV, s, 1)
147 idx = fop.name.index('\x00')
148 name = fop.name[:idx]
152 return fop.crid, name
157 return _findop(-1, name)[0]
160 def getcridname(crid):
161 return _findop(crid, '')[1]
163 def __init__(self, cipher=0, key=None, mac=0, mackey=None,
164 crid=CRYPTOCAP_F_SOFTWARE | CRYPTOCAP_F_HARDWARE, maclen=None):
166 self._maclen = maclen
172 ses.keylen = len(key)
173 k = array.array('B', key)
174 ses.key = k.buffer_info()[0]
178 if mackey is not None:
179 ses.mackeylen = len(mackey)
180 mk = array.array('B', mackey)
181 ses.mackey = mk.buffer_info()[0]
183 if not cipher and not mac:
184 raise ValueError('one of cipher or mac MUST be specified.')
187 s = array.array('B', ses.pack_hdr())
189 ioctl(_cryptodev, CIOCGSESSION2, s, 1)
195 if self._ses is None:
199 ioctl(_cryptodev, CIOCFSESSION, _pack('I', self._ses))
204 def _doop(self, op, src, iv):
210 s = array.array('B', src)
211 cop.src = cop.dst = s.buffer_info()[0]
212 if self._maclen is not None:
213 m = array.array('B', [0] * self._maclen)
214 cop.mac = m.buffer_info()[0]
215 ivbuf = array.array('B', iv)
216 cop.iv = ivbuf.buffer_info()[0]
219 ioctl(_cryptodev, CIOCCRYPT, str(cop))
222 if self._maclen is not None:
223 return s, m.tostring()
227 def _doaead(self, op, src, aad, iv, tag=None):
229 caead.ses = self._ses
231 caead.flags = CRD_F_IV_EXPLICIT
234 s = array.array('B', src)
235 caead.src = caead.dst = s.buffer_info()[0]
236 caead.aadlen = len(aad)
237 saad = array.array('B', aad)
238 caead.aad = saad.buffer_info()[0]
240 if self._maclen is None:
241 raise ValueError('must have a tag length')
244 tag = array.array('B', [0] * self._maclen)
246 assert len(tag) == self._maclen, \
247 '%d != %d' % (len(tag), self._maclen)
248 tag = array.array('B', tag)
250 caead.tag = tag.buffer_info()[0]
252 ivbuf = array.array('B', iv)
253 caead.ivlen = len(iv)
254 caead.iv = ivbuf.buffer_info()[0]
256 ioctl(_cryptodev, CIOCCRYPTAEAD, str(caead))
260 return s, tag.tostring()
262 def perftest(self, op, size, timeo=3):
263 inp = array.array('B', (random.randint(0, 255) for x in range(size)))
264 out = array.array('B', inp)
272 s = array.array('B', inp)
273 cop.src = s.buffer_info()[0]
274 cop.dst = out.buffer_info()[0]
275 if self._maclen is not None:
276 m = array.array('B', [0] * self._maclen)
277 cop.mac = m.buffer_info()[0]
278 ivbuf = array.array('B', (random.randint(0, 255) for x in range(16)))
279 cop.iv = ivbuf.buffer_info()[0]
282 def alarmhandle(a, b, exit=exit):
285 oldalarm = signal.signal(signal.SIGALRM, alarmhandle)
291 ioctl(_cryptodev, CIOCCRYPT, str(cop))
296 signal.signal(signal.SIGALRM, oldalarm)
298 print('time:', end - start)
299 print('perf MB/sec:', (reps * size) / (end - start) / 1024 / 1024)
301 def encrypt(self, data, iv, aad=None):
303 return self._doop(COP_ENCRYPT, data, iv)
305 return self._doaead(COP_ENCRYPT, data, aad,
308 def decrypt(self, data, iv, aad=None, tag=None):
310 return self._doop(COP_DECRYPT, data, iv)
312 return self._doaead(COP_DECRYPT, data, aad,
315 class MismatchError(Exception):
319 def __init__(self, fname, fields):
320 self.fp = open(fname)
321 self.fields = set(fields)
327 if self._pending is not None:
331 i = self.fp.readline()
334 if didread and not i:
337 if (i and i[0] == '#') or not i.strip():
340 yield i[1:].split(']', 1)[0], self.fielditer()
342 raise ValueError('unknown line: %r' % repr(i))
346 line = self.fp.readline()
360 line = self.eatblanks()
361 if not line or line[0] == '[':
367 f, v = line.split(' =')
372 print('line:', repr(line))
377 raise ValueError('already present: %r' % repr(f))
379 line = self.fp.readline().strip()
383 # we should have everything
384 remain = self.fields.copy() - set(values.keys())
385 # XXX - special case GCM decrypt
386 if remain and not ('FAIL' in values and 'PT' in remain):
387 raise ValueError('not all fields found: %r' % repr(remain))
391 # The CCM files use a bit of a different syntax that doesn't quite fit
392 # the generic KATParser. In particular, some keys are set globally at
393 # the start of the file, and some are set globally at the start of a
396 def __init__(self, fname):
397 self.fp = open(fname)
401 def read_globals(self):
402 self.global_values = {}
404 line = self.fp.readline()
407 if line[0] == '#' or not line.strip():
414 f, v = line.split(' =')
416 print('line:', repr(line))
421 if f in self.global_values:
422 raise ValueError('already present: %r' % repr(f))
423 self.global_values[f] = v
425 def read_section_values(self, kwpairs):
426 self.section_values = self.global_values.copy()
427 for pair in kwpairs.split(', '):
428 f, v = pair.split(' = ')
429 if f in self.section_values:
430 raise ValueError('already present: %r' % repr(f))
431 self.section_values[f] = v
434 line = self.fp.readline()
437 if line[0] == '#' or not line.strip():
444 f, v = line.split(' =')
446 print('line:', repr(line))
455 if f in self.section_values:
456 raise ValueError('already present: %r' % repr(f))
457 self.section_values[f] = v
465 line = self.fp.readline()
469 if (line and line[0] == '#') or not line.strip():
473 section = line[1:].split(']', 1)[0]
474 self.read_section_values(section)
477 values = self.section_values.copy()
481 f, v = line.split(' =')
483 print('line:', repr(line))
488 raise ValueError('already present: %r' % repr(f))
490 line = self.fp.readline().strip()
498 return binascii.hexlify(''.join(s.split()))
500 if __name__ == '__main__':
503 crid = Crypto.findcrid('aesni0')
504 print('aesni:', crid)
506 print('aesni0 not found')
510 name = Crypto.getcridname(i)
511 print('%2d: %r' % (i, repr(name)))
515 kp = KATParser('/usr/home/jmg/aesni.testing/format tweak value input - data unit seq no/XTSGenAES128.rsp', [ 'COUNT', 'DataUnitLen', 'Key', 'DataUnitSeqNumber', 'PT', 'CT' ])
521 key = _spdechex('c939cc13397c1d37de6ae0e1cb7c423c')
522 iv = _spdechex('00000000000000000000000000000001')
523 pt = _spdechex('ab3cabed693a32946055524052afe3c9cb49664f09fc8b7da824d924006b7496353b8c1657c5dec564d8f38d7432e1de35aae9d95590e66278d4acce883e51abaf94977fcd3679660109a92bf7b2973ccd547f065ec6cee4cb4a72a5e9f45e615d920d76cb34cba482467b3e21422a7242e7d931330c0fbf465c3a3a46fae943029fd899626dda542750a1eee253df323c6ef1573f1c8c156613e2ea0a6cdbf2ae9701020be2d6a83ecb7f3f9d8e')
524 #pt = _spdechex('00000000000000000000000000000000')
525 ct = _spdechex('f42c33853ecc5ce2949865fdb83de3bff1089e9360c94f830baebfaff72836ab5236f77212f1e7396c8c54ac73d81986375a6e9e299cfeca5ba051ed25e8d1affa5beaf6c1d2b45e90802408f2ced21663497e906de5f29341e5e52ddfea5363d628b3eb7806835e17bae051b3a6da3f8e2941fe44384eac17a9d298d2c331ca8320c775b5d53263a5e905059d891b21dede2d8110fd427c7bd5a9a274ddb47b1945ee79522203b6e297d0e399ef')
527 c = Crypto(CRYPTO_AES_ICM, key)
528 enc = c.encrypt(pt, iv)
530 print('enc:', binascii.hexlify(enc))
531 print(' ct:', binascii.hexlify(ct))
535 dec = c.decrypt(ct, iv)
537 print('dec:', binascii.hexlify(dec))
538 print(' pt:', binascii.hexlify(pt))
542 key = _spdechex('c939cc13397c1d37de6ae0e1cb7c423c')
543 iv = _spdechex('00000000000000000000000000000001')
544 pt = _spdechex('ab3cabed693a32946055524052afe3c9cb49664f09fc8b7da824d924006b7496353b8c1657c5dec564d8f38d7432e1de35aae9d95590e66278d4acce883e51abaf94977fcd3679660109a92bf7b2973ccd547f065ec6cee4cb4a72a5e9f45e615d920d76cb34cba482467b3e21422a7242e7d931330c0fbf465c3a3a46fae943029fd899626dda542750a1eee253df323c6ef1573f1c8c156613e2ea0a6cdbf2ae9701020be2d6a83ecb7f3f9d8e0a3f')
545 #pt = _spdechex('00000000000000000000000000000000')
546 ct = _spdechex('f42c33853ecc5ce2949865fdb83de3bff1089e9360c94f830baebfaff72836ab5236f77212f1e7396c8c54ac73d81986375a6e9e299cfeca5ba051ed25e8d1affa5beaf6c1d2b45e90802408f2ced21663497e906de5f29341e5e52ddfea5363d628b3eb7806835e17bae051b3a6da3f8e2941fe44384eac17a9d298d2c331ca8320c775b5d53263a5e905059d891b21dede2d8110fd427c7bd5a9a274ddb47b1945ee79522203b6e297d0e399ef3768')
548 c = Crypto(CRYPTO_AES_ICM, key)
549 enc = c.encrypt(pt, iv)
551 print('enc:', binascii.hexlify(enc))
552 print(' ct:', binascii.hexlify(ct))
556 dec = c.decrypt(ct, iv)
558 print('dec:', binascii.hexlify(dec))
559 print(' pt:', binascii.hexlify(pt))
563 key = _spdechex('c939cc13397c1d37de6ae0e1cb7c423c')
564 iv = _spdechex('6eba2716ec0bd6fa5cdef5e6d3a795bc')
565 pt = _spdechex('ab3cabed693a32946055524052afe3c9cb49664f09fc8b7da824d924006b7496353b8c1657c5dec564d8f38d7432e1de35aae9d95590e66278d4acce883e51abaf94977fcd3679660109a92bf7b2973ccd547f065ec6cee4cb4a72a5e9f45e615d920d76cb34cba482467b3e21422a7242e7d931330c0fbf465c3a3a46fae943029fd899626dda542750a1eee253df323c6ef1573f1c8c156613e2ea0a6cdbf2ae9701020be2d6a83ecb7f3f9d8e0a3f')
566 ct = _spdechex('f1f81f12e72e992dbdc304032705dc75dc3e4180eff8ee4819906af6aee876d5b00b7c36d282a445ce3620327be481e8e53a8e5a8e5ca9abfeb2281be88d12ffa8f46d958d8224738c1f7eea48bda03edbf9adeb900985f4fa25648b406d13a886c25e70cfdecdde0ad0f2991420eb48a61c64fd797237cf2798c2675b9bb744360b0a3f329ac53bbceb4e3e7456e6514f1a9d2f06c236c31d0f080b79c15dce1096357416602520daa098b17d1af427')
567 c = Crypto(CRYPTO_AES_CBC, key)
569 enc = c.encrypt(pt, iv)
571 print('enc:', binascii.hexlify(enc))
572 print(' ct:', binascii.hexlify(ct))
576 dec = c.decrypt(ct, iv)
578 print('dec:', binascii.hexlify(dec))
579 print(' pt:', binascii.hexlify(pt))
583 key = _spdechex('c939cc13397c1d37de6ae0e1cb7c423c')
584 iv = _spdechex('b3d8cc017cbb89b39e0f67e2')
585 pt = _spdechex('c3b3c41f113a31b73d9a5cd4321030')
586 aad = _spdechex('24825602bd12a984e0092d3e448eda5f')
587 ct = _spdechex('93fe7d9e9bfd10348a5606e5cafa7354')
588 ct = _spdechex('93fe7d9e9bfd10348a5606e5cafa73')
589 tag = _spdechex('0032a1dc85f1c9786925a2e71d8272dd')
590 tag = _spdechex('8d11a0929cb3fbe1fef01a4a38d5f8ea')
592 c = Crypto(CRYPTO_AES_NIST_GCM_16, key,
593 mac=CRYPTO_AES_128_NIST_GMAC, mackey=key)
595 enc, enctag = c.encrypt(pt, iv, aad=aad)
597 print('enc:', binascii.hexlify(enc))
598 print(' ct:', binascii.hexlify(ct))
602 print('etg:', binascii.hexlify(enctag))
603 print('tag:', binascii.hexlify(tag))
606 # Make sure we get EBADMSG
607 #enctag = enctag[:-1] + 'a'
608 dec, dectag = c.decrypt(ct, iv, aad=aad, tag=enctag)
610 print('dec:', binascii.hexlify(dec))
611 print(' pt:', binascii.hexlify(pt))
615 print('dtg:', binascii.hexlify(dectag))
616 print('tag:', binascii.hexlify(tag))
620 key = _spdechex('c939cc13397c1d37de6ae0e1cb7c423c')
621 iv = _spdechex('b3d8cc017cbb89b39e0f67e2')
624 pt = _spdechex('c3b3c41f113a31b73d9a5cd432103069')
625 aad = _spdechex('24825602bd12a984e0092d3e448eda5f')
626 ct = _spdechex('93fe7d9e9bfd10348a5606e5cafa7354')
627 tag = _spdechex('0032a1dc85f1c9786925a2e71d8272dd')
629 c = Crypto(CRYPTO_AES_GCM_16, key, mac=CRYPTO_AES_128_GMAC, mackey=key)
631 enc, enctag = c.encrypt(pt, iv, aad=aad)
633 print('enc:', binascii.hexlify(enc))
634 print(' ct:', binascii.hexlify(ct))
638 print('etg:', binascii.hexlify(enctag))
639 print('tag:', binascii.hexlify(tag))
642 for i in range(100000):
643 c = Crypto(CRYPTO_AES_XTS, binascii.unhexlify('1bbfeadf539daedcae33ced497343f3ca1f2474ad932b903997d44707db41382'))
644 data = binascii.unhexlify('52a42bca4e9425a25bbc8c8bf6129dec')
645 ct = binascii.unhexlify('517e602becd066b65fa4f4f56ddfe240')
646 iv = _pack('QQ', 71, 0)
648 enc = c.encrypt(data, iv)
651 c = Crypto(CRYPTO_AES_XTS, binascii.unhexlify('1bbfeadf539daedcae33ced497343f3ca1f2474ad932b903997d44707db41382'))
652 data = binascii.unhexlify('52a42bca4e9425a25bbc8c8bf6129dec')
653 ct = binascii.unhexlify('517e602becd066b65fa4f4f56ddfe240')
654 iv = _pack('QQ', 71, 0)
656 enc = c.encrypt(data, iv)
659 dec = c.decrypt(enc, iv)
662 #c.perftest(COP_ENCRYPT, 192*1024, reps=30000)
665 key = binascii.unhexlify('1bbfeadf539daedcae33ced497343f3ca1f2474ad932b903997d44707db41382')
666 print('XTS %d testing:' % (len(key) * 8))
667 c = Crypto(CRYPTO_AES_XTS, key)
668 for i in [ 8192, 192*1024]:
669 print('block size: %d' % i)
670 c.perftest(COP_ENCRYPT, i)
671 c.perftest(COP_DECRYPT, i)