Cryptographic signing

The golden rule of web application security is to never trust data from untrusted sources. Sometimes it can be useful to pass data through an untrusted medium. Cryptographically signed values can be passed through an untrusted 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 API for setting and reading signed cookies, one of the most common uses of signing in web applications.

Você também pode achar a assinatura útil para o seguinte:

  • Gerar URLs do tipo “recuperar minha conta” para enviar a usuários que perderam suas senhas.
  • Garantir que dados armazenados em campos hidden de formulários não foram alterados.
  • Gerar URLs secretas de uso único para permitir acesso temporário a recursos protegidos, por exemplo um arquivo baixável pelo qual um usuário pagou.

Protecting SECRET_KEY and SECRET_KEY_FALLBACKS

Quando você cria um novo projeto Django usando startproject, o arquivo settings.py é gerado automaticamente e recebe um valor aleatório para a SECRET_KEY. Esse valor é a chave para proteger dados assinados – Ela é vital para manter isso seguro, ou atacantes podem usá-la para gerar seus próprios valores assinados.

SECRET_KEY_FALLBACKS can be used to rotate secret keys. The values will not be used to sign data, but if specified, they will be used to validate signed data and must be kept secure.

Changed in Django 4.1:

The SECRET_KEY_FALLBACKS setting was added.

Utilizando a API de baixo nível

Os métodos de assinatura estão localizados no módulo django.core.signing. Para assinar um valor, primeiro é preciso instanciar a classe Signer:

>>> from django.core.signing import Signer
>>> signer = Signer()
>>> value = signer.sign('My string')
>>> value
'My string:GdMGD6HNQ_qdgxYP8yBZAdAIV1w'

A assinatura é anexada no final da string, seguida de “:”. Você pode recuperar o valor original usando o método unsign:

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

If you pass a non-string value to sign, the value will be forced to string before being signed, and the unsign result will give you that string value:

>>> signed = signer.sign(2.5)
>>> original = signer.unsign(signed)
>>> original
'2.5'

If you wish to protect a list, tuple, or dictionary you can do so using the sign_object() and unsign_object() methods:

>>> signed_obj = signer.sign_object({'message': 'Hello!'})
>>> signed_obj
'eyJtZXNzYWdlIjoiSGVsbG8hIn0:Xdc-mOFDjs22KsQAqfVfi8PQSPdo3ckWJxPWwQOFhR4'
>>> obj = signer.unsign_object(signed_obj)
>>> obj
{'message': 'Hello!'}

See Protegendo estruturas de dados complexas for more details.

Se a assinatura ou valor forem alterados de qualquer situação, uma exceção do tipo django.core.signing.BadSignature será lançada:

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

Por padrão, a classe Signer utiliza a configuração SECRET_KEY para gerar assinaturas. Você pode usar uma chave diferente passando ela no construtor de Signer:

>>> signer = Signer('my-other-secret')
>>> value = signer.sign('My string')
>>> value
'My string:EkfQJafvGyiofrdGnuthdxImIJw'
class Signer(key=None, sep=':', salt=None, algorithm=None, fallback_keys=None)[código fonte]

Returns a signer which uses key to generate signatures and sep to separate values. sep cannot be in the URL safe base64 alphabet. This alphabet contains alphanumeric characters, hyphens, and underscores. algorithm must be an algorithm supported by hashlib, it defaults to 'sha256'. fallback_keys is a list of additional values used to validate signed data, defaults to SECRET_KEY_FALLBACKS.

Changed in Django 4.1:

The fallback_keys argument was added.

Usando o parâmetro salt

Se você não quiser que toda a ocorrência de uma string em particular possua a mesma assinatura hash, você pode usar o argumento opcional salt na classe Signer. Assim a função de assinatura hash usará tanto o argumento salt quanto a sua SECRET_KEY:

>>> signer = Signer()
>>> signer.sign('My string')
'My string:GdMGD6HNQ_qdgxYP8yBZAdAIV1w'
>>> signer.sign_object({'message': 'Hello!'})
'eyJtZXNzYWdlIjoiSGVsbG8hIn0:Xdc-mOFDjs22KsQAqfVfi8PQSPdo3ckWJxPWwQOFhR4'
>>> signer = Signer(salt='extra')
>>> signer.sign('My string')
'My string:Ee7vGi-ING6n02gkcJ-QLHg6vFw'
>>> signer.unsign('My string:Ee7vGi-ING6n02gkcJ-QLHg6vFw')
'My string'
>>> signer.sign_object({'message': 'Hello!'})
'eyJtZXNzYWdlIjoiSGVsbG8hIn0:-UWSLCE-oUAHzhkHviYz3SOZYBjFKllEOyVZNuUtM-I'
>>> signer.unsign_object('eyJtZXNzYWdlIjoiSGVsbG8hIn0:-UWSLCE-oUAHzhkHviYz3SOZYBjFKllEOyVZNuUtM-I')
{'message': 'Hello!'}

Utilizar o argumento salt dessa forma coloca as diferentes assinaturas em diferentes namespaces. A assinatura proveniente de um namespace (um valor para o argumento salt em particular) não pode ser usada para validar a mesma string em texto simples em um namespace diferente usando um valor de salt diferente. Esse resutado é para prevenir um invasor de usar a string gerada e assinada em um local no código como entrada para outro pedaço de código que está gerando (e verificando) assinaturas usando um valor diferente para o argumento salt.

Ao contrário de sua SECRET_KEY, o seu argumento salt não precisa ser mantido em segredo.

Verificando valores com timestamp

A classe TimestampSigner é uma subclasse da classe Signer que adiciona um rótulo contendo o tempo, ou seja, um timestamp ao valor. Isso permite que você confirme que o valor assinado foi criado dentro de um determinado período de tempo:

>>> from datetime import timedelta
>>> from django.core.signing import TimestampSigner
>>> signer = TimestampSigner()
>>> value = signer.sign('hello')
>>> value
'hello:1NMg5H:oPVuCqlJWmChm1rA2lyTUtelC-c'
>>> signer.unsign(value)
'hello'
>>> signer.unsign(value, max_age=10)
...
SignatureExpired: Signature age 15.5289158821 > 10 seconds
>>> signer.unsign(value, max_age=20)
'hello'
>>> signer.unsign(value, max_age=timedelta(seconds=20))
'hello'
class TimestampSigner(key=None, sep=':', salt=None, algorithm='sha256')[código fonte]
sign(value)[código fonte]

Assina um value e adiciona um rótulo com o horário atual nele.

unsign(value, max_age=None)[código fonte]

Verifica se o valor foi assinado a menos de max_age segundos atrás, caso contrário lança SignatureExpired. O parâmetro max_age pode aceitar um inteiro ou um objeto da classe datetime.timedelta.

sign_object(obj, serializer=JSONSerializer, compress=False)

Encode, optionally compress, append current timestamp, and sign complex data structure (e.g. list, tuple, or dictionary).

unsign_object(signed_obj, serializer=JSONSerializer, max_age=None)

Checks if signed_obj was signed less than max_age seconds ago, otherwise raises SignatureExpired. The max_age parameter can accept an integer or a datetime.timedelta object.

Protegendo estruturas de dados complexas

If you wish to protect a list, tuple or dictionary you can do so using the Signer.sign_object() and unsign_object() methods, or signing module’s dumps() or loads() functions (which are shortcuts for TimestampSigner(salt='django.core.signing').sign_object()/unsign_object()). These use JSON serialization under the hood. JSON ensures that even if your SECRET_KEY is stolen an attacker will not be able to execute arbitrary commands by exploiting the pickle format:

>>> from django.core import signing
>>> signer = signing.TimestampSigner()
>>> value = signer.sign_object({'foo': 'bar'})
>>> value
'eyJmb28iOiJiYXIifQ:1kx6R3:D4qGKiptAqo5QW9iv4eNLc6xl4RwiFfes6oOcYhkYnc'
>>> signer.unsign_object(value)
{'foo': 'bar'}
>>> value = signing.dumps({'foo': 'bar'})
>>> value
'eyJmb28iOiJiYXIifQ:1kx6Rf:LBB39RQmME-SRvilheUe5EmPYRbuDBgQp2tCAi7KGLk'
>>> signing.loads(value)
{'foo': 'bar'}

Por causa da natureza do JSON (não há distinção nativa entre listas e tuplas) se você passar uma tupla para signing.loads(object), você terá uma lista:

>>> from django.core import signing
>>> value = signing.dumps(('a','b','c'))
>>> signing.loads(value)
['a', 'b', 'c']
dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False)[código fonte]

Returns URL-safe, signed base64 compressed JSON string. Serialized object is signed using TimestampSigner.

loads(string, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None, fallback_keys=None)[código fonte]

Inverso da função dumps(), lança BadSignature se a assinatura falhar. Verifica o max_age (em segundos) se fornecido.

Changed in Django 4.1:

The fallback_keys argument was added.