ciphers.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. import typing
  5. from cryptography.exceptions import InvalidTag, UnsupportedAlgorithm, _Reasons
  6. from cryptography.hazmat.primitives import ciphers
  7. from cryptography.hazmat.primitives.ciphers import algorithms, modes
  8. if typing.TYPE_CHECKING:
  9. from cryptography.hazmat.backends.openssl.backend import Backend
  10. class _CipherContext:
  11. _ENCRYPT = 1
  12. _DECRYPT = 0
  13. _MAX_CHUNK_SIZE = 2**30 - 1
  14. def __init__(
  15. self, backend: "Backend", cipher, mode, operation: int
  16. ) -> None:
  17. self._backend = backend
  18. self._cipher = cipher
  19. self._mode = mode
  20. self._operation = operation
  21. self._tag: typing.Optional[bytes] = None
  22. if isinstance(self._cipher, ciphers.BlockCipherAlgorithm):
  23. self._block_size_bytes = self._cipher.block_size // 8
  24. else:
  25. self._block_size_bytes = 1
  26. ctx = self._backend._lib.EVP_CIPHER_CTX_new()
  27. ctx = self._backend._ffi.gc(
  28. ctx, self._backend._lib.EVP_CIPHER_CTX_free
  29. )
  30. registry = self._backend._cipher_registry
  31. try:
  32. adapter = registry[type(cipher), type(mode)]
  33. except KeyError:
  34. raise UnsupportedAlgorithm(
  35. "cipher {} in {} mode is not supported "
  36. "by this backend.".format(
  37. cipher.name, mode.name if mode else mode
  38. ),
  39. _Reasons.UNSUPPORTED_CIPHER,
  40. )
  41. evp_cipher = adapter(self._backend, cipher, mode)
  42. if evp_cipher == self._backend._ffi.NULL:
  43. msg = "cipher {0.name} ".format(cipher)
  44. if mode is not None:
  45. msg += "in {0.name} mode ".format(mode)
  46. msg += (
  47. "is not supported by this backend (Your version of OpenSSL "
  48. "may be too old. Current version: {}.)"
  49. ).format(self._backend.openssl_version_text())
  50. raise UnsupportedAlgorithm(msg, _Reasons.UNSUPPORTED_CIPHER)
  51. if isinstance(mode, modes.ModeWithInitializationVector):
  52. iv_nonce = self._backend._ffi.from_buffer(
  53. mode.initialization_vector
  54. )
  55. elif isinstance(mode, modes.ModeWithTweak):
  56. iv_nonce = self._backend._ffi.from_buffer(mode.tweak)
  57. elif isinstance(mode, modes.ModeWithNonce):
  58. iv_nonce = self._backend._ffi.from_buffer(mode.nonce)
  59. elif isinstance(cipher, algorithms.ChaCha20):
  60. iv_nonce = self._backend._ffi.from_buffer(cipher.nonce)
  61. else:
  62. iv_nonce = self._backend._ffi.NULL
  63. # begin init with cipher and operation type
  64. res = self._backend._lib.EVP_CipherInit_ex(
  65. ctx,
  66. evp_cipher,
  67. self._backend._ffi.NULL,
  68. self._backend._ffi.NULL,
  69. self._backend._ffi.NULL,
  70. operation,
  71. )
  72. self._backend.openssl_assert(res != 0)
  73. # set the key length to handle variable key ciphers
  74. res = self._backend._lib.EVP_CIPHER_CTX_set_key_length(
  75. ctx, len(cipher.key)
  76. )
  77. self._backend.openssl_assert(res != 0)
  78. if isinstance(mode, modes.GCM):
  79. res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
  80. ctx,
  81. self._backend._lib.EVP_CTRL_AEAD_SET_IVLEN,
  82. len(iv_nonce),
  83. self._backend._ffi.NULL,
  84. )
  85. self._backend.openssl_assert(res != 0)
  86. if mode.tag is not None:
  87. res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
  88. ctx,
  89. self._backend._lib.EVP_CTRL_AEAD_SET_TAG,
  90. len(mode.tag),
  91. mode.tag,
  92. )
  93. self._backend.openssl_assert(res != 0)
  94. self._tag = mode.tag
  95. # pass key/iv
  96. res = self._backend._lib.EVP_CipherInit_ex(
  97. ctx,
  98. self._backend._ffi.NULL,
  99. self._backend._ffi.NULL,
  100. self._backend._ffi.from_buffer(cipher.key),
  101. iv_nonce,
  102. operation,
  103. )
  104. # Check for XTS mode duplicate keys error
  105. errors = self._backend._consume_errors()
  106. lib = self._backend._lib
  107. if res == 0 and (
  108. (
  109. lib.CRYPTOGRAPHY_OPENSSL_111D_OR_GREATER
  110. and errors[0]._lib_reason_match(
  111. lib.ERR_LIB_EVP, lib.EVP_R_XTS_DUPLICATED_KEYS
  112. )
  113. )
  114. or (
  115. lib.Cryptography_HAS_PROVIDERS
  116. and errors[0]._lib_reason_match(
  117. lib.ERR_LIB_PROV, lib.PROV_R_XTS_DUPLICATED_KEYS
  118. )
  119. )
  120. ):
  121. raise ValueError("In XTS mode duplicated keys are not allowed")
  122. self._backend.openssl_assert(res != 0, errors=errors)
  123. # We purposely disable padding here as it's handled higher up in the
  124. # API.
  125. self._backend._lib.EVP_CIPHER_CTX_set_padding(ctx, 0)
  126. self._ctx = ctx
  127. def update(self, data: bytes) -> bytes:
  128. buf = bytearray(len(data) + self._block_size_bytes - 1)
  129. n = self.update_into(data, buf)
  130. return bytes(buf[:n])
  131. def update_into(self, data: bytes, buf: bytes) -> int:
  132. total_data_len = len(data)
  133. if len(buf) < (total_data_len + self._block_size_bytes - 1):
  134. raise ValueError(
  135. "buffer must be at least {} bytes for this "
  136. "payload".format(len(data) + self._block_size_bytes - 1)
  137. )
  138. data_processed = 0
  139. total_out = 0
  140. outlen = self._backend._ffi.new("int *")
  141. baseoutbuf = self._backend._ffi.from_buffer(buf)
  142. baseinbuf = self._backend._ffi.from_buffer(data)
  143. while data_processed != total_data_len:
  144. outbuf = baseoutbuf + total_out
  145. inbuf = baseinbuf + data_processed
  146. inlen = min(self._MAX_CHUNK_SIZE, total_data_len - data_processed)
  147. res = self._backend._lib.EVP_CipherUpdate(
  148. self._ctx, outbuf, outlen, inbuf, inlen
  149. )
  150. if res == 0 and isinstance(self._mode, modes.XTS):
  151. self._backend._consume_errors()
  152. raise ValueError(
  153. "In XTS mode you must supply at least a full block in the "
  154. "first update call. For AES this is 16 bytes."
  155. )
  156. else:
  157. self._backend.openssl_assert(res != 0)
  158. data_processed += inlen
  159. total_out += outlen[0]
  160. return total_out
  161. def finalize(self) -> bytes:
  162. if (
  163. self._operation == self._DECRYPT
  164. and isinstance(self._mode, modes.ModeWithAuthenticationTag)
  165. and self.tag is None
  166. ):
  167. raise ValueError(
  168. "Authentication tag must be provided when decrypting."
  169. )
  170. buf = self._backend._ffi.new("unsigned char[]", self._block_size_bytes)
  171. outlen = self._backend._ffi.new("int *")
  172. res = self._backend._lib.EVP_CipherFinal_ex(self._ctx, buf, outlen)
  173. if res == 0:
  174. errors = self._backend._consume_errors()
  175. if not errors and isinstance(self._mode, modes.GCM):
  176. raise InvalidTag
  177. lib = self._backend._lib
  178. self._backend.openssl_assert(
  179. errors[0]._lib_reason_match(
  180. lib.ERR_LIB_EVP,
  181. lib.EVP_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH,
  182. )
  183. or (
  184. lib.Cryptography_HAS_PROVIDERS
  185. and errors[0]._lib_reason_match(
  186. lib.ERR_LIB_PROV,
  187. lib.PROV_R_WRONG_FINAL_BLOCK_LENGTH,
  188. )
  189. )
  190. or (
  191. lib.CRYPTOGRAPHY_IS_BORINGSSL
  192. and errors[0].reason
  193. == lib.CIPHER_R_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH
  194. ),
  195. errors=errors,
  196. )
  197. raise ValueError(
  198. "The length of the provided data is not a multiple of "
  199. "the block length."
  200. )
  201. if (
  202. isinstance(self._mode, modes.GCM)
  203. and self._operation == self._ENCRYPT
  204. ):
  205. tag_buf = self._backend._ffi.new(
  206. "unsigned char[]", self._block_size_bytes
  207. )
  208. res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
  209. self._ctx,
  210. self._backend._lib.EVP_CTRL_AEAD_GET_TAG,
  211. self._block_size_bytes,
  212. tag_buf,
  213. )
  214. self._backend.openssl_assert(res != 0)
  215. self._tag = self._backend._ffi.buffer(tag_buf)[:]
  216. res = self._backend._lib.EVP_CIPHER_CTX_reset(self._ctx)
  217. self._backend.openssl_assert(res == 1)
  218. return self._backend._ffi.buffer(buf)[: outlen[0]]
  219. def finalize_with_tag(self, tag: bytes) -> bytes:
  220. tag_len = len(tag)
  221. if tag_len < self._mode._min_tag_length:
  222. raise ValueError(
  223. "Authentication tag must be {} bytes or longer.".format(
  224. self._mode._min_tag_length
  225. )
  226. )
  227. elif tag_len > self._block_size_bytes:
  228. raise ValueError(
  229. "Authentication tag cannot be more than {} bytes.".format(
  230. self._block_size_bytes
  231. )
  232. )
  233. res = self._backend._lib.EVP_CIPHER_CTX_ctrl(
  234. self._ctx, self._backend._lib.EVP_CTRL_AEAD_SET_TAG, len(tag), tag
  235. )
  236. self._backend.openssl_assert(res != 0)
  237. self._tag = tag
  238. return self.finalize()
  239. def authenticate_additional_data(self, data: bytes) -> None:
  240. outlen = self._backend._ffi.new("int *")
  241. res = self._backend._lib.EVP_CipherUpdate(
  242. self._ctx,
  243. self._backend._ffi.NULL,
  244. outlen,
  245. self._backend._ffi.from_buffer(data),
  246. len(data),
  247. )
  248. self._backend.openssl_assert(res != 0)
  249. @property
  250. def tag(self) -> typing.Optional[bytes]:
  251. return self._tag