| 1 |
===================== |
| 2 |
Cryptographic signing |
| 3 |
===================== |
| 4 |
|
| 5 |
.. module:: django.core.signing |
| 6 |
:synopsis: Django's signing framework. |
| 7 |
|
| 8 |
The golden rule of web application security is to never trust data from |
| 9 |
untrusted sources. Sometimes it can be useful to pass data through an |
| 10 |
untrusted medium. Cryptographically signed values can be passed through an |
| 11 |
untrusted channel safe in the knowledge that any tampering will be detected. |
| 12 |
|
| 13 |
Django provides both a low-level API for signing values and a high-level API |
| 14 |
for setting and reading signed cookies, one of the most common uses of |
| 15 |
signing in web applications. |
| 16 |
|
| 17 |
You may also find signing useful for the following: |
| 18 |
|
| 19 |
* Generating "recover my account" URLs for sending to users who have |
| 20 |
lost their password. |
| 21 |
|
| 22 |
* Ensuring data stored in hidden form fields has not been tampered with. |
| 23 |
|
| 24 |
* Generating one-time secret URLs for allowing temporary access to a |
| 25 |
protected resource, for example a downloadable file that a user has |
| 26 |
paid for. |
| 27 |
|
| 28 |
Protecting ``SECRET_KEY`` and ``SECRET_KEY_FALLBACKS`` |
| 29 |
====================================================== |
| 30 |
|
| 31 |
When you create a new Django project using :djadmin:`startproject`, the |
| 32 |
``settings.py`` file is generated automatically and gets a random |
| 33 |
:setting:`SECRET_KEY` value. This value is the key to securing signed |
| 34 |
data -- it is vital you keep this secure, or attackers could use it to |
| 35 |
generate their own signed values. |
| 36 |
|
| 37 |
:setting:`SECRET_KEY_FALLBACKS` can be used to rotate secret keys. The |
| 38 |
values will not be used to sign data, but if specified, they will be used to |
| 39 |
validate signed data and must be kept secure. |
| 40 |
|
| 41 |
Using the low-level API |
| 42 |
======================= |
| 43 |
|
| 44 |
Django's signing methods live in the ``django.core.signing`` module. |
| 45 |
To sign a value, first instantiate a ``Signer`` instance: |
| 46 |
|
| 47 |
.. code-block:: pycon |
| 48 |
|
| 49 |
>>> from django.core.signing import Signer |
| 50 |
>>> signer = Signer() |
| 51 |
>>> value = signer.sign("My string") |
| 52 |
>>> value |
| 53 |
'My string:v9G-nxfz3iQGTXrePqYPlGvH79WTcIgj1QIQSUODTW0' |
| 54 |
|
| 55 |
The signature is appended to the end of the string, following the colon. |
| 56 |
You can retrieve the original value using the ``unsign`` method: |
| 57 |
|
| 58 |
.. code-block:: pycon |
| 59 |
|
| 60 |
>>> original = signer.unsign(value) |
| 61 |
>>> original |
| 62 |
'My string' |
| 63 |
|
| 64 |
If you pass a non-string value to ``sign``, the value will be forced to string |
| 65 |
before being signed, and the ``unsign`` result will give you that string |
| 66 |
value: |
| 67 |
|
| 68 |
.. code-block:: pycon |
| 69 |
|
| 70 |
>>> signed = signer.sign(2.5) |
| 71 |
>>> original = signer.unsign(signed) |
| 72 |
>>> original |
| 73 |
'2.5' |
| 74 |
|
| 75 |
If you wish to protect a list, tuple, or dictionary you can do so using the |
| 76 |
``sign_object()`` and ``unsign_object()`` methods: |
| 77 |
|
| 78 |
.. code-block:: pycon |
| 79 |
|
| 80 |
>>> signed_obj = signer.sign_object({"message": "Hello!"}) |
| 81 |
>>> signed_obj |
| 82 |
'eyJtZXNzYWdlIjoiSGVsbG8hIn0:bzb48DBkB-bwLaCnUVB75r5VAPUEpzWJPrTb80JMIXM' |
| 83 |
>>> obj = signer.unsign_object(signed_obj) |
| 84 |
>>> obj |
| 85 |
{'message': 'Hello!'} |
| 86 |
|
| 87 |
See :ref:`signing-complex-data` for more details. |
| 88 |
|
| 89 |
If the signature or value have been altered in any way, a |
| 90 |
``django.core.signing.BadSignature`` exception will be raised: |
| 91 |
|
| 92 |
.. code-block:: pycon |
| 93 |
|
| 94 |
>>> from django.core import signing |
| 95 |
>>> value += "m" |
| 96 |
>>> try: |
| 97 |
... original = signer.unsign(value) |
| 98 |
... except signing.BadSignature: |
| 99 |
... print("Tampering detected!") |
| 100 |
... |
| 101 |
|
| 102 |
By default, the ``Signer`` class uses the :setting:`SECRET_KEY` setting to |
| 103 |
generate signatures. You can use a different secret by passing it to the |
| 104 |
``Signer`` constructor: |
| 105 |
|
| 106 |
.. code-block:: pycon |
| 107 |
|
| 108 |
>>> signer = Signer(key="my-other-secret") |
| 109 |
>>> value = signer.sign("My string") |
| 110 |
>>> value |
| 111 |
'My string:o3DrrsT6JRB73t-HDymfDNbTSxfMlom2d8TiUlb1hWY' |
| 112 |
|
| 113 |
.. class:: Signer(*, key=None, sep=':', salt=None, algorithm=None, fallback_keys=None) |
| 114 |
|
| 115 |
Returns a signer which uses ``key`` to generate signatures and ``sep`` to |
| 116 |
separate values. ``sep`` cannot be in the :rfc:`URL safe base64 alphabet |
| 117 |
<4648#section-5>`. This alphabet contains alphanumeric characters, hyphens, |
| 118 |
and underscores. ``algorithm`` must be an algorithm supported by |
| 119 |
:py:mod:`hashlib`, it defaults to ``'sha256'``. ``fallback_keys`` is a list |
| 120 |
of additional values used to validate signed data, defaults to |
| 121 |
:setting:`SECRET_KEY_FALLBACKS`. |
| 122 |
|
| 123 |
Using the ``salt`` argument |
| 124 |
--------------------------- |
| 125 |
|
| 126 |
If you do not wish for every occurrence of a particular string to have the same |
| 127 |
signature hash, you can use the optional ``salt`` argument to the ``Signer`` |
| 128 |
class. Using a salt will seed the signing hash function with both the salt and |
| 129 |
your :setting:`SECRET_KEY`: |
| 130 |
|
| 131 |
.. code-block:: pycon |
| 132 |
|
| 133 |
>>> signer = Signer() |
| 134 |
>>> signer.sign("My string") |
| 135 |
'My string:v9G-nxfz3iQGTXrePqYPlGvH79WTcIgj1QIQSUODTW0' |
| 136 |
>>> signer.sign_object({"message": "Hello!"}) |
| 137 |
'eyJtZXNzYWdlIjoiSGVsbG8hIn0:bzb48DBkB-bwLaCnUVB75r5VAPUEpzWJPrTb80JMIXM' |
| 138 |
>>> signer = Signer(salt="extra") |
| 139 |
>>> signer.sign("My string") |
| 140 |
'My string:YMD-FR6rof3heDkFRffdmG4pXbAZSOtb-aQxg3vmmfc' |
| 141 |
>>> signer.unsign("My string:YMD-FR6rof3heDkFRffdmG4pXbAZSOtb-aQxg3vmmfc") |
| 142 |
'My string' |
| 143 |
>>> signer.sign_object({"message": "Hello!"}) |
| 144 |
'eyJtZXNzYWdlIjoiSGVsbG8hIn0:-UWSLCE-oUAHzhkHviYz3SOZYBjFKllEOyVZNuUtM-I' |
| 145 |
>>> signer.unsign_object( |
| 146 |
... "eyJtZXNzYWdlIjoiSGVsbG8hIn0:-UWSLCE-oUAHzhkHviYz3SOZYBjFKllEOyVZNuUtM-I" |
| 147 |
... ) |
| 148 |
{'message': 'Hello!'} |
| 149 |
|
| 150 |
Using salt in this way puts the different signatures into different |
| 151 |
namespaces. A signature that comes from one namespace (a particular salt |
| 152 |
value) cannot be used to validate the same plaintext string in a different |
| 153 |
namespace that is using a different salt setting. The result is to prevent an |
| 154 |
attacker from using a signed string generated in one place in the code as input |
| 155 |
to another piece of code that is generating (and verifying) signatures using a |
| 156 |
different salt. |
| 157 |
|
| 158 |
Unlike your :setting:`SECRET_KEY`, your salt argument does not need to stay |
| 159 |
secret. |
| 160 |
|
| 161 |
Verifying timestamped values |
| 162 |
---------------------------- |
| 163 |
|
| 164 |
``TimestampSigner`` is a subclass of :class:`~Signer` that appends a signed |
| 165 |
timestamp to the value. This allows you to confirm that a signed value was |
| 166 |
created within a specified period of time: |
| 167 |
|
| 168 |
.. code-block:: pycon |
| 169 |
|
| 170 |
>>> from datetime import timedelta |
| 171 |
>>> from django.core.signing import TimestampSigner |
| 172 |
>>> signer = TimestampSigner() |
| 173 |
>>> value = signer.sign("hello") |
| 174 |
>>> value |
| 175 |
'hello:1stLqR:_rvr4oXCgT4HyfwjXaU39QvTnuNuUthFRCzNOy4Hqt0' |
| 176 |
>>> signer.unsign(value) |
| 177 |
'hello' |
| 178 |
>>> signer.unsign(value, max_age=10) |
| 179 |
SignatureExpired: Signature age 15.5289158821 > 10 seconds |
| 180 |
>>> signer.unsign(value, max_age=20) |
| 181 |
'hello' |
| 182 |
>>> signer.unsign(value, max_age=timedelta(seconds=20)) |
| 183 |
'hello' |
| 184 |
|
| 185 |
.. class:: TimestampSigner(*, key=None, sep=':', salt=None, algorithm='sha256') |
| 186 |
|
| 187 |
.. method:: sign(value) |
| 188 |
|
| 189 |
Sign ``value`` and append current timestamp to it. |
| 190 |
|
| 191 |
.. method:: unsign(value, max_age=None) |
| 192 |
|
| 193 |
Checks if ``value`` was signed less than ``max_age`` seconds ago, |
| 194 |
otherwise raises ``SignatureExpired``. The ``max_age`` parameter can |
| 195 |
accept an integer or a :py:class:`datetime.timedelta` object. |
| 196 |
|
| 197 |
.. method:: sign_object(obj, serializer=JSONSerializer, compress=False) |
| 198 |
|
| 199 |
Encode, optionally compress, append current timestamp, and sign complex |
| 200 |
data structure (e.g. list, tuple, or dictionary). |
| 201 |
|
| 202 |
.. method:: unsign_object(signed_obj, serializer=JSONSerializer, max_age=None) |
| 203 |
|
| 204 |
Checks if ``signed_obj`` was signed less than ``max_age`` seconds ago, |
| 205 |
otherwise raises ``SignatureExpired``. The ``max_age`` parameter can |
| 206 |
accept an integer or a :py:class:`datetime.timedelta` object. |
| 207 |
|
| 208 |
.. _signing-complex-data: |
| 209 |
|
| 210 |
Protecting complex data structures |
| 211 |
---------------------------------- |
| 212 |
|
| 213 |
If you wish to protect a list, tuple or dictionary you can do so using the |
| 214 |
``Signer.sign_object()`` and ``unsign_object()`` methods, or signing module's |
| 215 |
``dumps()`` or ``loads()`` functions (which are shortcuts for |
| 216 |
``TimestampSigner(salt='django.core.signing').sign_object()/unsign_object()``). |
| 217 |
These use JSON serialization under the hood. JSON ensures that even if your |
| 218 |
:setting:`SECRET_KEY` is stolen an attacker will not be able to execute |
| 219 |
arbitrary commands by exploiting the pickle format: |
| 220 |
|
| 221 |
.. code-block:: pycon |
| 222 |
|
| 223 |
>>> from django.core import signing |
| 224 |
>>> signer = signing.TimestampSigner() |
| 225 |
>>> value = signer.sign_object({"foo": "bar"}) |
| 226 |
>>> value |
| 227 |
'eyJmb28iOiJiYXIifQ:1stLrZ:_QiOBHafwucBF9FyAr54qEs84ZO1UdsO1XiTJCvvdno' |
| 228 |
>>> signer.unsign_object(value) |
| 229 |
{'foo': 'bar'} |
| 230 |
>>> value = signing.dumps({"foo": "bar"}) |
| 231 |
>>> value |
| 232 |
'eyJmb28iOiJiYXIifQ:1stLsC:JItq2ZVjmAK6ivrWI-v1Gk1QVf2hOF52oaEqhZHca7I' |
| 233 |
>>> signing.loads(value) |
| 234 |
{'foo': 'bar'} |
| 235 |
|
| 236 |
Because of the nature of JSON (there is no native distinction between lists |
| 237 |
and tuples) if you pass in a tuple, you will get a list from |
| 238 |
``signing.loads(object)``: |
| 239 |
|
| 240 |
.. code-block:: pycon |
| 241 |
|
| 242 |
>>> from django.core import signing |
| 243 |
>>> value = signing.dumps(("a", "b", "c")) |
| 244 |
>>> signing.loads(value) |
| 245 |
['a', 'b', 'c'] |
| 246 |
|
| 247 |
.. function:: dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False) |
| 248 |
|
| 249 |
Returns URL-safe, signed base64 compressed JSON string. Serialized object |
| 250 |
is signed using :class:`~TimestampSigner`. |
| 251 |
|
| 252 |
.. function:: loads(string, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None, fallback_keys=None) |
| 253 |
|
| 254 |
Reverse of ``dumps()``, raises ``BadSignature`` if signature fails. |
| 255 |
Checks ``max_age`` (in seconds) if given. |