fernet.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  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 annotations
  5. import base64
  6. import binascii
  7. import os
  8. import time
  9. import typing
  10. from cryptography import utils
  11. from cryptography.exceptions import InvalidSignature
  12. from cryptography.hazmat.primitives import hashes, padding
  13. from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
  14. from cryptography.hazmat.primitives.hmac import HMAC
  15. class InvalidToken(Exception):
  16. pass
  17. _MAX_CLOCK_SKEW = 60
  18. class Fernet:
  19. def __init__(
  20. self,
  21. key: bytes | str,
  22. backend: typing.Any = None,
  23. ) -> None:
  24. try:
  25. key = base64.urlsafe_b64decode(key)
  26. except binascii.Error as exc:
  27. raise ValueError(
  28. "Fernet key must be 32 url-safe base64-encoded bytes."
  29. ) from exc
  30. if len(key) != 32:
  31. raise ValueError(
  32. "Fernet key must be 32 url-safe base64-encoded bytes."
  33. )
  34. self._signing_key = key[:16]
  35. self._encryption_key = key[16:]
  36. @classmethod
  37. def generate_key(cls) -> bytes:
  38. return base64.urlsafe_b64encode(os.urandom(32))
  39. def encrypt(self, data: bytes) -> bytes:
  40. return self.encrypt_at_time(data, int(time.time()))
  41. def encrypt_at_time(self, data: bytes, current_time: int) -> bytes:
  42. iv = os.urandom(16)
  43. return self._encrypt_from_parts(data, current_time, iv)
  44. def _encrypt_from_parts(
  45. self, data: bytes, current_time: int, iv: bytes
  46. ) -> bytes:
  47. utils._check_bytes("data", data)
  48. padder = padding.PKCS7(algorithms.AES.block_size).padder()
  49. padded_data = padder.update(data) + padder.finalize()
  50. encryptor = Cipher(
  51. algorithms.AES(self._encryption_key),
  52. modes.CBC(iv),
  53. ).encryptor()
  54. ciphertext = encryptor.update(padded_data) + encryptor.finalize()
  55. basic_parts = (
  56. b"\x80"
  57. + current_time.to_bytes(length=8, byteorder="big")
  58. + iv
  59. + ciphertext
  60. )
  61. h = HMAC(self._signing_key, hashes.SHA256())
  62. h.update(basic_parts)
  63. hmac = h.finalize()
  64. return base64.urlsafe_b64encode(basic_parts + hmac)
  65. def decrypt(self, token: bytes | str, ttl: int | None = None) -> bytes:
  66. timestamp, data = Fernet._get_unverified_token_data(token)
  67. if ttl is None:
  68. time_info = None
  69. else:
  70. time_info = (ttl, int(time.time()))
  71. return self._decrypt_data(data, timestamp, time_info)
  72. def decrypt_at_time(
  73. self, token: bytes | str, ttl: int, current_time: int
  74. ) -> bytes:
  75. if ttl is None:
  76. raise ValueError(
  77. "decrypt_at_time() can only be used with a non-None ttl"
  78. )
  79. timestamp, data = Fernet._get_unverified_token_data(token)
  80. return self._decrypt_data(data, timestamp, (ttl, current_time))
  81. def extract_timestamp(self, token: bytes | str) -> int:
  82. timestamp, data = Fernet._get_unverified_token_data(token)
  83. # Verify the token was not tampered with.
  84. self._verify_signature(data)
  85. return timestamp
  86. @staticmethod
  87. def _get_unverified_token_data(token: bytes | str) -> tuple[int, bytes]:
  88. if not isinstance(token, (str, bytes)):
  89. raise TypeError("token must be bytes or str")
  90. try:
  91. data = base64.urlsafe_b64decode(token)
  92. except (TypeError, binascii.Error):
  93. raise InvalidToken
  94. if not data or data[0] != 0x80:
  95. raise InvalidToken
  96. if len(data) < 9:
  97. raise InvalidToken
  98. timestamp = int.from_bytes(data[1:9], byteorder="big")
  99. return timestamp, data
  100. def _verify_signature(self, data: bytes) -> None:
  101. h = HMAC(self._signing_key, hashes.SHA256())
  102. h.update(data[:-32])
  103. try:
  104. h.verify(data[-32:])
  105. except InvalidSignature:
  106. raise InvalidToken
  107. def _decrypt_data(
  108. self,
  109. data: bytes,
  110. timestamp: int,
  111. time_info: tuple[int, int] | None,
  112. ) -> bytes:
  113. if time_info is not None:
  114. ttl, current_time = time_info
  115. if timestamp + ttl < current_time:
  116. raise InvalidToken
  117. if current_time + _MAX_CLOCK_SKEW < timestamp:
  118. raise InvalidToken
  119. self._verify_signature(data)
  120. iv = data[9:25]
  121. ciphertext = data[25:-32]
  122. decryptor = Cipher(
  123. algorithms.AES(self._encryption_key), modes.CBC(iv)
  124. ).decryptor()
  125. plaintext_padded = decryptor.update(ciphertext)
  126. try:
  127. plaintext_padded += decryptor.finalize()
  128. except ValueError:
  129. raise InvalidToken
  130. unpadder = padding.PKCS7(algorithms.AES.block_size).unpadder()
  131. unpadded = unpadder.update(plaintext_padded)
  132. try:
  133. unpadded += unpadder.finalize()
  134. except ValueError:
  135. raise InvalidToken
  136. return unpadded
  137. class MultiFernet:
  138. def __init__(self, fernets: typing.Iterable[Fernet]):
  139. fernets = list(fernets)
  140. if not fernets:
  141. raise ValueError(
  142. "MultiFernet requires at least one Fernet instance"
  143. )
  144. self._fernets = fernets
  145. def encrypt(self, msg: bytes) -> bytes:
  146. return self.encrypt_at_time(msg, int(time.time()))
  147. def encrypt_at_time(self, msg: bytes, current_time: int) -> bytes:
  148. return self._fernets[0].encrypt_at_time(msg, current_time)
  149. def rotate(self, msg: bytes | str) -> bytes:
  150. timestamp, data = Fernet._get_unverified_token_data(msg)
  151. for f in self._fernets:
  152. try:
  153. p = f._decrypt_data(data, timestamp, None)
  154. break
  155. except InvalidToken:
  156. pass
  157. else:
  158. raise InvalidToken
  159. iv = os.urandom(16)
  160. return self._fernets[0]._encrypt_from_parts(p, timestamp, iv)
  161. def decrypt(self, msg: bytes | str, ttl: int | None = None) -> bytes:
  162. for f in self._fernets:
  163. try:
  164. return f.decrypt(msg, ttl)
  165. except InvalidToken:
  166. pass
  167. raise InvalidToken
  168. def decrypt_at_time(
  169. self, msg: bytes | str, ttl: int, current_time: int
  170. ) -> bytes:
  171. for f in self._fernets:
  172. try:
  173. return f.decrypt_at_time(msg, ttl, current_time)
  174. except InvalidToken:
  175. pass
  176. raise InvalidToken