2011-05-21 22:41:14 +08:00
|
|
|
"""
|
|
|
|
Functions for creating and restoring url-safe signed JSON objects.
|
|
|
|
|
|
|
|
The format used looks like this:
|
|
|
|
|
2011-06-27 01:00:24 +08:00
|
|
|
>>> signing.dumps("hello")
|
|
|
|
'ImhlbGxvIg:1QaUZC:YIye-ze3TTx7gtSv422nZA4sgmk'
|
2011-05-21 22:41:14 +08:00
|
|
|
|
2011-06-27 17:00:12 +08:00
|
|
|
There are two components here, separated by a ':'. The first component is a
|
2011-05-21 22:41:14 +08:00
|
|
|
URLsafe base64 encoded JSON of the object passed to dumps(). The second
|
2011-06-27 01:00:24 +08:00
|
|
|
component is a base64 encoded hmac/SHA1 hash of "$first_component:$secret"
|
2011-05-21 22:41:14 +08:00
|
|
|
|
2014-03-02 22:25:53 +08:00
|
|
|
signing.loads(s) checks the signature and returns the deserialized object.
|
2011-05-21 22:41:14 +08:00
|
|
|
If the signature fails, a BadSignature exception is raised.
|
|
|
|
|
2011-06-27 01:00:24 +08:00
|
|
|
>>> signing.loads("ImhlbGxvIg:1QaUZC:YIye-ze3TTx7gtSv422nZA4sgmk")
|
2017-01-20 20:38:17 +08:00
|
|
|
'hello'
|
2011-06-27 01:00:24 +08:00
|
|
|
>>> signing.loads("ImhlbGxvIg:1QaUZC:YIye-ze3TTx7gtSv422nZA4sgmk-modified")
|
2011-05-21 22:41:14 +08:00
|
|
|
...
|
2011-06-27 01:00:24 +08:00
|
|
|
BadSignature: Signature failed: ImhlbGxvIg:1QaUZC:YIye-ze3TTx7gtSv422nZA4sgmk-modified
|
2011-05-21 22:41:14 +08:00
|
|
|
|
|
|
|
You can optionally compress the JSON prior to base64 encoding it to save
|
|
|
|
space, using the compress=True argument. This checks if compression actually
|
|
|
|
helps and only applies compression if the result is a shorter string:
|
|
|
|
|
2018-11-09 20:26:46 +08:00
|
|
|
>>> signing.dumps(list(range(1, 20)), compress=True)
|
2011-06-27 01:00:24 +08:00
|
|
|
'.eJwFwcERACAIwLCF-rCiILN47r-GyZVJsNgkxaFxoDgxcOHGxMKD_T7vhAml:1QaUaL:BA0thEZrp4FQVXIXuOvYJtLJSrQ'
|
2011-05-21 22:41:14 +08:00
|
|
|
|
|
|
|
The fact that the string is compressed is signalled by the prefixed '.' at the
|
|
|
|
start of the base64 JSON.
|
|
|
|
|
2011-06-27 01:00:24 +08:00
|
|
|
There are 65 url-safe characters: the 64 used by url-safe base64 and the ':'.
|
2011-05-21 22:41:14 +08:00
|
|
|
These functions make use of all of them.
|
|
|
|
"""
|
2012-08-25 19:02:52 +08:00
|
|
|
|
2011-05-21 22:41:14 +08:00
|
|
|
import base64
|
2014-11-15 18:03:04 +08:00
|
|
|
import datetime
|
2012-04-30 01:58:00 +08:00
|
|
|
import json
|
2014-06-10 06:15:21 +08:00
|
|
|
import re
|
2011-05-21 22:41:14 +08:00
|
|
|
import time
|
|
|
|
import zlib
|
|
|
|
|
|
|
|
from django.conf import settings
|
2012-04-30 01:58:00 +08:00
|
|
|
from django.utils import baseconv
|
2011-05-21 22:41:14 +08:00
|
|
|
from django.utils.crypto import constant_time_compare, salted_hmac
|
2017-02-07 16:17:38 +08:00
|
|
|
from django.utils.encoding import force_bytes
|
2014-01-21 04:15:14 +08:00
|
|
|
from django.utils.module_loading import import_string
|
2011-05-21 22:41:14 +08:00
|
|
|
|
2014-06-10 06:15:21 +08:00
|
|
|
_SEP_UNSAFE = re.compile(r'^[A-z0-9-_=]*$')
|
|
|
|
|
2011-05-21 22:41:14 +08:00
|
|
|
|
|
|
|
class BadSignature(Exception):
|
2017-01-26 03:02:33 +08:00
|
|
|
"""Signature does not match."""
|
2011-05-21 22:41:14 +08:00
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
class SignatureExpired(BadSignature):
|
2017-01-26 03:02:33 +08:00
|
|
|
"""Signature timestamp is older than required max_age."""
|
2011-05-21 22:41:14 +08:00
|
|
|
pass
|
|
|
|
|
|
|
|
|
|
|
|
def b64_encode(s):
|
2012-08-25 19:02:52 +08:00
|
|
|
return base64.urlsafe_b64encode(s).strip(b'=')
|
2011-05-21 22:41:14 +08:00
|
|
|
|
|
|
|
|
|
|
|
def b64_decode(s):
|
2012-08-25 19:02:52 +08:00
|
|
|
pad = b'=' * (-len(s) % 4)
|
|
|
|
return base64.urlsafe_b64decode(s + pad)
|
2011-05-21 22:41:14 +08:00
|
|
|
|
|
|
|
|
|
|
|
def base64_hmac(salt, value, key):
|
2017-02-07 16:17:38 +08:00
|
|
|
return b64_encode(salted_hmac(salt, value, key).digest()).decode()
|
2011-05-21 22:41:14 +08:00
|
|
|
|
|
|
|
|
|
|
|
def get_cookie_signer(salt='django.core.signing.get_cookie_signer'):
|
2014-01-21 04:15:14 +08:00
|
|
|
Signer = import_string(settings.SIGNING_BACKEND)
|
2018-02-08 01:47:34 +08:00
|
|
|
key = force_bytes(settings.SECRET_KEY) # SECRET_KEY may be str or bytes.
|
2014-02-16 21:47:51 +08:00
|
|
|
return Signer(b'django.http.cookies' + key, salt=salt)
|
2011-05-21 22:41:14 +08:00
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class JSONSerializer:
|
2011-06-27 01:00:24 +08:00
|
|
|
"""
|
2012-04-30 01:58:00 +08:00
|
|
|
Simple wrapper around json to be used in signing.dumps and
|
2011-06-27 01:00:24 +08:00
|
|
|
signing.loads.
|
|
|
|
"""
|
|
|
|
def dumps(self, obj):
|
2012-10-28 23:42:34 +08:00
|
|
|
return json.dumps(obj, separators=(',', ':')).encode('latin-1')
|
2011-06-27 01:00:24 +08:00
|
|
|
|
|
|
|
def loads(self, data):
|
2012-10-28 23:42:34 +08:00
|
|
|
return json.loads(data.decode('latin-1'))
|
2011-06-27 01:00:24 +08:00
|
|
|
|
|
|
|
|
|
|
|
def dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False):
|
2011-05-21 22:41:14 +08:00
|
|
|
"""
|
2017-02-28 14:36:37 +08:00
|
|
|
Return URL-safe, hmac/SHA1 signed base64 compressed JSON string. If key is
|
2017-01-26 03:02:33 +08:00
|
|
|
None, use settings.SECRET_KEY instead.
|
2011-05-21 22:41:14 +08:00
|
|
|
|
2017-01-26 03:02:33 +08:00
|
|
|
If compress is True (not the default), check if compressing using zlib can
|
|
|
|
save some space. Prepend a '.' to signify compression. This is included
|
2011-05-21 22:41:14 +08:00
|
|
|
in the signature, to protect against zip bombs.
|
|
|
|
|
2011-06-27 00:52:01 +08:00
|
|
|
Salt can be used to namespace the hash, so that a signed string is
|
|
|
|
only valid for a given namespace. Leaving this at the default
|
|
|
|
value or re-using a salt value across different parts of your
|
|
|
|
application without good cause is a security risk.
|
2012-10-28 23:42:34 +08:00
|
|
|
|
|
|
|
The serializer is expected to return a bytestring.
|
2011-05-21 22:41:14 +08:00
|
|
|
"""
|
2012-10-28 23:42:34 +08:00
|
|
|
data = serializer().dumps(obj)
|
2011-05-21 22:41:14 +08:00
|
|
|
|
|
|
|
# Flag for if it's been compressed or not
|
|
|
|
is_compressed = False
|
|
|
|
|
|
|
|
if compress:
|
|
|
|
# Avoid zlib dependency unless compress is being used
|
2012-08-25 19:02:52 +08:00
|
|
|
compressed = zlib.compress(data)
|
2011-06-27 01:00:24 +08:00
|
|
|
if len(compressed) < (len(data) - 1):
|
|
|
|
data = compressed
|
2011-05-21 22:41:14 +08:00
|
|
|
is_compressed = True
|
2017-02-07 16:17:38 +08:00
|
|
|
base64d = b64_encode(data).decode()
|
2011-05-21 22:41:14 +08:00
|
|
|
if is_compressed:
|
2017-02-07 16:17:38 +08:00
|
|
|
base64d = '.' + base64d
|
2011-05-21 22:41:14 +08:00
|
|
|
return TimestampSigner(key, salt=salt).sign(base64d)
|
|
|
|
|
|
|
|
|
2011-06-27 01:00:24 +08:00
|
|
|
def loads(s, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None):
|
2011-05-21 22:41:14 +08:00
|
|
|
"""
|
2017-01-26 03:02:33 +08:00
|
|
|
Reverse of dumps(), raise BadSignature if signature fails.
|
2012-10-28 23:42:34 +08:00
|
|
|
|
|
|
|
The serializer is expected to accept a bytestring.
|
2011-05-21 22:41:14 +08:00
|
|
|
"""
|
2017-01-21 05:04:05 +08:00
|
|
|
# TimestampSigner.unsign() returns str but base64 and zlib compression
|
|
|
|
# operate on bytes.
|
2018-02-08 01:47:34 +08:00
|
|
|
base64d = TimestampSigner(key, salt=salt).unsign(s, max_age=max_age).encode()
|
2018-01-12 22:05:16 +08:00
|
|
|
decompress = base64d[:1] == b'.'
|
|
|
|
if decompress:
|
2011-05-21 22:41:14 +08:00
|
|
|
# It's compressed; uncompress it first
|
|
|
|
base64d = base64d[1:]
|
2011-06-27 01:00:24 +08:00
|
|
|
data = b64_decode(base64d)
|
2011-05-21 22:41:14 +08:00
|
|
|
if decompress:
|
2011-06-27 01:00:24 +08:00
|
|
|
data = zlib.decompress(data)
|
2012-10-28 23:42:34 +08:00
|
|
|
return serializer().loads(data)
|
2011-05-21 22:41:14 +08:00
|
|
|
|
|
|
|
|
2017-01-19 15:39:46 +08:00
|
|
|
class Signer:
|
2012-08-25 19:02:52 +08:00
|
|
|
|
2011-05-21 22:41:14 +08:00
|
|
|
def __init__(self, key=None, sep=':', salt=None):
|
2012-08-25 19:02:52 +08:00
|
|
|
# Use of native strings in all versions of Python
|
2014-02-16 21:47:51 +08:00
|
|
|
self.key = key or settings.SECRET_KEY
|
2017-01-12 06:17:25 +08:00
|
|
|
self.sep = sep
|
2014-06-10 06:15:21 +08:00
|
|
|
if _SEP_UNSAFE.match(self.sep):
|
2015-09-05 22:31:09 +08:00
|
|
|
raise ValueError(
|
|
|
|
'Unsafe Signer separator: %r (cannot be empty or consist of '
|
|
|
|
'only A-z0-9-_=)' % sep,
|
|
|
|
)
|
2017-01-12 06:17:25 +08:00
|
|
|
self.salt = salt or '%s.%s' % (self.__class__.__module__, self.__class__.__name__)
|
2011-05-21 22:41:14 +08:00
|
|
|
|
|
|
|
def signature(self, value):
|
2017-02-07 16:17:38 +08:00
|
|
|
return base64_hmac(self.salt + 'signer', value, self.key)
|
2011-05-21 22:41:14 +08:00
|
|
|
|
|
|
|
def sign(self, value):
|
2017-01-12 06:17:25 +08:00
|
|
|
return '%s%s%s' % (value, self.sep, self.signature(value))
|
2011-05-21 22:41:14 +08:00
|
|
|
|
|
|
|
def unsign(self, signed_value):
|
2014-03-31 03:11:05 +08:00
|
|
|
if self.sep not in signed_value:
|
2011-05-21 22:41:14 +08:00
|
|
|
raise BadSignature('No "%s" found in value' % self.sep)
|
|
|
|
value, sig = signed_value.rsplit(self.sep, 1)
|
|
|
|
if constant_time_compare(sig, self.signature(value)):
|
2017-02-07 16:17:38 +08:00
|
|
|
return value
|
2011-05-21 22:41:14 +08:00
|
|
|
raise BadSignature('Signature "%s" does not match' % sig)
|
|
|
|
|
|
|
|
|
|
|
|
class TimestampSigner(Signer):
|
2011-06-27 01:00:24 +08:00
|
|
|
|
2011-05-21 22:41:14 +08:00
|
|
|
def timestamp(self):
|
2011-06-17 17:47:08 +08:00
|
|
|
return baseconv.base62.encode(int(time.time()))
|
2011-05-21 22:41:14 +08:00
|
|
|
|
|
|
|
def sign(self, value):
|
2017-02-07 16:17:38 +08:00
|
|
|
value = '%s%s%s' % (value, self.sep, self.timestamp())
|
2017-01-21 21:13:44 +08:00
|
|
|
return super().sign(value)
|
2011-05-21 22:41:14 +08:00
|
|
|
|
|
|
|
def unsign(self, value, max_age=None):
|
2013-07-03 14:13:38 +08:00
|
|
|
"""
|
|
|
|
Retrieve original value and check it wasn't signed more
|
|
|
|
than max_age seconds ago.
|
|
|
|
"""
|
2017-01-21 21:13:44 +08:00
|
|
|
result = super().unsign(value)
|
2011-05-21 22:41:14 +08:00
|
|
|
value, timestamp = result.rsplit(self.sep, 1)
|
2011-06-17 17:47:08 +08:00
|
|
|
timestamp = baseconv.base62.decode(timestamp)
|
2011-05-21 22:41:14 +08:00
|
|
|
if max_age is not None:
|
2014-11-15 18:03:04 +08:00
|
|
|
if isinstance(max_age, datetime.timedelta):
|
|
|
|
max_age = max_age.total_seconds()
|
2011-05-21 22:41:14 +08:00
|
|
|
# Check timestamp is not older than max_age
|
2011-06-17 17:47:08 +08:00
|
|
|
age = time.time() - timestamp
|
2011-05-21 22:41:14 +08:00
|
|
|
if age > max_age:
|
|
|
|
raise SignatureExpired(
|
|
|
|
'Signature age %s > %s seconds' % (age, max_age))
|
|
|
|
return value
|