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
43 from cryptodevh import *
45 __all__ = [ 'Crypto', 'MismatchError', ]
47 class FindOp(dpkt.Packet):
54 class SessionOp(dpkt.Packet):
61 ('mackeylen', 'i', 0),
66 class SessionOp2(dpkt.Packet):
73 ('mackeylen', 'i', 0),
83 class CryptOp(dpkt.Packet):
96 class CryptAEAD(dpkt.Packet):
112 # h2py.py can't handle multiarg macros
114 CIOCGSESSION = 3224396645
115 CIOCGSESSION2 = 3225445226
116 CIOCFSESSION = 2147771238
117 CIOCCRYPT = 3224396647
119 CIOCASYMFEAT = 1074029417
120 CIOCKEY2 = 3230688107
121 CIOCFINDDEV = 3223610220
122 CIOCCRYPTAEAD = 3225445229
125 fd = os.open('/dev/crypto', os.O_RDWR)
126 buf = array.array('I', [0])
127 ioctl(fd, CRIOGET, buf, 1)
132 _cryptodev = _getdev()
134 def _findop(crid, name):
138 s = array.array('B', fop.pack_hdr())
139 ioctl(_cryptodev, CIOCFINDDEV, s, 1)
143 idx = fop.name.index('\x00')
144 name = fop.name[:idx]
148 return fop.crid, name
153 return _findop(-1, name)[0]
156 def getcridname(crid):
157 return _findop(crid, '')[1]
159 def __init__(self, cipher=0, key=None, mac=0, mackey=None,
160 crid=CRYPTOCAP_F_SOFTWARE | CRYPTOCAP_F_HARDWARE, maclen=None):
162 self._maclen = maclen
168 ses.keylen = len(key)
169 k = array.array('B', key)
170 ses.key = k.buffer_info()[0]
174 if mackey is not None:
175 ses.mackeylen = len(mackey)
176 mk = array.array('B', mackey)
177 ses.mackey = mk.buffer_info()[0]
179 if not cipher and not mac:
180 raise ValueError('one of cipher or mac MUST be specified.')
183 s = array.array('B', ses.pack_hdr())
185 ioctl(_cryptodev, CIOCGSESSION2, s, 1)
191 if self._ses is None:
195 ioctl(_cryptodev, CIOCFSESSION, _pack('I', self._ses))
200 def _doop(self, op, src, iv):
206 s = array.array('B', src)
207 cop.src = cop.dst = s.buffer_info()[0]
208 if self._maclen is not None:
209 m = array.array('B', [0] * self._maclen)
210 cop.mac = m.buffer_info()[0]
211 ivbuf = array.array('B', iv)
212 cop.iv = ivbuf.buffer_info()[0]
215 ioctl(_cryptodev, CIOCCRYPT, str(cop))
218 if self._maclen is not None:
219 return s, m.tostring()
223 def _doaead(self, op, src, aad, iv, tag=None):
225 caead.ses = self._ses
227 caead.flags = CRD_F_IV_EXPLICIT
230 s = array.array('B', src)
231 caead.src = caead.dst = s.buffer_info()[0]
232 caead.aadlen = len(aad)
233 saad = array.array('B', aad)
234 caead.aad = saad.buffer_info()[0]
236 if self._maclen is None:
237 raise ValueError('must have a tag length')
240 tag = array.array('B', [0] * self._maclen)
242 assert len(tag) == self._maclen, \
243 '%d != %d' % (len(tag), self._maclen)
244 tag = array.array('B', tag)
246 caead.tag = tag.buffer_info()[0]
248 ivbuf = array.array('B', iv)
249 caead.ivlen = len(iv)
250 caead.iv = ivbuf.buffer_info()[0]
252 ioctl(_cryptodev, CIOCCRYPTAEAD, str(caead))
256 return s, tag.tostring()
258 def perftest(self, op, size, timeo=3):
259 inp = array.array('B', (random.randint(0, 255) for x in xrange(size)))
260 out = array.array('B', 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]
278 def alarmhandle(a, b, exit=exit):
281 oldalarm = signal.signal(signal.SIGALRM, alarmhandle)
287 ioctl(_cryptodev, CIOCCRYPT, str(cop))
292 signal.signal(signal.SIGALRM, oldalarm)
294 print('time:', end - start)
295 print('perf MB/sec:', (reps * size) / (end - start) / 1024 / 1024)
297 def encrypt(self, data, iv, aad=None):
299 return self._doop(COP_ENCRYPT, data, iv)
301 return self._doaead(COP_ENCRYPT, data, aad,
304 def decrypt(self, data, iv, aad=None, tag=None):
306 return self._doop(COP_DECRYPT, data, iv)
308 return self._doaead(COP_DECRYPT, data, aad,
311 class MismatchError(Exception):
315 def __init__(self, fname, fields):
316 self.fp = open(fname)
317 self.fields = set(fields)
323 if self._pending is not None:
327 i = self.fp.readline()
330 if didread and not i:
333 if (i and i[0] == '#') or not i.strip():
336 yield i[1:].split(']', 1)[0], self.fielditer()
338 raise ValueError('unknown line: %r' % repr(i))
342 line = self.fp.readline()
356 line = self.eatblanks()
357 if not line or line[0] == '[':
363 f, v = line.split(' =')
368 print('line:', repr(line))
373 raise ValueError('already present: %r' % repr(f))
375 line = self.fp.readline().strip()
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: %r' % repr(remain))
387 # The CCM files use a bit of a different syntax that doesn't quite fit
388 # the generic KATParser. In particular, some keys are set globally at
389 # the start of the file, and some are set globally at the start of a
392 def __init__(self, fname):
393 self.fp = open(fname)
397 def read_globals(self):
398 self.global_values = {}
400 line = self.fp.readline()
403 if line[0] == '#' or not line.strip():
410 f, v = line.split(' =')
412 print('line:', repr(line))
417 if f in self.global_values:
418 raise ValueError('already present: %r' % repr(f))
419 self.global_values[f] = v
421 def read_section_values(self, kwpairs):
422 self.section_values = self.global_values.copy()
423 for pair in kwpairs.split(', '):
424 f, v = pair.split(' = ')
425 if f in self.section_values:
426 raise ValueError('already present: %r' % repr(f))
427 self.section_values[f] = v
430 line = self.fp.readline()
433 if line[0] == '#' or not line.strip():
440 f, v = line.split(' =')
442 print('line:', repr(line))
451 if f in self.section_values:
452 raise ValueError('already present: %r' % repr(f))
453 self.section_values[f] = v
461 line = self.fp.readline()
465 if (line and line[0] == '#') or not line.strip():
469 section = line[1:].split(']', 1)[0]
470 self.read_section_values(section)
473 values = self.section_values.copy()
477 f, v = line.split(' =')
479 print('line:', repr(line))
484 raise ValueError('already present: %r' % repr(f))
486 line = self.fp.readline().strip()
494 return ''.join(s.split()).decode('hex')
496 if __name__ == '__main__':
499 crid = Crypto.findcrid('aesni0')
500 print('aesni:', crid)
502 print('aesni0 not found')
506 name = Crypto.getcridname(i)
507 print('%2d: %r' % (i, repr(name)))
511 kp = KATParser('/usr/home/jmg/aesni.testing/format tweak value input - data unit seq no/XTSGenAES128.rsp', [ 'COUNT', 'DataUnitLen', 'Key', 'DataUnitSeqNumber', 'PT', 'CT' ])
517 key = _spdechex('c939cc13397c1d37de6ae0e1cb7c423c')
518 iv = _spdechex('00000000000000000000000000000001')
519 pt = _spdechex('ab3cabed693a32946055524052afe3c9cb49664f09fc8b7da824d924006b7496353b8c1657c5dec564d8f38d7432e1de35aae9d95590e66278d4acce883e51abaf94977fcd3679660109a92bf7b2973ccd547f065ec6cee4cb4a72a5e9f45e615d920d76cb34cba482467b3e21422a7242e7d931330c0fbf465c3a3a46fae943029fd899626dda542750a1eee253df323c6ef1573f1c8c156613e2ea0a6cdbf2ae9701020be2d6a83ecb7f3f9d8e')
520 #pt = _spdechex('00000000000000000000000000000000')
521 ct = _spdechex('f42c33853ecc5ce2949865fdb83de3bff1089e9360c94f830baebfaff72836ab5236f77212f1e7396c8c54ac73d81986375a6e9e299cfeca5ba051ed25e8d1affa5beaf6c1d2b45e90802408f2ced21663497e906de5f29341e5e52ddfea5363d628b3eb7806835e17bae051b3a6da3f8e2941fe44384eac17a9d298d2c331ca8320c775b5d53263a5e905059d891b21dede2d8110fd427c7bd5a9a274ddb47b1945ee79522203b6e297d0e399ef')
523 c = Crypto(CRYPTO_AES_ICM, key)
524 enc = c.encrypt(pt, iv)
526 print('enc:', enc.encode('hex'))
527 print(' ct:', ct.encode('hex'))
531 dec = c.decrypt(ct, iv)
533 print('dec:', dec.encode('hex'))
534 print(' pt:', pt.encode('hex'))
538 key = _spdechex('c939cc13397c1d37de6ae0e1cb7c423c')
539 iv = _spdechex('00000000000000000000000000000001')
540 pt = _spdechex('ab3cabed693a32946055524052afe3c9cb49664f09fc8b7da824d924006b7496353b8c1657c5dec564d8f38d7432e1de35aae9d95590e66278d4acce883e51abaf94977fcd3679660109a92bf7b2973ccd547f065ec6cee4cb4a72a5e9f45e615d920d76cb34cba482467b3e21422a7242e7d931330c0fbf465c3a3a46fae943029fd899626dda542750a1eee253df323c6ef1573f1c8c156613e2ea0a6cdbf2ae9701020be2d6a83ecb7f3f9d8e0a3f')
541 #pt = _spdechex('00000000000000000000000000000000')
542 ct = _spdechex('f42c33853ecc5ce2949865fdb83de3bff1089e9360c94f830baebfaff72836ab5236f77212f1e7396c8c54ac73d81986375a6e9e299cfeca5ba051ed25e8d1affa5beaf6c1d2b45e90802408f2ced21663497e906de5f29341e5e52ddfea5363d628b3eb7806835e17bae051b3a6da3f8e2941fe44384eac17a9d298d2c331ca8320c775b5d53263a5e905059d891b21dede2d8110fd427c7bd5a9a274ddb47b1945ee79522203b6e297d0e399ef3768')
544 c = Crypto(CRYPTO_AES_ICM, key)
545 enc = c.encrypt(pt, iv)
547 print('enc:', enc.encode('hex'))
548 print(' ct:', ct.encode('hex'))
552 dec = c.decrypt(ct, iv)
554 print('dec:', dec.encode('hex'))
555 print(' pt:', pt.encode('hex'))
559 key = _spdechex('c939cc13397c1d37de6ae0e1cb7c423c')
560 iv = _spdechex('6eba2716ec0bd6fa5cdef5e6d3a795bc')
561 pt = _spdechex('ab3cabed693a32946055524052afe3c9cb49664f09fc8b7da824d924006b7496353b8c1657c5dec564d8f38d7432e1de35aae9d95590e66278d4acce883e51abaf94977fcd3679660109a92bf7b2973ccd547f065ec6cee4cb4a72a5e9f45e615d920d76cb34cba482467b3e21422a7242e7d931330c0fbf465c3a3a46fae943029fd899626dda542750a1eee253df323c6ef1573f1c8c156613e2ea0a6cdbf2ae9701020be2d6a83ecb7f3f9d8e0a3f')
562 ct = _spdechex('f1f81f12e72e992dbdc304032705dc75dc3e4180eff8ee4819906af6aee876d5b00b7c36d282a445ce3620327be481e8e53a8e5a8e5ca9abfeb2281be88d12ffa8f46d958d8224738c1f7eea48bda03edbf9adeb900985f4fa25648b406d13a886c25e70cfdecdde0ad0f2991420eb48a61c64fd797237cf2798c2675b9bb744360b0a3f329ac53bbceb4e3e7456e6514f1a9d2f06c236c31d0f080b79c15dce1096357416602520daa098b17d1af427')
563 c = Crypto(CRYPTO_AES_CBC, key)
565 enc = c.encrypt(pt, iv)
567 print('enc:', enc.encode('hex'))
568 print(' ct:', ct.encode('hex'))
572 dec = c.decrypt(ct, iv)
574 print('dec:', dec.encode('hex'))
575 print(' pt:', pt.encode('hex'))
579 key = _spdechex('c939cc13397c1d37de6ae0e1cb7c423c')
580 iv = _spdechex('b3d8cc017cbb89b39e0f67e2')
581 pt = _spdechex('c3b3c41f113a31b73d9a5cd4321030')
582 aad = _spdechex('24825602bd12a984e0092d3e448eda5f')
583 ct = _spdechex('93fe7d9e9bfd10348a5606e5cafa7354')
584 ct = _spdechex('93fe7d9e9bfd10348a5606e5cafa73')
585 tag = _spdechex('0032a1dc85f1c9786925a2e71d8272dd')
586 tag = _spdechex('8d11a0929cb3fbe1fef01a4a38d5f8ea')
588 c = Crypto(CRYPTO_AES_NIST_GCM_16, key,
589 mac=CRYPTO_AES_128_NIST_GMAC, mackey=key)
591 enc, enctag = c.encrypt(pt, iv, aad=aad)
593 print('enc:', enc.encode('hex'))
594 print(' ct:', ct.encode('hex'))
598 print('etg:', enctag.encode('hex'))
599 print('tag:', tag.encode('hex'))
602 # Make sure we get EBADMSG
603 #enctag = enctag[:-1] + 'a'
604 dec, dectag = c.decrypt(ct, iv, aad=aad, tag=enctag)
606 print('dec:', dec.encode('hex'))
607 print(' pt:', pt.encode('hex'))
611 print('dtg:', dectag.encode('hex'))
612 print('tag:', tag.encode('hex'))
616 key = _spdechex('c939cc13397c1d37de6ae0e1cb7c423c')
617 iv = _spdechex('b3d8cc017cbb89b39e0f67e2')
620 pt = _spdechex('c3b3c41f113a31b73d9a5cd432103069')
621 aad = _spdechex('24825602bd12a984e0092d3e448eda5f')
622 ct = _spdechex('93fe7d9e9bfd10348a5606e5cafa7354')
623 tag = _spdechex('0032a1dc85f1c9786925a2e71d8272dd')
625 c = Crypto(CRYPTO_AES_GCM_16, key, mac=CRYPTO_AES_128_GMAC, mackey=key)
627 enc, enctag = c.encrypt(pt, iv, aad=aad)
629 print('enc:', enc.encode('hex'))
630 print(' ct:', ct.encode('hex'))
634 print('etg:', enctag.encode('hex'))
635 print('tag:', tag.encode('hex'))
638 for i in xrange(100000):
639 c = Crypto(CRYPTO_AES_XTS, '1bbfeadf539daedcae33ced497343f3ca1f2474ad932b903997d44707db41382'.decode('hex'))
640 data = '52a42bca4e9425a25bbc8c8bf6129dec'.decode('hex')
641 ct = '517e602becd066b65fa4f4f56ddfe240'.decode('hex')
642 iv = _pack('QQ', 71, 0)
644 enc = c.encrypt(data, iv)
647 c = Crypto(CRYPTO_AES_XTS, '1bbfeadf539daedcae33ced497343f3ca1f2474ad932b903997d44707db41382'.decode('hex'))
648 data = '52a42bca4e9425a25bbc8c8bf6129dec'.decode('hex')
649 ct = '517e602becd066b65fa4f4f56ddfe240'.decode('hex')
650 iv = _pack('QQ', 71, 0)
652 enc = c.encrypt(data, iv)
655 dec = c.decrypt(enc, iv)
658 #c.perftest(COP_ENCRYPT, 192*1024, reps=30000)
661 key = '1bbfeadf539daedcae33ced497343f3ca1f2474ad932b903997d44707db41382'.decode('hex')
662 print('XTS %d testing:' % (len(key) * 8))
663 c = Crypto(CRYPTO_AES_XTS, key)
664 for i in [ 8192, 192*1024]:
665 print('block size: %d' % i)
666 c.perftest(COP_ENCRYPT, i)
667 c.perftest(COP_DECRYPT, i)