_mode_siv.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. Synthetic Initialization Vector (SIV) mode.
  32. """
  33. __all__ = ['SivMode']
  34. from binascii import hexlify, unhexlify
  35. from tls.Crypto.Util.py3compat import bord, _copy_bytes
  36. from tls.Crypto.Util._raw_api import is_buffer
  37. from tls.Crypto.Util.number import long_to_bytes, bytes_to_long
  38. from tls.Crypto.Protocol.KDF import _S2V
  39. from tls.Crypto.Hash import BLAKE2s
  40. from tls.Crypto.Random import get_random_bytes
  41. class SivMode(object):
  42. """Synthetic Initialization Vector (SIV).
  43. This is an Authenticated Encryption with Associated Data (`AEAD`_) mode.
  44. It provides both confidentiality and authenticity.
  45. The header of the message may be left in the clear, if needed, and it will
  46. still be subject to authentication. The decryption step tells the receiver
  47. if the message comes from a source that really knowns the secret key.
  48. Additionally, decryption detects if any part of the message - including the
  49. header - has been modified or corrupted.
  50. Unlike other AEAD modes such as CCM, EAX or GCM, accidental reuse of a
  51. nonce is not catastrophic for the confidentiality of the message. The only
  52. effect is that an attacker can tell when the same plaintext (and same
  53. associated data) is protected with the same key.
  54. The length of the MAC is fixed to the block size of the underlying cipher.
  55. The key size is twice the length of the key of the underlying cipher.
  56. This mode is only available for AES ciphers.
  57. +--------------------+---------------+-------------------+
  58. | Cipher | SIV MAC size | SIV key length |
  59. | | (bytes) | (bytes) |
  60. +====================+===============+===================+
  61. | AES-128 | 16 | 32 |
  62. +--------------------+---------------+-------------------+
  63. | AES-192 | 16 | 48 |
  64. +--------------------+---------------+-------------------+
  65. | AES-256 | 16 | 64 |
  66. +--------------------+---------------+-------------------+
  67. See `RFC5297`_ and the `original paper`__.
  68. .. _RFC5297: https://tools.ietf.org/html/rfc5297
  69. .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html
  70. .. __: http://www.cs.ucdavis.edu/~rogaway/papers/keywrap.pdf
  71. :undocumented: __init__
  72. """
  73. def __init__(self, factory, key, nonce, kwargs):
  74. self.block_size = factory.block_size
  75. """The block size of the underlying cipher, in bytes."""
  76. self._factory = factory
  77. self._cipher_params = kwargs
  78. if len(key) not in (32, 48, 64):
  79. raise ValueError("Incorrect key length (%d bytes)" % len(key))
  80. if nonce is not None:
  81. if not is_buffer(nonce):
  82. raise TypeError("When provided, the nonce must be bytes, bytearray or memoryview")
  83. if len(nonce) == 0:
  84. raise ValueError("When provided, the nonce must be non-empty")
  85. self.nonce = _copy_bytes(None, None, nonce)
  86. """Public attribute is only available in case of non-deterministic
  87. encryption."""
  88. subkey_size = len(key) // 2
  89. self._mac_tag = None # Cache for MAC tag
  90. self._kdf = _S2V(key[:subkey_size],
  91. ciphermod=factory,
  92. cipher_params=self._cipher_params)
  93. self._subkey_cipher = key[subkey_size:]
  94. # Purely for the purpose of verifying that cipher_params are OK
  95. factory.new(key[:subkey_size], factory.MODE_ECB, **kwargs)
  96. # Allowed transitions after initialization
  97. self._next = [self.update, self.encrypt, self.decrypt,
  98. self.digest, self.verify]
  99. def _create_ctr_cipher(self, v):
  100. """Create a new CTR cipher from V in SIV mode"""
  101. v_int = bytes_to_long(v)
  102. q = v_int & 0xFFFFFFFFFFFFFFFF7FFFFFFF7FFFFFFF
  103. return self._factory.new(
  104. self._subkey_cipher,
  105. self._factory.MODE_CTR,
  106. initial_value=q,
  107. nonce=b"",
  108. **self._cipher_params)
  109. def update(self, component):
  110. """Protect one associated data component
  111. For SIV, the associated data is a sequence (*vector*) of non-empty
  112. byte strings (*components*).
  113. This method consumes the next component. It must be called
  114. once for each of the components that constitue the associated data.
  115. Note that the components have clear boundaries, so that:
  116. >>> cipher.update(b"builtin")
  117. >>> cipher.update(b"securely")
  118. is not equivalent to:
  119. >>> cipher.update(b"built")
  120. >>> cipher.update(b"insecurely")
  121. If there is no associated data, this method must not be called.
  122. :Parameters:
  123. component : bytes/bytearray/memoryview
  124. The next associated data component.
  125. """
  126. if self.update not in self._next:
  127. raise TypeError("update() can only be called"
  128. " immediately after initialization")
  129. self._next = [self.update, self.encrypt, self.decrypt,
  130. self.digest, self.verify]
  131. return self._kdf.update(component)
  132. def encrypt(self, plaintext):
  133. """
  134. For SIV, encryption and MAC authentication must take place at the same
  135. point. This method shall not be used.
  136. Use `encrypt_and_digest` instead.
  137. """
  138. raise TypeError("encrypt() not allowed for SIV mode."
  139. " Use encrypt_and_digest() instead.")
  140. def decrypt(self, ciphertext):
  141. """
  142. For SIV, decryption and verification must take place at the same
  143. point. This method shall not be used.
  144. Use `decrypt_and_verify` instead.
  145. """
  146. raise TypeError("decrypt() not allowed for SIV mode."
  147. " Use decrypt_and_verify() instead.")
  148. def digest(self):
  149. """Compute the *binary* MAC tag.
  150. The caller invokes this function at the very end.
  151. This method returns the MAC that shall be sent to the receiver,
  152. together with the ciphertext.
  153. :Return: the MAC, as a byte string.
  154. """
  155. if self.digest not in self._next:
  156. raise TypeError("digest() cannot be called when decrypting"
  157. " or validating a message")
  158. self._next = [self.digest]
  159. if self._mac_tag is None:
  160. self._mac_tag = self._kdf.derive()
  161. return self._mac_tag
  162. def hexdigest(self):
  163. """Compute the *printable* MAC tag.
  164. This method is like `digest`.
  165. :Return: the MAC, as a hexadecimal string.
  166. """
  167. return "".join(["%02x" % bord(x) for x in self.digest()])
  168. def verify(self, received_mac_tag):
  169. """Validate the *binary* MAC tag.
  170. The caller invokes this function at the very end.
  171. This method checks if the decrypted message is indeed valid
  172. (that is, if the key is correct) and it has not been
  173. tampered with while in transit.
  174. :Parameters:
  175. received_mac_tag : bytes/bytearray/memoryview
  176. This is the *binary* MAC, as received from the sender.
  177. :Raises ValueError:
  178. if the MAC does not match. The message has been tampered with
  179. or the key is incorrect.
  180. """
  181. if self.verify not in self._next:
  182. raise TypeError("verify() cannot be called"
  183. " when encrypting a message")
  184. self._next = [self.verify]
  185. if self._mac_tag is None:
  186. self._mac_tag = self._kdf.derive()
  187. secret = get_random_bytes(16)
  188. mac1 = BLAKE2s.new(digest_bits=160, key=secret, data=self._mac_tag)
  189. mac2 = BLAKE2s.new(digest_bits=160, key=secret, data=received_mac_tag)
  190. if mac1.digest() != mac2.digest():
  191. raise ValueError("MAC check failed")
  192. def hexverify(self, hex_mac_tag):
  193. """Validate the *printable* MAC tag.
  194. This method is like `verify`.
  195. :Parameters:
  196. hex_mac_tag : string
  197. This is the *printable* MAC, as received from the sender.
  198. :Raises ValueError:
  199. if the MAC does not match. The message has been tampered with
  200. or the key is incorrect.
  201. """
  202. self.verify(unhexlify(hex_mac_tag))
  203. def encrypt_and_digest(self, plaintext, output=None):
  204. """Perform encrypt() and digest() in one step.
  205. :Parameters:
  206. plaintext : bytes/bytearray/memoryview
  207. The piece of data to encrypt.
  208. :Keywords:
  209. output : bytearray/memoryview
  210. The location where the ciphertext must be written to.
  211. If ``None``, the ciphertext is returned.
  212. :Return:
  213. a tuple with two items:
  214. - the ciphertext, as ``bytes``
  215. - the MAC tag, as ``bytes``
  216. The first item becomes ``None`` when the ``output`` parameter
  217. specified a location for the result.
  218. """
  219. if self.encrypt not in self._next:
  220. raise TypeError("encrypt() can only be called after"
  221. " initialization or an update()")
  222. self._next = [ self.digest ]
  223. # Compute V (MAC)
  224. if hasattr(self, 'nonce'):
  225. self._kdf.update(self.nonce)
  226. self._kdf.update(plaintext)
  227. self._mac_tag = self._kdf.derive()
  228. cipher = self._create_ctr_cipher(self._mac_tag)
  229. return cipher.encrypt(plaintext, output=output), self._mac_tag
  230. def decrypt_and_verify(self, ciphertext, mac_tag, output=None):
  231. """Perform decryption and verification in one step.
  232. A cipher object is stateful: once you have decrypted a message
  233. you cannot decrypt (or encrypt) another message with the same
  234. object.
  235. You cannot reuse an object for encrypting
  236. or decrypting other data with the same key.
  237. This function does not remove any padding from the plaintext.
  238. :Parameters:
  239. ciphertext : bytes/bytearray/memoryview
  240. The piece of data to decrypt.
  241. It can be of any length.
  242. mac_tag : bytes/bytearray/memoryview
  243. This is the *binary* MAC, as received from the sender.
  244. :Keywords:
  245. output : bytearray/memoryview
  246. The location where the plaintext must be written to.
  247. If ``None``, the plaintext is returned.
  248. :Return: the plaintext as ``bytes`` or ``None`` when the ``output``
  249. parameter specified a location for the result.
  250. :Raises ValueError:
  251. if the MAC does not match. The message has been tampered with
  252. or the key is incorrect.
  253. """
  254. if self.decrypt not in self._next:
  255. raise TypeError("decrypt() can only be called"
  256. " after initialization or an update()")
  257. self._next = [ self.verify ]
  258. # Take the MAC and start the cipher for decryption
  259. self._cipher = self._create_ctr_cipher(mac_tag)
  260. plaintext = self._cipher.decrypt(ciphertext, output=output)
  261. if hasattr(self, 'nonce'):
  262. self._kdf.update(self.nonce)
  263. self._kdf.update(plaintext if output is None else output)
  264. self.verify(mac_tag)
  265. return plaintext
  266. def _create_siv_cipher(factory, **kwargs):
  267. """Create a new block cipher, configured in
  268. Synthetic Initializaton Vector (SIV) mode.
  269. :Parameters:
  270. factory : object
  271. A symmetric cipher module from `Crypto.Cipher`
  272. (like `Crypto.Cipher.AES`).
  273. :Keywords:
  274. key : bytes/bytearray/memoryview
  275. The secret key to use in the symmetric cipher.
  276. It must be 32, 48 or 64 bytes long.
  277. If AES is the chosen cipher, the variants *AES-128*,
  278. *AES-192* and or *AES-256* will be used internally.
  279. nonce : bytes/bytearray/memoryview
  280. For deterministic encryption, it is not present.
  281. Otherwise, it is a value that must never be reused
  282. for encrypting message under this key.
  283. There are no restrictions on its length,
  284. but it is recommended to use at least 16 bytes.
  285. """
  286. try:
  287. key = kwargs.pop("key")
  288. except KeyError as e:
  289. raise TypeError("Missing parameter: " + str(e))
  290. nonce = kwargs.pop("nonce", None)
  291. return SivMode(factory, key, nonce, kwargs)