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,269 @@
|
|
|
1
|
+
import json
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
|
|
4
|
+
import click
|
|
5
|
+
from rich.panel import Panel
|
|
6
|
+
from rich.table import Table
|
|
7
|
+
|
|
8
|
+
from jwt_toolkit.cli.algorithms import ensure_signing_algorithm, is_hmac
|
|
9
|
+
from jwt_toolkit.cli.console import console
|
|
10
|
+
from jwt_toolkit.cli.decoding import JSON_SCHEMA_VERSION, resolve_token, safe_decode
|
|
11
|
+
from jwt_toolkit.core.auditor import Grade, Report, Severity, run_audit
|
|
12
|
+
from jwt_toolkit.core.crypto import verify_asymmetric, verify_signature
|
|
13
|
+
from jwt_toolkit.core.errors import UnsupportedAlgorithmError
|
|
14
|
+
|
|
15
|
+
# Audit command — decodes a JWT, runs the security auditor, and emits a verdict.
|
|
16
|
+
# Static checks only by default; --secret adds live signature verification.
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
_SEVERITY_COLORS = {
|
|
20
|
+
Severity.CRITICAL: "bold red",
|
|
21
|
+
Severity.WARN: "yellow",
|
|
22
|
+
Severity.INFO: "cyan",
|
|
23
|
+
Severity.PASS: "green",
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
_GRADE_STYLES: dict[Grade, tuple[str, str]] = {
|
|
27
|
+
Grade.A: ("SECURE", "green"),
|
|
28
|
+
Grade.B: ("WEAK", "yellow"),
|
|
29
|
+
Grade.C: ("WEAK", "yellow"),
|
|
30
|
+
Grade.F: ("INSECURE", "red"),
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
@click.command(help="Audit a JWT and emit a security verdict.")
|
|
35
|
+
@click.argument("token")
|
|
36
|
+
@click.option(
|
|
37
|
+
"--strict",
|
|
38
|
+
is_flag=True,
|
|
39
|
+
help="Treat WARN findings as failures (exit 1).",
|
|
40
|
+
)
|
|
41
|
+
@click.option(
|
|
42
|
+
"--json",
|
|
43
|
+
"as_json",
|
|
44
|
+
is_flag=True,
|
|
45
|
+
help="Emit a machine-readable report. Schema is experimental.",
|
|
46
|
+
)
|
|
47
|
+
@click.option(
|
|
48
|
+
"--secret",
|
|
49
|
+
default=None,
|
|
50
|
+
help="HMAC secret — when provided, signature verification is included in the report.",
|
|
51
|
+
)
|
|
52
|
+
@click.option(
|
|
53
|
+
"--public-key",
|
|
54
|
+
"public_key_path",
|
|
55
|
+
default=None,
|
|
56
|
+
type=click.Path(exists=True, dir_okay=False, readable=True, path_type=Path),
|
|
57
|
+
help="PEM public key (RS*/PS*/ES*) — when provided, asymmetric signature verification "
|
|
58
|
+
"is included in the report. Mutually exclusive with --secret.",
|
|
59
|
+
)
|
|
60
|
+
@click.option(
|
|
61
|
+
"--require",
|
|
62
|
+
"required_claims",
|
|
63
|
+
default="",
|
|
64
|
+
metavar="CLAIMS",
|
|
65
|
+
help=(
|
|
66
|
+
"Comma-separated claims to require (e.g. iss,aud). "
|
|
67
|
+
"Missing required claims are flagged WARN instead of INFO."
|
|
68
|
+
),
|
|
69
|
+
)
|
|
70
|
+
def audit(
|
|
71
|
+
token: str,
|
|
72
|
+
strict: bool,
|
|
73
|
+
as_json: bool,
|
|
74
|
+
secret: str | None,
|
|
75
|
+
public_key_path: Path | None,
|
|
76
|
+
required_claims: str,
|
|
77
|
+
):
|
|
78
|
+
token = resolve_token(token)
|
|
79
|
+
decoded = safe_decode(token, as_json=as_json)
|
|
80
|
+
required = frozenset(c.strip() for c in required_claims.split(",") if c.strip())
|
|
81
|
+
report = run_audit(decoded.header, decoded.payload, required_claims=required)
|
|
82
|
+
exit_code = _resolve_exit_code(report, strict=strict)
|
|
83
|
+
|
|
84
|
+
if secret is not None and public_key_path is not None:
|
|
85
|
+
click.echo("Pass either --secret or --public-key, not both", err=True)
|
|
86
|
+
raise SystemExit(2)
|
|
87
|
+
|
|
88
|
+
sig_result: tuple[bool, str] | None = None
|
|
89
|
+
if secret is not None or public_key_path is not None:
|
|
90
|
+
sig_result = _check_signature(decoded, secret=secret, public_key_path=public_key_path)
|
|
91
|
+
if not sig_result[0]:
|
|
92
|
+
exit_code = max(exit_code, 1)
|
|
93
|
+
|
|
94
|
+
if as_json:
|
|
95
|
+
_emit_json(
|
|
96
|
+
decoded.header,
|
|
97
|
+
decoded.payload,
|
|
98
|
+
decoded.signature,
|
|
99
|
+
report,
|
|
100
|
+
exit_code,
|
|
101
|
+
strict,
|
|
102
|
+
sig_result,
|
|
103
|
+
)
|
|
104
|
+
else:
|
|
105
|
+
_emit_rich(decoded.header, decoded.payload, decoded.signature, report, sig_result)
|
|
106
|
+
|
|
107
|
+
raise SystemExit(exit_code)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _check_signature(
|
|
111
|
+
decoded, *, secret: str | None, public_key_path: Path | None
|
|
112
|
+
) -> tuple[bool, str]:
|
|
113
|
+
# Returns (valid, detail_message). Handles unsupported algorithms and key
|
|
114
|
+
# mismatches gracefully so the audit report still renders.
|
|
115
|
+
try:
|
|
116
|
+
alg = ensure_signing_algorithm(decoded.header)
|
|
117
|
+
except UnsupportedAlgorithmError as exc:
|
|
118
|
+
return (False, f"Cannot verify: {exc.headline}")
|
|
119
|
+
|
|
120
|
+
if is_hmac(alg):
|
|
121
|
+
if secret is None:
|
|
122
|
+
return (False, f"{alg} requires --secret to verify the signature")
|
|
123
|
+
valid = verify_signature(
|
|
124
|
+
decoded.header_b64, decoded.payload_b64, decoded.signature, secret, alg
|
|
125
|
+
)
|
|
126
|
+
else:
|
|
127
|
+
if public_key_path is None:
|
|
128
|
+
return (False, f"{alg} requires --public-key to verify the signature")
|
|
129
|
+
try:
|
|
130
|
+
pem_bytes = public_key_path.read_bytes()
|
|
131
|
+
valid = verify_asymmetric(
|
|
132
|
+
decoded.header_b64, decoded.payload_b64, decoded.signature, pem_bytes, alg
|
|
133
|
+
)
|
|
134
|
+
except ValueError as exc:
|
|
135
|
+
return (False, f"Cannot verify: {exc}")
|
|
136
|
+
|
|
137
|
+
if valid:
|
|
138
|
+
return (True, "Signature is valid")
|
|
139
|
+
return (False, "Signature is invalid — wrong key or tampered token")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _resolve_exit_code(report: Report, *, strict: bool) -> int:
|
|
143
|
+
if report.grade is Grade.F:
|
|
144
|
+
return 1
|
|
145
|
+
if strict and report.counts.get(Severity.WARN, 0) > 0:
|
|
146
|
+
return 1
|
|
147
|
+
return 0
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _emit_json(
|
|
151
|
+
header: dict,
|
|
152
|
+
payload: dict,
|
|
153
|
+
signature: str,
|
|
154
|
+
report: Report,
|
|
155
|
+
exit_code: int,
|
|
156
|
+
strict: bool,
|
|
157
|
+
sig_result: tuple[bool, str] | None,
|
|
158
|
+
) -> None:
|
|
159
|
+
verdict, _ = _GRADE_STYLES[report.grade]
|
|
160
|
+
document = {
|
|
161
|
+
"schema_version": JSON_SCHEMA_VERSION,
|
|
162
|
+
"grade": report.grade.value,
|
|
163
|
+
"verdict": verdict,
|
|
164
|
+
"exit_code": exit_code,
|
|
165
|
+
"strict": strict,
|
|
166
|
+
"counts": {s.value: report.counts.get(s, 0) for s in Severity},
|
|
167
|
+
"header": header,
|
|
168
|
+
"payload": payload,
|
|
169
|
+
"signature_present": bool(signature),
|
|
170
|
+
"findings": [
|
|
171
|
+
{
|
|
172
|
+
"severity": f.severity.value,
|
|
173
|
+
"field": f.field,
|
|
174
|
+
"message": f.message,
|
|
175
|
+
"recommendation": f.recommendation,
|
|
176
|
+
}
|
|
177
|
+
for f in report.findings
|
|
178
|
+
],
|
|
179
|
+
}
|
|
180
|
+
if sig_result is not None:
|
|
181
|
+
document["signature_valid"] = sig_result[0]
|
|
182
|
+
document["signature_detail"] = sig_result[1]
|
|
183
|
+
click.echo(json.dumps(document, indent=2, sort_keys=False, default=str))
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _emit_rich(
|
|
187
|
+
header: dict,
|
|
188
|
+
payload: dict,
|
|
189
|
+
signature: str,
|
|
190
|
+
report: Report,
|
|
191
|
+
sig_result: tuple[bool, str] | None,
|
|
192
|
+
) -> None:
|
|
193
|
+
console.print(Panel(json.dumps(header, indent=2), title="Header", border_style="blue"))
|
|
194
|
+
console.print(Panel(json.dumps(payload, indent=2), title="Payload", border_style="blue"))
|
|
195
|
+
console.print(Panel(signature or "(none)", title="Signature", border_style="blue"))
|
|
196
|
+
|
|
197
|
+
if sig_result is not None:
|
|
198
|
+
valid, detail = sig_result
|
|
199
|
+
color = "green" if valid else "red"
|
|
200
|
+
label = "VALID" if valid else "INVALID"
|
|
201
|
+
console.print(
|
|
202
|
+
Panel(
|
|
203
|
+
f"[bold {color}]{label}[/bold {color}] [dim]{detail}[/dim]",
|
|
204
|
+
title="Signature Verification",
|
|
205
|
+
border_style=color,
|
|
206
|
+
)
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
console.print(_render_verdict(report))
|
|
210
|
+
console.print(_render_findings_table(report))
|
|
211
|
+
footer = _render_footer(report)
|
|
212
|
+
if footer is not None:
|
|
213
|
+
console.print(footer)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
def _render_verdict(report: Report) -> Panel:
|
|
217
|
+
verdict, colour = _GRADE_STYLES[report.grade]
|
|
218
|
+
counts = report.counts
|
|
219
|
+
summary = (
|
|
220
|
+
f"[{colour}]Verdict : {verdict}[/{colour}]\n"
|
|
221
|
+
f"[bold {colour}]Grade : {report.grade.value}[/bold {colour}]\n\n"
|
|
222
|
+
f"[dim]CRITICAL : {counts.get(Severity.CRITICAL, 0)} "
|
|
223
|
+
f"WARN : {counts.get(Severity.WARN, 0)} "
|
|
224
|
+
f"INFO : {counts.get(Severity.INFO, 0)} "
|
|
225
|
+
f"PASS : {counts.get(Severity.PASS, 0)}[/dim]"
|
|
226
|
+
)
|
|
227
|
+
return Panel(
|
|
228
|
+
summary, title=f"[bold {colour}]Security Verdict[/bold {colour}]", border_style=colour
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _render_findings_table(report: Report) -> Table:
|
|
233
|
+
show_recs = any(f.recommendation for f in report.findings)
|
|
234
|
+
|
|
235
|
+
table = Table(title="Findings", show_lines=True)
|
|
236
|
+
table.add_column("Severity", style="bold", width=10)
|
|
237
|
+
table.add_column("Field", width=14)
|
|
238
|
+
table.add_column("Detail")
|
|
239
|
+
if show_recs:
|
|
240
|
+
table.add_column("Recommendation", style="dim")
|
|
241
|
+
|
|
242
|
+
for f in report.findings:
|
|
243
|
+
colour = _SEVERITY_COLORS[f.severity]
|
|
244
|
+
row = [
|
|
245
|
+
f"[{colour}]{f.severity.value}[/{colour}]",
|
|
246
|
+
f.field,
|
|
247
|
+
f.message,
|
|
248
|
+
]
|
|
249
|
+
if show_recs:
|
|
250
|
+
row.append(f.recommendation or "")
|
|
251
|
+
table.add_row(*row)
|
|
252
|
+
|
|
253
|
+
return table
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def _render_footer(report: Report) -> Panel | None:
|
|
257
|
+
hints: list[str] = []
|
|
258
|
+
fields = {f.field for f in report.findings if f.severity in (Severity.CRITICAL, Severity.WARN)}
|
|
259
|
+
|
|
260
|
+
if "alg" in fields:
|
|
261
|
+
hints.append(
|
|
262
|
+
"[dim]Test the HMAC secret strength : [/dim]jwt-toolkit crack <token> <wordlist>"
|
|
263
|
+
)
|
|
264
|
+
if fields & {"alg", "exp", "kid", "jwk", "jku", "x5u"}:
|
|
265
|
+
hints.append("[dim]Generate a strong secret : [/dim]jwt-toolkit generate-secret")
|
|
266
|
+
|
|
267
|
+
if not hints:
|
|
268
|
+
return None
|
|
269
|
+
return Panel("\n".join(hints), title="Next steps", border_style="blue")
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
import hmac as _hmac
|
|
2
|
+
import os
|
|
3
|
+
import threading
|
|
4
|
+
import time
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import click
|
|
8
|
+
from rich.panel import Panel
|
|
9
|
+
from rich.progress import (
|
|
10
|
+
BarColumn,
|
|
11
|
+
Progress,
|
|
12
|
+
SpinnerColumn,
|
|
13
|
+
TaskProgressColumn,
|
|
14
|
+
TextColumn,
|
|
15
|
+
TimeElapsedColumn,
|
|
16
|
+
)
|
|
17
|
+
|
|
18
|
+
from jwt_toolkit.cli.algorithms import ensure_hmac_algorithm
|
|
19
|
+
from jwt_toolkit.cli.console import console
|
|
20
|
+
from jwt_toolkit.cli.decoding import render_algorithm_error, resolve_token, safe_decode
|
|
21
|
+
from jwt_toolkit.cli.panels import print_error
|
|
22
|
+
from jwt_toolkit.core.crypto import SUPPORTED_ALGORITHMS
|
|
23
|
+
from jwt_toolkit.core.encoding import base64_decode_padded, base64url_encode
|
|
24
|
+
from jwt_toolkit.core.errors import UnsupportedAlgorithmError
|
|
25
|
+
|
|
26
|
+
# Crack command — brute-forces a weak HMAC JWT secret against a wordlist.
|
|
27
|
+
|
|
28
|
+
# Items pulled from the generator per lock acquisition — reduces contention
|
|
29
|
+
# on the hot loop without buffering the whole file in memory.
|
|
30
|
+
_BATCH_SIZE = 200
|
|
31
|
+
|
|
32
|
+
# Expansion factor used to estimate total candidates before streaming starts.
|
|
33
|
+
_ENCODING_MULTIPLIER = {"utf-8": 1, "hex": 1, "base64": 1, "all": 3}
|
|
34
|
+
|
|
35
|
+
_DEFAULT_THREADS = min(os.cpu_count() or 4, 8)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _iter_candidates(wordlist_path: str, encoding: str):
|
|
39
|
+
"""Stream (label, secret_bytes) pairs from a wordlist file.
|
|
40
|
+
|
|
41
|
+
Handles P2 (no full-file load) and P3 (dedup by bytes) in one pass.
|
|
42
|
+
"""
|
|
43
|
+
seen: set[bytes] = set()
|
|
44
|
+
with Path(wordlist_path).open(errors="ignore") as f:
|
|
45
|
+
for line in f:
|
|
46
|
+
word = line.strip()
|
|
47
|
+
if not word or word.startswith("#"):
|
|
48
|
+
continue
|
|
49
|
+
if encoding in ("utf-8", "all"):
|
|
50
|
+
sbytes = word.encode("utf-8", errors="replace")
|
|
51
|
+
if sbytes not in seen:
|
|
52
|
+
seen.add(sbytes)
|
|
53
|
+
yield word, sbytes
|
|
54
|
+
if encoding in ("hex", "all"):
|
|
55
|
+
try:
|
|
56
|
+
sbytes = bytes.fromhex(word)
|
|
57
|
+
if sbytes not in seen:
|
|
58
|
+
seen.add(sbytes)
|
|
59
|
+
yield f"{word} [hex]", sbytes
|
|
60
|
+
except ValueError:
|
|
61
|
+
pass
|
|
62
|
+
if encoding in ("base64", "all"):
|
|
63
|
+
try:
|
|
64
|
+
sbytes = base64_decode_padded(word)
|
|
65
|
+
if sbytes not in seen:
|
|
66
|
+
seen.add(sbytes)
|
|
67
|
+
yield f"{word} [b64]", sbytes
|
|
68
|
+
# Invalid base64; skip and try next candidate.
|
|
69
|
+
except Exception: # nosec B110
|
|
70
|
+
pass
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _count_raw_lines(wordlist_path: str) -> int:
|
|
74
|
+
"""Fast pre-scan: count valid (non-empty, non-comment) lines."""
|
|
75
|
+
count = 0
|
|
76
|
+
with Path(wordlist_path).open(errors="ignore") as f:
|
|
77
|
+
for line in f:
|
|
78
|
+
s = line.strip()
|
|
79
|
+
if s and not s.startswith("#"):
|
|
80
|
+
count += 1
|
|
81
|
+
return count
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _format_rate(rate: float) -> str:
|
|
85
|
+
if rate >= 1_000_000:
|
|
86
|
+
return f"{rate / 1_000_000:.1f}M c/s"
|
|
87
|
+
if rate >= 1_000:
|
|
88
|
+
return f"{rate / 1_000:.1f}k c/s"
|
|
89
|
+
return f"{rate:.0f} c/s"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
@click.command(help="Brute-force a weak HMAC JWT secret using a wordlist.")
|
|
93
|
+
@click.argument("token")
|
|
94
|
+
@click.argument("wordlist", type=click.Path(exists=True, readable=True))
|
|
95
|
+
@click.option(
|
|
96
|
+
"--threads",
|
|
97
|
+
default=_DEFAULT_THREADS,
|
|
98
|
+
show_default=True,
|
|
99
|
+
type=click.IntRange(1, 64),
|
|
100
|
+
help="Worker threads (1-64)",
|
|
101
|
+
)
|
|
102
|
+
@click.option(
|
|
103
|
+
"--encoding",
|
|
104
|
+
type=click.Choice(["utf-8", "hex", "base64", "all"]),
|
|
105
|
+
default="utf-8",
|
|
106
|
+
show_default=True,
|
|
107
|
+
help="How to interpret each candidate before signing",
|
|
108
|
+
)
|
|
109
|
+
@click.option(
|
|
110
|
+
"--output",
|
|
111
|
+
default=None,
|
|
112
|
+
type=click.Path(),
|
|
113
|
+
help="Write found secret to this file",
|
|
114
|
+
)
|
|
115
|
+
def crack(token: str, wordlist: str, threads: int, encoding: str, output: str | None):
|
|
116
|
+
token = resolve_token(token)
|
|
117
|
+
decoded = safe_decode(token)
|
|
118
|
+
|
|
119
|
+
if not decoded.signature:
|
|
120
|
+
print_error(
|
|
121
|
+
"Token has an empty signature — nothing to crack",
|
|
122
|
+
"An empty signature is characteristic of an alg:none attack",
|
|
123
|
+
"Use audit to examine the token structure",
|
|
124
|
+
title="Cannot Crack",
|
|
125
|
+
)
|
|
126
|
+
raise SystemExit(2)
|
|
127
|
+
|
|
128
|
+
try:
|
|
129
|
+
alg = ensure_hmac_algorithm(decoded.header, action="crack")
|
|
130
|
+
except UnsupportedAlgorithmError as exc:
|
|
131
|
+
render_algorithm_error(exc)
|
|
132
|
+
raise SystemExit(2) from exc
|
|
133
|
+
|
|
134
|
+
raw_count = _count_raw_lines(wordlist)
|
|
135
|
+
if raw_count == 0:
|
|
136
|
+
print_error(
|
|
137
|
+
"Wordlist is empty",
|
|
138
|
+
f"File : {wordlist}",
|
|
139
|
+
title="Invalid Wordlist",
|
|
140
|
+
)
|
|
141
|
+
raise SystemExit(2)
|
|
142
|
+
|
|
143
|
+
total_estimate = raw_count * _ENCODING_MULTIPLIER.get(encoding, 1)
|
|
144
|
+
|
|
145
|
+
if not os.environ.get("JWT_TOOLKIT_QUIET"):
|
|
146
|
+
console.print(
|
|
147
|
+
f"[dim]Algorithm : {alg} "
|
|
148
|
+
f"Candidates : ~{total_estimate:,} "
|
|
149
|
+
f"Threads : {threads} "
|
|
150
|
+
f"Encoding : {encoding}[/dim]"
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
result, final_attempts, elapsed = _run_crack(
|
|
154
|
+
wordlist,
|
|
155
|
+
encoding,
|
|
156
|
+
total_estimate,
|
|
157
|
+
threads,
|
|
158
|
+
alg,
|
|
159
|
+
decoded.header_b64,
|
|
160
|
+
decoded.payload_b64,
|
|
161
|
+
decoded.signature,
|
|
162
|
+
)
|
|
163
|
+
avg_rate = final_attempts / elapsed if elapsed > 0 else 0
|
|
164
|
+
|
|
165
|
+
if result is not None:
|
|
166
|
+
_render_found(result, alg, total_estimate, elapsed, avg_rate, output)
|
|
167
|
+
raise SystemExit(1)
|
|
168
|
+
_render_not_found(alg, final_attempts, elapsed, avg_rate)
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def _run_crack( # noqa: PLR0915 — thread orchestration; splitting hurts readability
|
|
172
|
+
wordlist_path: str,
|
|
173
|
+
encoding: str,
|
|
174
|
+
total_estimate: int,
|
|
175
|
+
threads: int,
|
|
176
|
+
alg: str,
|
|
177
|
+
header_b64: str,
|
|
178
|
+
payload_b64: str,
|
|
179
|
+
signature: str,
|
|
180
|
+
) -> tuple[tuple[str, int] | None, int, float]:
|
|
181
|
+
digestmod = SUPPORTED_ALGORITHMS[alg]
|
|
182
|
+
signing_input = f"{header_b64}.{payload_b64}".encode()
|
|
183
|
+
|
|
184
|
+
def _check(sbytes: bytes) -> bool:
|
|
185
|
+
digest = _hmac.new(sbytes, signing_input, digestmod).digest()
|
|
186
|
+
# compare_digest avoids leaking signature length via short-circuit.
|
|
187
|
+
return _hmac.compare_digest(base64url_encode(digest), signature)
|
|
188
|
+
|
|
189
|
+
gen = _iter_candidates(wordlist_path, encoding)
|
|
190
|
+
gen_lock = threading.Lock()
|
|
191
|
+
position_counter: list[int] = [0]
|
|
192
|
+
stop_event = threading.Event()
|
|
193
|
+
lock = threading.Lock()
|
|
194
|
+
found_box: list[tuple[str, int] | None] = [None]
|
|
195
|
+
attempts_box: list[int] = [0]
|
|
196
|
+
|
|
197
|
+
def worker() -> None:
|
|
198
|
+
local_attempts = 0
|
|
199
|
+
while not stop_event.is_set():
|
|
200
|
+
# Pull a batch under a single lock acquisition to keep contention low.
|
|
201
|
+
with gen_lock:
|
|
202
|
+
batch: list[tuple[int, tuple[str, bytes]]] = []
|
|
203
|
+
for _ in range(_BATCH_SIZE):
|
|
204
|
+
item = next(gen, None)
|
|
205
|
+
if item is None:
|
|
206
|
+
break
|
|
207
|
+
pos = position_counter[0]
|
|
208
|
+
position_counter[0] += 1
|
|
209
|
+
batch.append((pos, item))
|
|
210
|
+
if not batch:
|
|
211
|
+
break
|
|
212
|
+
for pos, (label, sbytes) in batch:
|
|
213
|
+
if stop_event.is_set():
|
|
214
|
+
break
|
|
215
|
+
if _check(sbytes):
|
|
216
|
+
with lock:
|
|
217
|
+
found_box[0] = (label, pos)
|
|
218
|
+
stop_event.set()
|
|
219
|
+
break
|
|
220
|
+
local_attempts += 1
|
|
221
|
+
if local_attempts % 500 == 0:
|
|
222
|
+
with lock:
|
|
223
|
+
attempts_box[0] += local_attempts
|
|
224
|
+
local_attempts = 0
|
|
225
|
+
with lock:
|
|
226
|
+
attempts_box[0] += local_attempts
|
|
227
|
+
|
|
228
|
+
thread_list = [threading.Thread(target=worker, daemon=True) for _ in range(threads)]
|
|
229
|
+
start = time.perf_counter()
|
|
230
|
+
|
|
231
|
+
with Progress(
|
|
232
|
+
SpinnerColumn(),
|
|
233
|
+
TextColumn("[progress.description]{task.description}"),
|
|
234
|
+
BarColumn(),
|
|
235
|
+
TaskProgressColumn(),
|
|
236
|
+
TextColumn("[dim]{task.fields[rate]}[/dim]"),
|
|
237
|
+
TimeElapsedColumn(),
|
|
238
|
+
console=console, # type: ignore[arg-type] # _ConsoleProxy duck-types Console
|
|
239
|
+
transient=True,
|
|
240
|
+
) as progress:
|
|
241
|
+
task = progress.add_task("Cracking…", total=total_estimate, rate="-")
|
|
242
|
+
|
|
243
|
+
for t in thread_list:
|
|
244
|
+
t.start()
|
|
245
|
+
|
|
246
|
+
prev_attempts = 0
|
|
247
|
+
prev_time = start
|
|
248
|
+
|
|
249
|
+
# Poll workers every 150ms; refresh rate display every 400ms.
|
|
250
|
+
while not stop_event.is_set() and any(t.is_alive() for t in thread_list):
|
|
251
|
+
time.sleep(0.15)
|
|
252
|
+
with lock:
|
|
253
|
+
done = attempts_box[0]
|
|
254
|
+
|
|
255
|
+
now = time.perf_counter()
|
|
256
|
+
dt = now - prev_time
|
|
257
|
+
if dt >= 0.4:
|
|
258
|
+
rate = (done - prev_attempts) / dt
|
|
259
|
+
progress.update(task, completed=done, rate=_format_rate(rate))
|
|
260
|
+
prev_attempts = done
|
|
261
|
+
prev_time = now
|
|
262
|
+
else:
|
|
263
|
+
progress.update(task, completed=done)
|
|
264
|
+
|
|
265
|
+
for t in thread_list:
|
|
266
|
+
t.join()
|
|
267
|
+
|
|
268
|
+
elapsed = time.perf_counter() - start
|
|
269
|
+
with lock:
|
|
270
|
+
return found_box[0], attempts_box[0], elapsed
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _render_found(
|
|
274
|
+
result: tuple[str, int],
|
|
275
|
+
alg: str,
|
|
276
|
+
total_estimate: int,
|
|
277
|
+
elapsed: float,
|
|
278
|
+
avg_rate: float,
|
|
279
|
+
output: str | None,
|
|
280
|
+
) -> None:
|
|
281
|
+
label, idx = result
|
|
282
|
+
saved_line = ""
|
|
283
|
+
if output:
|
|
284
|
+
try:
|
|
285
|
+
with Path(output).open("w") as fout:
|
|
286
|
+
fout.write(label + "\n")
|
|
287
|
+
saved_line = f"\n[dim]Saved to : {output}[/dim]"
|
|
288
|
+
except OSError as exc:
|
|
289
|
+
saved_line = f"\n[dim yellow]Could not save: {exc}[/dim yellow]"
|
|
290
|
+
|
|
291
|
+
# Cracked = bad: the secret is dangerously weak.
|
|
292
|
+
console.print(
|
|
293
|
+
Panel(
|
|
294
|
+
f"[bold red]Secret:[/bold red] [bold yellow]{label}[/bold yellow]{saved_line}\n\n"
|
|
295
|
+
f"[dim]Algorithm : {alg}[/dim]\n"
|
|
296
|
+
f"[dim]Position : #{idx + 1} of ~{total_estimate:,} candidates[/dim]\n"
|
|
297
|
+
f"[dim]Candidates tried : {idx + 1:,}[/dim]\n"
|
|
298
|
+
f"[dim]Time elapsed : {elapsed:.3f}s[/dim]\n"
|
|
299
|
+
f"[dim]Average rate : {_format_rate(avg_rate)}[/dim]\n\n"
|
|
300
|
+
"[bold red]This secret is in a common wordlist — it is not safe.[/bold red]\n"
|
|
301
|
+
"[dim]Generate a strong secret with: jwt-toolkit generate-secret[/dim]",
|
|
302
|
+
title="[bold red]Weak Secret Detected[/bold red]",
|
|
303
|
+
border_style="red",
|
|
304
|
+
)
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def _render_not_found(alg: str, attempts: int, elapsed: float, avg_rate: float) -> None:
|
|
309
|
+
console.print(
|
|
310
|
+
Panel(
|
|
311
|
+
"[bold green]Secret not found in this wordlist[/bold green]\n\n"
|
|
312
|
+
f"[dim]Algorithm : {alg}[/dim]\n"
|
|
313
|
+
f"[dim]Candidates tried : {attempts:,}[/dim]\n"
|
|
314
|
+
f"[dim]Time elapsed : {elapsed:.3f}s[/dim]\n"
|
|
315
|
+
f"[dim]Average rate : {_format_rate(avg_rate)}[/dim]\n\n"
|
|
316
|
+
"[dim]This does not guarantee the secret is strong — a larger[/dim]\n"
|
|
317
|
+
"[dim]wordlist may still find it. Use jwt-toolkit generate-secret[/dim]\n"
|
|
318
|
+
"[dim]if you need a cryptographically strong secret.[/dim]",
|
|
319
|
+
title="[bold green]Wordlist Check Passed[/bold green]",
|
|
320
|
+
border_style="green",
|
|
321
|
+
)
|
|
322
|
+
)
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
import click
|
|
4
|
+
from rich.panel import Panel
|
|
5
|
+
from rich.syntax import Syntax
|
|
6
|
+
|
|
7
|
+
from jwt_toolkit.cli.console import console
|
|
8
|
+
from jwt_toolkit.cli.decoding import JSON_SCHEMA_VERSION, resolve_token, safe_decode
|
|
9
|
+
|
|
10
|
+
# Decode command — pretty-print the header and payload of a JWT without audit noise.
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@click.command(help="Decode a JWT and pretty-print its header and payload.")
|
|
14
|
+
@click.argument("token")
|
|
15
|
+
@click.option("--json", "as_json", is_flag=True, help="Emit machine-readable JSON output.")
|
|
16
|
+
def decode(token: str, as_json: bool):
|
|
17
|
+
token = resolve_token(token)
|
|
18
|
+
decoded = safe_decode(token, as_json=as_json)
|
|
19
|
+
|
|
20
|
+
if as_json:
|
|
21
|
+
click.echo(
|
|
22
|
+
json.dumps(
|
|
23
|
+
{
|
|
24
|
+
"schema_version": JSON_SCHEMA_VERSION,
|
|
25
|
+
"header": decoded.header,
|
|
26
|
+
"payload": decoded.payload,
|
|
27
|
+
"signature": decoded.signature,
|
|
28
|
+
},
|
|
29
|
+
indent=2,
|
|
30
|
+
)
|
|
31
|
+
)
|
|
32
|
+
return
|
|
33
|
+
|
|
34
|
+
console.print(
|
|
35
|
+
Panel(
|
|
36
|
+
Syntax(json.dumps(decoded.header, indent=2), "json", theme="monokai"),
|
|
37
|
+
title="Header",
|
|
38
|
+
border_style="blue",
|
|
39
|
+
)
|
|
40
|
+
)
|
|
41
|
+
console.print(
|
|
42
|
+
Panel(
|
|
43
|
+
Syntax(json.dumps(decoded.payload, indent=2), "json", theme="monokai"),
|
|
44
|
+
title="Payload",
|
|
45
|
+
border_style="blue",
|
|
46
|
+
)
|
|
47
|
+
)
|
|
48
|
+
console.print(
|
|
49
|
+
Panel(
|
|
50
|
+
decoded.signature or "[dim](none)[/dim]",
|
|
51
|
+
title="Signature",
|
|
52
|
+
border_style="dim",
|
|
53
|
+
)
|
|
54
|
+
)
|