Signer broken when SECRET_KEY contains non-ASCII bytes
|Reported by:||nvie||Owned by:||MattBlack|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
This happens on Django 1.5 only.
When the SECRET_KEY setting contains non-ASCII bytes (which is very likely for randomly generated keys), the following code breaks
from django.conf import settings from django.core.signing import Signer settings.SECRET_KEY = b'\xe7' # binary key with non-ASCII chars s = Signer() print(s.sign('foo'))
Relevant stack trace:
Traceback (most recent call last): File "minimal_example.py", line 7, in <module> s.sign('foo') File "/Users/nvie/.virtualenvs/foo/lib/python2.7/site-packages/django/core/signing.py", line 175, in sign return str('%s%s%s') % (value, self.sep, self.signature(value)) File "/Users/nvie/.virtualenvs/foo/lib/python2.7/site-packages/django/core/signing.py", line 169, in signature signature = base64_hmac(self.salt + 'signer', value, self.key) File "/Users/nvie/.virtualenvs/foo/lib/python2.7/site-packages/django/core/signing.py", line 75, in base64_hmac return b64_encode(salted_hmac(salt, value, key).digest()) File "/Users/nvie/.virtualenvs/foo/lib/python2.7/site-packages/django/utils/crypto.py", line 48, in salted_hmac key = hashlib.sha1((key_salt + secret).encode('utf-8')).digest() UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 0: ordinal not in range(128)
This is due to the fact that unicode and bytes are concatenated and, as a result, the bytes are implicitly decoded, which is an invalid operation, hence the UnicodeDecodeError. The error, thus, is perfectly valid.
I think the source of the bug is that, internally, the Signer works with text-based keys, salts and values, where it should work with byte streams instead.
Change History (9)
comment:1 Changed 3 years ago by nvie
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
comment:2 Changed 3 years ago by claudep
- Triage Stage changed from Unreviewed to Design decision needed
comment:8 Changed 2 years ago by MattBlack
- Owner changed from nobody to MattBlack
- Status changed from new to assigned