1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
|
=====================
Cryptographic signing
=====================
.. module:: django.core.signing
:synopsis: Django's signing framework.
The golden rule of web application security is to never trust data from
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
signing in web applications.
You may also find signing useful for the following:
* Generating "recover my account" URLs for sending to users who have
lost their password.
* Ensuring data stored in hidden form fields has not been tampered with.
* Generating one-time secret URLs for allowing temporary access to a
protected resource, for example a downloadable file that a user has
paid for.
Protecting ``SECRET_KEY`` and ``SECRET_KEY_FALLBACKS``
======================================================
When you create a new Django project using :djadmin:`startproject`, the
``settings.py`` file is generated automatically and gets a random
: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.
: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.
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:
.. code-block:: pycon
>>> from django.core.signing import Signer
>>> signer = Signer()
>>> value = signer.sign("My string")
>>> value
'My string:v9G-nxfz3iQGTXrePqYPlGvH79WTcIgj1QIQSUODTW0'
The signature is appended to the end of the string, following the colon.
You can retrieve the original value using the ``unsign`` method:
.. code-block:: pycon
>>> original = signer.unsign(value)
>>> original
'My string'
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:
.. code-block:: pycon
>>> signed = signer.sign(2.5)
>>> original = signer.unsign(signed)
>>> original
'2.5'
If you wish to protect a list, tuple, or dictionary you can do so using the
``sign_object()`` and ``unsign_object()`` methods:
.. code-block:: pycon
>>> signed_obj = signer.sign_object({"message": "Hello!"})
>>> signed_obj
'eyJtZXNzYWdlIjoiSGVsbG8hIn0:bzb48DBkB-bwLaCnUVB75r5VAPUEpzWJPrTb80JMIXM'
>>> obj = signer.unsign_object(signed_obj)
>>> obj
{'message': 'Hello!'}
See :ref:`signing-complex-data` for more details.
If the signature or value have been altered in any way, a
``django.core.signing.BadSignature`` exception will be raised:
.. code-block:: pycon
>>> from django.core import signing
>>> value += "m"
>>> try:
... original = signer.unsign(value)
... except signing.BadSignature:
... print("Tampering detected!")
...
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:
.. code-block:: pycon
>>> signer = Signer(key="my-other-secret")
>>> value = signer.sign("My string")
>>> value
'My string:o3DrrsT6JRB73t-HDymfDNbTSxfMlom2d8TiUlb1hWY'
.. class:: Signer(*, key=None, sep=':', salt=None, algorithm=None, fallback_keys=None)
Returns a signer which uses ``key`` to generate signatures and ``sep`` to
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
: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`.
Using the ``salt`` argument
---------------------------
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`:
.. code-block:: pycon
>>> signer = Signer()
>>> signer.sign("My string")
'My string:v9G-nxfz3iQGTXrePqYPlGvH79WTcIgj1QIQSUODTW0'
>>> signer.sign_object({"message": "Hello!"})
'eyJtZXNzYWdlIjoiSGVsbG8hIn0:bzb48DBkB-bwLaCnUVB75r5VAPUEpzWJPrTb80JMIXM'
>>> signer = Signer(salt="extra")
>>> signer.sign("My string")
'My string:YMD-FR6rof3heDkFRffdmG4pXbAZSOtb-aQxg3vmmfc'
>>> signer.unsign("My string:YMD-FR6rof3heDkFRffdmG4pXbAZSOtb-aQxg3vmmfc")
'My string'
>>> signer.sign_object({"message": "Hello!"})
'eyJtZXNzYWdlIjoiSGVsbG8hIn0:-UWSLCE-oUAHzhkHviYz3SOZYBjFKllEOyVZNuUtM-I'
>>> signer.unsign_object(
... "eyJtZXNzYWdlIjoiSGVsbG8hIn0:-UWSLCE-oUAHzhkHviYz3SOZYBjFKllEOyVZNuUtM-I"
... )
{'message': 'Hello!'}
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.
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:
.. code-block:: pycon
>>> from datetime import timedelta
>>> from django.core.signing import TimestampSigner
>>> signer = TimestampSigner()
>>> value = signer.sign("hello")
>>> value
'hello:1stLqR:_rvr4oXCgT4HyfwjXaU39QvTnuNuUthFRCzNOy4Hqt0'
>>> signer.unsign(value)
'hello'
>>> signer.unsign(value, max_age=10)
SignatureExpired: Signature age 15.5289158821 > 10 seconds
>>> signer.unsign(value, max_age=20)
'hello'
>>> signer.unsign(value, max_age=timedelta(seconds=20))
'hello'
.. class:: TimestampSigner(*, key=None, sep=':', salt=None, algorithm='sha256')
.. 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,
otherwise raises ``SignatureExpired``. The ``max_age`` parameter can
accept an integer or a :class:`datetime.timedelta` object.
.. 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 :class:`datetime.timedelta` object.
.. _signing-complex-data:
Protecting complex data structures
----------------------------------
If you wish to protect a list, tuple or dictionary you can do so using the
``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:
.. code-block:: pycon
>>> from django.core import signing
>>> signer = signing.TimestampSigner()
>>> value = signer.sign_object({"foo": "bar"})
>>> value
'eyJmb28iOiJiYXIifQ:1stLrZ:_QiOBHafwucBF9FyAr54qEs84ZO1UdsO1XiTJCvvdno'
>>> signer.unsign_object(value)
{'foo': 'bar'}
>>> value = signing.dumps({"foo": "bar"})
>>> value
'eyJmb28iOiJiYXIifQ:1stLsC:JItq2ZVjmAK6ivrWI-v1Gk1QVf2hOF52oaEqhZHca7I'
>>> signing.loads(value)
{'foo': 'bar'}
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)``:
.. code-block:: pycon
>>> from django.core import signing
>>> value = signing.dumps(("a", "b", "c"))
>>> signing.loads(value)
['a', 'b', 'c']
.. function:: dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False)
Returns URL-safe, signed base64 compressed JSON string. Serialized object
is signed using :class:`~TimestampSigner`.
.. function:: loads(string, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None, fallback_keys=None)
Reverse of ``dumps()``, raises ``BadSignature`` if signature fails.
Checks ``max_age`` (in seconds) if given.
|