]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - tests/sys/opencrypto/cryptotest.py
cryptotest.py: Actually use NIST-KAT HMAC test vectors and test the right hashes
[FreeBSD/FreeBSD.git] / tests / sys / opencrypto / cryptotest.py
1 #!/usr/bin/env python
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 import cryptodev
33 import itertools
34 import os
35 import struct
36 import unittest
37 from cryptodev import *
38 from glob import iglob
39
40 katdir = '/usr/local/share/nist-kat'
41
42 def katg(base, glob):
43         assert os.path.exists(os.path.join(katdir, base)), "Please 'pkg install nist-kat'"
44         return iglob(os.path.join(katdir, base, glob))
45
46 aesmodules = [ 'cryptosoft0', 'aesni0', 'ccr0' ]
47 desmodules = [ 'cryptosoft0', ]
48 shamodules = [ 'cryptosoft0', 'ccr0' ]
49
50 def GenTestCase(cname):
51         try:
52                 crid = cryptodev.Crypto.findcrid(cname)
53         except IOError:
54                 return None
55
56         class GendCryptoTestCase(unittest.TestCase):
57                 ###############
58                 ##### AES #####
59                 ###############
60                 @unittest.skipIf(cname not in aesmodules, 'skipping AES on %s' % `cname`)
61                 def test_xts(self):
62                         for i in katg('XTSTestVectors/format tweak value input - data unit seq no', '*.rsp'):
63                                 self.runXTS(i, cryptodev.CRYPTO_AES_XTS)
64
65                 @unittest.skipIf(cname not in aesmodules, 'skipping AES on %s' % `cname`)
66                 def test_cbc(self):
67                         for i in katg('KAT_AES', 'CBC[GKV]*.rsp'):
68                                 self.runCBC(i)
69
70                 @unittest.skipIf(cname not in aesmodules, 'skipping AES on %s' % `cname`)
71                 def test_gcm(self):
72                         for i in katg('gcmtestvectors', 'gcmEncrypt*'):
73                                 self.runGCM(i, 'ENCRYPT')
74
75                         for i in katg('gcmtestvectors', 'gcmDecrypt*'):
76                                 self.runGCM(i, 'DECRYPT')
77
78                 _gmacsizes = { 32: cryptodev.CRYPTO_AES_256_NIST_GMAC,
79                         24: cryptodev.CRYPTO_AES_192_NIST_GMAC,
80                         16: cryptodev.CRYPTO_AES_128_NIST_GMAC,
81                 }
82                 def runGCM(self, fname, mode):
83                         curfun = None
84                         if mode == 'ENCRYPT':
85                                 swapptct = False
86                                 curfun = Crypto.encrypt
87                         elif mode == 'DECRYPT':
88                                 swapptct = True
89                                 curfun = Crypto.decrypt
90                         else:
91                                 raise RuntimeError('unknown mode: %s' % `mode`)
92
93                         for bogusmode, lines in cryptodev.KATParser(fname,
94                             [ 'Count', 'Key', 'IV', 'CT', 'AAD', 'Tag', 'PT', ]):
95                                 for data in lines:
96                                         curcnt = int(data['Count'])
97                                         cipherkey = data['Key'].decode('hex')
98                                         iv = data['IV'].decode('hex')
99                                         aad = data['AAD'].decode('hex')
100                                         tag = data['Tag'].decode('hex')
101                                         if 'FAIL' not in data:
102                                                 pt = data['PT'].decode('hex')
103                                         ct = data['CT'].decode('hex')
104
105                                         if len(iv) != 12:
106                                                 # XXX - isn't supported
107                                                 continue
108
109                                         c = Crypto(cryptodev.CRYPTO_AES_NIST_GCM_16,
110                                             cipherkey,
111                                             mac=self._gmacsizes[len(cipherkey)],
112                                             mackey=cipherkey, crid=crid)
113
114                                         if mode == 'ENCRYPT':
115                                                 rct, rtag = c.encrypt(pt, iv, aad)
116                                                 rtag = rtag[:len(tag)]
117                                                 data['rct'] = rct.encode('hex')
118                                                 data['rtag'] = rtag.encode('hex')
119                                                 self.assertEqual(rct, ct, `data`)
120                                                 self.assertEqual(rtag, tag, `data`)
121                                         else:
122                                                 if len(tag) != 16:
123                                                         continue
124                                                 args = (ct, iv, aad, tag)
125                                                 if 'FAIL' in data:
126                                                         self.assertRaises(IOError,
127                                                                 c.decrypt, *args)
128                                                 else:
129                                                         rpt, rtag = c.decrypt(*args)
130                                                         data['rpt'] = rpt.encode('hex')
131                                                         data['rtag'] = rtag.encode('hex')
132                                                         self.assertEqual(rpt, pt,
133                                                             `data`)
134
135                 def runCBC(self, fname):
136                         curfun = None
137                         for mode, lines in cryptodev.KATParser(fname,
138                             [ 'COUNT', 'KEY', 'IV', 'PLAINTEXT', 'CIPHERTEXT', ]):
139                                 if mode == 'ENCRYPT':
140                                         swapptct = False
141                                         curfun = Crypto.encrypt
142                                 elif mode == 'DECRYPT':
143                                         swapptct = True
144                                         curfun = Crypto.decrypt
145                                 else:
146                                         raise RuntimeError('unknown mode: %s' % `mode`)
147
148                                 for data in lines:
149                                         curcnt = int(data['COUNT'])
150                                         cipherkey = data['KEY'].decode('hex')
151                                         iv = data['IV'].decode('hex')
152                                         pt = data['PLAINTEXT'].decode('hex')
153                                         ct = data['CIPHERTEXT'].decode('hex')
154
155                                         if swapptct:
156                                                 pt, ct = ct, pt
157                                         # run the fun
158                                         c = Crypto(cryptodev.CRYPTO_AES_CBC, cipherkey, crid=crid)
159                                         r = curfun(c, pt, iv)
160                                         self.assertEqual(r, ct)
161
162                 def runXTS(self, fname, meth):
163                         curfun = None
164                         for mode, lines in cryptodev.KATParser(fname,
165                             [ 'COUNT', 'DataUnitLen', 'Key', 'DataUnitSeqNumber', 'PT',
166                             'CT' ]):
167                                 if mode == 'ENCRYPT':
168                                         swapptct = False
169                                         curfun = Crypto.encrypt
170                                 elif mode == 'DECRYPT':
171                                         swapptct = True
172                                         curfun = Crypto.decrypt
173                                 else:
174                                         raise RuntimeError('unknown mode: %s' % `mode`)
175
176                                 for data in lines:
177                                         curcnt = int(data['COUNT'])
178                                         nbits = int(data['DataUnitLen'])
179                                         cipherkey = data['Key'].decode('hex')
180                                         iv = struct.pack('QQ', int(data['DataUnitSeqNumber']), 0)
181                                         pt = data['PT'].decode('hex')
182                                         ct = data['CT'].decode('hex')
183
184                                         if nbits % 128 != 0:
185                                                 # XXX - mark as skipped
186                                                 continue
187                                         if swapptct:
188                                                 pt, ct = ct, pt
189                                         # run the fun
190                                         c = Crypto(meth, cipherkey, crid=crid)
191                                         r = curfun(c, pt, iv)
192                                         self.assertEqual(r, ct)
193
194                 ###############
195                 ##### DES #####
196                 ###############
197                 @unittest.skipIf(cname not in desmodules, 'skipping DES on %s' % `cname`)
198                 def test_tdes(self):
199                         for i in katg('KAT_TDES', 'TCBC[a-z]*.rsp'):
200                                 self.runTDES(i)
201
202                 def runTDES(self, fname):
203                         curfun = None
204                         for mode, lines in cryptodev.KATParser(fname,
205                             [ 'COUNT', 'KEYs', 'IV', 'PLAINTEXT', 'CIPHERTEXT', ]):
206                                 if mode == 'ENCRYPT':
207                                         swapptct = False
208                                         curfun = Crypto.encrypt
209                                 elif mode == 'DECRYPT':
210                                         swapptct = True
211                                         curfun = Crypto.decrypt
212                                 else:
213                                         raise RuntimeError('unknown mode: %s' % `mode`)
214
215                                 for data in lines:
216                                         curcnt = int(data['COUNT'])
217                                         key = data['KEYs'] * 3
218                                         cipherkey = key.decode('hex')
219                                         iv = data['IV'].decode('hex')
220                                         pt = data['PLAINTEXT'].decode('hex')
221                                         ct = data['CIPHERTEXT'].decode('hex')
222
223                                         if swapptct:
224                                                 pt, ct = ct, pt
225                                         # run the fun
226                                         c = Crypto(cryptodev.CRYPTO_3DES_CBC, cipherkey, crid=crid)
227                                         r = curfun(c, pt, iv)
228                                         self.assertEqual(r, ct)
229
230                 ###############
231                 ##### SHA #####
232                 ###############
233                 @unittest.skipIf(cname not in shamodules, 'skipping SHA on %s' % `cname`)
234                 def test_sha(self):
235                         # SHA not available in software
236                         pass
237                         #for i in iglob('SHA1*'):
238                         #       self.runSHA(i)
239
240                 def test_sha1hmac(self):
241                         for i in katg('hmactestvectors', 'HMAC.rsp'):
242                                 self.runSHA1HMAC(i)
243
244                 def runSHA1HMAC(self, fname):
245                         for hashlength, lines in cryptodev.KATParser(fname,
246                             [ 'Count', 'Klen', 'Tlen', 'Key', 'Msg', 'Mac' ]):
247                                 # E.g., hashlength will be "L=20" (bytes)
248                                 hashlen = int(hashlength.split("=")[1])
249
250                                 blocksize = None
251                                 if hashlen == 20:
252                                     alg = cryptodev.CRYPTO_SHA1_HMAC
253                                     blocksize = 64
254                                 elif hashlen == 28:
255                                     # Cryptodev doesn't support SHA-224
256                                     # Slurp remaining input in section
257                                     for data in lines:
258                                         continue
259                                     continue
260                                 elif hashlen == 32:
261                                     alg = cryptodev.CRYPTO_SHA2_256_HMAC
262                                     blocksize = 64
263                                 elif hashlen == 48:
264                                     alg = cryptodev.CRYPTO_SHA2_384_HMAC
265                                     blocksize = 128
266                                 elif hashlen == 64:
267                                     alg = cryptodev.CRYPTO_SHA2_512_HMAC
268                                     blocksize = 128
269                                 else:
270                                     # Skip unsupported hashes
271                                     # Slurp remaining input in section
272                                     for data in lines:
273                                         continue
274                                     continue
275
276                                 for data in lines:
277                                         key = data['Key'].decode('hex')
278                                         msg = data['Msg'].decode('hex')
279                                         mac = data['Mac'].decode('hex')
280                                         tlen = int(data['Tlen'])
281
282                                         if len(key) > blocksize:
283                                                 continue
284
285                                         c = Crypto(mac=alg, mackey=key,
286                                             crid=crid)
287
288                                         _, r = c.encrypt(msg, iv="")
289
290                                         # A limitation in cryptodev.py means we
291                                         # can only store MACs up to 16 bytes.
292                                         # That's good enough to validate the
293                                         # correct behavior, more or less.
294                                         maclen = min(tlen, 16)
295                                         self.assertEqual(r[:maclen], mac[:maclen], "Actual: " + \
296                                             repr(r[:maclen].encode("hex")) + " Expected: " + repr(data))
297
298         return GendCryptoTestCase
299
300 cryptosoft = GenTestCase('cryptosoft0')
301 aesni = GenTestCase('aesni0')
302 ccr = GenTestCase('ccr0')
303
304 if __name__ == '__main__':
305         unittest.main()