diff options
Diffstat (limited to 'tests')
-rw-r--r-- | tests/sys/Makefile | 1 | ||||
-rw-r--r-- | tests/sys/opencrypto/Makefile | 14 | ||||
-rw-r--r-- | tests/sys/opencrypto/cryptodev.py | 561 | ||||
-rw-r--r-- | tests/sys/opencrypto/cryptodevh.py | 250 | ||||
-rw-r--r-- | tests/sys/opencrypto/cryptotest.py | 265 | ||||
-rw-r--r-- | tests/sys/opencrypto/dpkt.py | 160 | ||||
-rw-r--r-- | tests/sys/opencrypto/runtests.sh | 60 |
7 files changed, 1311 insertions, 0 deletions
diff --git a/tests/sys/Makefile b/tests/sys/Makefile index daa74f3..18a24a4 100644 --- a/tests/sys/Makefile +++ b/tests/sys/Makefile @@ -14,6 +14,7 @@ TESTS_SUBDIRS+= kqueue TESTS_SUBDIRS+= mac TESTS_SUBDIRS+= mqueue TESTS_SUBDIRS+= netinet +TESTS_SUBDIRS+= opencrypto TESTS_SUBDIRS+= posixshm TESTS_SUBDIRS+= vfs TESTS_SUBDIRS+= vm diff --git a/tests/sys/opencrypto/Makefile b/tests/sys/opencrypto/Makefile new file mode 100644 index 0000000..1696920 --- /dev/null +++ b/tests/sys/opencrypto/Makefile @@ -0,0 +1,14 @@ +# $FreeBSD$ + +TESTSDIR= ${TESTSBASE}/sys/opencrypto +BINDIR= ${TESTSDIR} + +PLAIN_TESTS_SH= runtests + +TEST_METADATA.foo+=required_programs="python" +PYMODULES= cryptodev.py cryptodevh.py cryptotest.py dpkt.py + +FILESDIR= ${TESTSDIR} +FILES= ${PYMODULES} + +.include <bsd.test.mk> diff --git a/tests/sys/opencrypto/cryptodev.py b/tests/sys/opencrypto/cryptodev.py new file mode 100644 index 0000000..d9f764a --- /dev/null +++ b/tests/sys/opencrypto/cryptodev.py @@ -0,0 +1,561 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014 The FreeBSD Foundation +# Copyright 2014 John-Mark Gurney +# All rights reserved. +# +# This software was developed by John-Mark Gurney under +# the sponsorship from the FreeBSD Foundation. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +# SUCH DAMAGE. +# +# $FreeBSD$ +# + +import array +import dpkt +from fcntl import ioctl +import os +import signal +from struct import pack as _pack + +from cryptodevh import * + +__all__ = [ 'Crypto', 'MismatchError', ] + +class FindOp(dpkt.Packet): + __byte_order__ = '@' + __hdr__ = ( ('crid', 'i', 0), + ('name', '32s', 0), + ) + +class SessionOp(dpkt.Packet): + __byte_order__ = '@' + __hdr__ = ( ('cipher', 'I', 0), + ('mac', 'I', 0), + ('keylen', 'I', 0), + ('key', 'P', 0), + ('mackeylen', 'i', 0), + ('mackey', 'P', 0), + ('ses', 'I', 0), + ) + +class SessionOp2(dpkt.Packet): + __byte_order__ = '@' + __hdr__ = ( ('cipher', 'I', 0), + ('mac', 'I', 0), + ('keylen', 'I', 0), + ('key', 'P', 0), + ('mackeylen', 'i', 0), + ('mackey', 'P', 0), + ('ses', 'I', 0), + ('crid', 'i', 0), + ('pad0', 'i', 0), + ('pad1', 'i', 0), + ('pad2', 'i', 0), + ('pad3', 'i', 0), + ) + +class CryptOp(dpkt.Packet): + __byte_order__ = '@' + __hdr__ = ( ('ses', 'I', 0), + ('op', 'H', 0), + ('flags', 'H', 0), + ('len', 'I', 0), + ('src', 'P', 0), + ('dst', 'P', 0), + ('mac', 'P', 0), + ('iv', 'P', 0), + ) + +class CryptAEAD(dpkt.Packet): + __byte_order__ = '@' + __hdr__ = ( + ('ses', 'I', 0), + ('op', 'H', 0), + ('flags', 'H', 0), + ('len', 'I', 0), + ('aadlen', 'I', 0), + ('ivlen', 'I', 0), + ('src', 'P', 0), + ('dst', 'P', 0), + ('aad', 'P', 0), + ('tag', 'P', 0), + ('iv', 'P', 0), + ) + +# h2py.py can't handle multiarg macros +CRIOGET = 3221513060 +CIOCGSESSION = 3224396645 +CIOCGSESSION2 = 3225445226 +CIOCFSESSION = 2147771238 +CIOCCRYPT = 3224396647 +CIOCKEY = 3230688104 +CIOCASYMFEAT = 1074029417 +CIOCKEY2 = 3230688107 +CIOCFINDDEV = 3223610220 +CIOCCRYPTAEAD = 3225445229 + +def _getdev(): + fd = os.open('/dev/crypto', os.O_RDWR) + buf = array.array('I', [0]) + ioctl(fd, CRIOGET, buf, 1) + os.close(fd) + + return buf[0] + +_cryptodev = _getdev() + +def _findop(crid, name): + fop = FindOp() + fop.crid = crid + fop.name = name + s = array.array('B', fop.pack_hdr()) + ioctl(_cryptodev, CIOCFINDDEV, s, 1) + fop.unpack(s) + + try: + idx = fop.name.index('\x00') + name = fop.name[:idx] + except ValueError: + name = fop.name + + return fop.crid, name + +class Crypto: + @staticmethod + def findcrid(name): + return _findop(-1, name)[0] + + @staticmethod + def getcridname(crid): + return _findop(crid, '')[1] + + def __init__(self, cipher=0, key=None, mac=0, mackey=None, + crid=CRYPTOCAP_F_SOFTWARE | CRYPTOCAP_F_HARDWARE): + self._ses = None + ses = SessionOp2() + ses.cipher = cipher + ses.mac = mac + + if key is not None: + ses.keylen = len(key) + k = array.array('B', key) + ses.key = k.buffer_info()[0] + else: + self.key = None + + if mackey is not None: + ses.mackeylen = len(mackey) + mk = array.array('B', mackey) + ses.mackey = mk.buffer_info()[0] + self._maclen = 16 # parameterize? + else: + self._maclen = None + + if not cipher and not mac: + raise ValueError('one of cipher or mac MUST be specified.') + ses.crid = CRYPTOCAP_F_SOFTWARE | CRYPTOCAP_F_HARDWARE + #ses.crid = CRYPTOCAP_F_HARDWARE + #ses.crid = CRYPTOCAP_F_SOFTWARE + #ses.crid = 0 + #print `ses` + s = array.array('B', ses.pack_hdr()) + #print `s` + ioctl(_cryptodev, CIOCGSESSION2, s, 1) + ses.unpack(s) + + self._ses = ses.ses + + def __del__(self): + if self._ses is None: + return + + try: + ioctl(_cryptodev, CIOCFSESSION, _pack('I', self._ses)) + except TypeError: + pass + self._ses = None + + def _doop(self, op, src, iv): + cop = CryptOp() + cop.ses = self._ses + cop.op = op + cop.flags = 0 + cop.len = len(src) + s = array.array('B', src) + cop.src = cop.dst = s.buffer_info()[0] + if self._maclen is not None: + m = array.array('B', [0] * self._maclen) + cop.mac = m.buffer_info()[0] + ivbuf = array.array('B', iv) + cop.iv = ivbuf.buffer_info()[0] + + #print 'cop:', `cop` + ioctl(_cryptodev, CIOCCRYPT, str(cop)) + + s = s.tostring() + if self._maclen is not None: + return s, m.tostring() + + return s + + def _doaead(self, op, src, aad, iv, tag=None): + caead = CryptAEAD() + caead.ses = self._ses + caead.op = op + caead.flags = CRD_F_IV_EXPLICIT + caead.flags = 0 + caead.len = len(src) + s = array.array('B', src) + caead.src = caead.dst = s.buffer_info()[0] + caead.aadlen = len(aad) + saad = array.array('B', aad) + caead.aad = saad.buffer_info()[0] + + if self._maclen is None: + raise ValueError('must have a tag length') + + if tag is None: + tag = array.array('B', [0] * self._maclen) + else: + assert len(tag) == self._maclen, `len(tag), self._maclen` + tag = array.array('B', tag) + + caead.tag = tag.buffer_info()[0] + + ivbuf = array.array('B', iv) + caead.ivlen = len(iv) + caead.iv = ivbuf.buffer_info()[0] + + ioctl(_cryptodev, CIOCCRYPTAEAD, str(caead)) + + s = s.tostring() + + return s, tag.tostring() + + def perftest(self, op, size, timeo=3): + import random + import time + + inp = array.array('B', (random.randint(0, 255) for x in xrange(size))) + out = array.array('B', inp) + + # prep ioctl + cop = CryptOp() + cop.ses = self._ses + cop.op = op + cop.flags = 0 + cop.len = len(inp) + s = array.array('B', inp) + cop.src = s.buffer_info()[0] + cop.dst = out.buffer_info()[0] + if self._maclen is not None: + m = array.array('B', [0] * self._maclen) + cop.mac = m.buffer_info()[0] + ivbuf = array.array('B', (random.randint(0, 255) for x in xrange(16))) + cop.iv = ivbuf.buffer_info()[0] + + exit = [ False ] + def alarmhandle(a, b, exit=exit): + exit[0] = True + + oldalarm = signal.signal(signal.SIGALRM, alarmhandle) + signal.alarm(timeo) + + start = time.time() + reps = 0 + while not exit[0]: + ioctl(_cryptodev, CIOCCRYPT, str(cop)) + reps += 1 + + end = time.time() + + signal.signal(signal.SIGALRM, oldalarm) + + print 'time:', end - start + print 'perf MB/sec:', (reps * size) / (end - start) / 1024 / 1024 + + def encrypt(self, data, iv, aad=None): + if aad is None: + return self._doop(COP_ENCRYPT, data, iv) + else: + return self._doaead(COP_ENCRYPT, data, aad, + iv) + + def decrypt(self, data, iv, aad=None, tag=None): + if aad is None: + return self._doop(COP_DECRYPT, data, iv) + else: + return self._doaead(COP_DECRYPT, data, aad, + iv, tag=tag) + +class MismatchError(Exception): + pass + +class KATParser: + def __init__(self, fname, fields): + self.fp = open(fname) + self.fields = set(fields) + self._pending = None + + def __iter__(self): + while True: + didread = False + if self._pending is not None: + i = self._pending + self._pending = None + else: + i = self.fp.readline() + didread = True + + if didread and not i: + return + + if (i and i[0] == '#') or not i.strip(): + continue + if i[0] == '[': + yield i[1:].split(']', 1)[0], self.fielditer() + else: + raise ValueError('unknown line: %s' % `i`) + + def eatblanks(self): + while True: + line = self.fp.readline() + if line == '': + break + + line = line.strip() + if line: + break + + return line + + def fielditer(self): + while True: + values = {} + + line = self.eatblanks() + if not line or line[0] == '[': + self._pending = line + return + + while True: + try: + f, v = line.split(' =') + except: + if line == 'FAIL': + f, v = 'FAIL', '' + else: + print 'line:', `line` + raise + v = v.strip() + + if f in values: + raise ValueError('already present: %s' % `f`) + values[f] = v + line = self.fp.readline().strip() + if not line: + break + + # we should have everything + remain = self.fields.copy() - set(values.keys()) + # XXX - special case GCM decrypt + if remain and not ('FAIL' in values and 'PT' in remain): + raise ValueError('not all fields found: %s' % `remain`) + + yield values + +def _spdechex(s): + return ''.join(s.split()).decode('hex') + +if __name__ == '__main__': + if True: + try: + crid = Crypto.findcrid('aesni0') + print 'aesni:', crid + except IOError: + print 'aesni0 not found' + + for i in xrange(10): + try: + name = Crypto.getcridname(i) + print '%2d: %s' % (i, `name`) + except IOError: + pass + elif False: + kp = KATParser('/usr/home/jmg/aesni.testing/format tweak value input - data unit seq no/XTSGenAES128.rsp', [ 'COUNT', 'DataUnitLen', 'Key', 'DataUnitSeqNumber', 'PT', 'CT' ]) + for mode, ni in kp: + print `i`, `ni` + for j in ni: + print `j` + elif False: + key = _spdechex('c939cc13397c1d37de6ae0e1cb7c423c') + iv = _spdechex('00000000000000000000000000000001') + pt = _spdechex('ab3cabed693a32946055524052afe3c9cb49664f09fc8b7da824d924006b7496353b8c1657c5dec564d8f38d7432e1de35aae9d95590e66278d4acce883e51abaf94977fcd3679660109a92bf7b2973ccd547f065ec6cee4cb4a72a5e9f45e615d920d76cb34cba482467b3e21422a7242e7d931330c0fbf465c3a3a46fae943029fd899626dda542750a1eee253df323c6ef1573f1c8c156613e2ea0a6cdbf2ae9701020be2d6a83ecb7f3f9d8e') + #pt = _spdechex('00000000000000000000000000000000') + ct = _spdechex('f42c33853ecc5ce2949865fdb83de3bff1089e9360c94f830baebfaff72836ab5236f77212f1e7396c8c54ac73d81986375a6e9e299cfeca5ba051ed25e8d1affa5beaf6c1d2b45e90802408f2ced21663497e906de5f29341e5e52ddfea5363d628b3eb7806835e17bae051b3a6da3f8e2941fe44384eac17a9d298d2c331ca8320c775b5d53263a5e905059d891b21dede2d8110fd427c7bd5a9a274ddb47b1945ee79522203b6e297d0e399ef') + + c = Crypto(CRYPTO_AES_ICM, key) + enc = c.encrypt(pt, iv) + + print 'enc:', enc.encode('hex') + print ' ct:', ct.encode('hex') + + assert ct == enc + + dec = c.decrypt(ct, iv) + + print 'dec:', dec.encode('hex') + print ' pt:', pt.encode('hex') + + assert pt == dec + elif False: + key = _spdechex('c939cc13397c1d37de6ae0e1cb7c423c') + iv = _spdechex('00000000000000000000000000000001') + pt = _spdechex('ab3cabed693a32946055524052afe3c9cb49664f09fc8b7da824d924006b7496353b8c1657c5dec564d8f38d7432e1de35aae9d95590e66278d4acce883e51abaf94977fcd3679660109a92bf7b2973ccd547f065ec6cee4cb4a72a5e9f45e615d920d76cb34cba482467b3e21422a7242e7d931330c0fbf465c3a3a46fae943029fd899626dda542750a1eee253df323c6ef1573f1c8c156613e2ea0a6cdbf2ae9701020be2d6a83ecb7f3f9d8e0a3f') + #pt = _spdechex('00000000000000000000000000000000') + ct = _spdechex('f42c33853ecc5ce2949865fdb83de3bff1089e9360c94f830baebfaff72836ab5236f77212f1e7396c8c54ac73d81986375a6e9e299cfeca5ba051ed25e8d1affa5beaf6c1d2b45e90802408f2ced21663497e906de5f29341e5e52ddfea5363d628b3eb7806835e17bae051b3a6da3f8e2941fe44384eac17a9d298d2c331ca8320c775b5d53263a5e905059d891b21dede2d8110fd427c7bd5a9a274ddb47b1945ee79522203b6e297d0e399ef3768') + + c = Crypto(CRYPTO_AES_ICM, key) + enc = c.encrypt(pt, iv) + + print 'enc:', enc.encode('hex') + print ' ct:', ct.encode('hex') + + assert ct == enc + + dec = c.decrypt(ct, iv) + + print 'dec:', dec.encode('hex') + print ' pt:', pt.encode('hex') + + assert pt == dec + elif False: + key = _spdechex('c939cc13397c1d37de6ae0e1cb7c423c') + iv = _spdechex('6eba2716ec0bd6fa5cdef5e6d3a795bc') + pt = _spdechex('ab3cabed693a32946055524052afe3c9cb49664f09fc8b7da824d924006b7496353b8c1657c5dec564d8f38d7432e1de35aae9d95590e66278d4acce883e51abaf94977fcd3679660109a92bf7b2973ccd547f065ec6cee4cb4a72a5e9f45e615d920d76cb34cba482467b3e21422a7242e7d931330c0fbf465c3a3a46fae943029fd899626dda542750a1eee253df323c6ef1573f1c8c156613e2ea0a6cdbf2ae9701020be2d6a83ecb7f3f9d8e0a3f') + ct = _spdechex('f1f81f12e72e992dbdc304032705dc75dc3e4180eff8ee4819906af6aee876d5b00b7c36d282a445ce3620327be481e8e53a8e5a8e5ca9abfeb2281be88d12ffa8f46d958d8224738c1f7eea48bda03edbf9adeb900985f4fa25648b406d13a886c25e70cfdecdde0ad0f2991420eb48a61c64fd797237cf2798c2675b9bb744360b0a3f329ac53bbceb4e3e7456e6514f1a9d2f06c236c31d0f080b79c15dce1096357416602520daa098b17d1af427') + c = Crypto(CRYPTO_AES_CBC, key) + + enc = c.encrypt(pt, iv) + + print 'enc:', enc.encode('hex') + print ' ct:', ct.encode('hex') + + assert ct == enc + + dec = c.decrypt(ct, iv) + + print 'dec:', dec.encode('hex') + print ' pt:', pt.encode('hex') + + assert pt == dec + elif False: + key = _spdechex('c939cc13397c1d37de6ae0e1cb7c423c') + iv = _spdechex('b3d8cc017cbb89b39e0f67e2') + pt = _spdechex('c3b3c41f113a31b73d9a5cd4321030') + aad = _spdechex('24825602bd12a984e0092d3e448eda5f') + ct = _spdechex('93fe7d9e9bfd10348a5606e5cafa7354') + ct = _spdechex('93fe7d9e9bfd10348a5606e5cafa73') + tag = _spdechex('0032a1dc85f1c9786925a2e71d8272dd') + tag = _spdechex('8d11a0929cb3fbe1fef01a4a38d5f8ea') + + c = Crypto(CRYPTO_AES_NIST_GCM_16, key, + mac=CRYPTO_AES_128_NIST_GMAC, mackey=key) + + enc, enctag = c.encrypt(pt, iv, aad=aad) + + print 'enc:', enc.encode('hex') + print ' ct:', ct.encode('hex') + + assert enc == ct + + print 'etg:', enctag.encode('hex') + print 'tag:', tag.encode('hex') + assert enctag == tag + + # Make sure we get EBADMSG + #enctag = enctag[:-1] + 'a' + dec, dectag = c.decrypt(ct, iv, aad=aad, tag=enctag) + + print 'dec:', dec.encode('hex') + print ' pt:', pt.encode('hex') + + assert dec == pt + + print 'dtg:', dectag.encode('hex') + print 'tag:', tag.encode('hex') + + assert dectag == tag + elif False: + key = _spdechex('c939cc13397c1d37de6ae0e1cb7c423c') + iv = _spdechex('b3d8cc017cbb89b39e0f67e2') + key = key + iv[:4] + iv = iv[4:] + pt = _spdechex('c3b3c41f113a31b73d9a5cd432103069') + aad = _spdechex('24825602bd12a984e0092d3e448eda5f') + ct = _spdechex('93fe7d9e9bfd10348a5606e5cafa7354') + tag = _spdechex('0032a1dc85f1c9786925a2e71d8272dd') + + c = Crypto(CRYPTO_AES_GCM_16, key, mac=CRYPTO_AES_128_GMAC, mackey=key) + + enc, enctag = c.encrypt(pt, iv, aad=aad) + + print 'enc:', enc.encode('hex') + print ' ct:', ct.encode('hex') + + assert enc == ct + + print 'etg:', enctag.encode('hex') + print 'tag:', tag.encode('hex') + assert enctag == tag + elif False: + for i in xrange(100000): + c = Crypto(CRYPTO_AES_XTS, '1bbfeadf539daedcae33ced497343f3ca1f2474ad932b903997d44707db41382'.decode('hex')) + data = '52a42bca4e9425a25bbc8c8bf6129dec'.decode('hex') + ct = '517e602becd066b65fa4f4f56ddfe240'.decode('hex') + iv = _pack('QQ', 71, 0) + + enc = c.encrypt(data, iv) + assert enc == ct + elif True: + c = Crypto(CRYPTO_AES_XTS, '1bbfeadf539daedcae33ced497343f3ca1f2474ad932b903997d44707db41382'.decode('hex')) + data = '52a42bca4e9425a25bbc8c8bf6129dec'.decode('hex') + ct = '517e602becd066b65fa4f4f56ddfe240'.decode('hex') + iv = _pack('QQ', 71, 0) + + enc = c.encrypt(data, iv) + assert enc == ct + + dec = c.decrypt(enc, iv) + assert dec == data + + #c.perftest(COP_ENCRYPT, 192*1024, reps=30000) + + else: + key = '1bbfeadf539daedcae33ced497343f3ca1f2474ad932b903997d44707db41382'.decode('hex') + print 'XTS %d testing:' % (len(key) * 8) + c = Crypto(CRYPTO_AES_XTS, key) + for i in [ 8192, 192*1024]: + print 'block size: %d' % i + c.perftest(COP_ENCRYPT, i) + c.perftest(COP_DECRYPT, i) diff --git a/tests/sys/opencrypto/cryptodevh.py b/tests/sys/opencrypto/cryptodevh.py new file mode 100644 index 0000000..ee024e9 --- /dev/null +++ b/tests/sys/opencrypto/cryptodevh.py @@ -0,0 +1,250 @@ +# $FreeBSD$ +# Generated by h2py from stdin + +# Included from sys/ioccom.h +IOCPARM_SHIFT = 13 +IOCPARM_MASK = ((1 << IOCPARM_SHIFT) - 1) +def IOCPARM_LEN(x): return (((x) >> 16) & IOCPARM_MASK) + +def IOCBASECMD(x): return ((x) & ~(IOCPARM_MASK << 16)) + +def IOCGROUP(x): return (((x) >> 8) & 0xff) + +IOCPARM_MAX = (1 << IOCPARM_SHIFT) +IOC_VOID = 0x20000000 +IOC_OUT = 0x40000000 +IOC_IN = 0x80000000 +IOC_INOUT = (IOC_IN|IOC_OUT) +IOC_DIRMASK = (IOC_VOID|IOC_OUT|IOC_IN) + +# Included from sys/cdefs.h +def __has_feature(x): return 0 + +def __has_include(x): return 0 + +def __has_builtin(x): return 0 + +__GNUCLIKE_ASM = 3 +__GNUCLIKE_ASM = 2 +__GNUCLIKE___TYPEOF = 1 +__GNUCLIKE___OFFSETOF = 1 +__GNUCLIKE___SECTION = 1 +__GNUCLIKE_CTOR_SECTION_HANDLING = 1 +__GNUCLIKE_BUILTIN_CONSTANT_P = 1 +__GNUCLIKE_BUILTIN_VARARGS = 1 +__GNUCLIKE_BUILTIN_STDARG = 1 +__GNUCLIKE_BUILTIN_VAALIST = 1 +__GNUC_VA_LIST_COMPATIBILITY = 1 +__GNUCLIKE_BUILTIN_NEXT_ARG = 1 +__GNUCLIKE_BUILTIN_MEMCPY = 1 +__CC_SUPPORTS_INLINE = 1 +__CC_SUPPORTS___INLINE = 1 +__CC_SUPPORTS___INLINE__ = 1 +__CC_SUPPORTS___FUNC__ = 1 +__CC_SUPPORTS_WARNING = 1 +__CC_SUPPORTS_VARADIC_XXX = 1 +__CC_SUPPORTS_DYNAMIC_ARRAY_INIT = 1 +def __P(protos): return protos + +def __STRING(x): return #x + +def __XSTRING(x): return __STRING(x) + +def __P(protos): return () + +def __STRING(x): return "x" + +def __aligned(x): return __attribute__((__aligned__(x))) + +def __section(x): return __attribute__((__section__(x))) + +def __aligned(x): return __attribute__((__aligned__(x))) + +def __section(x): return __attribute__((__section__(x))) + +def _Alignas(x): return alignas(x) + +def _Alignas(x): return __aligned(x) + +def _Alignof(x): return alignof(x) + +def _Alignof(x): return __alignof(x) + +def __nonnull(x): return __attribute__((__nonnull__(x))) + +def __predict_true(exp): return __builtin_expect((exp), 1) + +def __predict_false(exp): return __builtin_expect((exp), 0) + +def __predict_true(exp): return (exp) + +def __predict_false(exp): return (exp) + +def __format_arg(fmtarg): return __attribute__((__format_arg__ (fmtarg))) + +def __GLOBL(sym): return __GLOBL1(sym) + +def __FBSDID(s): return __IDSTRING(__CONCAT(__rcsid_,__LINE__),s) + +def __RCSID(s): return __IDSTRING(__CONCAT(__rcsid_,__LINE__),s) + +def __RCSID_SOURCE(s): return __IDSTRING(__CONCAT(__rcsid_source_,__LINE__),s) + +def __SCCSID(s): return __IDSTRING(__CONCAT(__sccsid_,__LINE__),s) + +def __COPYRIGHT(s): return __IDSTRING(__CONCAT(__copyright_,__LINE__),s) + +_POSIX_C_SOURCE = 199009 +_POSIX_C_SOURCE = 199209 +__XSI_VISIBLE = 700 +_POSIX_C_SOURCE = 200809 +__XSI_VISIBLE = 600 +_POSIX_C_SOURCE = 200112 +__XSI_VISIBLE = 500 +_POSIX_C_SOURCE = 199506 +_POSIX_C_SOURCE = 198808 +__POSIX_VISIBLE = 200809 +__ISO_C_VISIBLE = 1999 +__POSIX_VISIBLE = 200112 +__ISO_C_VISIBLE = 1999 +__POSIX_VISIBLE = 199506 +__ISO_C_VISIBLE = 1990 +__POSIX_VISIBLE = 199309 +__ISO_C_VISIBLE = 1990 +__POSIX_VISIBLE = 199209 +__ISO_C_VISIBLE = 1990 +__POSIX_VISIBLE = 199009 +__ISO_C_VISIBLE = 1990 +__POSIX_VISIBLE = 198808 +__ISO_C_VISIBLE = 0 +__POSIX_VISIBLE = 0 +__XSI_VISIBLE = 0 +__BSD_VISIBLE = 0 +__ISO_C_VISIBLE = 1990 +__POSIX_VISIBLE = 0 +__XSI_VISIBLE = 0 +__BSD_VISIBLE = 0 +__ISO_C_VISIBLE = 1999 +__POSIX_VISIBLE = 0 +__XSI_VISIBLE = 0 +__BSD_VISIBLE = 0 +__ISO_C_VISIBLE = 2011 +__POSIX_VISIBLE = 200809 +__XSI_VISIBLE = 700 +__BSD_VISIBLE = 1 +__ISO_C_VISIBLE = 2011 +__NO_TLS = 1 +CRYPTO_DRIVERS_INITIAL = 4 +CRYPTO_SW_SESSIONS = 32 +NULL_HASH_LEN = 16 +MD5_HASH_LEN = 16 +SHA1_HASH_LEN = 20 +RIPEMD160_HASH_LEN = 20 +SHA2_256_HASH_LEN = 32 +SHA2_384_HASH_LEN = 48 +SHA2_512_HASH_LEN = 64 +MD5_KPDK_HASH_LEN = 16 +SHA1_KPDK_HASH_LEN = 20 +HASH_MAX_LEN = SHA2_512_HASH_LEN +NULL_HMAC_BLOCK_LEN = 64 +MD5_HMAC_BLOCK_LEN = 64 +SHA1_HMAC_BLOCK_LEN = 64 +RIPEMD160_HMAC_BLOCK_LEN = 64 +SHA2_256_HMAC_BLOCK_LEN = 64 +SHA2_384_HMAC_BLOCK_LEN = 128 +SHA2_512_HMAC_BLOCK_LEN = 128 +HMAC_MAX_BLOCK_LEN = SHA2_512_HMAC_BLOCK_LEN +HMAC_IPAD_VAL = 0x36 +HMAC_OPAD_VAL = 0x5C +NULL_BLOCK_LEN = 4 +DES_BLOCK_LEN = 8 +DES3_BLOCK_LEN = 8 +BLOWFISH_BLOCK_LEN = 8 +SKIPJACK_BLOCK_LEN = 8 +CAST128_BLOCK_LEN = 8 +RIJNDAEL128_BLOCK_LEN = 16 +AES_BLOCK_LEN = RIJNDAEL128_BLOCK_LEN +CAMELLIA_BLOCK_LEN = 16 +EALG_MAX_BLOCK_LEN = AES_BLOCK_LEN +AALG_MAX_RESULT_LEN = 64 +CRYPTO_ALGORITHM_MIN = 1 +CRYPTO_DES_CBC = 1 +CRYPTO_3DES_CBC = 2 +CRYPTO_BLF_CBC = 3 +CRYPTO_CAST_CBC = 4 +CRYPTO_SKIPJACK_CBC = 5 +CRYPTO_MD5_HMAC = 6 +CRYPTO_SHA1_HMAC = 7 +CRYPTO_RIPEMD160_HMAC = 8 +CRYPTO_MD5_KPDK = 9 +CRYPTO_SHA1_KPDK = 10 +CRYPTO_RIJNDAEL128_CBC = 11 +CRYPTO_AES_CBC = 11 +CRYPTO_ARC4 = 12 +CRYPTO_MD5 = 13 +CRYPTO_SHA1 = 14 +CRYPTO_NULL_HMAC = 15 +CRYPTO_NULL_CBC = 16 +CRYPTO_DEFLATE_COMP = 17 +CRYPTO_SHA2_256_HMAC = 18 +CRYPTO_SHA2_384_HMAC = 19 +CRYPTO_SHA2_512_HMAC = 20 +CRYPTO_CAMELLIA_CBC = 21 +CRYPTO_AES_XTS = 22 +CRYPTO_AES_ICM = 23 +CRYPTO_AES_NIST_GMAC = 24 +CRYPTO_AES_NIST_GCM_16 = 25 +CRYPTO_AES_128_NIST_GMAC = 26 +CRYPTO_AES_192_NIST_GMAC = 27 +CRYPTO_AES_256_NIST_GMAC = 28 +CRYPTO_ALGORITHM_MAX = 28 +CRYPTO_ALG_FLAG_SUPPORTED = 0x01 +CRYPTO_ALG_FLAG_RNG_ENABLE = 0x02 +CRYPTO_ALG_FLAG_DSA_SHA = 0x04 +CRYPTO_FLAG_HARDWARE = 0x01000000 +CRYPTO_FLAG_SOFTWARE = 0x02000000 +COP_ENCRYPT = 1 +COP_DECRYPT = 2 +COP_F_BATCH = 0x0008 +CRK_MAXPARAM = 8 +CRK_ALGORITM_MIN = 0 +CRK_MOD_EXP = 0 +CRK_MOD_EXP_CRT = 1 +CRK_DSA_SIGN = 2 +CRK_DSA_VERIFY = 3 +CRK_DH_COMPUTE_KEY = 4 +CRK_ALGORITHM_MAX = 4 +CRF_MOD_EXP = (1 << CRK_MOD_EXP) +CRF_MOD_EXP_CRT = (1 << CRK_MOD_EXP_CRT) +CRF_DSA_SIGN = (1 << CRK_DSA_SIGN) +CRF_DSA_VERIFY = (1 << CRK_DSA_VERIFY) +CRF_DH_COMPUTE_KEY = (1 << CRK_DH_COMPUTE_KEY) +CRD_F_ENCRYPT = 0x01 +CRD_F_IV_PRESENT = 0x02 +CRD_F_IV_EXPLICIT = 0x04 +CRD_F_DSA_SHA_NEEDED = 0x08 +CRD_F_COMP = 0x0f +CRD_F_KEY_EXPLICIT = 0x10 +CRYPTO_F_IMBUF = 0x0001 +CRYPTO_F_IOV = 0x0002 +CRYPTO_F_BATCH = 0x0008 +CRYPTO_F_CBIMM = 0x0010 +CRYPTO_F_DONE = 0x0020 +CRYPTO_F_CBIFSYNC = 0x0040 +CRYPTO_BUF_CONTIG = 0x0 +CRYPTO_BUF_IOV = 0x1 +CRYPTO_BUF_MBUF = 0x2 +CRYPTO_OP_DECRYPT = 0x0 +CRYPTO_OP_ENCRYPT = 0x1 +CRYPTO_HINT_MORE = 0x1 +def CRYPTO_SESID2HID(_sid): return (((_sid) >> 32) & 0x00ffffff) + +def CRYPTO_SESID2CAPS(_sid): return (((_sid) >> 32) & 0xff000000) + +def CRYPTO_SESID2LID(_sid): return (((u_int32_t) (_sid)) & 0xffffffff) + +CRYPTOCAP_F_HARDWARE = CRYPTO_FLAG_HARDWARE +CRYPTOCAP_F_SOFTWARE = CRYPTO_FLAG_SOFTWARE +CRYPTOCAP_F_SYNC = 0x04000000 +CRYPTO_SYMQ = 0x1 +CRYPTO_ASYMQ = 0x2 diff --git a/tests/sys/opencrypto/cryptotest.py b/tests/sys/opencrypto/cryptotest.py new file mode 100644 index 0000000..e616baf --- /dev/null +++ b/tests/sys/opencrypto/cryptotest.py @@ -0,0 +1,265 @@ +#!/usr/bin/env python +# +# Copyright (c) 2014 The FreeBSD Foundation +# All rights reserved. +# +# This software was developed by John-Mark Gurney under +# the sponsorship from the FreeBSD Foundation. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +# SUCH DAMAGE. +# +# $FreeBSD$ +# + +import cryptodev +import itertools +import os +import struct +import unittest +from cryptodev import * +from glob import iglob + +katdir = '/usr/local/share/nist-kat' + +def katg(base, glob): + return iglob(os.path.join(katdir, base, glob)) + +aesmodules = [ 'cryptosoft0', 'aesni0', ] +desmodules = [ 'cryptosoft0', ] +shamodules = [ 'cryptosoft0', ] + +def GenTestCase(cname): + try: + crid = cryptodev.Crypto.findcrid(cname) + except IOError: + return None + + class GendCryptoTestCase(unittest.TestCase): + ############### + ##### AES ##### + ############### + @unittest.skipIf(cname not in aesmodules, 'skipping AES on %s' % `cname`) + def test_xts(self): + for i in katg('XTSTestVectors/format tweak value input - data unit seq no', '*.rsp'): + self.runXTS(i, cryptodev.CRYPTO_AES_XTS) + + def test_cbc(self): + for i in katg('KAT_AES', 'CBC[GKV]*.rsp'): + self.runCBC(i) + + def test_gcm(self): + for i in katg('gcmtestvectors', 'gcmEncrypt*'): + self.runGCM(i, 'ENCRYPT') + + for i in katg('gcmtestvectors', 'gcmDecrypt*'): + self.runGCM(i, 'DECRYPT') + + _gmacsizes = { 32: cryptodev.CRYPTO_AES_256_NIST_GMAC, + 24: cryptodev.CRYPTO_AES_192_NIST_GMAC, + 16: cryptodev.CRYPTO_AES_128_NIST_GMAC, + } + def runGCM(self, fname, mode): + curfun = None + if mode == 'ENCRYPT': + swapptct = False + curfun = Crypto.encrypt + elif mode == 'DECRYPT': + swapptct = True + curfun = Crypto.decrypt + else: + raise RuntimeError('unknown mode: %s' % `mode`) + + for bogusmode, lines in cryptodev.KATParser(fname, + [ 'Count', 'Key', 'IV', 'CT', 'AAD', 'Tag', 'PT', ]): + for data in lines: + curcnt = int(data['Count']) + cipherkey = data['Key'].decode('hex') + iv = data['IV'].decode('hex') + aad = data['AAD'].decode('hex') + tag = data['Tag'].decode('hex') + if 'FAIL' not in data: + pt = data['PT'].decode('hex') + ct = data['CT'].decode('hex') + + if len(iv) != 12: + # XXX - isn't supported + continue + + c = Crypto(cryptodev.CRYPTO_AES_NIST_GCM_16, + cipherkey, + mac=self._gmacsizes[len(cipherkey)], + mackey=cipherkey, crid=crid) + + if mode == 'ENCRYPT': + rct, rtag = c.encrypt(pt, iv, aad) + rtag = rtag[:len(tag)] + data['rct'] = rct.encode('hex') + data['rtag'] = rtag.encode('hex') + self.assertEqual(rct, ct, `data`) + self.assertEqual(rtag, tag, `data`) + else: + if len(tag) != 16: + continue + args = (ct, iv, aad, tag) + if 'FAIL' in data: + self.assertRaises(IOError, + c.decrypt, *args) + else: + rpt, rtag = c.decrypt(*args) + data['rpt'] = rpt.encode('hex') + data['rtag'] = rtag.encode('hex') + self.assertEqual(rpt, pt, + `data`) + + def runCBC(self, fname): + curfun = None + for mode, lines in cryptodev.KATParser(fname, + [ 'COUNT', 'KEY', 'IV', 'PLAINTEXT', 'CIPHERTEXT', ]): + if mode == 'ENCRYPT': + swapptct = False + curfun = Crypto.encrypt + elif mode == 'DECRYPT': + swapptct = True + curfun = Crypto.decrypt + else: + raise RuntimeError('unknown mode: %s' % `mode`) + + for data in lines: + curcnt = int(data['COUNT']) + cipherkey = data['KEY'].decode('hex') + iv = data['IV'].decode('hex') + pt = data['PLAINTEXT'].decode('hex') + ct = data['CIPHERTEXT'].decode('hex') + + if swapptct: + pt, ct = ct, pt + # run the fun + c = Crypto(cryptodev.CRYPTO_AES_CBC, cipherkey, crid=crid) + r = curfun(c, pt, iv) + self.assertEqual(r, ct) + + def runXTS(self, fname, meth): + curfun = None + for mode, lines in cryptodev.KATParser(fname, + [ 'COUNT', 'DataUnitLen', 'Key', 'DataUnitSeqNumber', 'PT', + 'CT' ]): + if mode == 'ENCRYPT': + swapptct = False + curfun = Crypto.encrypt + elif mode == 'DECRYPT': + swapptct = True + curfun = Crypto.decrypt + else: + raise RuntimeError('unknown mode: %s' % `mode`) + + for data in lines: + curcnt = int(data['COUNT']) + nbits = int(data['DataUnitLen']) + cipherkey = data['Key'].decode('hex') + iv = struct.pack('QQ', int(data['DataUnitSeqNumber']), 0) + pt = data['PT'].decode('hex') + ct = data['CT'].decode('hex') + + if nbits % 128 != 0: + # XXX - mark as skipped + continue + if swapptct: + pt, ct = ct, pt + # run the fun + c = Crypto(meth, cipherkey, crid=crid) + r = curfun(c, pt, iv) + self.assertEqual(r, ct) + + ############### + ##### DES ##### + ############### + @unittest.skipIf(cname not in desmodules, 'skipping DES on %s' % `cname`) + def test_tdes(self): + for i in katg('KAT_TDES', 'TCBC[a-z]*.rsp'): + self.runTDES(i) + + def runTDES(self, fname): + curfun = None + for mode, lines in cryptodev.KATParser(fname, + [ 'COUNT', 'KEYs', 'IV', 'PLAINTEXT', 'CIPHERTEXT', ]): + if mode == 'ENCRYPT': + swapptct = False + curfun = Crypto.encrypt + elif mode == 'DECRYPT': + swapptct = True + curfun = Crypto.decrypt + else: + raise RuntimeError('unknown mode: %s' % `mode`) + + for data in lines: + curcnt = int(data['COUNT']) + key = data['KEYs'] * 3 + cipherkey = key.decode('hex') + iv = data['IV'].decode('hex') + pt = data['PLAINTEXT'].decode('hex') + ct = data['CIPHERTEXT'].decode('hex') + + if swapptct: + pt, ct = ct, pt + # run the fun + c = Crypto(cryptodev.CRYPTO_3DES_CBC, cipherkey, crid=crid) + r = curfun(c, pt, iv) + self.assertEqual(r, ct) + + ############### + ##### SHA ##### + ############### + @unittest.skipIf(cname not in shamodules, 'skipping SHA on %s' % `cname`) + def test_sha(self): + # SHA not available in software + pass + #for i in iglob('SHA1*'): + # self.runSHA(i) + + def test_sha1hmac(self): + for i in katg('hmactestvectors', 'HMAC.rsp'): + self.runSHA1HMAC(i) + + def runSHA1HMAC(self, fname): + for bogusmode, lines in cryptodev.KATParser(fname, + [ 'Count', 'Klen', 'Tlen', 'Key', 'Msg', 'Mac' ]): + for data in lines: + key = data['Key'].decode('hex') + msg = data['Msg'].decode('hex') + mac = data['Mac'].decode('hex') + + if len(key) != 20: + # XXX - implementation bug + continue + + c = Crypto(mac=cryptodev.CRYPTO_SHA1_HMAC, + mackey=key, crid=crid) + + r = c.encrypt(msg) + self.assertEqual(r, mac, `data`) + + return GendCryptoTestCase + +cryptosoft = GenTestCase('cryptosoft0') +aesni = GenTestCase('aesni0') + +if __name__ == '__main__': + unittest.main() diff --git a/tests/sys/opencrypto/dpkt.py b/tests/sys/opencrypto/dpkt.py new file mode 100644 index 0000000..b74aa35 --- /dev/null +++ b/tests/sys/opencrypto/dpkt.py @@ -0,0 +1,160 @@ +# $FreeBSD$ +# $Id: dpkt.py 114 2005-09-11 15:15:12Z dugsong $ + +"""fast, simple packet creation / parsing, with definitions for the +basic TCP/IP protocols. +""" + +__author__ = 'Dug Song <dugsong@monkey.org>' +__copyright__ = 'Copyright (c) 2004 Dug Song' +__license__ = 'BSD' +__url__ = 'http://monkey.org/~dugsong/dpkt/' +__version__ = '1.2' + +try: + from itertools import izip as _it_izip +except ImportError: + _it_izip = zip + +from struct import calcsize as _st_calcsize, \ + pack as _st_pack, unpack as _st_unpack, error as _st_error +from re import compile as _re_compile + +intchr = _re_compile(r"(?P<int>[0-9]+)(?P<chr>.)") + +class MetaPacket(type): + def __new__(cls, clsname, clsbases, clsdict): + if '__hdr__' in clsdict: + st = clsdict['__hdr__'] + clsdict['__hdr_fields__'] = [ x[0] for x in st ] + clsdict['__hdr_fmt__'] = clsdict.get('__byte_order__', '>') + \ + ''.join([ x[1] for x in st ]) + clsdict['__hdr_len__'] = _st_calcsize(clsdict['__hdr_fmt__']) + clsdict['__hdr_defaults__'] = \ + dict(zip(clsdict['__hdr_fields__'], [ x[2] for x in st ])) + clsdict['__slots__'] = clsdict['__hdr_fields__'] + return type.__new__(cls, clsname, clsbases, clsdict) + +class Packet(object): + """Packet class + + __hdr__ should be defined as a list of (name, structfmt, default) tuples + __byte_order__ can be set to override the default ('>') + """ + __metaclass__ = MetaPacket + data = '' + + def __init__(self, *args, **kwargs): + """Packet constructor with ([buf], [field=val,...]) prototype. + + Arguments: + + buf -- packet buffer to unpack + + Optional keyword arguments correspond to packet field names. + """ + if args: + self.unpack(args[0]) + else: + for k in self.__hdr_fields__: + setattr(self, k, self.__hdr_defaults__[k]) + for k, v in kwargs.iteritems(): + setattr(self, k, v) + + def __len__(self): + return self.__hdr_len__ + len(self.data) + + def __repr__(self): + l = [ '%s=%r' % (k, getattr(self, k)) + for k in self.__hdr_defaults__ + if getattr(self, k) != self.__hdr_defaults__[k] ] + if self.data: + l.append('data=%r' % self.data) + return '%s(%s)' % (self.__class__.__name__, ', '.join(l)) + + def __str__(self): + return self.pack_hdr() + str(self.data) + + def pack_hdr(self): + """Return packed header string.""" + try: + return _st_pack(self.__hdr_fmt__, + *[ getattr(self, k) for k in self.__hdr_fields__ ]) + except _st_error: + vals = [] + for k in self.__hdr_fields__: + v = getattr(self, k) + if isinstance(v, tuple): + vals.extend(v) + else: + vals.append(v) + return _st_pack(self.__hdr_fmt__, *vals) + + def unpack(self, buf): + """Unpack packet header fields from buf, and set self.data.""" + + res = list(_st_unpack(self.__hdr_fmt__, buf[:self.__hdr_len__])) + for e, k in enumerate(self.__slots__): + sfmt = self.__hdr__[e][1] + mat = intchr.match(sfmt) + if mat and mat.group('chr') != 's': + cnt = int(mat.group('int')) + setattr(self, k, list(res[:cnt])) + del res[:cnt] + else: + if sfmt[-1] == 's': + i = res[0].find('\x00') + if i != -1: + res[0] = res[0][:i] + setattr(self, k, res[0]) + del res[0] + assert len(res) == 0 + self.data = buf[self.__hdr_len__:] + +# XXX - ''.join([(len(`chr(x)`)==3) and chr(x) or '.' for x in range(256)]) +__vis_filter = """................................ !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[.]^_`abcdefghijklmnopqrstuvwxyz{|}~.................................................................................................................................""" + +def hexdump(buf, length=16): + """Return a hexdump output string of the given buffer.""" + n = 0 + res = [] + while buf: + line, buf = buf[:length], buf[length:] + hexa = ' '.join(['%02x' % ord(x) for x in line]) + line = line.translate(__vis_filter) + res.append(' %04d: %-*s %s' % (n, length * 3, hexa, line)) + n += length + return '\n'.join(res) + +def in_cksum_add(s, buf): + """in_cksum_add(cksum, buf) -> cksum + + Return accumulated Internet checksum. + """ + nleft = len(buf) + i = 0 + while nleft > 1: + s += ord(buf[i]) * 256 + ord(buf[i+1]) + i += 2 + nleft -= 2 + if nleft: + s += ord(buf[i]) * 256 + return s + +def in_cksum_done(s): + """Fold and return Internet checksum.""" + while (s >> 16): + s = (s >> 16) + (s & 0xffff) + return (~s & 0xffff) + +def in_cksum(buf): + """Return computed Internet checksum.""" + return in_cksum_done(in_cksum_add(0, buf)) + +try: + import psyco + psyco.bind(in_cksum) + psyco.bind(Packet) +except ImportError: + pass + diff --git a/tests/sys/opencrypto/runtests.sh b/tests/sys/opencrypto/runtests.sh new file mode 100644 index 0000000..26c673a --- /dev/null +++ b/tests/sys/opencrypto/runtests.sh @@ -0,0 +1,60 @@ +#!/bin/sh - +# +# Copyright (c) 2014 The FreeBSD Foundation +# All rights reserved. +# +# This software was developed by John-Mark Gurney under +# the sponsorship from the FreeBSD Foundation. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +# SUCH DAMAGE. +# +# $FreeBSD$ +# + +set -e + +if [ ! -d /usr/local/share/nist-kat ]; then + echo 'Skipping, nist-kat package not installed for test vectors.' + exit 0 +fi + +if kldload aesni 2>/dev/null; then + unloadaesni=1 +fi + +if kldload cryptodev 2>/dev/null; then + unloadcdev=1 +fi + +# Run software crypto test +oldcdas=$(sysctl -e kern.cryptodevallowsoft) +sysctl kern.cryptodevallowsoft=1 + +python $(dirname $0)/cryptotest.py + +sysctl "$oldcdas" + +if [ x"$unloadcdev" = x"1" ]; then + kldunload cryptodev +fi +if [ x"$unloadaesni" = x"1" ]; then + kldunload aesni +fi |