Skip to content

Commit

Permalink
support FIPS builds without SHA-1 (#378)
Browse files Browse the repository at this point in the history
  • Loading branch information
davidism committed Apr 16, 2024
2 parents 93ae366 + 7f4dcf8 commit 2f69e84
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 3 deletions.
3 changes: 3 additions & 0 deletions CHANGES.rst
Expand Up @@ -13,6 +13,9 @@ Unreleased
By default it is ``Serializer[str]`` and ``dumps`` returns a ``str``. If a
different ``serializer`` argument is given, it will try to infer the return
type of its ``dumps`` method. :issue:`347`
- The default ``hashlib.sha1`` may not be available in FIPS builds. Don't
access it at import time so the developer has time to change the default.
:issue:`375`


Version 2.1.2
Expand Down
12 changes: 10 additions & 2 deletions src/itsdangerous/signer.py
Expand Up @@ -37,13 +37,21 @@ def get_signature(self, key: bytes, value: bytes) -> bytes:
return b""


def _lazy_sha1(string: bytes = b"") -> t.Any:
"""Don't access ``hashlib.sha1`` until runtime. FIPS builds may not include
SHA-1, in which case the import and use as a default would fail before the
developer can configure something else.
"""
return hashlib.sha1(string)


class HMACAlgorithm(SigningAlgorithm):
"""Provides signature generation using HMACs."""

#: The digest method to use with the MAC algorithm. This defaults to
#: SHA1, but can be changed to any other function in the hashlib
#: module.
default_digest_method: t.Any = staticmethod(hashlib.sha1)
default_digest_method: t.Any = staticmethod(_lazy_sha1)

def __init__(self, digest_method: t.Any = None):
if digest_method is None:
Expand Down Expand Up @@ -109,7 +117,7 @@ class Signer:
#: doesn't apply when used intermediately in HMAC.
#:
#: .. versionadded:: 0.14
default_digest_method: t.Any = staticmethod(hashlib.sha1)
default_digest_method: t.Any = staticmethod(_lazy_sha1)

#: The default scheme to use to derive the signing key from the
#: secret key and salt. The default is ``django-concat``. Possible
Expand Down
3 changes: 2 additions & 1 deletion tests/test_itsdangerous/test_serializer.py
Expand Up @@ -14,6 +14,7 @@
from itsdangerous.exc import BadPayload
from itsdangerous.exc import BadSignature
from itsdangerous.serializer import Serializer
from itsdangerous.signer import _lazy_sha1
from itsdangerous.signer import Signer


Expand Down Expand Up @@ -177,7 +178,7 @@ class Signer256(serializer.signer): # type: ignore
)

unsigners = serializer.iter_unsigners()
assert next(unsigners).digest_method == hashlib.sha1
assert next(unsigners).digest_method == _lazy_sha1

for signer in unsigners:
assert signer.digest_method == hashlib.sha256
Expand Down

0 comments on commit 2f69e84

Please sign in to comment.