signing.txt 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  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('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. Using the ``salt`` argument
  88. ---------------------------
  89. If you do not wish for every occurrence of a particular string to have the same
  90. signature hash, you can use the optional ``salt`` argument to the ``Signer``
  91. class. Using a salt will seed the signing hash function with both the salt and
  92. your :setting:`SECRET_KEY`::
  93. >>> signer = Signer()
  94. >>> signer.sign('My string')
  95. 'My string:GdMGD6HNQ_qdgxYP8yBZAdAIV1w'
  96. >>> signer.sign_object({'message': 'Hello!'})
  97. 'eyJtZXNzYWdlIjoiSGVsbG8hIn0:Xdc-mOFDjs22KsQAqfVfi8PQSPdo3ckWJxPWwQOFhR4'
  98. >>> signer = Signer(salt='extra')
  99. >>> signer.sign('My string')
  100. 'My string:Ee7vGi-ING6n02gkcJ-QLHg6vFw'
  101. >>> signer.unsign('My string:Ee7vGi-ING6n02gkcJ-QLHg6vFw')
  102. 'My string'
  103. >>> signer.sign_object({'message': 'Hello!'})
  104. 'eyJtZXNzYWdlIjoiSGVsbG8hIn0:-UWSLCE-oUAHzhkHviYz3SOZYBjFKllEOyVZNuUtM-I'
  105. >>> signer.unsign_object('eyJtZXNzYWdlIjoiSGVsbG8hIn0:-UWSLCE-oUAHzhkHviYz3SOZYBjFKllEOyVZNuUtM-I')
  106. {'message': 'Hello!'}
  107. Using salt in this way puts the different signatures into different
  108. namespaces. A signature that comes from one namespace (a particular salt
  109. value) cannot be used to validate the same plaintext string in a different
  110. namespace that is using a different salt setting. The result is to prevent an
  111. attacker from using a signed string generated in one place in the code as input
  112. to another piece of code that is generating (and verifying) signatures using a
  113. different salt.
  114. Unlike your :setting:`SECRET_KEY`, your salt argument does not need to stay
  115. secret.
  116. Verifying timestamped values
  117. ----------------------------
  118. ``TimestampSigner`` is a subclass of :class:`~Signer` that appends a signed
  119. timestamp to the value. This allows you to confirm that a signed value was
  120. created within a specified period of time::
  121. >>> from datetime import timedelta
  122. >>> from django.core.signing import TimestampSigner
  123. >>> signer = TimestampSigner()
  124. >>> value = signer.sign('hello')
  125. >>> value
  126. 'hello:1NMg5H:oPVuCqlJWmChm1rA2lyTUtelC-c'
  127. >>> signer.unsign(value)
  128. 'hello'
  129. >>> signer.unsign(value, max_age=10)
  130. ...
  131. SignatureExpired: Signature age 15.5289158821 > 10 seconds
  132. >>> signer.unsign(value, max_age=20)
  133. 'hello'
  134. >>> signer.unsign(value, max_age=timedelta(seconds=20))
  135. 'hello'
  136. .. class:: TimestampSigner(key=None, sep=':', salt=None, algorithm='sha256')
  137. .. method:: sign(value)
  138. Sign ``value`` and append current timestamp to it.
  139. .. method:: unsign(value, max_age=None)
  140. Checks if ``value`` was signed less than ``max_age`` seconds ago,
  141. otherwise raises ``SignatureExpired``. The ``max_age`` parameter can
  142. accept an integer or a :py:class:`datetime.timedelta` object.
  143. .. method:: sign_object(obj, serializer=JSONSerializer, compress=False)
  144. Encode, optionally compress, append current timestamp, and sign complex
  145. data structure (e.g. list, tuple, or dictionary).
  146. .. method:: unsign_object(signed_obj, serializer=JSONSerializer, max_age=None)
  147. Checks if ``signed_obj`` was signed less than ``max_age`` seconds ago,
  148. otherwise raises ``SignatureExpired``. The ``max_age`` parameter can
  149. accept an integer or a :py:class:`datetime.timedelta` object.
  150. .. _signing-complex-data:
  151. Protecting complex data structures
  152. ----------------------------------
  153. If you wish to protect a list, tuple or dictionary you can do so using the
  154. ``Signer.sign_object()`` and ``unsign_object()`` methods, or signing module's
  155. ``dumps()`` or ``loads()`` functions (which are shortcuts for
  156. ``TimestampSigner(salt='django.core.signing').sign_object()/unsign_object()``).
  157. These use JSON serialization under the hood. JSON ensures that even if your
  158. :setting:`SECRET_KEY` is stolen an attacker will not be able to execute
  159. arbitrary commands by exploiting the pickle format::
  160. >>> from django.core import signing
  161. >>> signer = signing.TimestampSigner()
  162. >>> value = signer.sign_object({'foo': 'bar'})
  163. >>> value
  164. 'eyJmb28iOiJiYXIifQ:1kx6R3:D4qGKiptAqo5QW9iv4eNLc6xl4RwiFfes6oOcYhkYnc'
  165. >>> signer.unsign_object(value)
  166. {'foo': 'bar'}
  167. >>> value = signing.dumps({'foo': 'bar'})
  168. >>> value
  169. 'eyJmb28iOiJiYXIifQ:1kx6Rf:LBB39RQmME-SRvilheUe5EmPYRbuDBgQp2tCAi7KGLk'
  170. >>> signing.loads(value)
  171. {'foo': 'bar'}
  172. Because of the nature of JSON (there is no native distinction between lists
  173. and tuples) if you pass in a tuple, you will get a list from
  174. ``signing.loads(object)``::
  175. >>> from django.core import signing
  176. >>> value = signing.dumps(('a','b','c'))
  177. >>> signing.loads(value)
  178. ['a', 'b', 'c']
  179. .. function:: dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False)
  180. Returns URL-safe, signed base64 compressed JSON string. Serialized object
  181. is signed using :class:`~TimestampSigner`.
  182. .. function:: loads(string, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None, fallback_keys=None)
  183. Reverse of ``dumps()``, raises ``BadSignature`` if signature fails.
  184. Checks ``max_age`` (in seconds) if given.
  185. .. versionchanged:: 4.1
  186. The ``fallback_keys`` argument was added.