Refactor tests/sys/opencrypto/runtests

* Convert from plain to TAP for slightly improved introspection when skipping
  the tests due to requirements not being met.
* Test for the net/py-dpkt (origin) package being required when running the
  tests, instead of relying on a copy of the dpkt.py module from 2014. This
  enables the tests to work with py3. Subsequently, remove
  `tests/sys/opencrypto/dpkt.py(c)?` via `make delete-old`.
* Parameterize out `python2` as `$PYTHON`.

PR:		237403
MFC after:	1 week
This commit is contained in:
Enji Cooper 2019-05-10 00:03:32 +00:00
parent 9ad8b64eb4
commit 16f35864df
4 changed files with 36 additions and 171 deletions

View File

@ -38,6 +38,9 @@
# xargs -n1 | sort | uniq -d;
# done
# 20190509: tests/sys/opencrypto requires the net/py-dpkt package.
OLD_FILES+=usr/tests/sys/opencrypto/dpkt.py
OLD_FILES+=usr/tests/sys/opencrypto/dpkt.pyc
# 20190304: new libc++ import which bumps version from 7.0.1 to 8.0.0.
OLD_FILES+=usr/include/c++/v1/experimental/dynarray
# 20190304: new clang import which bumps version from 7.0.1 to 8.0.0.

View File

@ -12,12 +12,12 @@ CFLAGS.poly1305_test.c += -I${SRCTOP}/sys/opencrypto
ATF_TESTS_C+= blake2_test poly1305_test
PLAIN_TESTS_SH= runtests
TAP_TESTS_SH+= runtests
TEST_METADATA.runtests+= required_programs="python2"
TEST_METADATA.runtests+= required_user="root"
PYMODULES= cryptodev.py cryptodevh.py cryptotest.py dpkt.py
PYMODULES= cryptodev.py cryptodevh.py cryptotest.py
${PACKAGE}FILES+= ${PYMODULES}

View File

@ -1,160 +0,0 @@
# $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

View File

@ -29,10 +29,15 @@
# $FreeBSD$
#
set -ex
: ${PYTHON=python2}
if [ ! -d /usr/local/share/nist-kat ]; then
echo 'Skipping, nist-kat package not installed for test vectors.'
echo "1..0 # SKIP: nist-kat package not installed for test vectors"
exit 0
fi
if ! $PYTHON -c "from dpkt import dpkt"; then
echo "1..0 # SKIP: py-dpkt package not installed"
exit 0
fi
@ -43,6 +48,10 @@ cleanup_tests()
set +e
if [ -n "$oldcdas" ]; then
sysctl "$oldcdas" 2>/dev/null
fi
# Unload modules in reverse order
for loaded_module in $(echo $loaded_modules | tr ' ' '\n' | sort -r); do
kldunload $loaded_module
@ -52,15 +61,28 @@ trap cleanup_tests EXIT INT TERM
for required_module in nexus/aesni cryptodev; do
if ! kldstat -q -m $required_module; then
kldload ${required_module#nexus/}
module_to_load=${required_module#nexus/}
if ! kldload ${module_to_load}; then
echo "1..0 # SKIP: could not load ${module_to_load}"
exit 0
fi
loaded_modules="$loaded_modules $required_module"
fi
done
# Run software crypto test
oldcdas=$(sysctl -e kern.cryptodevallowsoft)
sysctl kern.cryptodevallowsoft=1
cdas_sysctl=kern.cryptodevallowsoft
if ! oldcdas=$(sysctl -e $cdas_sysctl); then
echo "1..0 # SKIP: could not resolve sysctl: $cdas_sysctl"
exit 0
fi
if ! sysctl $cdas_sysctl=1; then
echo "1..0 # SKIP: could not enable /dev/crypto access via $cdas_sysctl sysctl."
exit 0
fi
python2 $(dirname $0)/cryptotest.py
sysctl "$oldcdas"
echo "1..1"
if "$PYTHON" $(dirname $0)/cryptotest.py; then
echo "ok 1"
else
echo "not ok 1"
fi