ciphers.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. # This file is dual licensed under the terms of the Apache License, Version
  2. # 2.0, and the BSD License. See the LICENSE file in the root of this repository
  3. # for complete details.
  4. from __future__ import absolute_import, division, print_function
  5. from cryptography import utils
  6. from cryptography.exceptions import InvalidTag, UnsupportedAlgorithm, _Reasons
  7. from cryptography.hazmat.primitives import ciphers
  8. from cryptography.hazmat.primitives.ciphers import modes
  9. @utils.register_interface(ciphers.CipherContext)
  10. @utils.register_interface(ciphers.AEADCipherContext)
  11. @utils.register_interface(ciphers.AEADEncryptionContext)
  12. @utils.register_interface(ciphers.AEADDecryptionContext)
  13. class _CipherContext(object):
  14. _ENCRYPT = 1
  15. _DECRYPT = 0
  16. _MAX_CHUNK_SIZE = 2 ** 31 - 1
  17. def __init__(self, backend, cipher, mode, operation):
  18. self._backend = backend
  19. self._cipher = cipher
  20. self._mode = mode
  21. self._operation = operation
  22. self._tag = None
  23. if isinstance(self._cipher, ciphers.BlockCipherAlgorithm):
  24. self._block_size_bytes = self._cipher.block_size // 8
  25. else:
  26. self._block_size_bytes = 1
  27. ctx = self._backend._lib.EVP_CIPHER_CTX_new()
  28. ctx = self._backend._ffi.gc(
  29. ctx, self._backend._lib.EVP_CIPHER_CTX_free
  30. )
  31. registry = self._backend._cipher_registry
  32. try:
  33. adapter = registry[type(cipher), type(mode)]
  34. except KeyError:
  35. raise UnsupportedAlgorithm(
  36. "cipher {} in {} mode is not supported "
  37. "by this backend.".format(
  38. cipher.name, mode.name if mode else mode
  39. ),
  40. _Reasons.UNSUPPORTED_CIPHER,
  41. )
  42. evp_cipher = adapter(self._backend, cipher, mode)
  43. if evp_cipher == self._backend._ffi.NULL:
  44. msg = "cipher {0.name} ".format(cipher)
  45. if mode is not None:
  46. msg += "in {0.name} mode ".format(mode)
  47. msg += (
  48. "is not supported by this backend (Your version of OpenSSL "
  49. "may be too old. Current version: {}.)"
  50. ).format(self._backend.openssl_version_text())
  51. raise UnsupportedAlgorithm(msg, _Reasons.UNSUPPORTED_CIPHER)
  52. if isinstance(mode, modes.ModeWithInitializationVector):
  53. iv_nonce = self._backend._ffi.from_buffer(
  54. mode.initialization_vector
  55. )
  56. elif isinstance(mode, modes.ModeWithTweak):
  57. iv_nonce = self._backend._ffi.from_buffer(mode.tweak)
  58. elif isinstance(mode, modes.ModeWithNonce):
  59. iv_nonce = self._backend._ffi.from_buffer(mode.nonce)
  60. elif isinstance(cipher, modes.ModeWithNonce):
  61. iv_nonce = self._backend._ffi.from_buffer(cipher.nonce)
  62. else:
  63. iv_nonce = self._backend._ffi.NULL
  64. # begin init with cipher and operation type
  65. res = self._backend._lib.EVP_CipherInit_ex(
  66. ctx,
  67. evp_cipher,
  68. self._backend._ffi.NULL,
  69. self._backend._ffi.NULL,
  70. self._backend._ffi.NULL,
  71. operation,
  72. )
  73. self._backend.openssl_assert(res != 0)
  74. # set the key length to handle variable key ciphers
  75. res = self._backend._lib.EVP_CIPHER_CTX_set_key_length(
  76. ctx, len(cipher.key)
  77. )
  78. self._backend.openssl_assert(res != 0)
  79. if isinstance(mode, modes.GCM):
  80. res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
  81. ctx,
  82. self._backend._lib.EVP_CTRL_AEAD_SET_IVLEN,
  83. len(iv_nonce),
  84. self._backend._ffi.NULL,
  85. )
  86. self._backend.openssl_assert(res != 0)
  87. if mode.tag is not None:
  88. res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
  89. ctx,
  90. self._backend._lib.EVP_CTRL_AEAD_SET_TAG,
  91. len(mode.tag),
  92. mode.tag,
  93. )
  94. self._backend.openssl_assert(res != 0)
  95. self._tag = mode.tag
  96. # pass key/iv
  97. res = self._backend._lib.EVP_CipherInit_ex(
  98. ctx,
  99. self._backend._ffi.NULL,
  100. self._backend._ffi.NULL,
  101. self._backend._ffi.from_buffer(cipher.key),
  102. iv_nonce,
  103. operation,
  104. )
  105. self._backend.openssl_assert(res != 0)
  106. # We purposely disable padding here as it's handled higher up in the
  107. # API.
  108. self._backend._lib.EVP_CIPHER_CTX_set_padding(ctx, 0)
  109. self._ctx = ctx
  110. def update(self, data):
  111. buf = bytearray(len(data) + self._block_size_bytes - 1)
  112. n = self.update_into(data, buf)
  113. return bytes(buf[:n])
  114. def update_into(self, data, buf):
  115. total_data_len = len(data)
  116. if len(buf) < (total_data_len + self._block_size_bytes - 1):
  117. raise ValueError(
  118. "buffer must be at least {} bytes for this "
  119. "payload".format(len(data) + self._block_size_bytes - 1)
  120. )
  121. data_processed = 0
  122. total_out = 0
  123. outlen = self._backend._ffi.new("int *")
  124. baseoutbuf = self._backend._ffi.from_buffer(buf)
  125. baseinbuf = self._backend._ffi.from_buffer(data)
  126. while data_processed != total_data_len:
  127. outbuf = baseoutbuf + total_out
  128. inbuf = baseinbuf + data_processed
  129. inlen = min(self._MAX_CHUNK_SIZE, total_data_len - data_processed)
  130. res = self._backend._lib.EVP_CipherUpdate(
  131. self._ctx, outbuf, outlen, inbuf, inlen
  132. )
  133. self._backend.openssl_assert(res != 0)
  134. data_processed += inlen
  135. total_out += outlen[0]
  136. return total_out
  137. def finalize(self):
  138. if (
  139. self._operation == self._DECRYPT
  140. and isinstance(self._mode, modes.ModeWithAuthenticationTag)
  141. and self.tag is None
  142. ):
  143. raise ValueError(
  144. "Authentication tag must be provided when decrypting."
  145. )
  146. buf = self._backend._ffi.new("unsigned char[]", self._block_size_bytes)
  147. outlen = self._backend._ffi.new("int *")
  148. res = self._backend._lib.EVP_CipherFinal_ex(self._ctx, buf, outlen)
  149. if res == 0:
  150. errors = self._backend._consume_errors()
  151. if not errors and isinstance(self._mode, modes.GCM):
  152. raise InvalidTag
  153. self._backend.openssl_assert(
  154. errors[0]._lib_reason_match(
  155. self._backend._lib.ERR_LIB_EVP,
  156. self._backend._lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH,
  157. ),
  158. errors=errors,
  159. )
  160. raise ValueError(
  161. "The length of the provided data is not a multiple of "
  162. "the block length."
  163. )
  164. if (
  165. isinstance(self._mode, modes.GCM)
  166. and self._operation == self._ENCRYPT
  167. ):
  168. tag_buf = self._backend._ffi.new(
  169. "unsigned char[]", self._block_size_bytes
  170. )
  171. res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
  172. self._ctx,
  173. self._backend._lib.EVP_CTRL_AEAD_GET_TAG,
  174. self._block_size_bytes,
  175. tag_buf,
  176. )
  177. self._backend.openssl_assert(res != 0)
  178. self._tag = self._backend._ffi.buffer(tag_buf)[:]
  179. res = self._backend._lib.EVP_CIPHER_CTX_cleanup(self._ctx)
  180. self._backend.openssl_assert(res == 1)
  181. return self._backend._ffi.buffer(buf)[: outlen[0]]
  182. def finalize_with_tag(self, tag):
  183. if len(tag) < self._mode._min_tag_length:
  184. raise ValueError(
  185. "Authentication tag must be {} bytes or longer.".format(
  186. self._mode._min_tag_length
  187. )
  188. )
  189. res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
  190. self._ctx, self._backend._lib.EVP_CTRL_AEAD_SET_TAG, len(tag), tag
  191. )
  192. self._backend.openssl_assert(res != 0)
  193. self._tag = tag
  194. return self.finalize()
  195. def authenticate_additional_data(self, data):
  196. outlen = self._backend._ffi.new("int *")
  197. res = self._backend._lib.EVP_CipherUpdate(
  198. self._ctx,
  199. self._backend._ffi.NULL,
  200. outlen,
  201. self._backend._ffi.from_buffer(data),
  202. len(data),
  203. )
  204. self._backend.openssl_assert(res != 0)
  205. tag = utils.read_only_property("_tag")