signing.txt 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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. .. versionchanged:: 4.1
  31. The ``SECRET_KEY_FALLBACKS`` setting was added.
  32. Using the low-level API
  33. =======================
  34. Django's signing methods live in the ``django.core.signing`` module.
  35. To sign a value, first instantiate a ``Signer`` instance::
  36. >>> from django.core.signing import Signer
  37. >>> signer = Signer()
  38. >>> value = signer.sign('My string')
  39. >>> value
  40. 'My string:GdMGD6HNQ_qdgxYP8yBZAdAIV1w'
  41. The signature is appended to the end of the string, following the colon.
  42. You can retrieve the original value using the ``unsign`` method::
  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. >>> signed = signer.sign(2.5)
  50. >>> original = signer.unsign(signed)
  51. >>> original
  52. '2.5'
  53. If you wish to protect a list, tuple, or dictionary you can do so using the
  54. ``sign_object()`` and ``unsign_object()`` methods::
  55. >>> signed_obj = signer.sign_object({'message': 'Hello!'})
  56. >>> signed_obj
  57. 'eyJtZXNzYWdlIjoiSGVsbG8hIn0:Xdc-mOFDjs22KsQAqfVfi8PQSPdo3ckWJxPWwQOFhR4'
  58. >>> obj = signer.unsign_object(signed_obj)
  59. >>> obj
  60. {'message': 'Hello!'}
  61. See :ref:`signing-complex-data` for more details.
  62. If the signature or value have been altered in any way, a
  63. ``django.core.signing.BadSignature`` exception will be raised::
  64. >>> from django.core import signing
  65. >>> value += 'm'
  66. >>> try:
  67. ... original = signer.unsign(value)
  68. ... except signing.BadSignature:
  69. ... print("Tampering detected!")
  70. By default, the ``Signer`` class uses the :setting:`SECRET_KEY` setting to
  71. generate signatures. You can use a different secret by passing it to the
  72. ``Signer`` constructor::
  73. >>> signer = Signer(key='my-other-secret')
  74. >>> value = signer.sign('My string')
  75. >>> value
  76. 'My string:EkfQJafvGyiofrdGnuthdxImIJw'
  77. .. class:: Signer(*, key=None, sep=':', salt=None, algorithm=None, fallback_keys=None)
  78. Returns a signer which uses ``key`` to generate signatures and ``sep`` to
  79. separate values. ``sep`` cannot be in the :rfc:`URL safe base64 alphabet
  80. <4648#section-5>`. This alphabet contains alphanumeric characters, hyphens,
  81. and underscores. ``algorithm`` must be an algorithm supported by
  82. :py:mod:`hashlib`, it defaults to ``'sha256'``. ``fallback_keys`` is a list
  83. of additional values used to validate signed data, defaults to
  84. :setting:`SECRET_KEY_FALLBACKS`.
  85. .. versionchanged:: 4.1
  86. The ``fallback_keys`` argument was added.
  87. .. deprecated:: 4.2
  88. Support for passing positional arguments is deprecated.
  89. Using the ``salt`` argument
  90. ---------------------------
  91. If you do not wish for every occurrence of a particular string to have the same
  92. signature hash, you can use the optional ``salt`` argument to the ``Signer``
  93. class. Using a salt will seed the signing hash function with both the salt and
  94. your :setting:`SECRET_KEY`::
  95. >>> signer = Signer()
  96. >>> signer.sign('My string')
  97. 'My string:GdMGD6HNQ_qdgxYP8yBZAdAIV1w'
  98. >>> signer.sign_object({'message': 'Hello!'})
  99. 'eyJtZXNzYWdlIjoiSGVsbG8hIn0:Xdc-mOFDjs22KsQAqfVfi8PQSPdo3ckWJxPWwQOFhR4'
  100. >>> signer = Signer(salt='extra')
  101. >>> signer.sign('My string')
  102. 'My string:Ee7vGi-ING6n02gkcJ-QLHg6vFw'
  103. >>> signer.unsign('My string:Ee7vGi-ING6n02gkcJ-QLHg6vFw')
  104. 'My string'
  105. >>> signer.sign_object({'message': 'Hello!'})
  106. 'eyJtZXNzYWdlIjoiSGVsbG8hIn0:-UWSLCE-oUAHzhkHviYz3SOZYBjFKllEOyVZNuUtM-I'
  107. >>> signer.unsign_object('eyJtZXNzYWdlIjoiSGVsbG8hIn0:-UWSLCE-oUAHzhkHviYz3SOZYBjFKllEOyVZNuUtM-I')
  108. {'message': 'Hello!'}
  109. Using salt in this way puts the different signatures into different
  110. namespaces. A signature that comes from one namespace (a particular salt
  111. value) cannot be used to validate the same plaintext string in a different
  112. namespace that is using a different salt setting. The result is to prevent an
  113. attacker from using a signed string generated in one place in the code as input
  114. to another piece of code that is generating (and verifying) signatures using a
  115. different salt.
  116. Unlike your :setting:`SECRET_KEY`, your salt argument does not need to stay
  117. secret.
  118. Verifying timestamped values
  119. ----------------------------
  120. ``TimestampSigner`` is a subclass of :class:`~Signer` that appends a signed
  121. timestamp to the value. This allows you to confirm that a signed value was
  122. created within a specified period of time::
  123. >>> from datetime import timedelta
  124. >>> from django.core.signing import TimestampSigner
  125. >>> signer = TimestampSigner()
  126. >>> value = signer.sign('hello')
  127. >>> value
  128. 'hello:1NMg5H:oPVuCqlJWmChm1rA2lyTUtelC-c'
  129. >>> signer.unsign(value)
  130. 'hello'
  131. >>> signer.unsign(value, max_age=10)
  132. ...
  133. SignatureExpired: Signature age 15.5289158821 > 10 seconds
  134. >>> signer.unsign(value, max_age=20)
  135. 'hello'
  136. >>> signer.unsign(value, max_age=timedelta(seconds=20))
  137. 'hello'
  138. .. class:: TimestampSigner(*, key=None, sep=':', salt=None, algorithm='sha256')
  139. .. method:: sign(value)
  140. Sign ``value`` and append current timestamp to it.
  141. .. method:: unsign(value, max_age=None)
  142. Checks if ``value`` was signed less than ``max_age`` seconds ago,
  143. otherwise raises ``SignatureExpired``. The ``max_age`` parameter can
  144. accept an integer or a :py:class:`datetime.timedelta` object.
  145. .. method:: sign_object(obj, serializer=JSONSerializer, compress=False)
  146. Encode, optionally compress, append current timestamp, and sign complex
  147. data structure (e.g. list, tuple, or dictionary).
  148. .. method:: unsign_object(signed_obj, serializer=JSONSerializer, max_age=None)
  149. Checks if ``signed_obj`` was signed less than ``max_age`` seconds ago,
  150. otherwise raises ``SignatureExpired``. The ``max_age`` parameter can
  151. accept an integer or a :py:class:`datetime.timedelta` object.
  152. .. deprecated:: 4.2
  153. Support for passing positional arguments is deprecated.
  154. .. _signing-complex-data:
  155. Protecting complex data structures
  156. ----------------------------------
  157. If you wish to protect a list, tuple or dictionary you can do so using the
  158. ``Signer.sign_object()`` and ``unsign_object()`` methods, or signing module's
  159. ``dumps()`` or ``loads()`` functions (which are shortcuts for
  160. ``TimestampSigner(salt='django.core.signing').sign_object()/unsign_object()``).
  161. These use JSON serialization under the hood. JSON ensures that even if your
  162. :setting:`SECRET_KEY` is stolen an attacker will not be able to execute
  163. arbitrary commands by exploiting the pickle format::
  164. >>> from django.core import signing
  165. >>> signer = signing.TimestampSigner()
  166. >>> value = signer.sign_object({'foo': 'bar'})
  167. >>> value
  168. 'eyJmb28iOiJiYXIifQ:1kx6R3:D4qGKiptAqo5QW9iv4eNLc6xl4RwiFfes6oOcYhkYnc'
  169. >>> signer.unsign_object(value)
  170. {'foo': 'bar'}
  171. >>> value = signing.dumps({'foo': 'bar'})
  172. >>> value
  173. 'eyJmb28iOiJiYXIifQ:1kx6Rf:LBB39RQmME-SRvilheUe5EmPYRbuDBgQp2tCAi7KGLk'
  174. >>> signing.loads(value)
  175. {'foo': 'bar'}
  176. Because of the nature of JSON (there is no native distinction between lists
  177. and tuples) if you pass in a tuple, you will get a list from
  178. ``signing.loads(object)``::
  179. >>> from django.core import signing
  180. >>> value = signing.dumps(('a','b','c'))
  181. >>> signing.loads(value)
  182. ['a', 'b', 'c']
  183. .. function:: dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False)
  184. Returns URL-safe, signed base64 compressed JSON string. Serialized object
  185. is signed using :class:`~TimestampSigner`.
  186. .. function:: loads(string, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None, fallback_keys=None)
  187. Reverse of ``dumps()``, raises ``BadSignature`` if signature fails.
  188. Checks ``max_age`` (in seconds) if given.
  189. .. versionchanged:: 4.1
  190. The ``fallback_keys`` argument was added.