]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - tests/sys/opencrypto/cryptotest.py
Use more descriptive algorithm names in skip messages.
[FreeBSD/FreeBSD.git] / tests / sys / opencrypto / cryptotest.py
1 #!/usr/local/bin/python2
2 #
3 # Copyright (c) 2014 The FreeBSD Foundation
4 # All rights reserved.
5 #
6 # This software was developed by John-Mark Gurney under
7 # the sponsorship from the FreeBSD Foundation.
8 # Redistribution and use in source and binary forms, with or without
9 # modification, are permitted provided that the following conditions
10 # are met:
11 # 1.  Redistributions of source code must retain the above copyright
12 #     notice, this list of conditions and the following disclaimer.
13 # 2.  Redistributions in binary form must reproduce the above copyright
14 #     notice, this list of conditions and the following disclaimer in the
15 #     documentation and/or other materials provided with the distribution.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18 # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21 # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 # SUCH DAMAGE.
28 #
29 # $FreeBSD$
30 #
31
32 from __future__ import print_function
33 import errno
34 import cryptodev
35 import itertools
36 import os
37 import struct
38 import unittest
39 from cryptodev import *
40 from glob import iglob
41
42 katdir = '/usr/local/share/nist-kat'
43
44 def katg(base, glob):
45         assert os.path.exists(katdir), "Please 'pkg install nist-kat'"
46         if not os.path.exists(os.path.join(katdir, base)):
47                 raise unittest.SkipTest("Missing %s test vectors" % (base))
48         return iglob(os.path.join(katdir, base, glob))
49
50 aesmodules = [ 'cryptosoft0', 'aesni0', 'ccr0', 'ccp0' ]
51 desmodules = [ 'cryptosoft0', ]
52 shamodules = [ 'cryptosoft0', 'aesni0', 'ccr0', 'ccp0' ]
53
54 def GenTestCase(cname):
55         try:
56                 crid = cryptodev.Crypto.findcrid(cname)
57         except IOError:
58                 return None
59
60         class GendCryptoTestCase(unittest.TestCase):
61                 ###############
62                 ##### AES #####
63                 ###############
64                 @unittest.skipIf(cname not in aesmodules, 'skipping AES-XTS on %s' % (cname))
65                 def test_xts(self):
66                         for i in katg('XTSTestVectors/format tweak value input - data unit seq no', '*.rsp'):
67                                 self.runXTS(i, cryptodev.CRYPTO_AES_XTS)
68
69                 @unittest.skipIf(cname not in aesmodules, 'skipping AES-CBC on %s' % (cname))
70                 def test_cbc(self):
71                         for i in katg('KAT_AES', 'CBC[GKV]*.rsp'):
72                                 self.runCBC(i)
73
74                 @unittest.skipIf(cname not in aesmodules, 'skipping AES-GCM on %s' % (cname))
75                 def test_gcm(self):
76                         for i in katg('gcmtestvectors', 'gcmEncrypt*'):
77                                 self.runGCM(i, 'ENCRYPT')
78
79                         for i in katg('gcmtestvectors', 'gcmDecrypt*'):
80                                 self.runGCM(i, 'DECRYPT')
81
82                 _gmacsizes = { 32: cryptodev.CRYPTO_AES_256_NIST_GMAC,
83                         24: cryptodev.CRYPTO_AES_192_NIST_GMAC,
84                         16: cryptodev.CRYPTO_AES_128_NIST_GMAC,
85                 }
86                 def runGCM(self, fname, mode):
87                         curfun = None
88                         if mode == 'ENCRYPT':
89                                 swapptct = False
90                                 curfun = Crypto.encrypt
91                         elif mode == 'DECRYPT':
92                                 swapptct = True
93                                 curfun = Crypto.decrypt
94                         else:
95                                 raise RuntimeError('unknown mode: %r' % repr(mode))
96
97                         for bogusmode, lines in cryptodev.KATParser(fname,
98                             [ 'Count', 'Key', 'IV', 'CT', 'AAD', 'Tag', 'PT', ]):
99                                 for data in lines:
100                                         curcnt = int(data['Count'])
101                                         cipherkey = data['Key'].decode('hex')
102                                         iv = data['IV'].decode('hex')
103                                         aad = data['AAD'].decode('hex')
104                                         tag = data['Tag'].decode('hex')
105                                         if 'FAIL' not in data:
106                                                 pt = data['PT'].decode('hex')
107                                         ct = data['CT'].decode('hex')
108
109                                         if len(iv) != 12:
110                                                 # XXX - isn't supported
111                                                 continue
112
113                                         try:
114                                                 c = Crypto(cryptodev.CRYPTO_AES_NIST_GCM_16,
115                                                     cipherkey,
116                                                     mac=self._gmacsizes[len(cipherkey)],
117                                                     mackey=cipherkey, crid=crid)
118                                         except EnvironmentError, e:
119                                                 # Can't test algorithms the driver does not support.
120                                                 if e.errno != errno.EOPNOTSUPP:
121                                                         raise
122                                                 continue
123
124                                         if mode == 'ENCRYPT':
125                                                 try:
126                                                         rct, rtag = c.encrypt(pt, iv, aad)
127                                                 except EnvironmentError, e:
128                                                         # Can't test inputs the driver does not support.
129                                                         if e.errno != errno.EINVAL:
130                                                                 raise
131                                                         continue
132                                                 rtag = rtag[:len(tag)]
133                                                 data['rct'] = rct.encode('hex')
134                                                 data['rtag'] = rtag.encode('hex')
135                                                 self.assertEqual(rct, ct, repr(data))
136                                                 self.assertEqual(rtag, tag, repr(data))
137                                         else:
138                                                 if len(tag) != 16:
139                                                         continue
140                                                 args = (ct, iv, aad, tag)
141                                                 if 'FAIL' in data:
142                                                         self.assertRaises(IOError,
143                                                                 c.decrypt, *args)
144                                                 else:
145                                                         try:
146                                                                 rpt, rtag = c.decrypt(*args)
147                                                         except EnvironmentError, e:
148                                                                 # Can't test inputs the driver does not support.
149                                                                 if e.errno != errno.EINVAL:
150                                                                         raise
151                                                                 continue
152                                                         data['rpt'] = rpt.encode('hex')
153                                                         data['rtag'] = rtag.encode('hex')
154                                                         self.assertEqual(rpt, pt,
155                                                             repr(data))
156
157                 def runCBC(self, fname):
158                         curfun = None
159                         for mode, lines in cryptodev.KATParser(fname,
160                             [ 'COUNT', 'KEY', 'IV', 'PLAINTEXT', 'CIPHERTEXT', ]):
161                                 if mode == 'ENCRYPT':
162                                         swapptct = False
163                                         curfun = Crypto.encrypt
164                                 elif mode == 'DECRYPT':
165                                         swapptct = True
166                                         curfun = Crypto.decrypt
167                                 else:
168                                         raise RuntimeError('unknown mode: %r' % repr(mode))
169
170                                 for data in lines:
171                                         curcnt = int(data['COUNT'])
172                                         cipherkey = data['KEY'].decode('hex')
173                                         iv = data['IV'].decode('hex')
174                                         pt = data['PLAINTEXT'].decode('hex')
175                                         ct = data['CIPHERTEXT'].decode('hex')
176
177                                         if swapptct:
178                                                 pt, ct = ct, pt
179                                         # run the fun
180                                         c = Crypto(cryptodev.CRYPTO_AES_CBC, cipherkey, crid=crid)
181                                         r = curfun(c, pt, iv)
182                                         self.assertEqual(r, ct)
183
184                 def runXTS(self, fname, meth):
185                         curfun = None
186                         for mode, lines in cryptodev.KATParser(fname,
187                             [ 'COUNT', 'DataUnitLen', 'Key', 'DataUnitSeqNumber', 'PT',
188                             'CT' ]):
189                                 if mode == 'ENCRYPT':
190                                         swapptct = False
191                                         curfun = Crypto.encrypt
192                                 elif mode == 'DECRYPT':
193                                         swapptct = True
194                                         curfun = Crypto.decrypt
195                                 else:
196                                         raise RuntimeError('unknown mode: %r' % repr(mode))
197
198                                 for data in lines:
199                                         curcnt = int(data['COUNT'])
200                                         nbits = int(data['DataUnitLen'])
201                                         cipherkey = data['Key'].decode('hex')
202                                         iv = struct.pack('QQ', int(data['DataUnitSeqNumber']), 0)
203                                         pt = data['PT'].decode('hex')
204                                         ct = data['CT'].decode('hex')
205
206                                         if nbits % 128 != 0:
207                                                 # XXX - mark as skipped
208                                                 continue
209                                         if swapptct:
210                                                 pt, ct = ct, pt
211                                         # run the fun
212                                         try:
213                                                 c = Crypto(meth, cipherkey, crid=crid)
214                                                 r = curfun(c, pt, iv)
215                                         except EnvironmentError, e:
216                                                 # Can't test hashes the driver does not support.
217                                                 if e.errno != errno.EOPNOTSUPP:
218                                                         raise
219                                                 continue
220                                         self.assertEqual(r, ct)
221
222                 ###############
223                 ##### DES #####
224                 ###############
225                 @unittest.skipIf(cname not in desmodules, 'skipping DES on %s' % (cname))
226                 def test_tdes(self):
227                         for i in katg('KAT_TDES', 'TCBC[a-z]*.rsp'):
228                                 self.runTDES(i)
229
230                 def runTDES(self, fname):
231                         curfun = None
232                         for mode, lines in cryptodev.KATParser(fname,
233                             [ 'COUNT', 'KEYs', 'IV', 'PLAINTEXT', 'CIPHERTEXT', ]):
234                                 if mode == 'ENCRYPT':
235                                         swapptct = False
236                                         curfun = Crypto.encrypt
237                                 elif mode == 'DECRYPT':
238                                         swapptct = True
239                                         curfun = Crypto.decrypt
240                                 else:
241                                         raise RuntimeError('unknown mode: %r' % repr(mode))
242
243                                 for data in lines:
244                                         curcnt = int(data['COUNT'])
245                                         key = data['KEYs'] * 3
246                                         cipherkey = key.decode('hex')
247                                         iv = data['IV'].decode('hex')
248                                         pt = data['PLAINTEXT'].decode('hex')
249                                         ct = data['CIPHERTEXT'].decode('hex')
250
251                                         if swapptct:
252                                                 pt, ct = ct, pt
253                                         # run the fun
254                                         c = Crypto(cryptodev.CRYPTO_3DES_CBC, cipherkey, crid=crid)
255                                         r = curfun(c, pt, iv)
256                                         self.assertEqual(r, ct)
257
258                 ###############
259                 ##### SHA #####
260                 ###############
261                 @unittest.skipIf(cname not in shamodules, 'skipping SHA on %s' % str(cname))
262                 def test_sha(self):
263                         # SHA not available in software
264                         pass
265                         #for i in iglob('SHA1*'):
266                         #       self.runSHA(i)
267
268                 @unittest.skipIf(cname not in shamodules, 'skipping SHA-HMAC on %s' % str(cname))
269                 def test_sha1hmac(self):
270                         for i in katg('hmactestvectors', 'HMAC.rsp'):
271                                 self.runSHA1HMAC(i)
272
273                 def runSHA1HMAC(self, fname):
274                         for hashlength, lines in cryptodev.KATParser(fname,
275                             [ 'Count', 'Klen', 'Tlen', 'Key', 'Msg', 'Mac' ]):
276                                 # E.g., hashlength will be "L=20" (bytes)
277                                 hashlen = int(hashlength.split("=")[1])
278
279                                 blocksize = None
280                                 if hashlen == 20:
281                                         alg = cryptodev.CRYPTO_SHA1_HMAC
282                                         blocksize = 64
283                                 elif hashlen == 28:
284                                         alg = cryptodev.CRYPTO_SHA2_224_HMAC
285                                         blocksize = 64
286                                 elif hashlen == 32:
287                                         alg = cryptodev.CRYPTO_SHA2_256_HMAC
288                                         blocksize = 64
289                                 elif hashlen == 48:
290                                         alg = cryptodev.CRYPTO_SHA2_384_HMAC
291                                         blocksize = 128
292                                 elif hashlen == 64:
293                                         alg = cryptodev.CRYPTO_SHA2_512_HMAC
294                                         blocksize = 128
295                                 else:
296                                         # Skip unsupported hashes
297                                         # Slurp remaining input in section
298                                         for data in lines:
299                                                 continue
300                                         continue
301
302                                 for data in lines:
303                                         key = data['Key'].decode('hex')
304                                         msg = data['Msg'].decode('hex')
305                                         mac = data['Mac'].decode('hex')
306                                         tlen = int(data['Tlen'])
307
308                                         if len(key) > blocksize:
309                                                 continue
310
311                                         try:
312                                                 c = Crypto(mac=alg, mackey=key,
313                                                     crid=crid)
314                                         except EnvironmentError, e:
315                                                 # Can't test hashes the driver does not support.
316                                                 if e.errno != errno.EOPNOTSUPP:
317                                                         raise
318                                                 continue
319
320                                         _, r = c.encrypt(msg, iv="")
321
322                                         # A limitation in cryptodev.py means we
323                                         # can only store MACs up to 16 bytes.
324                                         # That's good enough to validate the
325                                         # correct behavior, more or less.
326                                         maclen = min(tlen, 16)
327                                         self.assertEqual(r[:maclen], mac[:maclen], "Actual: " + \
328                                             repr(r[:maclen].encode("hex")) + " Expected: " + repr(data))
329
330         return GendCryptoTestCase
331
332 cryptosoft = GenTestCase('cryptosoft0')
333 aesni = GenTestCase('aesni0')
334 ccr = GenTestCase('ccr0')
335 ccp = GenTestCase('ccp0')
336
337 if __name__ == '__main__':
338         unittest.main()