signing.txt 6.4 KB

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