2011-05-21 22:41:14 +08:00
|
|
|
=====================
|
|
|
|
Cryptographic signing
|
|
|
|
=====================
|
|
|
|
|
|
|
|
.. module:: django.core.signing
|
|
|
|
:synopsis: Django's signing framework.
|
|
|
|
|
2021-07-23 14:48:16 +08:00
|
|
|
The golden rule of web application security is to never trust data from
|
2011-05-21 22:41:14 +08:00
|
|
|
untrusted sources. Sometimes it can be useful to pass data through an
|
|
|
|
untrusted medium. Cryptographically signed values can be passed through an
|
|
|
|
untrusted channel safe in the knowledge that any tampering will be detected.
|
|
|
|
|
|
|
|
Django provides both a low-level API for signing values and a high-level API
|
|
|
|
for setting and reading signed cookies, one of the most common uses of
|
2021-07-23 14:48:16 +08:00
|
|
|
signing in web applications.
|
2011-05-21 22:41:14 +08:00
|
|
|
|
|
|
|
You may also find signing useful for the following:
|
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
* Generating "recover my account" URLs for sending to users who have
|
|
|
|
lost their password.
|
2011-05-21 22:41:14 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
* Ensuring data stored in hidden form fields has not been tampered with.
|
2011-05-21 22:41:14 +08:00
|
|
|
|
2011-10-14 08:12:01 +08:00
|
|
|
* Generating one-time secret URLs for allowing temporary access to a
|
|
|
|
protected resource, for example a downloadable file that a user has
|
|
|
|
paid for.
|
2011-05-21 22:41:14 +08:00
|
|
|
|
2021-12-14 11:47:03 +08:00
|
|
|
Protecting ``SECRET_KEY`` and ``SECRET_KEY_FALLBACKS``
|
|
|
|
======================================================
|
2011-05-21 22:41:14 +08:00
|
|
|
|
|
|
|
When you create a new Django project using :djadmin:`startproject`, the
|
2011-05-23 21:23:00 +08:00
|
|
|
``settings.py`` file is generated automatically and gets a random
|
2011-05-21 22:41:14 +08:00
|
|
|
:setting:`SECRET_KEY` value. This value is the key to securing signed
|
|
|
|
data -- it is vital you keep this secure, or attackers could use it to
|
|
|
|
generate their own signed values.
|
|
|
|
|
2021-12-14 11:47:03 +08:00
|
|
|
:setting:`SECRET_KEY_FALLBACKS` can be used to rotate secret keys. The
|
|
|
|
values will not be used to sign data, but if specified, they will be used to
|
|
|
|
validate signed data and must be kept secure.
|
|
|
|
|
|
|
|
.. versionchanged:: 4.1
|
|
|
|
|
|
|
|
The ``SECRET_KEY_FALLBACKS`` setting was added.
|
|
|
|
|
2011-05-21 22:41:14 +08:00
|
|
|
Using the low-level API
|
|
|
|
=======================
|
|
|
|
|
|
|
|
Django's signing methods live in the ``django.core.signing`` module.
|
|
|
|
To sign a value, first instantiate a ``Signer`` instance::
|
|
|
|
|
|
|
|
>>> from django.core.signing import Signer
|
|
|
|
>>> signer = Signer()
|
|
|
|
>>> value = signer.sign('My string')
|
|
|
|
>>> value
|
|
|
|
'My string:GdMGD6HNQ_qdgxYP8yBZAdAIV1w'
|
|
|
|
|
|
|
|
The signature is appended to the end of the string, following the colon.
|
|
|
|
You can retrieve the original value using the ``unsign`` method::
|
|
|
|
|
|
|
|
>>> original = signer.unsign(value)
|
|
|
|
>>> original
|
2014-03-23 04:30:49 +08:00
|
|
|
'My string'
|
2011-05-21 22:41:14 +08:00
|
|
|
|
2020-01-30 17:31:47 +08:00
|
|
|
If you pass a non-string value to ``sign``, the value will be forced to string
|
|
|
|
before being signed, and the ``unsign`` result will give you that string
|
|
|
|
value::
|
|
|
|
|
|
|
|
>>> signed = signer.sign(2.5)
|
|
|
|
>>> original = signer.unsign(signed)
|
|
|
|
>>> original
|
|
|
|
'2.5'
|
|
|
|
|
2020-12-19 21:21:12 +08:00
|
|
|
If you wish to protect a list, tuple, or dictionary you can do so using the
|
|
|
|
``sign_object()`` and ``unsign_object()`` methods::
|
|
|
|
|
|
|
|
>>> signed_obj = signer.sign_object({'message': 'Hello!'})
|
|
|
|
>>> signed_obj
|
|
|
|
'eyJtZXNzYWdlIjoiSGVsbG8hIn0:Xdc-mOFDjs22KsQAqfVfi8PQSPdo3ckWJxPWwQOFhR4'
|
|
|
|
>>> obj = signer.unsign_object(signed_obj)
|
|
|
|
>>> obj
|
|
|
|
{'message': 'Hello!'}
|
|
|
|
|
|
|
|
See :ref:`signing-complex-data` for more details.
|
|
|
|
|
2011-05-21 22:41:14 +08:00
|
|
|
If the signature or value have been altered in any way, a
|
2011-05-23 21:23:00 +08:00
|
|
|
``django.core.signing.BadSignature`` exception will be raised::
|
2011-05-21 22:41:14 +08:00
|
|
|
|
2013-01-29 19:12:33 +08:00
|
|
|
>>> from django.core import signing
|
2011-05-21 22:41:14 +08:00
|
|
|
>>> value += 'm'
|
|
|
|
>>> try:
|
|
|
|
... original = signer.unsign(value)
|
|
|
|
... except signing.BadSignature:
|
2012-04-29 00:02:01 +08:00
|
|
|
... print("Tampering detected!")
|
2011-05-21 22:41:14 +08:00
|
|
|
|
|
|
|
By default, the ``Signer`` class uses the :setting:`SECRET_KEY` setting to
|
|
|
|
generate signatures. You can use a different secret by passing it to the
|
|
|
|
``Signer`` constructor::
|
|
|
|
|
|
|
|
>>> signer = Signer('my-other-secret')
|
|
|
|
>>> value = signer.sign('My string')
|
|
|
|
>>> value
|
|
|
|
'My string:EkfQJafvGyiofrdGnuthdxImIJw'
|
|
|
|
|
2021-12-14 11:47:03 +08:00
|
|
|
.. class:: Signer(key=None, sep=':', salt=None, algorithm=None, fallback_keys=None)
|
2013-07-03 14:13:38 +08:00
|
|
|
|
2013-10-30 02:36:22 +08:00
|
|
|
Returns a signer which uses ``key`` to generate signatures and ``sep`` to
|
2020-04-15 19:11:13 +08:00
|
|
|
separate values. ``sep`` cannot be in the :rfc:`URL safe base64 alphabet
|
|
|
|
<4648#section-5>`. This alphabet contains alphanumeric characters, hyphens,
|
|
|
|
and underscores. ``algorithm`` must be an algorithm supported by
|
2021-12-14 11:47:03 +08:00
|
|
|
:py:mod:`hashlib`, it defaults to ``'sha256'``. ``fallback_keys`` is a list
|
|
|
|
of additional values used to validate signed data, defaults to
|
|
|
|
:setting:`SECRET_KEY_FALLBACKS`.
|
|
|
|
|
|
|
|
.. versionchanged:: 4.1
|
|
|
|
|
|
|
|
The ``fallback_keys`` argument was added.
|
2020-02-14 03:55:48 +08:00
|
|
|
|
2016-01-25 05:26:11 +08:00
|
|
|
Using the ``salt`` argument
|
|
|
|
---------------------------
|
2011-05-21 22:41:14 +08:00
|
|
|
|
2011-08-26 16:18:05 +08:00
|
|
|
If you do not wish for every occurrence of a particular string to have the same
|
|
|
|
signature hash, you can use the optional ``salt`` argument to the ``Signer``
|
|
|
|
class. Using a salt will seed the signing hash function with both the salt and
|
|
|
|
your :setting:`SECRET_KEY`::
|
2011-05-21 22:41:14 +08:00
|
|
|
|
|
|
|
>>> signer = Signer()
|
|
|
|
>>> signer.sign('My string')
|
|
|
|
'My string:GdMGD6HNQ_qdgxYP8yBZAdAIV1w'
|
2020-12-19 21:21:12 +08:00
|
|
|
>>> signer.sign_object({'message': 'Hello!'})
|
|
|
|
'eyJtZXNzYWdlIjoiSGVsbG8hIn0:Xdc-mOFDjs22KsQAqfVfi8PQSPdo3ckWJxPWwQOFhR4'
|
2011-05-21 22:41:14 +08:00
|
|
|
>>> signer = Signer(salt='extra')
|
|
|
|
>>> signer.sign('My string')
|
|
|
|
'My string:Ee7vGi-ING6n02gkcJ-QLHg6vFw'
|
|
|
|
>>> signer.unsign('My string:Ee7vGi-ING6n02gkcJ-QLHg6vFw')
|
2014-03-23 04:30:49 +08:00
|
|
|
'My string'
|
2020-12-19 21:21:12 +08:00
|
|
|
>>> signer.sign_object({'message': 'Hello!'})
|
|
|
|
'eyJtZXNzYWdlIjoiSGVsbG8hIn0:-UWSLCE-oUAHzhkHviYz3SOZYBjFKllEOyVZNuUtM-I'
|
|
|
|
>>> signer.unsign_object('eyJtZXNzYWdlIjoiSGVsbG8hIn0:-UWSLCE-oUAHzhkHviYz3SOZYBjFKllEOyVZNuUtM-I')
|
|
|
|
{'message': 'Hello!'}
|
2011-05-21 22:41:14 +08:00
|
|
|
|
2011-08-26 16:18:05 +08:00
|
|
|
Using salt in this way puts the different signatures into different
|
|
|
|
namespaces. A signature that comes from one namespace (a particular salt
|
|
|
|
value) cannot be used to validate the same plaintext string in a different
|
|
|
|
namespace that is using a different salt setting. The result is to prevent an
|
|
|
|
attacker from using a signed string generated in one place in the code as input
|
|
|
|
to another piece of code that is generating (and verifying) signatures using a
|
|
|
|
different salt.
|
|
|
|
|
2011-05-21 22:41:14 +08:00
|
|
|
Unlike your :setting:`SECRET_KEY`, your salt argument does not need to stay
|
|
|
|
secret.
|
|
|
|
|
|
|
|
Verifying timestamped values
|
|
|
|
----------------------------
|
|
|
|
|
|
|
|
``TimestampSigner`` is a subclass of :class:`~Signer` that appends a signed
|
|
|
|
timestamp to the value. This allows you to confirm that a signed value was
|
|
|
|
created within a specified period of time::
|
|
|
|
|
2014-11-15 18:03:04 +08:00
|
|
|
>>> from datetime import timedelta
|
2011-05-21 22:41:14 +08:00
|
|
|
>>> from django.core.signing import TimestampSigner
|
|
|
|
>>> signer = TimestampSigner()
|
|
|
|
>>> value = signer.sign('hello')
|
|
|
|
>>> value
|
|
|
|
'hello:1NMg5H:oPVuCqlJWmChm1rA2lyTUtelC-c'
|
|
|
|
>>> signer.unsign(value)
|
2014-03-23 04:30:49 +08:00
|
|
|
'hello'
|
2011-05-21 22:41:14 +08:00
|
|
|
>>> signer.unsign(value, max_age=10)
|
|
|
|
...
|
|
|
|
SignatureExpired: Signature age 15.5289158821 > 10 seconds
|
|
|
|
>>> signer.unsign(value, max_age=20)
|
2014-03-23 04:30:49 +08:00
|
|
|
'hello'
|
2014-11-15 18:03:04 +08:00
|
|
|
>>> signer.unsign(value, max_age=timedelta(seconds=20))
|
|
|
|
'hello'
|
2011-05-21 22:41:14 +08:00
|
|
|
|
2020-02-14 03:55:48 +08:00
|
|
|
.. class:: TimestampSigner(key=None, sep=':', salt=None, algorithm='sha256')
|
2013-07-03 14:13:38 +08:00
|
|
|
|
|
|
|
.. method:: sign(value)
|
|
|
|
|
|
|
|
Sign ``value`` and append current timestamp to it.
|
|
|
|
|
|
|
|
.. method:: unsign(value, max_age=None)
|
|
|
|
|
|
|
|
Checks if ``value`` was signed less than ``max_age`` seconds ago,
|
2014-11-15 18:03:04 +08:00
|
|
|
otherwise raises ``SignatureExpired``. The ``max_age`` parameter can
|
|
|
|
accept an integer or a :py:class:`datetime.timedelta` object.
|
|
|
|
|
2020-12-19 21:21:12 +08:00
|
|
|
.. method:: sign_object(obj, serializer=JSONSerializer, compress=False)
|
|
|
|
|
|
|
|
Encode, optionally compress, append current timestamp, and sign complex
|
|
|
|
data structure (e.g. list, tuple, or dictionary).
|
|
|
|
|
|
|
|
.. method:: unsign_object(signed_obj, serializer=JSONSerializer, max_age=None)
|
|
|
|
|
|
|
|
Checks if ``signed_obj`` was signed less than ``max_age`` seconds ago,
|
|
|
|
otherwise raises ``SignatureExpired``. The ``max_age`` parameter can
|
|
|
|
accept an integer or a :py:class:`datetime.timedelta` object.
|
|
|
|
|
|
|
|
.. _signing-complex-data:
|
|
|
|
|
2011-05-21 22:41:14 +08:00
|
|
|
Protecting complex data structures
|
|
|
|
----------------------------------
|
|
|
|
|
|
|
|
If you wish to protect a list, tuple or dictionary you can do so using the
|
2020-12-19 21:21:12 +08:00
|
|
|
``Signer.sign_object()`` and ``unsign_object()`` methods, or signing module's
|
|
|
|
``dumps()`` or ``loads()`` functions (which are shortcuts for
|
|
|
|
``TimestampSigner(salt='django.core.signing').sign_object()/unsign_object()``).
|
|
|
|
These use JSON serialization under the hood. JSON ensures that even if your
|
|
|
|
:setting:`SECRET_KEY` is stolen an attacker will not be able to execute
|
|
|
|
arbitrary commands by exploiting the pickle format::
|
2011-05-21 22:41:14 +08:00
|
|
|
|
|
|
|
>>> from django.core import signing
|
2020-12-19 21:21:12 +08:00
|
|
|
>>> signer = signing.TimestampSigner()
|
|
|
|
>>> value = signer.sign_object({'foo': 'bar'})
|
|
|
|
>>> value
|
|
|
|
'eyJmb28iOiJiYXIifQ:1kx6R3:D4qGKiptAqo5QW9iv4eNLc6xl4RwiFfes6oOcYhkYnc'
|
|
|
|
>>> signer.unsign_object(value)
|
|
|
|
{'foo': 'bar'}
|
|
|
|
>>> value = signing.dumps({'foo': 'bar'})
|
2011-05-21 22:41:14 +08:00
|
|
|
>>> value
|
2020-12-19 21:21:12 +08:00
|
|
|
'eyJmb28iOiJiYXIifQ:1kx6Rf:LBB39RQmME-SRvilheUe5EmPYRbuDBgQp2tCAi7KGLk'
|
2011-05-21 22:41:14 +08:00
|
|
|
>>> signing.loads(value)
|
|
|
|
{'foo': 'bar'}
|
2011-05-23 21:23:00 +08:00
|
|
|
|
2014-02-16 19:21:35 +08:00
|
|
|
Because of the nature of JSON (there is no native distinction between lists
|
|
|
|
and tuples) if you pass in a tuple, you will get a list from
|
|
|
|
``signing.loads(object)``::
|
|
|
|
|
|
|
|
>>> from django.core import signing
|
|
|
|
>>> value = signing.dumps(('a','b','c'))
|
|
|
|
>>> signing.loads(value)
|
|
|
|
['a', 'b', 'c']
|
|
|
|
|
2020-07-31 13:38:01 +08:00
|
|
|
.. function:: dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False)
|
2011-05-23 21:23:00 +08:00
|
|
|
|
2020-07-31 13:33:13 +08:00
|
|
|
Returns URL-safe, signed base64 compressed JSON string. Serialized object
|
|
|
|
is signed using :class:`~TimestampSigner`.
|
2011-05-23 21:23:00 +08:00
|
|
|
|
2021-12-14 11:47:03 +08:00
|
|
|
.. function:: loads(string, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None, fallback_keys=None)
|
2011-05-23 21:23:00 +08:00
|
|
|
|
2013-07-03 14:13:38 +08:00
|
|
|
Reverse of ``dumps()``, raises ``BadSignature`` if signature fails.
|
|
|
|
Checks ``max_age`` (in seconds) if given.
|
2021-12-14 11:47:03 +08:00
|
|
|
|
|
|
|
.. versionchanged:: 4.1
|
|
|
|
|
|
|
|
The ``fallback_keys`` argument was added.
|