_mode_ocb.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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 tls.Crypto.Cipher import AES
  43. >>> from tls.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 tls.Crypto.Util.py3compat import bord, _copy_bytes
  65. from tls.Crypto.Util.number import long_to_bytes, bytes_to_long
  66. from tls.Crypto.Util.strxor import strxor
  67. from tls.Crypto.Hash import BLAKE2s
  68. from tls.Crypto.Random import get_random_bytes
  69. from tls.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 = [self.update, self.encrypt, self.decrypt,
  121. self.digest, self.verify]
  122. # Compute Offset_0
  123. params_without_key = dict(cipher_params)
  124. key = params_without_key.pop("key")
  125. nonce = (struct.pack('B', self._mac_len << 4 & 0xFF) +
  126. b'\x00' * (14 - len(nonce)) +
  127. b'\x01' + self.nonce)
  128. bottom_bits = bord(nonce[15]) & 0x3F # 6 bits, 0..63
  129. top_bits = bord(nonce[15]) & 0xC0 # 2 bits
  130. ktop_cipher = factory.new(key,
  131. factory.MODE_ECB,
  132. **params_without_key)
  133. ktop = ktop_cipher.encrypt(struct.pack('15sB',
  134. nonce[:15],
  135. top_bits))
  136. stretch = ktop + strxor(ktop[:8], ktop[1:9]) # 192 bits
  137. offset_0 = long_to_bytes(bytes_to_long(stretch) >>
  138. (64 - bottom_bits), 24)[8:]
  139. # Create low-level cipher instance
  140. raw_cipher = factory._create_base_cipher(cipher_params)
  141. if cipher_params:
  142. raise TypeError("Unknown keywords: " + str(cipher_params))
  143. self._state = VoidPointer()
  144. result = _raw_ocb_lib.OCB_start_operation(raw_cipher.get(),
  145. offset_0,
  146. c_size_t(len(offset_0)),
  147. self._state.address_of())
  148. if result:
  149. raise ValueError("Error %d while instantiating the OCB mode"
  150. % result)
  151. # Ensure that object disposal of this Python object will (eventually)
  152. # free the memory allocated by the raw library for the cipher mode
  153. self._state = SmartPointer(self._state.get(),
  154. _raw_ocb_lib.OCB_stop_operation)
  155. # Memory allocated for the underlying block cipher is now owed
  156. # by the cipher mode
  157. raw_cipher.release()
  158. def _update(self, assoc_data, assoc_data_len):
  159. result = _raw_ocb_lib.OCB_update(self._state.get(),
  160. c_uint8_ptr(assoc_data),
  161. c_size_t(assoc_data_len))
  162. if result:
  163. raise ValueError("Error %d while computing MAC in OCB mode" % result)
  164. def update(self, assoc_data):
  165. """Process the associated data.
  166. If there is any associated data, the caller has to invoke
  167. this method one or more times, before using
  168. ``decrypt`` or ``encrypt``.
  169. By *associated data* it is meant any data (e.g. packet headers) that
  170. will not be encrypted and will be transmitted in the clear.
  171. However, the receiver shall still able to detect modifications.
  172. If there is no associated data, this method must not be called.
  173. The caller may split associated data in segments of any size, and
  174. invoke this method multiple times, each time with the next segment.
  175. :Parameters:
  176. assoc_data : bytes/bytearray/memoryview
  177. A piece of associated data.
  178. """
  179. if self.update not in self._next:
  180. raise TypeError("update() can only be called"
  181. " immediately after initialization")
  182. self._next = [self.encrypt, self.decrypt, self.digest,
  183. self.verify, self.update]
  184. if len(self._cache_A) > 0:
  185. filler = min(16 - len(self._cache_A), len(assoc_data))
  186. self._cache_A += _copy_bytes(None, filler, assoc_data)
  187. assoc_data = assoc_data[filler:]
  188. if len(self._cache_A) < 16:
  189. return self
  190. # Clear the cache, and proceeding with any other aligned data
  191. self._cache_A, seg = b"", self._cache_A
  192. self.update(seg)
  193. update_len = len(assoc_data) // 16 * 16
  194. self._cache_A = _copy_bytes(update_len, None, assoc_data)
  195. self._update(assoc_data, update_len)
  196. return self
  197. def _transcrypt_aligned(self, in_data, in_data_len,
  198. trans_func, trans_desc):
  199. out_data = create_string_buffer(in_data_len)
  200. result = trans_func(self._state.get(),
  201. in_data,
  202. out_data,
  203. c_size_t(in_data_len))
  204. if result:
  205. raise ValueError("Error %d while %sing in OCB mode"
  206. % (result, trans_desc))
  207. return get_raw_buffer(out_data)
  208. def _transcrypt(self, in_data, trans_func, trans_desc):
  209. # Last piece to encrypt/decrypt
  210. if in_data is None:
  211. out_data = self._transcrypt_aligned(self._cache_P,
  212. len(self._cache_P),
  213. trans_func,
  214. trans_desc)
  215. self._cache_P = b""
  216. return out_data
  217. # Try to fill up the cache, if it already contains something
  218. prefix = b""
  219. if len(self._cache_P) > 0:
  220. filler = min(16 - len(self._cache_P), len(in_data))
  221. self._cache_P += _copy_bytes(None, filler, in_data)
  222. in_data = in_data[filler:]
  223. if len(self._cache_P) < 16:
  224. # We could not manage to fill the cache, so there is certainly
  225. # no output yet.
  226. return b""
  227. # Clear the cache, and proceeding with any other aligned data
  228. prefix = self._transcrypt_aligned(self._cache_P,
  229. len(self._cache_P),
  230. trans_func,
  231. trans_desc)
  232. self._cache_P = b""
  233. # Process data in multiples of the block size
  234. trans_len = len(in_data) // 16 * 16
  235. result = self._transcrypt_aligned(c_uint8_ptr(in_data),
  236. trans_len,
  237. trans_func,
  238. trans_desc)
  239. if prefix:
  240. result = prefix + result
  241. # Left-over
  242. self._cache_P = _copy_bytes(trans_len, None, in_data)
  243. return result
  244. def encrypt(self, plaintext=None):
  245. """Encrypt the next piece of plaintext.
  246. After the entire plaintext has been passed (but before `digest`),
  247. you **must** call this method one last time with no arguments to collect
  248. the final piece of ciphertext.
  249. If possible, use the method `encrypt_and_digest` instead.
  250. :Parameters:
  251. plaintext : bytes/bytearray/memoryview
  252. The next piece of data to encrypt or ``None`` to signify
  253. that encryption has finished and that any remaining ciphertext
  254. has to be produced.
  255. :Return:
  256. the ciphertext, as a byte string.
  257. Its length may not match the length of the *plaintext*.
  258. """
  259. if self.encrypt not in self._next:
  260. raise TypeError("encrypt() can only be called after"
  261. " initialization or an update()")
  262. if plaintext is None:
  263. self._next = [self.digest]
  264. else:
  265. self._next = [self.encrypt]
  266. return self._transcrypt(plaintext, _raw_ocb_lib.OCB_encrypt, "encrypt")
  267. def decrypt(self, ciphertext=None):
  268. """Decrypt the next piece of ciphertext.
  269. After the entire ciphertext has been passed (but before `verify`),
  270. you **must** call this method one last time with no arguments to collect
  271. the remaining piece of plaintext.
  272. If possible, use the method `decrypt_and_verify` instead.
  273. :Parameters:
  274. ciphertext : bytes/bytearray/memoryview
  275. The next piece of data to decrypt or ``None`` to signify
  276. that decryption has finished and that any remaining plaintext
  277. has to be produced.
  278. :Return:
  279. the plaintext, as a byte string.
  280. Its length may not match the length of the *ciphertext*.
  281. """
  282. if self.decrypt not in self._next:
  283. raise TypeError("decrypt() can only be called after"
  284. " initialization or an update()")
  285. if ciphertext is None:
  286. self._next = [self.verify]
  287. else:
  288. self._next = [self.decrypt]
  289. return self._transcrypt(ciphertext,
  290. _raw_ocb_lib.OCB_decrypt,
  291. "decrypt")
  292. def _compute_mac_tag(self):
  293. if self._mac_tag is not None:
  294. return
  295. if self._cache_A:
  296. self._update(self._cache_A, len(self._cache_A))
  297. self._cache_A = b""
  298. mac_tag = create_string_buffer(16)
  299. result = _raw_ocb_lib.OCB_digest(self._state.get(),
  300. mac_tag,
  301. c_size_t(len(mac_tag))
  302. )
  303. if result:
  304. raise ValueError("Error %d while computing digest in OCB mode"
  305. % result)
  306. self._mac_tag = get_raw_buffer(mac_tag)[:self._mac_len]
  307. def digest(self):
  308. """Compute the *binary* MAC tag.
  309. Call this method after the final `encrypt` (the one with no arguments)
  310. to obtain the MAC tag.
  311. The MAC tag is needed by the receiver to determine authenticity
  312. of the message.
  313. :Return: the MAC, as a byte string.
  314. """
  315. if self.digest not in self._next:
  316. raise TypeError("digest() cannot be called now for this cipher")
  317. assert(len(self._cache_P) == 0)
  318. self._next = [self.digest]
  319. if self._mac_tag is None:
  320. self._compute_mac_tag()
  321. return self._mac_tag
  322. def hexdigest(self):
  323. """Compute the *printable* MAC tag.
  324. This method is like `digest`.
  325. :Return: the MAC, as a hexadecimal string.
  326. """
  327. return "".join(["%02x" % bord(x) for x in self.digest()])
  328. def verify(self, received_mac_tag):
  329. """Validate the *binary* MAC tag.
  330. Call this method after the final `decrypt` (the one with no arguments)
  331. to check if the message is authentic and valid.
  332. :Parameters:
  333. received_mac_tag : bytes/bytearray/memoryview
  334. This is the *binary* MAC, as received from the sender.
  335. :Raises ValueError:
  336. if the MAC does not match. The message has been tampered with
  337. or the key is incorrect.
  338. """
  339. if self.verify not in self._next:
  340. raise TypeError("verify() cannot be called now for this cipher")
  341. assert(len(self._cache_P) == 0)
  342. self._next = [self.verify]
  343. if self._mac_tag is None:
  344. self._compute_mac_tag()
  345. secret = get_random_bytes(16)
  346. mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
  347. mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)
  348. if mac1.digest() != mac2.digest():
  349. raise ValueError("MAC check failed")
  350. def hexverify(self, hex_mac_tag):
  351. """Validate the *printable* MAC tag.
  352. This method is like `verify`.
  353. :Parameters:
  354. hex_mac_tag : string
  355. This is the *printable* MAC, as received from the sender.
  356. :Raises ValueError:
  357. if the MAC does not match. The message has been tampered with
  358. or the key is incorrect.
  359. """
  360. self.verify(unhexlify(hex_mac_tag))
  361. def encrypt_and_digest(self, plaintext):
  362. """Encrypt the message and create the MAC tag in one step.
  363. :Parameters:
  364. plaintext : bytes/bytearray/memoryview
  365. The entire message to encrypt.
  366. :Return:
  367. a tuple with two byte strings:
  368. - the encrypted data
  369. - the MAC
  370. """
  371. return self.encrypt(plaintext) + self.encrypt(), self.digest()
  372. def decrypt_and_verify(self, ciphertext, received_mac_tag):
  373. """Decrypted the message and verify its authenticity in one step.
  374. :Parameters:
  375. ciphertext : bytes/bytearray/memoryview
  376. The entire message to decrypt.
  377. received_mac_tag : byte string
  378. This is the *binary* MAC, as received from the sender.
  379. :Return: the decrypted data (byte string).
  380. :Raises ValueError:
  381. if the MAC does not match. The message has been tampered with
  382. or the key is incorrect.
  383. """
  384. plaintext = self.decrypt(ciphertext) + self.decrypt()
  385. self.verify(received_mac_tag)
  386. return plaintext
  387. def _create_ocb_cipher(factory, **kwargs):
  388. """Create a new block cipher, configured in OCB mode.
  389. :Parameters:
  390. factory : module
  391. A symmetric cipher module from `Crypto.Cipher`
  392. (like `Crypto.Cipher.AES`).
  393. :Keywords:
  394. nonce : bytes/bytearray/memoryview
  395. A value that must never be reused for any other encryption.
  396. Its length can vary from 1 to 15 bytes.
  397. If not specified, a random 15 bytes long nonce is generated.
  398. mac_len : integer
  399. Length of the MAC, in bytes.
  400. It must be in the range ``[8..16]``.
  401. The default is 16 (128 bits).
  402. Any other keyword will be passed to the underlying block cipher.
  403. See the relevant documentation for details (at least ``key`` will need
  404. to be present).
  405. """
  406. try:
  407. nonce = kwargs.pop("nonce", None)
  408. if nonce is None:
  409. nonce = get_random_bytes(15)
  410. mac_len = kwargs.pop("mac_len", 16)
  411. except KeyError as e:
  412. raise TypeError("Keyword missing: " + str(e))
  413. return OcbMode(factory, nonce, mac_len, kwargs)