signing.txt 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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 the ``SECRET_KEY``
  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. Using the low-level API
  28. =======================
  29. Django's signing methods live in the ``django.core.signing`` module.
  30. To sign a value, first instantiate a ``Signer`` instance::
  31. >>> from django.core.signing import Signer
  32. >>> signer = Signer()
  33. >>> value = signer.sign('My string')
  34. >>> value
  35. 'My string:GdMGD6HNQ_qdgxYP8yBZAdAIV1w'
  36. The signature is appended to the end of the string, following the colon.
  37. You can retrieve the original value using the ``unsign`` method::
  38. >>> original = signer.unsign(value)
  39. >>> original
  40. 'My string'
  41. If you pass a non-string value to ``sign``, the value will be forced to string
  42. before being signed, and the ``unsign`` result will give you that string
  43. value::
  44. >>> signed = signer.sign(2.5)
  45. >>> original = signer.unsign(signed)
  46. >>> original
  47. '2.5'
  48. If the signature or value have been altered in any way, a
  49. ``django.core.signing.BadSignature`` exception will be raised::
  50. >>> from django.core import signing
  51. >>> value += 'm'
  52. >>> try:
  53. ... original = signer.unsign(value)
  54. ... except signing.BadSignature:
  55. ... print("Tampering detected!")
  56. By default, the ``Signer`` class uses the :setting:`SECRET_KEY` setting to
  57. generate signatures. You can use a different secret by passing it to the
  58. ``Signer`` constructor::
  59. >>> signer = Signer('my-other-secret')
  60. >>> value = signer.sign('My string')
  61. >>> value
  62. 'My string:EkfQJafvGyiofrdGnuthdxImIJw'
  63. .. class:: Signer(key=None, sep=':', salt=None, algorithm=None)
  64. Returns a signer which uses ``key`` to generate signatures and ``sep`` to
  65. separate values. ``sep`` cannot be in the :rfc:`URL safe base64 alphabet
  66. <4648#section-5>`. This alphabet contains alphanumeric characters, hyphens,
  67. and underscores. ``algorithm`` must be an algorithm supported by
  68. :py:mod:`hashlib`, it defaults to ``'sha256'``.
  69. .. versionchanged:: 3.1
  70. The ``algorithm`` parameter was added.
  71. Using the ``salt`` argument
  72. ---------------------------
  73. If you do not wish for every occurrence of a particular string to have the same
  74. signature hash, you can use the optional ``salt`` argument to the ``Signer``
  75. class. Using a salt will seed the signing hash function with both the salt and
  76. your :setting:`SECRET_KEY`::
  77. >>> signer = Signer()
  78. >>> signer.sign('My string')
  79. 'My string:GdMGD6HNQ_qdgxYP8yBZAdAIV1w'
  80. >>> signer = Signer(salt='extra')
  81. >>> signer.sign('My string')
  82. 'My string:Ee7vGi-ING6n02gkcJ-QLHg6vFw'
  83. >>> signer.unsign('My string:Ee7vGi-ING6n02gkcJ-QLHg6vFw')
  84. 'My string'
  85. Using salt in this way puts the different signatures into different
  86. namespaces. A signature that comes from one namespace (a particular salt
  87. value) cannot be used to validate the same plaintext string in a different
  88. namespace that is using a different salt setting. The result is to prevent an
  89. attacker from using a signed string generated in one place in the code as input
  90. to another piece of code that is generating (and verifying) signatures using a
  91. different salt.
  92. Unlike your :setting:`SECRET_KEY`, your salt argument does not need to stay
  93. secret.
  94. Verifying timestamped values
  95. ----------------------------
  96. ``TimestampSigner`` is a subclass of :class:`~Signer` that appends a signed
  97. timestamp to the value. This allows you to confirm that a signed value was
  98. created within a specified period of time::
  99. >>> from datetime import timedelta
  100. >>> from django.core.signing import TimestampSigner
  101. >>> signer = TimestampSigner()
  102. >>> value = signer.sign('hello')
  103. >>> value
  104. 'hello:1NMg5H:oPVuCqlJWmChm1rA2lyTUtelC-c'
  105. >>> signer.unsign(value)
  106. 'hello'
  107. >>> signer.unsign(value, max_age=10)
  108. ...
  109. SignatureExpired: Signature age 15.5289158821 > 10 seconds
  110. >>> signer.unsign(value, max_age=20)
  111. 'hello'
  112. >>> signer.unsign(value, max_age=timedelta(seconds=20))
  113. 'hello'
  114. .. class:: TimestampSigner(key=None, sep=':', salt=None, algorithm='sha256')
  115. .. method:: sign(value)
  116. Sign ``value`` and append current timestamp to it.
  117. .. method:: unsign(value, max_age=None)
  118. Checks if ``value`` was signed less than ``max_age`` seconds ago,
  119. otherwise raises ``SignatureExpired``. The ``max_age`` parameter can
  120. accept an integer or a :py:class:`datetime.timedelta` object.
  121. .. versionchanged:: 3.1
  122. The ``algorithm`` parameter was added.
  123. Protecting complex data structures
  124. ----------------------------------
  125. If you wish to protect a list, tuple or dictionary you can do so using the
  126. signing module's ``dumps`` and ``loads`` functions. These imitate Python's
  127. pickle module, but use JSON serialization under the hood. JSON ensures that
  128. even if your :setting:`SECRET_KEY` is stolen an attacker will not be able
  129. to execute arbitrary commands by exploiting the pickle format::
  130. >>> from django.core import signing
  131. >>> value = signing.dumps({"foo": "bar"})
  132. >>> value
  133. 'eyJmb28iOiJiYXIifQ:1NMg1b:zGcDE4-TCkaeGzLeW9UQwZesciI'
  134. >>> signing.loads(value)
  135. {'foo': 'bar'}
  136. Because of the nature of JSON (there is no native distinction between lists
  137. and tuples) if you pass in a tuple, you will get a list from
  138. ``signing.loads(object)``::
  139. >>> from django.core import signing
  140. >>> value = signing.dumps(('a','b','c'))
  141. >>> signing.loads(value)
  142. ['a', 'b', 'c']
  143. .. function:: dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False)
  144. Returns URL-safe, signed base64 compressed JSON string. Serialized object
  145. is signed using :class:`~TimestampSigner`.
  146. .. function:: loads(string, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None)
  147. Reverse of ``dumps()``, raises ``BadSignature`` if signature fails.
  148. Checks ``max_age`` (in seconds) if given.