Debian Codegraph @

lib/Crypto/Cipher/_mode_ocb.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 Offset Codebook (OCB) mode.
33
34 OCB is Authenticated Encryption with Associated Data (AEAD) cipher mode
35 designed by Prof. Phillip Rogaway and specified in `RFC7253`_.
36
37 The algorithm provides both authenticity and privacy, it is very efficient,
38 it uses only one key and it can be used in online mode (so that encryption
39 or decryption can start before the end of the message is available).
40
41 This module implements the third and last variant of OCB (OCB3) and it only
42 works in combination with a 128-bit block symmetric cipher, like AES.
43
44 OCB is patented in US but `free licenses`_ exist for software implementations
45 meant for non-military purposes.
46
47 Example:
48 >>> from Crypto.Cipher import AES
49 >>> from Crypto.Random import get_random_bytes
50 >>>
51 >>> key = get_random_bytes(32)
52 >>> cipher = AES.new(key, AES.MODE_OCB)
53 >>> plaintext = b"Attack at dawn"
54 >>> ciphertext, mac = cipher.encrypt_and_digest(plaintext)
55 >>> # Deliver cipher.nonce, ciphertext and mac
56 ...
57 >>> cipher = AES.new(key, AES.MODE_OCB, nonce=nonce)
58 >>> try:
59 >>> plaintext = cipher.decrypt_and_verify(ciphertext, mac)
60 >>> except ValueError:
61 >>> print "Invalid message"
62 >>> else:
63 >>> print plaintext
64
65 :undocumented: __package__
66
67 .. _RFC7253: http://www.rfc-editor.org/info/rfc7253
68 .. _free licenses: http://web.cs.ucdavis.edu/~rogaway/ocb/license.htm
69 """
70
71 import struct
72 from binascii import unhexlify
73
74 from Crypto.Util.py3compat import bord, _copy_bytes, bchr
75 from Crypto.Util.number import long_to_bytes, bytes_to_long
76 from Crypto.Util.strxor import strxor
77
78 from Crypto.Hash import BLAKE2s
79 from Crypto.Random import get_random_bytes
80
81 from Crypto.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
82 create_string_buffer, get_raw_buffer,
83 SmartPointer, c_size_t, c_uint8_ptr,
84 is_buffer)
85
86 _raw_ocb_lib = load_pycryptodome_raw_lib("Crypto.Cipher._raw_ocb", """
87 int OCB_start_operation(void *cipher,
88 const uint8_t *offset_0,
89 size_t offset_0_len,
90 void **pState);
91 int OCB_encrypt(void *state,
92 const uint8_t *in,
93 uint8_t *out,
94 size_t data_len);
95 int OCB_decrypt(void *state,
96 const uint8_t *in,
97 uint8_t *out,
98 size_t data_len);
99 int OCB_update(void *state,
100 const uint8_t *in,
101 size_t data_len);
102 int OCB_digest(void *state,
103 uint8_t *tag,
104 size_t tag_len);
105 int OCB_stop_operation(void *state);
106 """)
107
108
109 class OcbMode(object):
110 """Offset Codebook (OCB) mode.
111
112 :undocumented: __init__
113 """
114
115 def __init__(self, factory, nonce, mac_len, cipher_params):
116
117 if factory.block_size != 16:
118 raise ValueError("OCB mode is only available for ciphers"
119 " that operate on 128 bits blocks")
120
121 self.block_size = 16
122 """The block size of the underlying cipher, in bytes."""
123
124 self.nonce = _copy_bytes(None, None, nonce)
125 """Nonce used for this session."""
126 if len(nonce) not in range(1, 16):
127 raise ValueError("Nonce must be at most 15 bytes long")
128 if not is_buffer(nonce):
129 raise TypeError("Nonce must be bytes, bytearray or memoryview")
130
131 self._mac_len = mac_len
132 if not 8 <= mac_len <= 16:
133 raise ValueError("MAC tag must be between 8 and 16 bytes long")
134
135 # Cache for MAC tag
136 self._mac_tag = None
137
138 # Cache for unaligned associated data
139 self._cache_A = b""
140
141 # Cache for unaligned ciphertext/plaintext
142 self._cache_P = b""
143
144 # Allowed transitions after initialization
145 self._next = ["update", "encrypt", "decrypt",
146 "digest", "verify"]
147
148 # Compute Offset_0
149 params_without_key = dict(cipher_params)
150 key = params_without_key.pop("key")
151
152 taglen_mod128 = (self._mac_len * 8) % 128
153 if len(self.nonce) < 15:
154 nonce = bchr(taglen_mod128 << 1) +\
155 b'\x00' * (14 - len(nonce)) +\
156 b'\x01' +\
157 self.nonce
158 else:
159 nonce = bchr((taglen_mod128 << 1) | 0x01) +\
160 self.nonce
161
162 bottom_bits = bord(nonce[15]) & 0x3F # 6 bits, 0..63
163 top_bits = bord(nonce[15]) & 0xC0 # 2 bits
164
165 ktop_cipher = factory.new(key,
166 factory.MODE_ECB,
167 **params_without_key)
168 ktop = ktop_cipher.encrypt(struct.pack('15sB',
169 nonce[:15],
170 top_bits))
171
172 stretch = ktop + strxor(ktop[:8], ktop[1:9]) # 192 bits
173 offset_0 = long_to_bytes(bytes_to_long(stretch) >>
174 (64 - bottom_bits), 24)[8:]
175
176 # Create low-level cipher instance
177 raw_cipher = factory._create_base_cipher(cipher_params)
178 if cipher_params:
179 raise TypeError("Unknown keywords: " + str(cipher_params))
180
181 self._state = VoidPointer()
182 result = _raw_ocb_lib.OCB_start_operation(raw_cipher.get(),
183 offset_0,
184 c_size_t(len(offset_0)),
185 self._state.address_of())
186 if result:
187 raise ValueError("Error %d while instantiating the OCB mode"
188 % result)
189
190 # Ensure that object disposal of this Python object will (eventually)
191 # free the memory allocated by the raw library for the cipher mode
192 self._state = SmartPointer(self._state.get(),
193 _raw_ocb_lib.OCB_stop_operation)
194
195 # Memory allocated for the underlying block cipher is now owed
196 # by the cipher mode
197 raw_cipher.release()
198
199 def _update(self, assoc_data, assoc_data_len):
200 result = _raw_ocb_lib.OCB_update(self._state.get(),
201 c_uint8_ptr(assoc_data),
202 c_size_t(assoc_data_len))
203 if result:
204 raise ValueError("Error %d while computing MAC in OCB mode" % result)
205
206 def update(self, assoc_data):
207 """Process the associated data.
208
209 If there is any associated data, the caller has to invoke
210 this method one or more times, before using
211 ``decrypt`` or ``encrypt``.
212
213 By *associated data* it is meant any data (e.g. packet headers) that
214 will not be encrypted and will be transmitted in the clear.
215 However, the receiver shall still able to detect modifications.
216
217 If there is no associated data, this method must not be called.
218
219 The caller may split associated data in segments of any size, and
220 invoke this method multiple times, each time with the next segment.
221
222 :Parameters:
223 assoc_data : bytes/bytearray/memoryview
224 A piece of associated data.
225 """
226
227 if "update" not in self._next:
228 raise TypeError("update() can only be called"
229 " immediately after initialization")
230
231 self._next = ["encrypt", "decrypt", "digest",
232 "verify", "update"]
233
234 if len(self._cache_A) > 0:
235 filler = min(16 - len(self._cache_A), len(assoc_data))
236 self._cache_A += _copy_bytes(None, filler, assoc_data)
237 assoc_data = assoc_data[filler:]
238
239 if len(self._cache_A) < 16:
240 return self
241
242 # Clear the cache, and proceeding with any other aligned data
243 self._cache_A, seg = b"", self._cache_A
244 self.update(seg)
245
246 update_len = len(assoc_data) // 16 * 16
247 self._cache_A = _copy_bytes(update_len, None, assoc_data)
248 self._update(assoc_data, update_len)
249 return self
250
251 def _transcrypt_aligned(self, in_data, in_data_len,
252 trans_func, trans_desc):
253
254 out_data = create_string_buffer(in_data_len)
255 result = trans_func(self._state.get(),
256 in_data,
257 out_data,
258 c_size_t(in_data_len))
259 if result:
260 raise ValueError("Error %d while %sing in OCB mode"
261 % (result, trans_desc))
262 return get_raw_buffer(out_data)
263
264 def _transcrypt(self, in_data, trans_func, trans_desc):
265 # Last piece to encrypt/decrypt
266 if in_data is None:
267 out_data = self._transcrypt_aligned(self._cache_P,
268 len(self._cache_P),
269 trans_func,
270 trans_desc)
271 self._cache_P = b""
272 return out_data
273
274 # Try to fill up the cache, if it already contains something
275 prefix = b""
276 if len(self._cache_P) > 0:
277 filler = min(16 - len(self._cache_P), len(in_data))
278 self._cache_P += _copy_bytes(None, filler, in_data)
279 in_data = in_data[filler:]
280
281 if len(self._cache_P) < 16:
282 # We could not manage to fill the cache, so there is certainly
283 # no output yet.
284 return b""
285
286 # Clear the cache, and proceeding with any other aligned data
287 prefix = self._transcrypt_aligned(self._cache_P,
288 len(self._cache_P),
289 trans_func,
290 trans_desc)
291 self._cache_P = b""
292
293 # Process data in multiples of the block size
294 trans_len = len(in_data) // 16 * 16
295 result = self._transcrypt_aligned(c_uint8_ptr(in_data),
296 trans_len,
297 trans_func,
298 trans_desc)
299 if prefix:
300 result = prefix + result
301
302 # Left-over
303 self._cache_P = _copy_bytes(trans_len, None, in_data)
304
305 return result
306
307 def encrypt(self, plaintext=None):
308 """Encrypt the next piece of plaintext.
309
310 After the entire plaintext has been passed (but before `digest`),
311 you **must** call this method one last time with no arguments to collect
312 the final piece of ciphertext.
313
314 If possible, use the method `encrypt_and_digest` instead.
315
316 :Parameters:
317 plaintext : bytes/bytearray/memoryview
318 The next piece of data to encrypt or ``None`` to signify
319 that encryption has finished and that any remaining ciphertext
320 has to be produced.
321 :Return:
322 the ciphertext, as a byte string.
323 Its length may not match the length of the *plaintext*.
324 """
325
326 if "encrypt" not in self._next:
327 raise TypeError("encrypt() can only be called after"
328 " initialization or an update()")
329
330 if plaintext is None:
331 self._next = ["digest"]
332 else:
333 self._next = ["encrypt"]
334 return self._transcrypt(plaintext, _raw_ocb_lib.OCB_encrypt, "encrypt")
335
336 def decrypt(self, ciphertext=None):
337 """Decrypt the next piece of ciphertext.
338
339 After the entire ciphertext has been passed (but before `verify`),
340 you **must** call this method one last time with no arguments to collect
341 the remaining piece of plaintext.
342
343 If possible, use the method `decrypt_and_verify` instead.
344
345 :Parameters:
346 ciphertext : bytes/bytearray/memoryview
347 The next piece of data to decrypt or ``None`` to signify
348 that decryption has finished and that any remaining plaintext
349 has to be produced.
350 :Return:
351 the plaintext, as a byte string.
352 Its length may not match the length of the *ciphertext*.
353 """
354
355 if "decrypt" not in self._next:
356 raise TypeError("decrypt() can only be called after"
357 " initialization or an update()")
358
359 if ciphertext is None:
360 self._next = ["verify"]
361 else:
362 self._next = ["decrypt"]
363 return self._transcrypt(ciphertext,
364 _raw_ocb_lib.OCB_decrypt,
365 "decrypt")
366
367 def _compute_mac_tag(self):
368
369 if self._mac_tag is not None:
370 return
371
372 if self._cache_A:
373 self._update(self._cache_A, len(self._cache_A))
374 self._cache_A = b""
375
376 mac_tag = create_string_buffer(16)
377 result = _raw_ocb_lib.OCB_digest(self._state.get(),
378 mac_tag,
379 c_size_t(len(mac_tag))
380 )
381 if result:
382 raise ValueError("Error %d while computing digest in OCB mode"
383 % result)
384 self._mac_tag = get_raw_buffer(mac_tag)[:self._mac_len]
385
386 def digest(self):
387 """Compute the *binary* MAC tag.
388
389 Call this method after the final `encrypt` (the one with no arguments)
390 to obtain the MAC tag.
391
392 The MAC tag is needed by the receiver to determine authenticity
393 of the message.
394
395 :Return: the MAC, as a byte string.
396 """
397
398 if "digest" not in self._next:
399 raise TypeError("digest() cannot be called now for this cipher")
400
401 assert(len(self._cache_P) == 0)
402
403 self._next = ["digest"]
404
405 if self._mac_tag is None:
406 self._compute_mac_tag()
407
408 return self._mac_tag
409
410 def hexdigest(self):
411 """Compute the *printable* MAC tag.
412
413 This method is like `digest`.
414
415 :Return: the MAC, as a hexadecimal string.
416 """
417 return "".join(["%02x" % bord(x) for x in self.digest()])
418
419 def verify(self, received_mac_tag):
420 """Validate the *binary* MAC tag.
421
422 Call this method after the final `decrypt` (the one with no arguments)
423 to check if the message is authentic and valid.
424
425 :Parameters:
426 received_mac_tag : bytes/bytearray/memoryview
427 This is the *binary* MAC, as received from the sender.
428 :Raises ValueError:
429 if the MAC does not match. The message has been tampered with
430 or the key is incorrect.
431 """
432
433 if "verify" not in self._next:
434 raise TypeError("verify() cannot be called now for this cipher")
435
436 assert(len(self._cache_P) == 0)
437
438 self._next = ["verify"]
439
440 if self._mac_tag is None:
441 self._compute_mac_tag()
442
443 secret = get_random_bytes(16)
444 mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
445 mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)
446
447 if mac1.digest() != mac2.digest():
448 raise ValueError("MAC check failed")
449
450 def hexverify(self, hex_mac_tag):
451 """Validate the *printable* MAC tag.
452
453 This method is like `verify`.
454
455 :Parameters:
456 hex_mac_tag : string
457 This is the *printable* MAC, as received from the sender.
458 :Raises ValueError:
459 if the MAC does not match. The message has been tampered with
460 or the key is incorrect.
461 """
462
463 self.verify(unhexlify(hex_mac_tag))
464
465 def encrypt_and_digest(self, plaintext):
466 """Encrypt the message and create the MAC tag in one step.
467
468 :Parameters:
469 plaintext : bytes/bytearray/memoryview
470 The entire message to encrypt.
471 :Return:
472 a tuple with two byte strings:
473
474 - the encrypted data
475 - the MAC
476 """
477
478 return self.encrypt(plaintext) + self.encrypt(), self.digest()
479
480 def decrypt_and_verify(self, ciphertext, received_mac_tag):
481 """Decrypted the message and verify its authenticity in one step.
482
483 :Parameters:
484 ciphertext : bytes/bytearray/memoryview
485 The entire message to decrypt.
486 received_mac_tag : byte string
487 This is the *binary* MAC, as received from the sender.
488
489 :Return: the decrypted data (byte string).
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 plaintext = self.decrypt(ciphertext) + self.decrypt()
496 self.verify(received_mac_tag)
497 return plaintext
498
499
500 def _create_ocb_cipher(factory, **kwargs):
501 """Create a new block cipher, configured in OCB mode.
502
503 :Parameters:
504 factory : module
505 A symmetric cipher module from `Crypto.Cipher`
506 (like `Crypto.Cipher.AES`).
507
508 :Keywords:
509 nonce : bytes/bytearray/memoryview
510 A value that must never be reused for any other encryption.
511 Its length can vary from 1 to 15 bytes.
512 If not specified, a random 15 bytes long nonce is generated.
513
514 mac_len : integer
515 Length of the MAC, in bytes.
516 It must be in the range ``[8..16]``.
517 The default is 16 (128 bits).
518
519 Any other keyword will be passed to the underlying block cipher.
520 See the relevant documentation for details (at least ``key`` will need
521 to be present).
522 """
523
524 try:
525 nonce = kwargs.pop("nonce", None)
526 if nonce is None:
527 nonce = get_random_bytes(15)
528 mac_len = kwargs.pop("mac_len", 16)
529 except KeyError as e:
530 raise TypeError("Keyword missing: " + str(e))
531
532 return OcbMode(factory, nonce, mac_len, kwargs)