_mode_eax.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  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. EAX mode.
  32. """
  33. __all__ = ['EaxMode']
  34. import struct
  35. from binascii import unhexlify
  36. from tls.Crypto.Util.py3compat import byte_string, bord, _copy_bytes
  37. from tls.Crypto.Util._raw_api import is_buffer
  38. from tls.Crypto.Util.strxor import strxor
  39. from tls.Crypto.Util.number import long_to_bytes, bytes_to_long
  40. from tls.Crypto.Hash import CMAC, BLAKE2s
  41. from tls.Crypto.Random import get_random_bytes
  42. class EaxMode(object):
  43. """*EAX* mode.
  44. This is an Authenticated Encryption with Associated Data
  45. (`AEAD`_) mode. It provides both confidentiality and authenticity.
  46. The header of the message may be left in the clear, if needed,
  47. and it will still be subject to authentication.
  48. The decryption step tells the receiver if the message comes
  49. from a source that really knowns the secret key.
  50. Additionally, decryption detects if any part of the message -
  51. including the header - has been modified or corrupted.
  52. This mode requires a *nonce*.
  53. This mode is only available for ciphers that operate on 64 or
  54. 128 bits blocks.
  55. There are no official standards defining EAX.
  56. The implementation is based on `a proposal`__ that
  57. was presented to NIST.
  58. .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html
  59. .. __: http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/eax/eax-spec.pdf
  60. :undocumented: __init__
  61. """
  62. def __init__(self, factory, key, nonce, mac_len, cipher_params):
  63. """EAX cipher mode"""
  64. self.block_size = factory.block_size
  65. """The block size of the underlying cipher, in bytes."""
  66. self.nonce = _copy_bytes(None, None, nonce)
  67. """The nonce originally used to create the object."""
  68. self._mac_len = mac_len
  69. self._mac_tag = None # Cache for MAC tag
  70. # Allowed transitions after initialization
  71. self._next = [self.update, self.encrypt, self.decrypt,
  72. self.digest, self.verify]
  73. # MAC tag length
  74. if not (4 <= self._mac_len <= self.block_size):
  75. raise ValueError("Parameter 'mac_len' must not be larger than %d"
  76. % self.block_size)
  77. # Nonce cannot be empty and must be a byte string
  78. if len(self.nonce) == 0:
  79. raise ValueError("Nonce cannot be empty in EAX mode")
  80. if not is_buffer(nonce):
  81. raise TypeError("nonce must be bytes, bytearray or memoryview")
  82. self._omac = [
  83. CMAC.new(key,
  84. b'\x00' * (self.block_size - 1) + struct.pack('B', i),
  85. ciphermod=factory,
  86. cipher_params=cipher_params)
  87. for i in range(0, 3)
  88. ]
  89. # Compute MAC of nonce
  90. self._omac[0].update(self.nonce)
  91. self._signer = self._omac[1]
  92. # MAC of the nonce is also the initial counter for CTR encryption
  93. counter_int = bytes_to_long(self._omac[0].digest())
  94. self._cipher = factory.new(key,
  95. factory.MODE_CTR,
  96. initial_value=counter_int,
  97. nonce=b"",
  98. **cipher_params)
  99. def update(self, assoc_data):
  100. """Protect associated data
  101. If there is any associated data, the caller has to invoke
  102. this function one or more times, before using
  103. ``decrypt`` or ``encrypt``.
  104. By *associated data* it is meant any data (e.g. packet headers) that
  105. will not be encrypted and will be transmitted in the clear.
  106. However, the receiver is still able to detect any modification to it.
  107. If there is no associated data, this method must not be called.
  108. The caller may split associated data in segments of any size, and
  109. invoke this method multiple times, each time with the next segment.
  110. :Parameters:
  111. assoc_data : bytes/bytearray/memoryview
  112. A piece of associated data. There are no restrictions on its size.
  113. """
  114. if self.update not in self._next:
  115. raise TypeError("update() can only be called"
  116. " immediately after initialization")
  117. self._next = [self.update, self.encrypt, self.decrypt,
  118. self.digest, self.verify]
  119. self._signer.update(assoc_data)
  120. return self
  121. def encrypt(self, plaintext, output=None):
  122. """Encrypt data with the key and the parameters set at initialization.
  123. A cipher object is stateful: once you have encrypted a message
  124. you cannot encrypt (or decrypt) another message using the same
  125. object.
  126. The data to encrypt can be broken up in two or
  127. more pieces and `encrypt` can be called multiple times.
  128. That is, the statement:
  129. >>> c.encrypt(a) + c.encrypt(b)
  130. is equivalent to:
  131. >>> c.encrypt(a+b)
  132. This function does not add any padding to the plaintext.
  133. :Parameters:
  134. plaintext : bytes/bytearray/memoryview
  135. The piece of data to encrypt.
  136. It can be of any length.
  137. :Keywords:
  138. output : bytearray/memoryview
  139. The location where the ciphertext must be written to.
  140. If ``None``, the ciphertext is returned.
  141. :Return:
  142. If ``output`` is ``None``, the ciphertext as ``bytes``.
  143. Otherwise, ``None``.
  144. """
  145. if self.encrypt not in self._next:
  146. raise TypeError("encrypt() can only be called after"
  147. " initialization or an update()")
  148. self._next = [self.encrypt, self.digest]
  149. ct = self._cipher.encrypt(plaintext, output=output)
  150. if output is None:
  151. self._omac[2].update(ct)
  152. else:
  153. self._omac[2].update(output)
  154. return ct
  155. def decrypt(self, ciphertext, output=None):
  156. """Decrypt data with the key and the parameters set at initialization.
  157. A cipher object is stateful: once you have decrypted a message
  158. you cannot decrypt (or encrypt) another message with the same
  159. object.
  160. The data to decrypt can be broken up in two or
  161. more pieces and `decrypt` can be called multiple times.
  162. That is, the statement:
  163. >>> c.decrypt(a) + c.decrypt(b)
  164. is equivalent to:
  165. >>> c.decrypt(a+b)
  166. This function does not remove any padding from the plaintext.
  167. :Parameters:
  168. ciphertext : bytes/bytearray/memoryview
  169. The piece of data to decrypt.
  170. It can be of any length.
  171. :Keywords:
  172. output : bytearray/memoryview
  173. The location where the plaintext must be written to.
  174. If ``None``, the plaintext is returned.
  175. :Return:
  176. If ``output`` is ``None``, the plaintext as ``bytes``.
  177. Otherwise, ``None``.
  178. """
  179. if self.decrypt not in self._next:
  180. raise TypeError("decrypt() can only be called"
  181. " after initialization or an update()")
  182. self._next = [self.decrypt, self.verify]
  183. self._omac[2].update(ciphertext)
  184. return self._cipher.decrypt(ciphertext, output=output)
  185. def digest(self):
  186. """Compute the *binary* MAC tag.
  187. The caller invokes this function at the very end.
  188. This method returns the MAC that shall be sent to the receiver,
  189. together with the ciphertext.
  190. :Return: the MAC, as a byte string.
  191. """
  192. if self.digest not in self._next:
  193. raise TypeError("digest() cannot be called when decrypting"
  194. " or validating a message")
  195. self._next = [self.digest]
  196. if not self._mac_tag:
  197. tag = b'\x00' * self.block_size
  198. for i in range(3):
  199. tag = strxor(tag, self._omac[i].digest())
  200. self._mac_tag = tag[:self._mac_len]
  201. return self._mac_tag
  202. def hexdigest(self):
  203. """Compute the *printable* MAC tag.
  204. This method is like `digest`.
  205. :Return: the MAC, as a hexadecimal string.
  206. """
  207. return "".join(["%02x" % bord(x) for x in self.digest()])
  208. def verify(self, received_mac_tag):
  209. """Validate the *binary* MAC tag.
  210. The caller invokes this function at the very end.
  211. This method checks if the decrypted message is indeed valid
  212. (that is, if the key is correct) and it has not been
  213. tampered with while in transit.
  214. :Parameters:
  215. received_mac_tag : bytes/bytearray/memoryview
  216. This is the *binary* MAC, as received from the sender.
  217. :Raises MacMismatchError:
  218. if the MAC does not match. The message has been tampered with
  219. or the key is incorrect.
  220. """
  221. if self.verify not in self._next:
  222. raise TypeError("verify() cannot be called"
  223. " when encrypting a message")
  224. self._next = [self.verify]
  225. if not self._mac_tag:
  226. tag = b'\x00' * self.block_size
  227. for i in range(3):
  228. tag = strxor(tag, self._omac[i].digest())
  229. self._mac_tag = tag[:self._mac_len]
  230. secret = get_random_bytes(16)
  231. mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
  232. mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)
  233. if mac1.digest() != mac2.digest():
  234. raise ValueError("MAC check failed")
  235. def hexverify(self, hex_mac_tag):
  236. """Validate the *printable* MAC tag.
  237. This method is like `verify`.
  238. :Parameters:
  239. hex_mac_tag : string
  240. This is the *printable* MAC, as received from the sender.
  241. :Raises MacMismatchError:
  242. if the MAC does not match. The message has been tampered with
  243. or the key is incorrect.
  244. """
  245. self.verify(unhexlify(hex_mac_tag))
  246. def encrypt_and_digest(self, plaintext, output=None):
  247. """Perform encrypt() and digest() in one step.
  248. :Parameters:
  249. plaintext : bytes/bytearray/memoryview
  250. The piece of data to encrypt.
  251. :Keywords:
  252. output : bytearray/memoryview
  253. The location where the ciphertext must be written to.
  254. If ``None``, the ciphertext is returned.
  255. :Return:
  256. a tuple with two items:
  257. - the ciphertext, as ``bytes``
  258. - the MAC tag, as ``bytes``
  259. The first item becomes ``None`` when the ``output`` parameter
  260. specified a location for the result.
  261. """
  262. return self.encrypt(plaintext, output=output), self.digest()
  263. def decrypt_and_verify(self, ciphertext, received_mac_tag, output=None):
  264. """Perform decrypt() and verify() in one step.
  265. :Parameters:
  266. ciphertext : bytes/bytearray/memoryview
  267. The piece of data to decrypt.
  268. received_mac_tag : bytes/bytearray/memoryview
  269. This is the *binary* MAC, as received from the sender.
  270. :Keywords:
  271. output : bytearray/memoryview
  272. The location where the plaintext must be written to.
  273. If ``None``, the plaintext is returned.
  274. :Return: the plaintext as ``bytes`` or ``None`` when the ``output``
  275. parameter specified a location for the result.
  276. :Raises MacMismatchError:
  277. if the MAC does not match. The message has been tampered with
  278. or the key is incorrect.
  279. """
  280. pt = self.decrypt(ciphertext, output=output)
  281. self.verify(received_mac_tag)
  282. return pt
  283. def _create_eax_cipher(factory, **kwargs):
  284. """Create a new block cipher, configured in EAX mode.
  285. :Parameters:
  286. factory : module
  287. A symmetric cipher module from `Crypto.Cipher` (like
  288. `Crypto.Cipher.AES`).
  289. :Keywords:
  290. key : bytes/bytearray/memoryview
  291. The secret key to use in the symmetric cipher.
  292. nonce : bytes/bytearray/memoryview
  293. A value that must never be reused for any other encryption.
  294. There are no restrictions on its length, but it is recommended to use
  295. at least 16 bytes.
  296. The nonce shall never repeat for two different messages encrypted with
  297. the same key, but it does not need to be random.
  298. If not specified, a 16 byte long random string is used.
  299. mac_len : integer
  300. Length of the MAC, in bytes. It must be no larger than the cipher
  301. block bytes (which is the default).
  302. """
  303. try:
  304. key = kwargs.pop("key")
  305. nonce = kwargs.pop("nonce", None)
  306. if nonce is None:
  307. nonce = get_random_bytes(16)
  308. mac_len = kwargs.pop("mac_len", factory.block_size)
  309. except KeyError as e:
  310. raise TypeError("Missing parameter: " + str(e))
  311. return EaxMode(factory, key, nonce, mac_len, kwargs)