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