fernet.py 6.5 KB

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