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.
@@ -0,0 +1,197 @@
1
+ import json
2
+ from urllib.error import URLError
3
+ from urllib.parse import urlparse
4
+ from urllib.request import urlopen
5
+
6
+ from cryptography.hazmat.primitives import serialization
7
+ from cryptography.hazmat.primitives.asymmetric import ec, rsa
8
+
9
+ from jwt_toolkit.core.encoding import base64url_decode
10
+
11
+ # JWKS module — resolve a verification key from a JSON Web Key Set (RFC 7517).
12
+ #
13
+ # The fetch helper is intentionally thin: stdlib urllib only, with a fixed
14
+ # timeout. Callers (and the audit module) are responsible for trust decisions
15
+ # such as host allow-listing — this module just retrieves and parses.
16
+
17
+ JWKS_FETCH_TIMEOUT_SECONDS = 10
18
+
19
+ # JWS algorithm → expected JWK key-type. Used to reject mismatches at selection
20
+ # time rather than producing a confusing crypto error later.
21
+ _KTY_BY_ALG = {
22
+ "RS256": "RSA",
23
+ "RS384": "RSA",
24
+ "RS512": "RSA",
25
+ "PS256": "RSA",
26
+ "PS384": "RSA",
27
+ "PS512": "RSA",
28
+ "ES256": "EC",
29
+ "ES384": "EC",
30
+ "ES512": "EC",
31
+ }
32
+
33
+ # JWS ES* alg → expected JWK `crv` parameter per RFC 7518 §6.2.1.1.
34
+ _CRV_BY_ALG = {
35
+ "ES256": "P-256",
36
+ "ES384": "P-384",
37
+ "ES512": "P-521",
38
+ }
39
+
40
+ # JWK `crv` → cryptography curve class.
41
+ _CURVE_BY_CRV: dict[str, type[ec.EllipticCurve]] = {
42
+ "P-256": ec.SECP256R1,
43
+ "P-384": ec.SECP384R1,
44
+ "P-521": ec.SECP521R1,
45
+ }
46
+
47
+
48
+ _PERMITTED_JWKS_SCHEMES = frozenset({"https", "http", "file"})
49
+
50
+
51
+ def fetch_jwks(url: str, *, timeout: int = JWKS_FETCH_TIMEOUT_SECONDS) -> dict:
52
+ # Retrieves and parses a JWKS document. Supports https://, http://, and
53
+ # file:// via urllib so tests can use local files without a live server.
54
+ # Network and JSON failures are normalised to ValueError so the CLI layer
55
+ # has a single exception class to render.
56
+ scheme = urlparse(url).scheme
57
+ if scheme not in _PERMITTED_JWKS_SCHEMES:
58
+ raise ValueError(f"JWKS URL scheme {scheme!r} is not permitted — use https or http")
59
+ try:
60
+ with urlopen(url, timeout=timeout) as response: # nosec B310 — scheme validated above
61
+ body = response.read()
62
+ except (URLError, ValueError, OSError) as exc:
63
+ raise ValueError(f"Could not fetch JWKS from {url!r}: {exc}") from exc
64
+ try:
65
+ document = json.loads(body)
66
+ except json.JSONDecodeError as exc:
67
+ raise ValueError(f"JWKS at {url!r} is not valid JSON: {exc.msg}") from exc
68
+ if not isinstance(document, dict) or "keys" not in document:
69
+ raise ValueError(f"JWKS at {url!r} has no 'keys' array")
70
+ return document
71
+
72
+
73
+ def select_jwk(jwks: dict, *, kid: str | None, alg: str) -> dict:
74
+ # Picks the single JWK that should verify a token with the given alg/kid.
75
+ # Returns the JWK dict so the caller can decide how to materialise the key.
76
+ keys = jwks.get("keys") or []
77
+ if not isinstance(keys, list) or not keys:
78
+ raise ValueError("JWKS has no keys")
79
+
80
+ candidates = _filter_by_kid(keys, kid)
81
+ if not candidates:
82
+ raise ValueError(f"No JWKS key matches kid={kid!r}")
83
+ if len(candidates) > 1:
84
+ # Ambiguity is a configuration bug — refusing it is safer than guessing.
85
+ raise ValueError(f"Multiple JWKS keys match kid={kid!r} — JWKS is ambiguous")
86
+
87
+ chosen = candidates[0]
88
+ _ensure_jwk_matches_alg(chosen, alg)
89
+ return chosen
90
+
91
+
92
+ def jwk_to_public_pem(jwk: dict, alg: str) -> bytes:
93
+ # Materialises a JWK into PEM bytes that `verify_asymmetric` can consume.
94
+ # Mismatches between the JWK shape and the requested alg surface as
95
+ # ValueError before any crypto operation runs.
96
+ _ensure_jwk_matches_alg(jwk, alg)
97
+ kty = jwk.get("kty")
98
+ public_key: rsa.RSAPublicKey | ec.EllipticCurvePublicKey
99
+ if kty == "RSA":
100
+ public_key = _rsa_public_key_from_jwk(jwk)
101
+ elif kty == "EC":
102
+ public_key = _ec_public_key_from_jwk(jwk, alg)
103
+ else:
104
+ # Defensive — _ensure_jwk_matches_alg already rejects unsupported algs,
105
+ # but we may be called directly via a kty that has no JWS counterpart.
106
+ raise ValueError(f"Unsupported JWK kty: {kty!r}")
107
+ return public_key.public_bytes(
108
+ serialization.Encoding.PEM,
109
+ serialization.PublicFormat.SubjectPublicKeyInfo,
110
+ )
111
+
112
+
113
+ def resolve_jwks_key(
114
+ url: str, *, kid: str | None, alg: str, timeout: int = JWKS_FETCH_TIMEOUT_SECONDS
115
+ ) -> bytes:
116
+ # End-to-end convenience: fetch → select → materialise. The CLI layer
117
+ # should call this so the three steps share one error surface.
118
+ jwks = fetch_jwks(url, timeout=timeout)
119
+ jwk = select_jwk(jwks, kid=kid, alg=alg)
120
+ return jwk_to_public_pem(jwk, alg)
121
+
122
+
123
+ # Internal helpers
124
+
125
+
126
+ def _filter_by_kid(keys: list, kid: str | None) -> list:
127
+ # If the token names a kid, require an exact match. If it does not, only
128
+ # an unambiguous single-key JWKS is acceptable — falling back to "guess
129
+ # the first key" is how kid-confusion bugs happen in real verifiers.
130
+ if kid is not None:
131
+ return [k for k in keys if isinstance(k, dict) and k.get("kid") == kid]
132
+ if len(keys) != 1:
133
+ raise ValueError(
134
+ "Token header has no kid and JWKS contains multiple keys — refusing to guess"
135
+ )
136
+ return list(keys)
137
+
138
+
139
+ def _ensure_jwk_matches_alg(jwk: dict, alg: str) -> None:
140
+ alg = alg.upper()
141
+ expected_kty = _KTY_BY_ALG.get(alg)
142
+ if expected_kty is None:
143
+ raise ValueError(f"Cannot resolve JWK for unsupported alg: {alg}")
144
+ actual_kty = jwk.get("kty")
145
+ if actual_kty != expected_kty:
146
+ raise ValueError(
147
+ f"JWK kty={actual_kty!r} does not match alg={alg} (expected {expected_kty})"
148
+ )
149
+
150
+ # A JWK may carry its own `alg` field — if present it must agree with the
151
+ # token's alg, otherwise the keyset is configured for a different purpose.
152
+ jwk_alg = jwk.get("alg")
153
+ if jwk_alg is not None and str(jwk_alg).upper() != alg:
154
+ raise ValueError(f"JWK alg={jwk_alg!r} does not match token alg={alg}")
155
+
156
+ # For EC keys, the curve in the JWK must match the curve required by the alg.
157
+ if expected_kty == "EC":
158
+ expected_crv = _CRV_BY_ALG[alg]
159
+ actual_crv = jwk.get("crv")
160
+ if actual_crv != expected_crv:
161
+ raise ValueError(
162
+ f"JWK crv={actual_crv!r} does not match alg={alg} (expected {expected_crv})"
163
+ )
164
+
165
+
166
+ def _rsa_public_key_from_jwk(jwk: dict) -> rsa.RSAPublicKey:
167
+ try:
168
+ n = _b64url_to_int(jwk["n"])
169
+ e = _b64url_to_int(jwk["e"])
170
+ except KeyError as exc:
171
+ raise ValueError(f"RSA JWK is missing required field: {exc.args[0]!r}") from exc
172
+ except ValueError as exc:
173
+ raise ValueError(f"RSA JWK has malformed numeric field: {exc}") from exc
174
+ return rsa.RSAPublicNumbers(e=e, n=n).public_key()
175
+
176
+
177
+ def _ec_public_key_from_jwk(jwk: dict, alg: str) -> ec.EllipticCurvePublicKey:
178
+ crv = jwk.get("crv")
179
+ curve_cls = _CURVE_BY_CRV.get(str(crv))
180
+ if curve_cls is None:
181
+ raise ValueError(f"Unsupported EC curve in JWK: {crv!r}")
182
+ try:
183
+ x = _b64url_to_int(jwk["x"])
184
+ y = _b64url_to_int(jwk["y"])
185
+ except KeyError as exc:
186
+ raise ValueError(f"EC JWK is missing required field: {exc.args[0]!r}") from exc
187
+ except ValueError as exc:
188
+ raise ValueError(f"EC JWK has malformed numeric field: {exc}") from exc
189
+ # Curve already validated against alg by _ensure_jwk_matches_alg.
190
+ del alg
191
+ return ec.EllipticCurvePublicNumbers(x=x, y=y, curve=curve_cls()).public_key()
192
+
193
+
194
+ def _b64url_to_int(value: str) -> int:
195
+ if not isinstance(value, str):
196
+ raise ValueError(f"expected base64url string, got {type(value).__name__}")
197
+ return int.from_bytes(base64url_decode(value), "big")
@@ -0,0 +1,116 @@
1
+ Metadata-Version: 2.4
2
+ Name: jwt-toolkit
3
+ Version: 0.1.0
4
+ Summary: A command-line toolkit for inspecting, verifying, cracking, and securing JSON Web Tokens. built to expose how JWT signing works and where it breaks.
5
+ Project-URL: Homepage, https://github.com/KhaledSaeed18/jwt-toolkit
6
+ Project-URL: Repository, https://github.com/KhaledSaeed18/jwt-toolkit
7
+ Project-URL: Issues, https://github.com/KhaledSaeed18/jwt-toolkit/issues
8
+ Project-URL: Changelog, https://github.com/KhaledSaeed18/jwt-toolkit/releases
9
+ Author-email: Khaled Saeed <khaled18saeed@gmail.com>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: appsec,audit,cli,cryptography,json-web-token,jwt,pentesting,security
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Environment :: Console
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Intended Audience :: Information Technology
17
+ Classifier: Intended Audience :: System Administrators
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Security
22
+ Classifier: Topic :: Security :: Cryptography
23
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
24
+ Classifier: Topic :: Utilities
25
+ Requires-Python: >=3.13
26
+ Requires-Dist: click>=8.4.1
27
+ Requires-Dist: cryptography>=48.0.0
28
+ Requires-Dist: pyfiglet>=1.0.2
29
+ Requires-Dist: rich>=15.0.0
30
+ Description-Content-Type: text/markdown
31
+
32
+ # JWT Toolkit
33
+
34
+ A command-line toolkit for inspecting, verifying, cracking, and securing JSON Web Tokens — built to expose how JWT signing works and where it breaks.
35
+
36
+ Use it to audit tokens for misconfigurations, verify signatures and standard claims (including JWKS), brute-force weak HMAC secrets against a wordlist, forge defensive attack-shaped variants for self-audit, and generate cryptographically strong secrets.
37
+
38
+ ## Installation
39
+
40
+ `jwt-toolkit` is a command-line tool, so the recommended way to install it is with [pipx](https://pipx.pypa.io), which installs CLI tools into isolated environments:
41
+
42
+ ```bash
43
+ pipx install jwt-toolkit
44
+ ```
45
+
46
+ Or with pip / uv:
47
+
48
+ ```bash
49
+ pip install jwt-toolkit
50
+ # or
51
+ uv tool install jwt-toolkit
52
+ ```
53
+
54
+ Requires Python 3.13+.
55
+
56
+ ## Quick start
57
+
58
+ ```bash
59
+ # Decode and pretty-print a token
60
+ jwt-toolkit decode <token>
61
+
62
+ # Static security audit (no key needed) — flags alg=none, weak HMAC, jwk-in-header, etc.
63
+ jwt-toolkit audit <token>
64
+ jwt-toolkit audit <token> --strict --json
65
+
66
+ # Verify signature + standard claims (exp, nbf, iat, iss, aud)
67
+ jwt-toolkit verify <token> --secret <secret> --issuer auth.example.com
68
+ jwt-toolkit verify <token> --jwks-url https://auth.example.com/.well-known/jwks.json
69
+
70
+ # Mint a JWT (HMAC or asymmetric)
71
+ jwt-toolkit sign --payload '{"sub":"1"}' --secret mysecret
72
+
73
+ # Generate defensive attack-shaped variants of a token (alg=none, alg confusion, etc.)
74
+ jwt-toolkit forge <token> --public-key key.pub.pem
75
+
76
+ # Brute-force a weak HMAC secret against a wordlist
77
+ jwt-toolkit crack <token> wordlists/common-secrets.txt --threads 8
78
+
79
+ # Generate a strong random secret
80
+ jwt-toolkit generate-secret --bits 256 --encoding base64
81
+
82
+ # Fetch the bundled common-secrets wordlist
83
+ jwt-toolkit download-wordlists --output-dir wordlists
84
+ ```
85
+
86
+ Run `jwt-toolkit COMMAND --help` for command-specific options.
87
+
88
+ ## Commands
89
+
90
+ | Command | Purpose |
91
+ | -------------------- | ------------------------------------------------------------------------------- |
92
+ | `decode` | Decode a JWT and pretty-print its header and payload. |
93
+ | `sign` | Mint a new JWT signed with an HMAC secret or an asymmetric key. |
94
+ | `audit` | Static security analysis of a JWT — no key required. CVE-referenced findings. |
95
+ | `verify` | Verify the signature and standard claims of a JWT (supports JWKS). |
96
+ | `forge` | Emit defensive attack-shaped variants of a JWT for self-audit. |
97
+ | `crack` | Brute-force a weak HMAC secret using a wordlist. |
98
+ | `generate-secret` | Emit a cryptographically strong random secret. |
99
+ | `download-wordlists` | Fetch the latest common-secrets wordlist. |
100
+
101
+ ## Scripting
102
+
103
+ Suppress the banner and color output for clean machine-readable runs:
104
+
105
+ ```bash
106
+ jwt-toolkit --quiet audit <token> --json
107
+ JWT_TOOLKIT_QUIET=1 NO_COLOR=1 jwt-toolkit audit <token> --json
108
+ ```
109
+
110
+ ## Use responsibly
111
+
112
+ `jwt-toolkit` is built for defensive work — auditing your own tokens, hardening your own systems, and learning how JWTs break. Only use it against tokens and systems you are authorized to test.
113
+
114
+ ## License
115
+
116
+ [MIT](./LICENSE) © Khaled Saeed
@@ -0,0 +1,29 @@
1
+ jwt_toolkit/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ jwt_toolkit/cli/__init__.py,sha256=rldvFIRmwALGj_yZebNIAayKNCPzixSyK4HR1pzddbg,3802
3
+ jwt_toolkit/cli/algorithms.py,sha256=XG8XwYnmqbDRos2QUvMdi5i2BpF_rEkzjsHhz-ypTBc,2536
4
+ jwt_toolkit/cli/banner.py,sha256=56hfgLGJvy36tJIH_s6jNS79UhjDRTrRns2BnCA0PrM,9094
5
+ jwt_toolkit/cli/console.py,sha256=0Gu2G8bGVwKPL2MNY2p18Jn07wVOAd4WvF9AJmcJwho,1005
6
+ jwt_toolkit/cli/decoding.py,sha256=pcqtTnSqYPSh4WsmK9oy10aLxRGwX0SCqjditlfyT84,2308
7
+ jwt_toolkit/cli/panels.py,sha256=Mxug7_hH3Xwf1TtumWJB93_8au5zU0zYKvlqh4lS6YM,859
8
+ jwt_toolkit/commands/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
9
+ jwt_toolkit/commands/audit.py,sha256=5V-gzXNp0MULLOz8GJDMraaUWKS-G60_Cztrlc_pKBk,8720
10
+ jwt_toolkit/commands/crack.py,sha256=gn5YAHOlWpSJnXItGIteOl4vjNOmKbkZCSASOBShx3o,11080
11
+ jwt_toolkit/commands/decode.py,sha256=10OWcJlqr0eW6iaHUQs-Mkl3hF_4bWHkD_bmSAPI5Q8,1548
12
+ jwt_toolkit/commands/download_wordlists.py,sha256=3JKDxTIXrsABS75KEtcdwpunlCk1Gw38OsOa7NN-Yuo,6656
13
+ jwt_toolkit/commands/forge.py,sha256=Y4rjtrekzhYNSASniwgZCBvHMRuG4i4pzb86MtHRT9Y,4294
14
+ jwt_toolkit/commands/generate_secret.py,sha256=M3wmpG5M-0FmA3SP6ezz2zady3sEB8hAcC_ejtHCXdI,2292
15
+ jwt_toolkit/commands/sign.py,sha256=WGyQiQ7B3-0O1ZDCXdwsYAE3L3knjcaS3tC2H_E4sow,4723
16
+ jwt_toolkit/commands/verify.py,sha256=VeVktM2B6OeJ7f-1tnpNyYy6xvvEmVl7dNZZBAhWLwI,9439
17
+ jwt_toolkit/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
18
+ jwt_toolkit/core/auditor.py,sha256=8-czFXwDvLzUg2qZzk4L9apFfO3iqja6CjjvJ6N5hKY,20130
19
+ jwt_toolkit/core/crypto.py,sha256=v7uHNCoXbxmZe4GeMtOAtxLRTRyDNcKJ8GG98cC3_N0,8732
20
+ jwt_toolkit/core/decoder.py,sha256=IcBm6v9ghBzmcfKmVc21K4lxaR_vcVHnJIUjueodGZI,2410
21
+ jwt_toolkit/core/encoding.py,sha256=6AL5xP09f_hyK4AJBmZeR8uHa0aH7yk-TCadYiXTlBc,662
22
+ jwt_toolkit/core/errors.py,sha256=u6KVIqJJrYhDOPCQYbwj4X0Lcvn-UpYXRSZ6Hm6YLOM,643
23
+ jwt_toolkit/core/forge.py,sha256=4lxX1gng1TGxmbCkASOklbf_8C1avdi_tUyyt3ysuTo,9345
24
+ jwt_toolkit/core/jwks.py,sha256=VDeyMIw8X7_4Wz64xE7gtUsuxjXQNI1f-Y6DbxbGmlk,7607
25
+ jwt_toolkit-0.1.0.dist-info/METADATA,sha256=HDajE4xOJEi8thFTKcPim-T-pDh6YHGjdwVAd0JO9KU,4814
26
+ jwt_toolkit-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
27
+ jwt_toolkit-0.1.0.dist-info/entry_points.txt,sha256=ea8YEdIgLylnUYOB7s3HzQYQpTr_uKAzl1EHjJRjoJ8,52
28
+ jwt_toolkit-0.1.0.dist-info/licenses/LICENSE,sha256=F-agkryZrxbVXlP1kyEiR2PeFtVr5tapP3kyCnkZinU,1069
29
+ jwt_toolkit-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ jwt-toolkit = jwt_toolkit.cli:cli
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Khaled Saeed
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.