Debian Codegraph @

lib/Crypto/Cipher/_mode_gcm.py

raw symbols SCIP
1 # ===================================================================
2 #
3 # Copyright (c) 2014, Legrandin <[email protected]>
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions
8 # are met:
9 #
10 # 1. Redistributions of source code must retain the above copyright
11 # notice, this list of conditions and the following disclaimer.
12 # 2. Redistributions in binary form must reproduce the above copyright
13 # notice, this list of conditions and the following disclaimer in
14 # the documentation and/or other materials provided with the
15 # distribution.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20 # FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
21 # COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22 # INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23 # BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24 # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25 # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26 # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 # POSSIBILITY OF SUCH DAMAGE.
29 # ===================================================================
30
31 """
32 Galois/Counter Mode (GCM).
33 """
34
35 __all__ = ['GcmMode']
36
37 from binascii import unhexlify
38
39 from Crypto.Util.py3compat import bord, _copy_bytes
40
41 from Crypto.Util._raw_api import is_buffer
42
43 from Crypto.Util.number import long_to_bytes, bytes_to_long
44 from Crypto.Hash import BLAKE2s
45 from Crypto.Random import get_random_bytes
46
47 from Crypto.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
48 create_string_buffer, get_raw_buffer,
49 SmartPointer, c_size_t, c_uint8_ptr)
50
51 from Crypto.Util import _cpu_features
52
53
54 # C API by module implementing GHASH
55 _ghash_api_template = """
56 int ghash_%imp%(uint8_t y_out[16],
57 const uint8_t block_data[],
58 size_t len,
59 const uint8_t y_in[16],
60 const void *exp_key);
61 int ghash_expand_%imp%(const uint8_t h[16],
62 void **ghash_tables);
63 int ghash_destroy_%imp%(void *ghash_tables);
64 """
65
66 def _build_impl(lib, postfix):
67 from collections import namedtuple
68
69 funcs = ( "ghash", "ghash_expand", "ghash_destroy" )
70 GHASH_Imp = namedtuple('_GHash_Imp', funcs)
71 try:
72 imp_funcs = [ getattr(lib, x + "_" + postfix) for x in funcs ]
73 except AttributeError: # Make sphinx stop complaining with its mocklib
74 imp_funcs = [ None ] * 3
75 params = dict(zip(funcs, imp_funcs))
76 return GHASH_Imp(**params)
77
78
79 def _get_ghash_portable():
80 api = _ghash_api_template.replace("%imp%", "portable")
81 lib = load_pycryptodome_raw_lib("Crypto.Hash._ghash_portable", api)
82 result = _build_impl(lib, "portable")
83 return result
84 _ghash_portable = _get_ghash_portable()
85
86
87 def _get_ghash_clmul():
88 """Return None if CLMUL implementation is not available"""
89
90 if not _cpu_features.have_clmul():
91 return None
92 try:
93 api = _ghash_api_template.replace("%imp%", "clmul")
94 lib = load_pycryptodome_raw_lib("Crypto.Hash._ghash_clmul", api)
95 result = _build_impl(lib, "clmul")
96 except OSError:
97 result = None
98 return result
99 _ghash_clmul = _get_ghash_clmul()
100
101
102 class _GHASH(object):
103 """GHASH function defined in NIST SP 800-38D, Algorithm 2.
104
105 If X_1, X_2, .. X_m are the blocks of input data, the function
106 computes:
107
108 X_1*H^{m} + X_2*H^{m-1} + ... + X_m*H
109
110 in the Galois field GF(2^256) using the reducing polynomial
111 (x^128 + x^7 + x^2 + x + 1).
112 """
113
114 def __init__(self, subkey, ghash_c):
115 assert len(subkey) == 16
116
117 self.ghash_c = ghash_c
118
119 self._exp_key = VoidPointer()
120 result = ghash_c.ghash_expand(c_uint8_ptr(subkey),
121 self._exp_key.address_of())
122 if result:
123 raise ValueError("Error %d while expanding the GHASH key" % result)
124
125 self._exp_key = SmartPointer(self._exp_key.get(),
126 ghash_c.ghash_destroy)
127
128 # create_string_buffer always returns a string of zeroes
129 self._last_y = create_string_buffer(16)
130
131 def update(self, block_data):
132 assert len(block_data) % 16 == 0
133
134 result = self.ghash_c.ghash(self._last_y,
135 c_uint8_ptr(block_data),
136 c_size_t(len(block_data)),
137 self._last_y,
138 self._exp_key.get())
139 if result:
140 raise ValueError("Error %d while updating GHASH" % result)
141
142 return self
143
144 def digest(self):
145 return get_raw_buffer(self._last_y)
146
147
148 def enum(**enums):
149 return type('Enum', (), enums)
150
151
152 MacStatus = enum(PROCESSING_AUTH_DATA=1, PROCESSING_CIPHERTEXT=2)
153
154
155 class GcmMode(object):
156 """Galois Counter Mode (GCM).
157
158 This is an Authenticated Encryption with Associated Data (`AEAD`_) mode.
159 It provides both confidentiality and authenticity.
160
161 The header of the message may be left in the clear, if needed, and it will
162 still be subject to authentication. The decryption step tells the receiver
163 if the message comes from a source that really knowns the secret key.
164 Additionally, decryption detects if any part of the message - including the
165 header - has been modified or corrupted.
166
167 This mode requires a *nonce*.
168
169 This mode is only available for ciphers that operate on 128 bits blocks
170 (e.g. AES but not TDES).
171
172 See `NIST SP800-38D`_.
173
174 .. _`NIST SP800-38D`: http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
175 .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html
176
177 :undocumented: __init__
178 """
179
180 def __init__(self, factory, key, nonce, mac_len, cipher_params, ghash_c):
181
182 self.block_size = factory.block_size
183 if self.block_size != 16:
184 raise ValueError("GCM mode is only available for ciphers"
185 " that operate on 128 bits blocks")
186
187 if len(nonce) == 0:
188 raise ValueError("Nonce cannot be empty")
189
190 if not is_buffer(nonce):
191 raise TypeError("Nonce must be bytes, bytearray or memoryview")
192
193 # See NIST SP 800 38D, 5.2.1.1
194 if len(nonce) > 2**64 - 1:
195 raise ValueError("Nonce exceeds maximum length")
196
197
198 self.nonce = _copy_bytes(None, None, nonce)
199 """Nonce"""
200
201 self._factory = factory
202 self._key = _copy_bytes(None, None, key)
203 self._tag = None # Cache for MAC tag
204
205 self._mac_len = mac_len
206 if not (4 <= mac_len <= 16):
207 raise ValueError("Parameter 'mac_len' must be in the range 4..16")
208
209 # Allowed transitions after initialization
210 self._next = ["update", "encrypt", "decrypt",
211 "digest", "verify"]
212
213 self._no_more_assoc_data = False
214
215 # Length of associated data
216 self._auth_len = 0
217
218 # Length of the ciphertext or plaintext
219 self._msg_len = 0
220
221 # Step 1 in SP800-38D, Algorithm 4 (encryption) - Compute H
222 # See also Algorithm 5 (decryption)
223 hash_subkey = factory.new(key,
224 self._factory.MODE_ECB,
225 **cipher_params
226 ).encrypt(b'\x00' * 16)
227
228 # Step 2 - Compute J0
229 if len(self.nonce) == 12:
230 j0 = self.nonce + b"\x00\x00\x00\x01"
231 else:
232 fill = (16 - (len(self.nonce) % 16)) % 16 + 8
233 ghash_in = (self.nonce +
234 b'\x00' * fill +
235 long_to_bytes(8 * len(self.nonce), 8))
236 j0 = _GHASH(hash_subkey, ghash_c).update(ghash_in).digest()
237
238 # Step 3 - Prepare GCTR cipher for encryption/decryption
239 nonce_ctr = j0[:12]
240 iv_ctr = (bytes_to_long(j0) + 1) & 0xFFFFFFFF
241 self._cipher = factory.new(key,
242 self._factory.MODE_CTR,
243 initial_value=iv_ctr,
244 nonce=nonce_ctr,
245 **cipher_params)
246
247 # Step 5 - Bootstrat GHASH
248 self._signer = _GHASH(hash_subkey, ghash_c)
249
250 # Step 6 - Prepare GCTR cipher for GMAC
251 self._tag_cipher = factory.new(key,
252 self._factory.MODE_CTR,
253 initial_value=j0,
254 nonce=b"",
255 **cipher_params)
256
257 # Cache for data to authenticate
258 self._cache = b""
259
260 self._status = MacStatus.PROCESSING_AUTH_DATA
261
262 def update(self, assoc_data):
263 """Protect associated data
264
265 If there is any associated data, the caller has to invoke
266 this function one or more times, before using
267 ``decrypt`` or ``encrypt``.
268
269 By *associated data* it is meant any data (e.g. packet headers) that
270 will not be encrypted and will be transmitted in the clear.
271 However, the receiver is still able to detect any modification to it.
272 In GCM, the *associated data* is also called
273 *additional authenticated data* (AAD).
274
275 If there is no associated data, this method must not be called.
276
277 The caller may split associated data in segments of any size, and
278 invoke this method multiple times, each time with the next segment.
279
280 :Parameters:
281 assoc_data : bytes/bytearray/memoryview
282 A piece of associated data. There are no restrictions on its size.
283 """
284
285 if "update" not in self._next:
286 raise TypeError("update() can only be called"
287 " immediately after initialization")
288
289 self._next = ["update", "encrypt", "decrypt",
290 "digest", "verify"]
291
292 self._update(assoc_data)
293 self._auth_len += len(assoc_data)
294
295 # See NIST SP 800 38D, 5.2.1.1
296 if self._auth_len > 2**64 - 1:
297 raise ValueError("Additional Authenticated Data exceeds maximum length")
298
299 return self
300
301 def _update(self, data):
302 assert(len(self._cache) < 16)
303
304 if len(self._cache) > 0:
305 filler = min(16 - len(self._cache), len(data))
306 self._cache += _copy_bytes(None, filler, data)
307 data = data[filler:]
308
309 if len(self._cache) < 16:
310 return
311
312 # The cache is exactly one block
313 self._signer.update(self._cache)
314 self._cache = b""
315
316 update_len = len(data) // 16 * 16
317 self._cache = _copy_bytes(update_len, None, data)
318 if update_len > 0:
319 self._signer.update(data[:update_len])
320
321 def _pad_cache_and_update(self):
322 assert(len(self._cache) < 16)
323
324 # The authenticated data A is concatenated to the minimum
325 # number of zero bytes (possibly none) such that the
326 # - ciphertext C is aligned to the 16 byte boundary.
327 # See step 5 in section 7.1
328 # - ciphertext C is aligned to the 16 byte boundary.
329 # See step 6 in section 7.2
330 len_cache = len(self._cache)
331 if len_cache > 0:
332 self._update(b'\x00' * (16 - len_cache))
333
334 def encrypt(self, plaintext, output=None):
335 """Encrypt data with the key and the parameters set at initialization.
336
337 A cipher object is stateful: once you have encrypted a message
338 you cannot encrypt (or decrypt) another message using the same
339 object.
340
341 The data to encrypt can be broken up in two or
342 more pieces and `encrypt` can be called multiple times.
343
344 That is, the statement:
345
346 >>> c.encrypt(a) + c.encrypt(b)
347
348 is equivalent to:
349
350 >>> c.encrypt(a+b)
351
352 This function does not add any padding to the plaintext.
353
354 :Parameters:
355 plaintext : bytes/bytearray/memoryview
356 The piece of data to encrypt.
357 It can be of any length.
358 :Keywords:
359 output : bytearray/memoryview
360 The location where the ciphertext must be written to.
361 If ``None``, the ciphertext is returned.
362 :Return:
363 If ``output`` is ``None``, the ciphertext as ``bytes``.
364 Otherwise, ``None``.
365 """
366
367 if "encrypt" not in self._next:
368 raise TypeError("encrypt() can only be called after"
369 " initialization or an update()")
370 self._next = ["encrypt", "digest"]
371
372 ciphertext = self._cipher.encrypt(plaintext, output=output)
373
374 if self._status == MacStatus.PROCESSING_AUTH_DATA:
375 self._pad_cache_and_update()
376 self._status = MacStatus.PROCESSING_CIPHERTEXT
377
378 self._update(ciphertext if output is None else output)
379 self._msg_len += len(plaintext)
380
381 # See NIST SP 800 38D, 5.2.1.1
382 if self._msg_len > 2**39 - 256:
383 raise ValueError("Plaintext exceeds maximum length")
384
385 return ciphertext
386
387 def decrypt(self, ciphertext, output=None):
388 """Decrypt data with the key and the parameters set at initialization.
389
390 A cipher object is stateful: once you have decrypted a message
391 you cannot decrypt (or encrypt) another message with the same
392 object.
393
394 The data to decrypt can be broken up in two or
395 more pieces and `decrypt` can be called multiple times.
396
397 That is, the statement:
398
399 >>> c.decrypt(a) + c.decrypt(b)
400
401 is equivalent to:
402
403 >>> c.decrypt(a+b)
404
405 This function does not remove any padding from the plaintext.
406
407 :Parameters:
408 ciphertext : bytes/bytearray/memoryview
409 The piece of data to decrypt.
410 It can be of any length.
411 :Keywords:
412 output : bytearray/memoryview
413 The location where the plaintext must be written to.
414 If ``None``, the plaintext is returned.
415 :Return:
416 If ``output`` is ``None``, the plaintext as ``bytes``.
417 Otherwise, ``None``.
418 """
419
420 if "decrypt" not in self._next:
421 raise TypeError("decrypt() can only be called"
422 " after initialization or an update()")
423 self._next = ["decrypt", "verify"]
424
425 if self._status == MacStatus.PROCESSING_AUTH_DATA:
426 self._pad_cache_and_update()
427 self._status = MacStatus.PROCESSING_CIPHERTEXT
428
429 self._update(ciphertext)
430 self._msg_len += len(ciphertext)
431
432 return self._cipher.decrypt(ciphertext, output=output)
433
434 def digest(self):
435 """Compute the *binary* MAC tag in an AEAD mode.
436
437 The caller invokes this function at the very end.
438
439 This method returns the MAC that shall be sent to the receiver,
440 together with the ciphertext.
441
442 :Return: the MAC, as a byte string.
443 """
444
445 if "digest" not in self._next:
446 raise TypeError("digest() cannot be called when decrypting"
447 " or validating a message")
448 self._next = ["digest"]
449
450 return self._compute_mac()
451
452 def _compute_mac(self):
453 """Compute MAC without any FSM checks."""
454
455 if self._tag:
456 return self._tag
457
458 # Step 5 in NIST SP 800-38D, Algorithm 4 - Compute S
459 self._pad_cache_and_update()
460 self._update(long_to_bytes(8 * self._auth_len, 8))
461 self._update(long_to_bytes(8 * self._msg_len, 8))
462 s_tag = self._signer.digest()
463
464 # Step 6 - Compute T
465 self._tag = self._tag_cipher.encrypt(s_tag)[:self._mac_len]
466
467 return self._tag
468
469 def hexdigest(self):
470 """Compute the *printable* MAC tag.
471
472 This method is like `digest`.
473
474 :Return: the MAC, as a hexadecimal string.
475 """
476 return "".join(["%02x" % bord(x) for x in self.digest()])
477
478 def verify(self, received_mac_tag):
479 """Validate the *binary* MAC tag.
480
481 The caller invokes this function at the very end.
482
483 This method checks if the decrypted message is indeed valid
484 (that is, if the key is correct) and it has not been
485 tampered with while in transit.
486
487 :Parameters:
488 received_mac_tag : bytes/bytearray/memoryview
489 This is the *binary* MAC, as received from the sender.
490 :Raises ValueError:
491 if the MAC does not match. The message has been tampered with
492 or the key is incorrect.
493 """
494
495 if "verify" not in self._next:
496 raise TypeError("verify() cannot be called"
497 " when encrypting a message")
498 self._next = ["verify"]
499
500 secret = get_random_bytes(16)
501
502 mac1 = BLAKE2s.new(digest_bits=160, key=secret,
503 data=self._compute_mac())
504 mac2 = BLAKE2s.new(digest_bits=160, key=secret,
505 data=received_mac_tag)
506
507 if mac1.digest() != mac2.digest():
508 raise ValueError("MAC check failed")
509
510 def hexverify(self, hex_mac_tag):
511 """Validate the *printable* MAC tag.
512
513 This method is like `verify`.
514
515 :Parameters:
516 hex_mac_tag : string
517 This is the *printable* MAC, as received from the sender.
518 :Raises ValueError:
519 if the MAC does not match. The message has been tampered with
520 or the key is incorrect.
521 """
522
523 self.verify(unhexlify(hex_mac_tag))
524
525 def encrypt_and_digest(self, plaintext, output=None):
526 """Perform encrypt() and digest() in one step.
527
528 :Parameters:
529 plaintext : bytes/bytearray/memoryview
530 The piece of data to encrypt.
531 :Keywords:
532 output : bytearray/memoryview
533 The location where the ciphertext must be written to.
534 If ``None``, the ciphertext is returned.
535 :Return:
536 a tuple with two items:
537
538 - the ciphertext, as ``bytes``
539 - the MAC tag, as ``bytes``
540
541 The first item becomes ``None`` when the ``output`` parameter
542 specified a location for the result.
543 """
544
545 return self.encrypt(plaintext, output=output), self.digest()
546
547 def decrypt_and_verify(self, ciphertext, received_mac_tag, output=None):
548 """Perform decrypt() and verify() in one step.
549
550 :Parameters:
551 ciphertext : bytes/bytearray/memoryview
552 The piece of data to decrypt.
553 received_mac_tag : byte string
554 This is the *binary* MAC, as received from the sender.
555 :Keywords:
556 output : bytearray/memoryview
557 The location where the plaintext must be written to.
558 If ``None``, the plaintext is returned.
559 :Return: the plaintext as ``bytes`` or ``None`` when the ``output``
560 parameter specified a location for the result.
561 :Raises ValueError:
562 if the MAC does not match. The message has been tampered with
563 or the key is incorrect.
564 """
565
566 plaintext = self.decrypt(ciphertext, output=output)
567 self.verify(received_mac_tag)
568 return plaintext
569
570
571 def _create_gcm_cipher(factory, **kwargs):
572 """Create a new block cipher, configured in Galois Counter Mode (GCM).
573
574 :Parameters:
575 factory : module
576 A block cipher module, taken from `Crypto.Cipher`.
577 The cipher must have block length of 16 bytes.
578 GCM has been only defined for `Crypto.Cipher.AES`.
579
580 :Keywords:
581 key : bytes/bytearray/memoryview
582 The secret key to use in the symmetric cipher.
583 It must be 16 (e.g. *AES-128*), 24 (e.g. *AES-192*)
584 or 32 (e.g. *AES-256*) bytes long.
585
586 nonce : bytes/bytearray/memoryview
587 A value that must never be reused for any other encryption.
588
589 There are no restrictions on its length,
590 but it is recommended to use at least 16 bytes.
591
592 The nonce shall never repeat for two
593 different messages encrypted with the same key,
594 but it does not need to be random.
595
596 If not provided, a 16 byte nonce will be randomly created.
597
598 mac_len : integer
599 Length of the MAC, in bytes.
600 It must be no larger than 16 bytes (which is the default).
601 """
602
603 try:
604 key = kwargs.pop("key")
605 except KeyError as e:
606 raise TypeError("Missing parameter:" + str(e))
607
608 nonce = kwargs.pop("nonce", None)
609 if nonce is None:
610 nonce = get_random_bytes(16)
611 mac_len = kwargs.pop("mac_len", 16)
612
613 # Not documented - only used for testing
614 use_clmul = kwargs.pop("use_clmul", True)
615 if use_clmul and _ghash_clmul:
616 ghash_c = _ghash_clmul
617 else:
618 ghash_c = _ghash_portable
619
620 return GcmMode(factory, key, nonce, mac_len, kwargs, ghash_c)