Skip to content

Commit 7bf3252

Browse files
jpadillajaideeppynepre-commit-ci[bot]
authored
Accept canonical Base64URL padding in JWT segments (#1216)
* Accept trailing Base64URL padding when decoding JWS segments The canonical encode/decode round-trip rejected AWS ALB tokens that include standard '=' padding. Keep rejecting non-alphabet junk such as '!!!!', but allow trailing padding so those tokens verify. Fixes #1209 * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * test: cover padded Base64URL segment validation * test: verify padded ALB-style ES256 JWT decoding --------- Co-authored-by: jaideeppyne <[email protected]> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> Co-authored-by: José Padilla <[email protected]>
1 parent 1d41a64 commit 7bf3252

4 files changed

Lines changed: 79 additions & 6 deletions

File tree

‎CHANGELOG.rst‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,14 @@ This project adheres to `Semantic Versioning <https://semver.org/>`__.
77
`Unreleased <https://github.com/jpadilla/pyjwt/compare/2.15.0...HEAD>`__
88
-------------------------------------------------------------------------
99

10+
Fixed
11+
~~~~~
12+
13+
- Accept trailing Base64URL ``=`` padding when decoding JWS segments, so
14+
tokens issued by AWS ALB and similar systems verify instead of raising
15+
``DecodeError: Invalid crypto padding``. Non-alphabet junk such as
16+
``!!!!`` remains rejected (`#1209 <https://github.com/jpadilla/pyjwt/issues/1209>`__).
17+
1018
`v2.15.0 <https://github.com/jpadilla/pyjwt/compare/2.14.0...2.15.0>`__
1119
-----------------------------------------------------------------------
1220

‎jwt/api_jws.py‎

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -325,17 +325,30 @@ def get_unverified_header(self, jwt: str | bytes) -> dict[str, Any]:
325325

326326
@staticmethod
327327
def _decode_base64url_segment(segment: bytes, name: str) -> bytes:
328-
if len(segment) % 4 == 1 or any(
329-
character not in _BASE64URL_ALPHABET for character in segment
328+
# Accept trailing '=' used by some issuers (e.g. AWS ALB). Still
329+
# reject non-alphabet junk such as '!!!!' (GHSA-hxm8-2xgr-2p9m).
330+
padding = 0
331+
stripped = segment
332+
while stripped.endswith(b"="):
333+
stripped = stripped[:-1]
334+
padding += 1
335+
if padding > 2:
336+
raise DecodeError(f"Invalid {name} padding")
337+
338+
if padding and len(segment) % 4 != 0:
339+
raise DecodeError(f"Invalid {name} padding")
340+
341+
if len(stripped) % 4 == 1 or any(
342+
character not in _BASE64URL_ALPHABET for character in stripped
330343
):
331344
raise DecodeError(f"Invalid {name} padding")
332345

333346
try:
334-
decoded = base64url_decode(segment)
347+
decoded = base64url_decode(stripped)
335348
except (TypeError, binascii.Error) as err:
336349
raise DecodeError(f"Invalid {name} padding") from err
337350

338-
if base64url_encode(decoded) != segment:
351+
if base64url_encode(decoded) != stripped:
339352
raise DecodeError(f"Invalid {name} padding")
340353

341354
return decoded

‎tests/test_api_jws.py‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -681,6 +681,50 @@ def test_decode_rejects_non_canonical_crypto_segment(
681681
with pytest.raises(DecodeError, match="Invalid crypto padding"):
682682
jws.decode(mutated_token, secret, algorithms=["HS256"])
683683

684+
def test_decode_accepts_padded_crypto_segment(
685+
self, jws: PyJWS, payload: bytes
686+
) -> None:
687+
secret = "a" * 32
688+
token = jws.encode(payload, secret, algorithm="HS256")
689+
header, encoded_payload, signature = token.split(".")
690+
pad = "=" * ((4 - len(signature) % 4) % 4)
691+
assert pad, (
692+
"HS256 signatures should need padding when restored to 4-char groups"
693+
)
694+
padded_token = ".".join((header, encoded_payload, signature + pad))
695+
696+
assert jws.decode(padded_token, secret, algorithms=["HS256"]) == payload
697+
698+
def test_decode_rejects_embedded_padding_in_crypto_segment(
699+
self, jws: PyJWS, payload: bytes
700+
) -> None:
701+
secret = "a" * 32
702+
token = jws.encode(payload, secret, algorithm="HS256")
703+
header, encoded_payload, signature = token.split(".")
704+
mutated_token = ".".join(
705+
(header, encoded_payload, signature[:2] + "=" + signature[2:])
706+
)
707+
708+
with pytest.raises(DecodeError, match="Invalid crypto padding"):
709+
jws.decode(mutated_token, secret, algorithms=["HS256"])
710+
711+
@pytest.mark.parametrize(
712+
("segment", "decoded"),
713+
[(b"Zg", b"f"), (b"Zg==", b"f"), (b"Zm8=", b"fo")],
714+
)
715+
def test_decode_accepts_canonical_base64url_padding(
716+
self, segment: bytes, decoded: bytes
717+
) -> None:
718+
assert PyJWS._decode_base64url_segment(segment, "crypto") == decoded
719+
720+
@pytest.mark.parametrize(
721+
"segment",
722+
[b"Zg===", b"Zg=", b"a", b"Z?==", b"Zh", b"Zh=="],
723+
)
724+
def test_decode_rejects_invalid_base64url_padding(self, segment: bytes) -> None:
725+
with pytest.raises(DecodeError, match="Invalid crypto padding"):
726+
PyJWS._decode_base64url_segment(segment, "crypto")
727+
684728
def test_decode_with_algo_none_should_fail(
685729
self, jws: PyJWS, payload: bytes
686730
) -> None:

‎tests/test_api_jwt.py‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -418,7 +418,12 @@ def test_encode_datetime(self, jwt: PyJWT) -> None:
418418
# encoding / decoding operations equally (causing tests
419419
# to still pass).
420420
@crypto_required
421-
def test_decodes_valid_es256_jwt(self, jwt: PyJWT) -> None:
421+
@pytest.mark.parametrize(
422+
"signature_padding", [b"", b"=="], ids=["compact", "alb-padded"]
423+
)
424+
def test_decodes_valid_es256_jwt(
425+
self, jwt: PyJWT, signature_padding: bytes
426+
) -> None:
422427
example_payload = {"hello": "world"}
423428
with open(key_path("testkey_ec.pub")) as fp:
424429
example_pubkey = fp.read()
@@ -428,7 +433,10 @@ def test_decodes_valid_es256_jwt(self, jwt: PyJWT) -> None:
428433
b"d2SsX8hhlnWelQFmPFSf_JzC2EbLnar92t-bXsDovzxp25ExazrVHkfPkQ"
429434
)
430435

431-
decoded_payload = jwt.decode(example_jwt, example_pubkey, algorithms=["ES256"])
436+
# AWS ALB can include standard padding on its ES256 signature (#1209).
437+
decoded_payload = jwt.decode(
438+
example_jwt + signature_padding, example_pubkey, algorithms=["ES256"]
439+
)
432440
assert decoded_payload == example_payload
433441

434442
# 'Control' RSA JWT created by another library.

0 commit comments

Comments
 (0)