_mode_ocb.py 19 KB

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