signing.txt 9.3 KB

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