Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

signing.py 6.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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/SHA1 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-ze3TTx7gtSv422nZA4sgmk-modified")
  14. ...
  15. BadSignature: Signature failed: ImhlbGxvIg:1QaUZC:YIye-ze3TTx7gtSv422nZA4sgmk-modified
  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(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 re
  30. import time
  31. import zlib
  32. from django.conf import settings
  33. from django.utils import baseconv
  34. from django.utils.crypto import constant_time_compare, salted_hmac
  35. from django.utils.encoding import force_bytes
  36. from django.utils.module_loading import import_string
  37. _SEP_UNSAFE = re.compile(r'^[A-z0-9-_=]*$')
  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 b64_encode(s):
  45. return base64.urlsafe_b64encode(s).strip(b'=')
  46. def b64_decode(s):
  47. pad = b'=' * (-len(s) % 4)
  48. return base64.urlsafe_b64decode(s + pad)
  49. def base64_hmac(salt, value, key):
  50. return b64_encode(salted_hmac(salt, value, key).digest()).decode()
  51. def get_cookie_signer(salt='django.core.signing.get_cookie_signer'):
  52. Signer = import_string(settings.SIGNING_BACKEND)
  53. key = force_bytes(settings.SECRET_KEY) # SECRET_KEY may be str or bytes.
  54. return Signer(b'django.http.cookies' + key, salt=salt)
  55. class JSONSerializer:
  56. """
  57. Simple wrapper around json to be used in signing.dumps and
  58. signing.loads.
  59. """
  60. def dumps(self, obj):
  61. return json.dumps(obj, separators=(',', ':')).encode('latin-1')
  62. def loads(self, data):
  63. return json.loads(data.decode('latin-1'))
  64. def dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False):
  65. """
  66. Return URL-safe, hmac/SHA1 signed base64 compressed JSON string. If key is
  67. None, use settings.SECRET_KEY instead.
  68. If compress is True (not the default), check if compressing using zlib can
  69. save some space. Prepend a '.' to signify compression. This is included
  70. in the signature, to protect against zip bombs.
  71. Salt can be used to namespace the hash, so that a signed string is
  72. only valid for a given namespace. Leaving this at the default
  73. value or re-using a salt value across different parts of your
  74. application without good cause is a security risk.
  75. The serializer is expected to return a bytestring.
  76. """
  77. data = serializer().dumps(obj)
  78. # Flag for if it's been compressed or not
  79. is_compressed = False
  80. if compress:
  81. # Avoid zlib dependency unless compress is being used
  82. compressed = zlib.compress(data)
  83. if len(compressed) < (len(data) - 1):
  84. data = compressed
  85. is_compressed = True
  86. base64d = b64_encode(data).decode()
  87. if is_compressed:
  88. base64d = '.' + base64d
  89. return TimestampSigner(key, salt=salt).sign(base64d)
  90. def loads(s, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None):
  91. """
  92. Reverse of dumps(), raise BadSignature if signature fails.
  93. The serializer is expected to accept a bytestring.
  94. """
  95. # TimestampSigner.unsign() returns str but base64 and zlib compression
  96. # operate on bytes.
  97. base64d = TimestampSigner(key, salt=salt).unsign(s, max_age=max_age).encode()
  98. decompress = base64d[:1] == b'.'
  99. if decompress:
  100. # It's compressed; uncompress it first
  101. base64d = base64d[1:]
  102. data = b64_decode(base64d)
  103. if decompress:
  104. data = zlib.decompress(data)
  105. return serializer().loads(data)
  106. class Signer:
  107. def __init__(self, key=None, sep=':', salt=None):
  108. # Use of native strings in all versions of Python
  109. self.key = key or settings.SECRET_KEY
  110. self.sep = sep
  111. if _SEP_UNSAFE.match(self.sep):
  112. raise ValueError(
  113. 'Unsafe Signer separator: %r (cannot be empty or consist of '
  114. 'only A-z0-9-_=)' % sep,
  115. )
  116. self.salt = salt or '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
  117. def signature(self, value):
  118. return base64_hmac(self.salt + 'signer', value, self.key)
  119. def sign(self, value):
  120. return '%s%s%s' % (value, self.sep, self.signature(value))
  121. def unsign(self, signed_value):
  122. if self.sep not in signed_value:
  123. raise BadSignature('No "%s" found in value' % self.sep)
  124. value, sig = signed_value.rsplit(self.sep, 1)
  125. if constant_time_compare(sig, self.signature(value)):
  126. return value
  127. raise BadSignature('Signature "%s" does not match' % sig)
  128. class TimestampSigner(Signer):
  129. def timestamp(self):
  130. return baseconv.base62.encode(int(time.time()))
  131. def sign(self, value):
  132. value = '%s%s%s' % (value, self.sep, self.timestamp())
  133. return super().sign(value)
  134. def unsign(self, value, max_age=None):
  135. """
  136. Retrieve original value and check it wasn't signed more
  137. than max_age seconds ago.
  138. """
  139. result = super().unsign(value)
  140. value, timestamp = result.rsplit(self.sep, 1)
  141. timestamp = baseconv.base62.decode(timestamp)
  142. if max_age is not None:
  143. if isinstance(max_age, datetime.timedelta):
  144. max_age = max_age.total_seconds()
  145. # Check timestamp is not older than max_age
  146. age = time.time() - timestamp
  147. if age > max_age:
  148. raise SignatureExpired(
  149. 'Signature age %s > %s seconds' % (age, max_age))
  150. return value