_mode_gcm.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  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. Galois/Counter Mode (GCM).
  32. """
  33. __all__ = ['GcmMode']
  34. from binascii import 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.Hash import BLAKE2s
  39. from tls.Crypto.Random import get_random_bytes
  40. from tls.Crypto.Util._raw_api import (load_pycryptodome_raw_lib, VoidPointer,
  41. create_string_buffer, get_raw_buffer,
  42. SmartPointer, c_size_t, c_uint8_ptr)
  43. from tls.Crypto.Util import _cpu_features
  44. # C API by module implementing GHASH
  45. _ghash_api_template = """
  46. int ghash_%imp%(uint8_t y_out[16],
  47. const uint8_t block_data[],
  48. size_t len,
  49. const uint8_t y_in[16],
  50. const void *exp_key);
  51. int ghash_expand_%imp%(const uint8_t h[16],
  52. void **ghash_tables);
  53. int ghash_destroy_%imp%(void *ghash_tables);
  54. """
  55. def _build_impl(lib, postfix):
  56. from collections import namedtuple
  57. funcs = ( "ghash", "ghash_expand", "ghash_destroy" )
  58. GHASH_Imp = namedtuple('_GHash_Imp', funcs)
  59. try:
  60. imp_funcs = [ getattr(lib, x + "_" + postfix) for x in funcs ]
  61. except AttributeError: # Make sphinx stop complaining with its mocklib
  62. imp_funcs = [ None ] * 3
  63. params = dict(zip(funcs, imp_funcs))
  64. return GHASH_Imp(**params)
  65. def _get_ghash_portable():
  66. api = _ghash_api_template.replace("%imp%", "portable")
  67. lib = load_pycryptodome_raw_lib("Crypto.Hash._ghash_portable", api)
  68. result = _build_impl(lib, "portable")
  69. return result
  70. _ghash_portable = _get_ghash_portable()
  71. def _get_ghash_clmul():
  72. """Return None if CLMUL implementation is not available"""
  73. if not _cpu_features.have_clmul():
  74. return None
  75. try:
  76. api = _ghash_api_template.replace("%imp%", "clmul")
  77. lib = load_pycryptodome_raw_lib("Crypto.Hash._ghash_clmul", api)
  78. result = _build_impl(lib, "clmul")
  79. except OSError:
  80. result = None
  81. return result
  82. _ghash_clmul = _get_ghash_clmul()
  83. class _GHASH(object):
  84. """GHASH function defined in NIST SP 800-38D, Algorithm 2.
  85. If X_1, X_2, .. X_m are the blocks of input data, the function
  86. computes:
  87. X_1*H^{m} + X_2*H^{m-1} + ... + X_m*H
  88. in the Galois field GF(2^256) using the reducing polynomial
  89. (x^128 + x^7 + x^2 + x + 1).
  90. """
  91. def __init__(self, subkey, ghash_c):
  92. assert len(subkey) == 16
  93. self.ghash_c = ghash_c
  94. self._exp_key = VoidPointer()
  95. result = ghash_c.ghash_expand(c_uint8_ptr(subkey),
  96. self._exp_key.address_of())
  97. if result:
  98. raise ValueError("Error %d while expanding the GHASH key" % result)
  99. self._exp_key = SmartPointer(self._exp_key.get(),
  100. ghash_c.ghash_destroy)
  101. # create_string_buffer always returns a string of zeroes
  102. self._last_y = create_string_buffer(16)
  103. def update(self, block_data):
  104. assert len(block_data) % 16 == 0
  105. result = self.ghash_c.ghash(self._last_y,
  106. c_uint8_ptr(block_data),
  107. c_size_t(len(block_data)),
  108. self._last_y,
  109. self._exp_key.get())
  110. if result:
  111. raise ValueError("Error %d while updating GHASH" % result)
  112. return self
  113. def digest(self):
  114. return get_raw_buffer(self._last_y)
  115. def enum(**enums):
  116. return type('Enum', (), enums)
  117. MacStatus = enum(PROCESSING_AUTH_DATA=1, PROCESSING_CIPHERTEXT=2)
  118. class GcmMode(object):
  119. """Galois Counter Mode (GCM).
  120. This is an Authenticated Encryption with Associated Data (`AEAD`_) mode.
  121. It provides both confidentiality and authenticity.
  122. The header of the message may be left in the clear, if needed, and it will
  123. still be subject to authentication. The decryption step tells the receiver
  124. if the message comes from a source that really knowns the secret key.
  125. Additionally, decryption detects if any part of the message - including the
  126. header - has been modified or corrupted.
  127. This mode requires a *nonce*.
  128. This mode is only available for ciphers that operate on 128 bits blocks
  129. (e.g. AES but not TDES).
  130. See `NIST SP800-38D`_.
  131. .. _`NIST SP800-38D`: http://csrc.nist.gov/publications/nistpubs/800-38D/SP-800-38D.pdf
  132. .. _AEAD: http://blog.cryptographyengineering.com/2012/05/how-to-choose-authenticated-encryption.html
  133. :undocumented: __init__
  134. """
  135. def __init__(self, factory, key, nonce, mac_len, cipher_params, ghash_c):
  136. self.block_size = factory.block_size
  137. if self.block_size != 16:
  138. raise ValueError("GCM mode is only available for ciphers"
  139. " that operate on 128 bits blocks")
  140. if len(nonce) == 0:
  141. raise ValueError("Nonce cannot be empty")
  142. if not is_buffer(nonce):
  143. raise TypeError("Nonce must be bytes, bytearray or memoryview")
  144. # See NIST SP 800 38D, 5.2.1.1
  145. if len(nonce) > 2**64 - 1:
  146. raise ValueError("Nonce exceeds maximum length")
  147. self.nonce = _copy_bytes(None, None, nonce)
  148. """Nonce"""
  149. self._factory = factory
  150. self._key = _copy_bytes(None, None, key)
  151. self._tag = None # Cache for MAC tag
  152. self._mac_len = mac_len
  153. if not (4 <= mac_len <= 16):
  154. raise ValueError("Parameter 'mac_len' must be in the range 4..16")
  155. # Allowed transitions after initialization
  156. self._next = [self.update, self.encrypt, self.decrypt,
  157. self.digest, self.verify]
  158. self._no_more_assoc_data = False
  159. # Length of associated data
  160. self._auth_len = 0
  161. # Length of the ciphertext or plaintext
  162. self._msg_len = 0
  163. # Step 1 in SP800-38D, Algorithm 4 (encryption) - Compute H
  164. # See also Algorithm 5 (decryption)
  165. hash_subkey = factory.new(key,
  166. self._factory.MODE_ECB,
  167. **cipher_params
  168. ).encrypt(b'\x00' * 16)
  169. # Step 2 - Compute J0
  170. if len(self.nonce) == 12:
  171. j0 = self.nonce + b"\x00\x00\x00\x01"
  172. else:
  173. fill = (16 - (len(nonce) % 16)) % 16 + 8
  174. ghash_in = (self.nonce +
  175. b'\x00' * fill +
  176. long_to_bytes(8 * len(nonce), 8))
  177. j0 = _GHASH(hash_subkey, ghash_c).update(ghash_in).digest()
  178. # Step 3 - Prepare GCTR cipher for encryption/decryption
  179. nonce_ctr = j0[:12]
  180. iv_ctr = (bytes_to_long(j0) + 1) & 0xFFFFFFFF
  181. self._cipher = factory.new(key,
  182. self._factory.MODE_CTR,
  183. initial_value=iv_ctr,
  184. nonce=nonce_ctr,
  185. **cipher_params)
  186. # Step 5 - Bootstrat GHASH
  187. self._signer = _GHASH(hash_subkey, ghash_c)
  188. # Step 6 - Prepare GCTR cipher for GMAC
  189. self._tag_cipher = factory.new(key,
  190. self._factory.MODE_CTR,
  191. initial_value=j0,
  192. nonce=b"",
  193. **cipher_params)
  194. # Cache for data to authenticate
  195. self._cache = b""
  196. self._status = MacStatus.PROCESSING_AUTH_DATA
  197. def update(self, assoc_data):
  198. """Protect associated data
  199. If there is any associated data, the caller has to invoke
  200. this function one or more times, before using
  201. ``decrypt`` or ``encrypt``.
  202. By *associated data* it is meant any data (e.g. packet headers) that
  203. will not be encrypted and will be transmitted in the clear.
  204. However, the receiver is still able to detect any modification to it.
  205. In GCM, the *associated data* is also called
  206. *additional authenticated data* (AAD).
  207. If there is no associated data, this method must not be called.
  208. The caller may split associated data in segments of any size, and
  209. invoke this method multiple times, each time with the next segment.
  210. :Parameters:
  211. assoc_data : bytes/bytearray/memoryview
  212. A piece of associated data. There are no restrictions on its size.
  213. """
  214. if self.update not in self._next:
  215. raise TypeError("update() can only be called"
  216. " immediately after initialization")
  217. self._next = [self.update, self.encrypt, self.decrypt,
  218. self.digest, self.verify]
  219. self._update(assoc_data)
  220. self._auth_len += len(assoc_data)
  221. # See NIST SP 800 38D, 5.2.1.1
  222. if self._auth_len > 2**64 - 1:
  223. raise ValueError("Additional Authenticated Data exceeds maximum length")
  224. return self
  225. def _update(self, data):
  226. assert(len(self._cache) < 16)
  227. if len(self._cache) > 0:
  228. filler = min(16 - len(self._cache), len(data))
  229. self._cache += _copy_bytes(None, filler, data)
  230. data = data[filler:]
  231. if len(self._cache) < 16:
  232. return
  233. # The cache is exactly one block
  234. self._signer.update(self._cache)
  235. self._cache = b""
  236. update_len = len(data) // 16 * 16
  237. self._cache = _copy_bytes(update_len, None, data)
  238. if update_len > 0:
  239. self._signer.update(data[:update_len])
  240. def _pad_cache_and_update(self):
  241. assert(len(self._cache) < 16)
  242. # The authenticated data A is concatenated to the minimum
  243. # number of zero bytes (possibly none) such that the
  244. # - ciphertext C is aligned to the 16 byte boundary.
  245. # See step 5 in section 7.1
  246. # - ciphertext C is aligned to the 16 byte boundary.
  247. # See step 6 in section 7.2
  248. len_cache = len(self._cache)
  249. if len_cache > 0:
  250. self._update(b'\x00' * (16 - len_cache))
  251. def encrypt(self, plaintext, output=None):
  252. """Encrypt data with the key and the parameters set at initialization.
  253. A cipher object is stateful: once you have encrypted a message
  254. you cannot encrypt (or decrypt) another message using the same
  255. object.
  256. The data to encrypt can be broken up in two or
  257. more pieces and `encrypt` can be called multiple times.
  258. That is, the statement:
  259. >>> c.encrypt(a) + c.encrypt(b)
  260. is equivalent to:
  261. >>> c.encrypt(a+b)
  262. This function does not add any padding to the plaintext.
  263. :Parameters:
  264. plaintext : bytes/bytearray/memoryview
  265. The piece of data to encrypt.
  266. It can be of any length.
  267. :Keywords:
  268. output : bytearray/memoryview
  269. The location where the ciphertext must be written to.
  270. If ``None``, the ciphertext is returned.
  271. :Return:
  272. If ``output`` is ``None``, the ciphertext as ``bytes``.
  273. Otherwise, ``None``.
  274. """
  275. if self.encrypt not in self._next:
  276. raise TypeError("encrypt() can only be called after"
  277. " initialization or an update()")
  278. self._next = [self.encrypt, self.digest]
  279. ciphertext = self._cipher.encrypt(plaintext, output=output)
  280. if self._status == MacStatus.PROCESSING_AUTH_DATA:
  281. self._pad_cache_and_update()
  282. self._status = MacStatus.PROCESSING_CIPHERTEXT
  283. self._update(ciphertext if output is None else output)
  284. self._msg_len += len(plaintext)
  285. # See NIST SP 800 38D, 5.2.1.1
  286. if self._msg_len > 2**39 - 256:
  287. raise ValueError("Plaintext exceeds maximum length")
  288. return ciphertext
  289. def decrypt(self, ciphertext, output=None):
  290. """Decrypt data with the key and the parameters set at initialization.
  291. A cipher object is stateful: once you have decrypted a message
  292. you cannot decrypt (or encrypt) another message with the same
  293. object.
  294. The data to decrypt can be broken up in two or
  295. more pieces and `decrypt` can be called multiple times.
  296. That is, the statement:
  297. >>> c.decrypt(a) + c.decrypt(b)
  298. is equivalent to:
  299. >>> c.decrypt(a+b)
  300. This function does not remove any padding from the plaintext.
  301. :Parameters:
  302. ciphertext : bytes/bytearray/memoryview
  303. The piece of data to decrypt.
  304. It can be of any length.
  305. :Keywords:
  306. output : bytearray/memoryview
  307. The location where the plaintext must be written to.
  308. If ``None``, the plaintext is returned.
  309. :Return:
  310. If ``output`` is ``None``, the plaintext as ``bytes``.
  311. Otherwise, ``None``.
  312. """
  313. if self.decrypt not in self._next:
  314. raise TypeError("decrypt() can only be called"
  315. " after initialization or an update()")
  316. self._next = [self.decrypt, self.verify]
  317. if self._status == MacStatus.PROCESSING_AUTH_DATA:
  318. self._pad_cache_and_update()
  319. self._status = MacStatus.PROCESSING_CIPHERTEXT
  320. self._update(ciphertext)
  321. self._msg_len += len(ciphertext)
  322. return self._cipher.decrypt(ciphertext, output=output)
  323. def digest(self):
  324. """Compute the *binary* MAC tag in an AEAD mode.
  325. The caller invokes this function at the very end.
  326. This method returns the MAC that shall be sent to the receiver,
  327. together with the ciphertext.
  328. :Return: the MAC, as a byte string.
  329. """
  330. if self.digest not in self._next:
  331. raise TypeError("digest() cannot be called when decrypting"
  332. " or validating a message")
  333. self._next = [self.digest]
  334. return self._compute_mac()
  335. def _compute_mac(self):
  336. """Compute MAC without any FSM checks."""
  337. if self._tag:
  338. return self._tag
  339. # Step 5 in NIST SP 800-38D, Algorithm 4 - Compute S
  340. self._pad_cache_and_update()
  341. self._update(long_to_bytes(8 * self._auth_len, 8))
  342. self._update(long_to_bytes(8 * self._msg_len, 8))
  343. s_tag = self._signer.digest()
  344. # Step 6 - Compute T
  345. self._tag = self._tag_cipher.encrypt(s_tag)[:self._mac_len]
  346. return self._tag
  347. def hexdigest(self):
  348. """Compute the *printable* MAC tag.
  349. This method is like `digest`.
  350. :Return: the MAC, as a hexadecimal string.
  351. """
  352. return "".join(["%02x" % bord(x) for x in self.digest()])
  353. def verify(self, received_mac_tag):
  354. """Validate the *binary* MAC tag.
  355. The caller invokes this function at the very end.
  356. This method checks if the decrypted message is indeed valid
  357. (that is, if the key is correct) and it has not been
  358. tampered with while in transit.
  359. :Parameters:
  360. received_mac_tag : bytes/bytearray/memoryview
  361. This is the *binary* 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. if self.verify not in self._next:
  367. raise TypeError("verify() cannot be called"
  368. " when encrypting a message")
  369. self._next = [self.verify]
  370. secret = get_random_bytes(16)
  371. mac1 = BLAKE2s.new(digest_bits=160, key=secret,
  372. data=self._compute_mac())
  373. mac2 = BLAKE2s.new(digest_bits=160, key=secret,
  374. data=received_mac_tag)
  375. if mac1.digest() != mac2.digest():
  376. raise ValueError("MAC check failed")
  377. def hexverify(self, hex_mac_tag):
  378. """Validate the *printable* MAC tag.
  379. This method is like `verify`.
  380. :Parameters:
  381. hex_mac_tag : string
  382. This is the *printable* MAC, as received from the sender.
  383. :Raises ValueError:
  384. if the MAC does not match. The message has been tampered with
  385. or the key is incorrect.
  386. """
  387. self.verify(unhexlify(hex_mac_tag))
  388. def encrypt_and_digest(self, plaintext, output=None):
  389. """Perform encrypt() and digest() in one step.
  390. :Parameters:
  391. plaintext : bytes/bytearray/memoryview
  392. The piece of data to encrypt.
  393. :Keywords:
  394. output : bytearray/memoryview
  395. The location where the ciphertext must be written to.
  396. If ``None``, the ciphertext is returned.
  397. :Return:
  398. a tuple with two items:
  399. - the ciphertext, as ``bytes``
  400. - the MAC tag, as ``bytes``
  401. The first item becomes ``None`` when the ``output`` parameter
  402. specified a location for the result.
  403. """
  404. return self.encrypt(plaintext, output=output), self.digest()
  405. def decrypt_and_verify(self, ciphertext, received_mac_tag, output=None):
  406. """Perform decrypt() and verify() in one step.
  407. :Parameters:
  408. ciphertext : bytes/bytearray/memoryview
  409. The piece of data to decrypt.
  410. received_mac_tag : byte string
  411. This is the *binary* MAC, as received from the sender.
  412. :Keywords:
  413. output : bytearray/memoryview
  414. The location where the plaintext must be written to.
  415. If ``None``, the plaintext is returned.
  416. :Return: the plaintext as ``bytes`` or ``None`` when the ``output``
  417. parameter specified a location for the result.
  418. :Raises ValueError:
  419. if the MAC does not match. The message has been tampered with
  420. or the key is incorrect.
  421. """
  422. plaintext = self.decrypt(ciphertext, output=output)
  423. self.verify(received_mac_tag)
  424. return plaintext
  425. def _create_gcm_cipher(factory, **kwargs):
  426. """Create a new block cipher, configured in Galois Counter Mode (GCM).
  427. :Parameters:
  428. factory : module
  429. A block cipher module, taken from `Crypto.Cipher`.
  430. The cipher must have block length of 16 bytes.
  431. GCM has been only defined for `Crypto.Cipher.AES`.
  432. :Keywords:
  433. key : bytes/bytearray/memoryview
  434. The secret key to use in the symmetric cipher.
  435. It must be 16 (e.g. *AES-128*), 24 (e.g. *AES-192*)
  436. or 32 (e.g. *AES-256*) bytes long.
  437. nonce : bytes/bytearray/memoryview
  438. A value that must never be reused for any other encryption.
  439. There are no restrictions on its length,
  440. but it is recommended to use at least 16 bytes.
  441. The nonce shall never repeat for two
  442. different messages encrypted with the same key,
  443. but it does not need to be random.
  444. If not provided, a 16 byte nonce will be randomly created.
  445. mac_len : integer
  446. Length of the MAC, in bytes.
  447. It must be no larger than 16 bytes (which is the default).
  448. """
  449. try:
  450. key = kwargs.pop("key")
  451. except KeyError as e:
  452. raise TypeError("Missing parameter:" + str(e))
  453. nonce = kwargs.pop("nonce", None)
  454. if nonce is None:
  455. nonce = get_random_bytes(16)
  456. mac_len = kwargs.pop("mac_len", 16)
  457. # Not documented - only used for testing
  458. use_clmul = kwargs.pop("use_clmul", True)
  459. if use_clmul and _ghash_clmul:
  460. ghash_c = _ghash_clmul
  461. else:
  462. ghash_c = _ghash_portable
  463. return GcmMode(factory, key, nonce, mac_len, kwargs, ghash_c)