signing.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277
  1. """
  2. Functions for creating and restoring url-safe signed JSON objects.
  3. The format used looks like this:
  4. >>> signing.dumps("hello")
  5. 'ImhlbGxvIg:1QaUZC:YIye-ze3TTx7gtSv422nZA4sgmk'
  6. There are two components here, separated by a ':'. The first component is a
  7. URLsafe base64 encoded JSON of the object passed to dumps(). The second
  8. component is a base64 encoded hmac/SHA-256 hash of "$first_component:$secret"
  9. signing.loads(s) checks the signature and returns the deserialized object.
  10. If the signature fails, a BadSignature exception is raised.
  11. >>> signing.loads("ImhlbGxvIg:1QaUZC:YIye-ze3TTx7gtSv422nZA4sgmk")
  12. 'hello'
  13. >>> signing.loads("ImhlbGxvIg:1QaUZC:YIye-ze3TTx7gtSv42-modified")
  14. ...
  15. BadSignature: Signature "ImhlbGxvIg:1QaUZC:YIye-ze3TTx7gtSv42-modified" does not match
  16. You can optionally compress the JSON prior to base64 encoding it to save
  17. space, using the compress=True argument. This checks if compression actually
  18. helps and only applies compression if the result is a shorter string:
  19. >>> signing.dumps(list(range(1, 20)), compress=True)
  20. '.eJwFwcERACAIwLCF-rCiILN47r-GyZVJsNgkxaFxoDgxcOHGxMKD_T7vhAml:1QaUaL:BA0thEZrp4FQVXIXuOvYJtLJSrQ'
  21. The fact that the string is compressed is signalled by the prefixed '.' at the
  22. start of the base64 JSON.
  23. There are 65 url-safe characters: the 64 used by url-safe base64 and the ':'.
  24. These functions make use of all of them.
  25. """
  26. import base64
  27. import datetime
  28. import json
  29. import time
  30. import zlib
  31. from django.conf import settings
  32. from django.utils.crypto import constant_time_compare, salted_hmac
  33. from django.utils.encoding import force_bytes
  34. from django.utils.module_loading import import_string
  35. from django.utils.regex_helper import _lazy_re_compile
  36. _SEP_UNSAFE = _lazy_re_compile(r"^[A-z0-9-_=]*$")
  37. BASE62_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  38. class BadSignature(Exception):
  39. """Signature does not match."""
  40. pass
  41. class SignatureExpired(BadSignature):
  42. """Signature timestamp is older than required max_age."""
  43. pass
  44. def b62_encode(s):
  45. if s == 0:
  46. return "0"
  47. sign = "-" if s < 0 else ""
  48. s = abs(s)
  49. encoded = ""
  50. while s > 0:
  51. s, remainder = divmod(s, 62)
  52. encoded = BASE62_ALPHABET[remainder] + encoded
  53. return sign + encoded
  54. def b62_decode(s):
  55. if s == "0":
  56. return 0
  57. sign = 1
  58. if s[0] == "-":
  59. s = s[1:]
  60. sign = -1
  61. decoded = 0
  62. for digit in s:
  63. decoded = decoded * 62 + BASE62_ALPHABET.index(digit)
  64. return sign * decoded
  65. def b64_encode(s):
  66. return base64.urlsafe_b64encode(s).strip(b"=")
  67. def b64_decode(s):
  68. pad = b"=" * (-len(s) % 4)
  69. return base64.urlsafe_b64decode(s + pad)
  70. def base64_hmac(salt, value, key, algorithm="sha1"):
  71. return b64_encode(
  72. salted_hmac(salt, value, key, algorithm=algorithm).digest()
  73. ).decode()
  74. def _cookie_signer_key(key):
  75. # SECRET_KEYS items may be str or bytes.
  76. return b"django.http.cookies" + force_bytes(key)
  77. def get_cookie_signer(salt="django.core.signing.get_cookie_signer"):
  78. Signer = import_string(settings.SIGNING_BACKEND)
  79. return Signer(
  80. key=_cookie_signer_key(settings.SECRET_KEY),
  81. fallback_keys=map(_cookie_signer_key, settings.SECRET_KEY_FALLBACKS),
  82. salt=salt,
  83. )
  84. class JSONSerializer:
  85. """
  86. Simple wrapper around json to be used in signing.dumps and
  87. signing.loads.
  88. """
  89. def dumps(self, obj):
  90. return json.dumps(obj, separators=(",", ":")).encode("latin-1")
  91. def loads(self, data):
  92. return json.loads(data.decode("latin-1"))
  93. def dumps(
  94. obj, key=None, salt="django.core.signing", serializer=JSONSerializer, compress=False
  95. ):
  96. """
  97. Return URL-safe, hmac signed base64 compressed JSON string. If key is
  98. None, use settings.SECRET_KEY instead. The hmac algorithm is the default
  99. Signer algorithm.
  100. If compress is True (not the default), check if compressing using zlib can
  101. save some space. Prepend a '.' to signify compression. This is included
  102. in the signature, to protect against zip bombs.
  103. Salt can be used to namespace the hash, so that a signed string is
  104. only valid for a given namespace. Leaving this at the default
  105. value or re-using a salt value across different parts of your
  106. application without good cause is a security risk.
  107. The serializer is expected to return a bytestring.
  108. """
  109. return TimestampSigner(key=key, salt=salt).sign_object(
  110. obj, serializer=serializer, compress=compress
  111. )
  112. def loads(
  113. s,
  114. key=None,
  115. salt="django.core.signing",
  116. serializer=JSONSerializer,
  117. max_age=None,
  118. fallback_keys=None,
  119. ):
  120. """
  121. Reverse of dumps(), raise BadSignature if signature fails.
  122. The serializer is expected to accept a bytestring.
  123. """
  124. return TimestampSigner(
  125. key=key, salt=salt, fallback_keys=fallback_keys
  126. ).unsign_object(
  127. s,
  128. serializer=serializer,
  129. max_age=max_age,
  130. )
  131. class Signer:
  132. def __init__(
  133. self, *, key=None, sep=":", salt=None, algorithm=None, fallback_keys=None
  134. ):
  135. self.key = key or settings.SECRET_KEY
  136. self.fallback_keys = (
  137. fallback_keys
  138. if fallback_keys is not None
  139. else settings.SECRET_KEY_FALLBACKS
  140. )
  141. self.sep = sep
  142. self.salt = salt or "%s.%s" % (
  143. self.__class__.__module__,
  144. self.__class__.__name__,
  145. )
  146. self.algorithm = algorithm or "sha256"
  147. if _SEP_UNSAFE.match(self.sep):
  148. raise ValueError(
  149. "Unsafe Signer separator: %r (cannot be empty or consist of "
  150. "only A-z0-9-_=)" % sep,
  151. )
  152. def signature(self, value, key=None):
  153. key = key or self.key
  154. return base64_hmac(self.salt + "signer", value, key, algorithm=self.algorithm)
  155. def sign(self, value):
  156. return "%s%s%s" % (value, self.sep, self.signature(value))
  157. def unsign(self, signed_value):
  158. if self.sep not in signed_value:
  159. raise BadSignature('No "%s" found in value' % self.sep)
  160. value, sig = signed_value.rsplit(self.sep, 1)
  161. for key in [self.key, *self.fallback_keys]:
  162. if constant_time_compare(sig, self.signature(value, key)):
  163. return value
  164. raise BadSignature('Signature "%s" does not match' % sig)
  165. def sign_object(self, obj, serializer=JSONSerializer, compress=False):
  166. """
  167. Return URL-safe, hmac signed base64 compressed JSON string.
  168. If compress is True (not the default), check if compressing using zlib
  169. can save some space. Prepend a '.' to signify compression. This is
  170. included in the signature, to protect against zip bombs.
  171. The serializer is expected to return a bytestring.
  172. """
  173. data = serializer().dumps(obj)
  174. # Flag for if it's been compressed or not.
  175. is_compressed = False
  176. if compress:
  177. # Avoid zlib dependency unless compress is being used.
  178. compressed = zlib.compress(data)
  179. if len(compressed) < (len(data) - 1):
  180. data = compressed
  181. is_compressed = True
  182. base64d = b64_encode(data).decode()
  183. if is_compressed:
  184. base64d = "." + base64d
  185. return self.sign(base64d)
  186. def unsign_object(self, signed_obj, serializer=JSONSerializer, **kwargs):
  187. # Signer.unsign() returns str but base64 and zlib compression operate
  188. # on bytes.
  189. base64d = self.unsign(signed_obj, **kwargs).encode()
  190. decompress = base64d[:1] == b"."
  191. if decompress:
  192. # It's compressed; uncompress it first.
  193. base64d = base64d[1:]
  194. data = b64_decode(base64d)
  195. if decompress:
  196. data = zlib.decompress(data)
  197. return serializer().loads(data)
  198. class TimestampSigner(Signer):
  199. def timestamp(self):
  200. return b62_encode(int(time.time()))
  201. def sign(self, value):
  202. value = "%s%s%s" % (value, self.sep, self.timestamp())
  203. return super().sign(value)
  204. def unsign(self, value, max_age=None):
  205. """
  206. Retrieve original value and check it wasn't signed more
  207. than max_age seconds ago.
  208. """
  209. result = super().unsign(value)
  210. value, timestamp = result.rsplit(self.sep, 1)
  211. timestamp = b62_decode(timestamp)
  212. if max_age is not None:
  213. if isinstance(max_age, datetime.timedelta):
  214. max_age = max_age.total_seconds()
  215. # Check timestamp is not older than max_age
  216. age = time.time() - timestamp
  217. if age > max_age:
  218. raise SignatureExpired("Signature age %s > %s seconds" % (age, max_age))
  219. return value