Cryptographic signing

The golden rule of Web application security is to never trust data fromuntrusted sources. Sometimes it can be useful to pass data through anuntrusted medium. Cryptographically signed values can be passed through anuntrusted channel safe in the knowledge that any tampering will be detected.

Django provides both a low-level API for signing values and a high-level APIfor setting and reading signed cookies, one of the most common uses ofsigning in Web applications.

You may also find signing useful for the following:

  • Generating “recover my account” URLs for sending to users who havelost their password.
  • Ensuring data stored in hidden form fields has not been tampered with.
  • Generating one-time secret URLs for allowing temporary access to aprotected resource, for example a downloadable file that a user haspaid for.

Protecting the SECRET_KEY

When you create a new Django project using startproject, thesettings.py file is generated automatically and gets a randomSECRET_KEY value. This value is the key to securing signeddata – it is vital you keep this secure, or attackers could use it togenerate their own signed values.

Using the low-level API

Django’s signing methods live in the django.core.signing module.To sign a value, first instantiate a Signer instance:

  1. >>> from django.core.signing import Signer
  2. >>> signer = Signer()
  3. >>> value = signer.sign('My string')
  4. >>> value
  5. 'My string:GdMGD6HNQ_qdgxYP8yBZAdAIV1w'

The signature is appended to the end of the string, following the colon.You can retrieve the original value using the unsign method:

  1. >>> original = signer.unsign(value)
  2. >>> original
  3. 'My string'

If the signature or value have been altered in any way, adjango.core.signing.BadSignature exception will be raised:

  1. >>> from django.core import signing
  2. >>> value += 'm'
  3. >>> try:
  4. ... original = signer.unsign(value)
  5. ... except signing.BadSignature:
  6. ... print("Tampering detected!")

By default, the Signer class uses the SECRET_KEY setting togenerate signatures. You can use a different secret by passing it to theSigner constructor:

  1. >>> signer = Signer('my-other-secret')
  2. >>> value = signer.sign('My string')
  3. >>> value
  4. 'My string:EkfQJafvGyiofrdGnuthdxImIJw'
  • class Signer(key=None, sep=':', salt=None)
  • Returns a signer which uses key to generate signatures and sep toseparate values. sep cannot be in the URL safe base64 alphabet. This alphabet containsalphanumeric characters, hyphens, and underscores.

Using the salt argument

If you do not wish for every occurrence of a particular string to have the samesignature hash, you can use the optional salt argument to the Signerclass. Using a salt will seed the signing hash function with both the salt andyour SECRET_KEY:

  1. >>> signer = Signer()
  2. >>> signer.sign('My string')
  3. 'My string:GdMGD6HNQ_qdgxYP8yBZAdAIV1w'
  4. >>> signer = Signer(salt='extra')
  5. >>> signer.sign('My string')
  6. 'My string:Ee7vGi-ING6n02gkcJ-QLHg6vFw'
  7. >>> signer.unsign('My string:Ee7vGi-ING6n02gkcJ-QLHg6vFw')
  8. 'My string'

Using salt in this way puts the different signatures into differentnamespaces. A signature that comes from one namespace (a particular saltvalue) cannot be used to validate the same plaintext string in a differentnamespace that is using a different salt setting. The result is to prevent anattacker from using a signed string generated in one place in the code as inputto another piece of code that is generating (and verifying) signatures using adifferent salt.

Unlike your SECRET_KEY, your salt argument does not need to staysecret.

Verifying timestamped values

TimestampSigner is a subclass of Signer that appends a signedtimestamp to the value. This allows you to confirm that a signed value wascreated within a specified period of time:

  1. >>> from datetime import timedelta
  2. >>> from django.core.signing import TimestampSigner
  3. >>> signer = TimestampSigner()
  4. >>> value = signer.sign('hello')
  5. >>> value
  6. 'hello:1NMg5H:oPVuCqlJWmChm1rA2lyTUtelC-c'
  7. >>> signer.unsign(value)
  8. 'hello'
  9. >>> signer.unsign(value, max_age=10)
  10. ...
  11. SignatureExpired: Signature age 15.5289158821 > 10 seconds
  12. >>> signer.unsign(value, max_age=20)
  13. 'hello'
  14. >>> signer.unsign(value, max_age=timedelta(seconds=20))
  15. 'hello'
  • class TimestampSigner(key=None, sep=':', salt=None)
    • sign(value)
    • Sign value and append current timestamp to it.

    • unsign(value, max_age=None)

    • Checks if value was signed less than max_age seconds ago,otherwise raises SignatureExpired. The max_age parameter canaccept an integer or a datetime.timedelta object.

Protecting complex data structures

If you wish to protect a list, tuple or dictionary you can do so using thesigning module’s dumps and loads functions. These imitate Python’spickle module, but use JSON serialization under the hood. JSON ensures thateven if your SECRET_KEY is stolen an attacker will not be ableto execute arbitrary commands by exploiting the pickle format:

  1. >>> from django.core import signing
  2. >>> value = signing.dumps({"foo": "bar"})
  3. >>> value
  4. 'eyJmb28iOiJiYXIifQ:1NMg1b:zGcDE4-TCkaeGzLeW9UQwZesciI'
  5. >>> signing.loads(value)
  6. {'foo': 'bar'}

Because of the nature of JSON (there is no native distinction between listsand tuples) if you pass in a tuple, you will get a list fromsigning.loads(object):

  1. >>> from django.core import signing
  2. >>> value = signing.dumps(('a','b','c'))
  3. >>> signing.loads(value)
  4. ['a', 'b', 'c']
  • dumps(obj, key=None, salt='django.core.signing', compress=False)
  • Returns URL-safe, sha1 signed base64 compressed JSON string. Serializedobject is signed using TimestampSigner.

  • loads(string, key=None, salt='django.core.signing', max_age=None)

  • Reverse of dumps(), raises BadSignature if signature fails.Checks max_age (in seconds) if given.