Debian Codegraph @

lib/Crypto/Cipher/_mode_ccm.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 Counter with CBC-MAC (CCM) mode.
33 """
34
35 __all__ = ['CcmMode']
36
37 import struct
38 from binascii import unhexlify
39
40 from Crypto.Util.py3compat import (byte_string, bord,
41 _copy_bytes)
42 from Crypto.Util._raw_api import is_writeable_buffer
43
44 from Crypto.Util.strxor import strxor
45 from Crypto.Util.number import long_to_bytes
46
47 from Crypto.Hash import BLAKE2s
48 from Crypto.Random import get_random_bytes
49
50
51 def enum(**enums):
52 return type('Enum', (), enums)
53
54 MacStatus = enum(NOT_STARTED=0, PROCESSING_AUTH_DATA=1, PROCESSING_PLAINTEXT=2)
55
56
57 class CcmMode(object):
58 """Counter with CBC-MAC (CCM).
59
60 This is an Authenticated Encryption with Associated Data (`AEAD`_) mode.
61 It provides both confidentiality and authenticity.
62
63 The header of the message may be left in the clear, if needed, and it will
64 still be subject to authentication. The decryption step tells the receiver
65 if the message comes from a source that really knowns the secret key.
66 Additionally, decryption detects if any part of the message - including the
67 header - has been modified or corrupted.
68
69 This mode requires a nonce. The nonce shall never repeat for two
70 different messages encrypted with the same key, but it does not need
71 to be random.
72 Note that there is a trade-off between the size of the nonce and the
73 maximum size of a single message you can encrypt.
74
75 It is important to use a large nonce if the key is reused across several
76 messages and the nonce is chosen randomly.
77
78 It is acceptable to us a short nonce if the key is only used a few times or
79 if the nonce is taken from a counter.
80
81 The following table shows the trade-off when the nonce is chosen at
82 random. The column on the left shows how many messages it takes
83 for the keystream to repeat **on average**. In practice, you will want to
84 stop using the key way before that.
85
86 +--------------------+---------------+-------------------+
87 | Avg. # of messages | nonce | Max. message |
88 | before keystream | size | size |
89 | repeats | (bytes) | (bytes) |
90 +====================+===============+===================+
91 | 2^52 | 13 | 64K |
92 +--------------------+---------------+-------------------+
93 | 2^48 | 12 | 16M |
94 +--------------------+---------------+-------------------+
95 | 2^44 | 11 | 4G |
96 +--------------------+---------------+-------------------+
97 | 2^40 | 10 | 1T |
98 +--------------------+---------------+-------------------+
99 | 2^36 | 9 | 64P |
100 +--------------------+---------------+-------------------+
101 | 2^32 | 8 | 16E |
102 +--------------------+---------------+-------------------+
103
104 This mode is only available for ciphers that operate on 128 bits blocks
105 (e.g. AES but not TDES).
106
107 See `NIST SP800-38C`_ or RFC3610_.
108
109 .. _`NIST SP800-38C`: http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C.pdf
110 .. _RFC3610: https://tools.ietf.org/html/rfc3610
111 .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html
112
113 :undocumented: __init__
114 """
115
116 def __init__(self, factory, key, nonce, mac_len, msg_len, assoc_len,
117 cipher_params):
118
119 self.block_size = factory.block_size
120 """The block size of the underlying cipher, in bytes."""
121
122 self.nonce = _copy_bytes(None, None, nonce)
123 """The nonce used for this cipher instance"""
124
125 self._factory = factory
126 self._key = _copy_bytes(None, None, key)
127 self._mac_len = mac_len
128 self._msg_len = msg_len
129 self._assoc_len = assoc_len
130 self._cipher_params = cipher_params
131
132 self._mac_tag = None # Cache for MAC tag
133
134 if self.block_size != 16:
135 raise ValueError("CCM mode is only available for ciphers"
136 " that operate on 128 bits blocks")
137
138 # MAC tag length (Tlen)
139 if mac_len not in (4, 6, 8, 10, 12, 14, 16):
140 raise ValueError("Parameter 'mac_len' must be even"
141 " and in the range 4..16 (not %d)" % mac_len)
142
143 # Nonce value
144 if not (nonce and 7 <= len(nonce) <= 13):
145 raise ValueError("Length of parameter 'nonce' must be"
146 " in the range 7..13 bytes")
147
148 # Create MAC object (the tag will be the last block
149 # bytes worth of ciphertext)
150 self._mac = self._factory.new(key,
151 factory.MODE_CBC,
152 iv=b'\x00' * 16,
153 **cipher_params)
154 self._mac_status = MacStatus.NOT_STARTED
155 self._t = None
156
157 # Allowed transitions after initialization
158 self._next = ["update", "encrypt", "decrypt",
159 "digest", "verify"]
160
161 # Cumulative lengths
162 self._cumul_assoc_len = 0
163 self._cumul_msg_len = 0
164
165 # Cache for unaligned associated data/plaintext.
166 # This is a list with byte strings, but when the MAC starts,
167 # it will become a binary string no longer than the block size.
168 self._cache = []
169
170 # Start CTR cipher, by formatting the counter (A.3)
171 q = 15 - len(nonce) # length of Q, the encoded message length
172 self._cipher = self._factory.new(key,
173 self._factory.MODE_CTR,
174 nonce=struct.pack("B", q - 1) + self.nonce,
175 **cipher_params)
176
177 # S_0, step 6 in 6.1 for j=0
178 self._s_0 = self._cipher.encrypt(b'\x00' * 16)
179
180 # Try to start the MAC
181 if None not in (assoc_len, msg_len):
182 self._start_mac()
183
184 def _start_mac(self):
185
186 assert(self._mac_status == MacStatus.NOT_STARTED)
187 assert(None not in (self._assoc_len, self._msg_len))
188 assert(isinstance(self._cache, list))
189
190 # Formatting control information and nonce (A.2.1)
191 q = 15 - len(self.nonce) # length of Q, the encoded message length
192 flags = (64 * (self._assoc_len > 0) + 8 * ((self._mac_len - 2) // 2) +
193 (q - 1))
194 b_0 = struct.pack("B", flags) + self.nonce + long_to_bytes(self._msg_len, q)
195
196 # Formatting associated data (A.2.2)
197 # Encoded 'a' is concatenated with the associated data 'A'
198 assoc_len_encoded = b''
199 if self._assoc_len > 0:
200 if self._assoc_len < (2 ** 16 - 2 ** 8):
201 enc_size = 2
202 elif self._assoc_len < (2 ** 32):
203 assoc_len_encoded = b'\xFF\xFE'
204 enc_size = 4
205 else:
206 assoc_len_encoded = b'\xFF\xFF'
207 enc_size = 8
208 assoc_len_encoded += long_to_bytes(self._assoc_len, enc_size)
209
210 # b_0 and assoc_len_encoded must be processed first
211 self._cache.insert(0, b_0)
212 self._cache.insert(1, assoc_len_encoded)
213
214 # Process all the data cached so far
215 first_data_to_mac = b"".join(self._cache)
216 self._cache = b""
217 self._mac_status = MacStatus.PROCESSING_AUTH_DATA
218 self._update(first_data_to_mac)
219
220 def _pad_cache_and_update(self):
221
222 assert(self._mac_status != MacStatus.NOT_STARTED)
223 assert(len(self._cache) < self.block_size)
224
225 # Associated data is concatenated with the least number
226 # of zero bytes (possibly none) to reach alignment to
227 # the 16 byte boundary (A.2.3)
228 len_cache = len(self._cache)
229 if len_cache > 0:
230 self._update(b'\x00' * (self.block_size - len_cache))
231
232 def update(self, assoc_data):
233 """Protect associated data
234
235 If there is any associated data, the caller has to invoke
236 this function one or more times, before using
237 ``decrypt`` or ``encrypt``.
238
239 By *associated data* it is meant any data (e.g. packet headers) that
240 will not be encrypted and will be transmitted in the clear.
241 However, the receiver is still able to detect any modification to it.
242 In CCM, the *associated data* is also called
243 *additional authenticated data* (AAD).
244
245 If there is no associated data, this method must not be called.
246
247 The caller may split associated data in segments of any size, and
248 invoke this method multiple times, each time with the next segment.
249
250 :Parameters:
251 assoc_data : bytes/bytearray/memoryview
252 A piece of associated data. There are no restrictions on its size.
253 """
254
255 if "update" not in self._next:
256 raise TypeError("update() can only be called"
257 " immediately after initialization")
258
259 self._next = ["update", "encrypt", "decrypt",
260 "digest", "verify"]
261
262 self._cumul_assoc_len += len(assoc_data)
263 if self._assoc_len is not None and \
264 self._cumul_assoc_len > self._assoc_len:
265 raise ValueError("Associated data is too long")
266
267 self._update(assoc_data)
268 return self
269
270 def _update(self, assoc_data_pt=b""):
271 """Update the MAC with associated data or plaintext
272 (without FSM checks)"""
273
274 # If MAC has not started yet, we just park the data into a list.
275 # If the data is mutable, we create a copy and store that instead.
276 if self._mac_status == MacStatus.NOT_STARTED:
277 if is_writeable_buffer(assoc_data_pt):
278 assoc_data_pt = _copy_bytes(None, None, assoc_data_pt)
279 self._cache.append(assoc_data_pt)
280 return
281
282 assert(len(self._cache) < self.block_size)
283
284 if len(self._cache) > 0:
285 filler = min(self.block_size - len(self._cache),
286 len(assoc_data_pt))
287 self._cache += _copy_bytes(None, filler, assoc_data_pt)
288 assoc_data_pt = _copy_bytes(filler, None, assoc_data_pt)
289
290 if len(self._cache) < self.block_size:
291 return
292
293 # The cache is exactly one block
294 self._t = self._mac.encrypt(self._cache)
295 self._cache = b""
296
297 update_len = len(assoc_data_pt) // self.block_size * self.block_size
298 self._cache = _copy_bytes(update_len, None, assoc_data_pt)
299 if update_len > 0:
300 self._t = self._mac.encrypt(assoc_data_pt[:update_len])[-16:]
301
302 def encrypt(self, plaintext, output=None):
303 """Encrypt data with the key set at initialization.
304
305 A cipher object is stateful: once you have encrypted a message
306 you cannot encrypt (or decrypt) another message using the same
307 object.
308
309 This method can be called only **once** if ``msg_len`` was
310 not passed at initialization.
311
312 If ``msg_len`` was given, the data to encrypt can be broken
313 up in two or more pieces and `encrypt` can be called
314 multiple times.
315
316 That is, the statement:
317
318 >>> c.encrypt(a) + c.encrypt(b)
319
320 is equivalent to:
321
322 >>> c.encrypt(a+b)
323
324 This function does not add any padding to the plaintext.
325
326 :Parameters:
327 plaintext : bytes/bytearray/memoryview
328 The piece of data to encrypt.
329 It can be of any length.
330 :Keywords:
331 output : bytearray/memoryview
332 The location where the ciphertext must be written to.
333 If ``None``, the ciphertext is returned.
334 :Return:
335 If ``output`` is ``None``, the ciphertext as ``bytes``.
336 Otherwise, ``None``.
337 """
338
339 if "encrypt" not in self._next:
340 raise TypeError("encrypt() can only be called after"
341 " initialization or an update()")
342 self._next = ["encrypt", "digest"]
343
344 # No more associated data allowed from now
345 if self._assoc_len is None:
346 assert(isinstance(self._cache, list))
347 self._assoc_len = sum([len(x) for x in self._cache])
348 if self._msg_len is not None:
349 self._start_mac()
350 else:
351 if self._cumul_assoc_len < self._assoc_len:
352 raise ValueError("Associated data is too short")
353
354 # Only once piece of plaintext accepted if message length was
355 # not declared in advance
356 if self._msg_len is None:
357 self._msg_len = len(plaintext)
358 self._start_mac()
359 self._next = ["digest"]
360
361 self._cumul_msg_len += len(plaintext)
362 if self._cumul_msg_len > self._msg_len:
363 raise ValueError("Message is too long")
364
365 if self._mac_status == MacStatus.PROCESSING_AUTH_DATA:
366 # Associated data is concatenated with the least number
367 # of zero bytes (possibly none) to reach alignment to
368 # the 16 byte boundary (A.2.3)
369 self._pad_cache_and_update()
370 self._mac_status = MacStatus.PROCESSING_PLAINTEXT
371
372 self._update(plaintext)
373 return self._cipher.encrypt(plaintext, output=output)
374
375 def decrypt(self, ciphertext, output=None):
376 """Decrypt data with the key set at initialization.
377
378 A cipher object is stateful: once you have decrypted a message
379 you cannot decrypt (or encrypt) another message with the same
380 object.
381
382 This method can be called only **once** if ``msg_len`` was
383 not passed at initialization.
384
385 If ``msg_len`` was given, the data to decrypt can be
386 broken up in two or more pieces and `decrypt` can be
387 called multiple times.
388
389 That is, the statement:
390
391 >>> c.decrypt(a) + c.decrypt(b)
392
393 is equivalent to:
394
395 >>> c.decrypt(a+b)
396
397 This function does not remove any padding from the plaintext.
398
399 :Parameters:
400 ciphertext : bytes/bytearray/memoryview
401 The piece of data to decrypt.
402 It can be of any length.
403 :Keywords:
404 output : bytearray/memoryview
405 The location where the plaintext must be written to.
406 If ``None``, the plaintext is returned.
407 :Return:
408 If ``output`` is ``None``, the plaintext as ``bytes``.
409 Otherwise, ``None``.
410 """
411
412 if "decrypt" not in self._next:
413 raise TypeError("decrypt() can only be called"
414 " after initialization or an update()")
415 self._next = ["decrypt", "verify"]
416
417 # No more associated data allowed from now
418 if self._assoc_len is None:
419 assert(isinstance(self._cache, list))
420 self._assoc_len = sum([len(x) for x in self._cache])
421 if self._msg_len is not None:
422 self._start_mac()
423 else:
424 if self._cumul_assoc_len < self._assoc_len:
425 raise ValueError("Associated data is too short")
426
427 # Only once piece of ciphertext accepted if message length was
428 # not declared in advance
429 if self._msg_len is None:
430 self._msg_len = len(ciphertext)
431 self._start_mac()
432 self._next = ["verify"]
433
434 self._cumul_msg_len += len(ciphertext)
435 if self._cumul_msg_len > self._msg_len:
436 raise ValueError("Message is too long")
437
438 if self._mac_status == MacStatus.PROCESSING_AUTH_DATA:
439 # Associated data is concatenated with the least number
440 # of zero bytes (possibly none) to reach alignment to
441 # the 16 byte boundary (A.2.3)
442 self._pad_cache_and_update()
443 self._mac_status = MacStatus.PROCESSING_PLAINTEXT
444
445 # Encrypt is equivalent to decrypt with the CTR mode
446 plaintext = self._cipher.encrypt(ciphertext, output=output)
447 if output is None:
448 self._update(plaintext)
449 else:
450 self._update(output)
451 return plaintext
452
453 def digest(self):
454 """Compute the *binary* MAC tag.
455
456 The caller invokes this function at the very end.
457
458 This method returns the MAC that shall be sent to the receiver,
459 together with the ciphertext.
460
461 :Return: the MAC, as a byte string.
462 """
463
464 if "digest" not in self._next:
465 raise TypeError("digest() cannot be called when decrypting"
466 " or validating a message")
467 self._next = ["digest"]
468 return self._digest()
469
470 def _digest(self):
471 if self._mac_tag:
472 return self._mac_tag
473
474 if self._assoc_len is None:
475 assert(isinstance(self._cache, list))
476 self._assoc_len = sum([len(x) for x in self._cache])
477 if self._msg_len is not None:
478 self._start_mac()
479 else:
480 if self._cumul_assoc_len < self._assoc_len:
481 raise ValueError("Associated data is too short")
482
483 if self._msg_len is None:
484 self._msg_len = 0
485 self._start_mac()
486
487 if self._cumul_msg_len != self._msg_len:
488 raise ValueError("Message is too short")
489
490 # Both associated data and payload are concatenated with the least
491 # number of zero bytes (possibly none) that align it to the
492 # 16 byte boundary (A.2.2 and A.2.3)
493 self._pad_cache_and_update()
494
495 # Step 8 in 6.1 (T xor MSB_Tlen(S_0))
496 self._mac_tag = strxor(self._t, self._s_0)[:self._mac_len]
497
498 return self._mac_tag
499
500 def hexdigest(self):
501 """Compute the *printable* MAC tag.
502
503 This method is like `digest`.
504
505 :Return: the MAC, as a hexadecimal string.
506 """
507 return "".join(["%02x" % bord(x) for x in self.digest()])
508
509 def verify(self, received_mac_tag):
510 """Validate the *binary* MAC tag.
511
512 The caller invokes this function at the very end.
513
514 This method checks if the decrypted message is indeed valid
515 (that is, if the key is correct) and it has not been
516 tampered with while in transit.
517
518 :Parameters:
519 received_mac_tag : bytes/bytearray/memoryview
520 This is the *binary* MAC, as received from the sender.
521 :Raises ValueError:
522 if the MAC does not match. The message has been tampered with
523 or the key is incorrect.
524 """
525
526 if "verify" not in self._next:
527 raise TypeError("verify() cannot be called"
528 " when encrypting a message")
529 self._next = ["verify"]
530
531 self._digest()
532 secret = get_random_bytes(16)
533
534 mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
535 mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)
536
537 if mac1.digest() != mac2.digest():
538 raise ValueError("MAC check failed")
539
540 def hexverify(self, hex_mac_tag):
541 """Validate the *printable* MAC tag.
542
543 This method is like `verify`.
544
545 :Parameters:
546 hex_mac_tag : string
547 This is the *printable* MAC, as received from the sender.
548 :Raises ValueError:
549 if the MAC does not match. The message has been tampered with
550 or the key is incorrect.
551 """
552
553 self.verify(unhexlify(hex_mac_tag))
554
555 def encrypt_and_digest(self, plaintext, output=None):
556 """Perform encrypt() and digest() in one step.
557
558 :Parameters:
559 plaintext : bytes/bytearray/memoryview
560 The piece of data to encrypt.
561 :Keywords:
562 output : bytearray/memoryview
563 The location where the ciphertext must be written to.
564 If ``None``, the ciphertext is returned.
565 :Return:
566 a tuple with two items:
567
568 - the ciphertext, as ``bytes``
569 - the MAC tag, as ``bytes``
570
571 The first item becomes ``None`` when the ``output`` parameter
572 specified a location for the result.
573 """
574
575 return self.encrypt(plaintext, output=output), self.digest()
576
577 def decrypt_and_verify(self, ciphertext, received_mac_tag, output=None):
578 """Perform decrypt() and verify() in one step.
579
580 :Parameters:
581 ciphertext : bytes/bytearray/memoryview
582 The piece of data to decrypt.
583 received_mac_tag : bytes/bytearray/memoryview
584 This is the *binary* MAC, as received from the sender.
585 :Keywords:
586 output : bytearray/memoryview
587 The location where the plaintext must be written to.
588 If ``None``, the plaintext is returned.
589 :Return: the plaintext as ``bytes`` or ``None`` when the ``output``
590 parameter specified a location for the result.
591 :Raises ValueError:
592 if the MAC does not match. The message has been tampered with
593 or the key is incorrect.
594 """
595
596 plaintext = self.decrypt(ciphertext, output=output)
597 self.verify(received_mac_tag)
598 return plaintext
599
600
601 def _create_ccm_cipher(factory, **kwargs):
602 """Create a new block cipher, configured in CCM mode.
603
604 :Parameters:
605 factory : module
606 A symmetric cipher module from `Crypto.Cipher` (like
607 `Crypto.Cipher.AES`).
608
609 :Keywords:
610 key : bytes/bytearray/memoryview
611 The secret key to use in the symmetric cipher.
612
613 nonce : bytes/bytearray/memoryview
614 A value that must never be reused for any other encryption.
615
616 Its length must be in the range ``[7..13]``.
617 11 or 12 bytes are reasonable values in general. Bear in
618 mind that with CCM there is a trade-off between nonce length and
619 maximum message size.
620
621 If not specified, a 11 byte long random string is used.
622
623 mac_len : integer
624 Length of the MAC, in bytes. It must be even and in
625 the range ``[4..16]``. The default is 16.
626
627 msg_len : integer
628 Length of the message to (de)cipher.
629 If not specified, ``encrypt`` or ``decrypt`` may only be called once.
630
631 assoc_len : integer
632 Length of the associated data.
633 If not specified, all data is internally buffered.
634 """
635
636 try:
637 key = key = kwargs.pop("key")
638 except KeyError as e:
639 raise TypeError("Missing parameter: " + str(e))
640
641 nonce = kwargs.pop("nonce", None) # N
642 if nonce is None:
643 nonce = get_random_bytes(11)
644 mac_len = kwargs.pop("mac_len", factory.block_size)
645 msg_len = kwargs.pop("msg_len", None) # p
646 assoc_len = kwargs.pop("assoc_len", None) # a
647 cipher_params = dict(kwargs)
648
649 return CcmMode(factory, key, nonce, mac_len, msg_len,
650 assoc_len, cipher_params)