keyprint-cli 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.
- keyprint/__init__.py +3 -0
- keyprint/__main__.py +4 -0
- keyprint/checksum.py +173 -0
- keyprint/cli.py +283 -0
- keyprint/context.py +90 -0
- keyprint/engine.py +390 -0
- keyprint/export.py +80 -0
- keyprint/fingerprint.py +268 -0
- keyprint/redact.py +20 -0
- keyprint/report.py +127 -0
- keyprint/rules/data/providers.json +1903 -0
- keyprint/ruleset.py +120 -0
- keyprint/scanner.py +96 -0
- keyprint/scoring.py +57 -0
- keyprint/style.py +82 -0
- keyprint/verify.py +234 -0
- keyprint_cli-0.1.0.dist-info/METADATA +380 -0
- keyprint_cli-0.1.0.dist-info/RECORD +22 -0
- keyprint_cli-0.1.0.dist-info/WHEEL +5 -0
- keyprint_cli-0.1.0.dist-info/entry_points.txt +2 -0
- keyprint_cli-0.1.0.dist-info/licenses/LICENSE +202 -0
- keyprint_cli-0.1.0.dist-info/top_level.txt +1 -0
keyprint/__init__.py
ADDED
keyprint/__main__.py
ADDED
keyprint/checksum.py
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""Checksum validators for credential formats that carry one.
|
|
2
|
+
|
|
3
|
+
A valid checksum is near-decisive evidence: random strings pass format
|
|
4
|
+
regexes all the time, but they essentially never pass a real checksum.
|
|
5
|
+
Conversely, a checksum failure *downgrades* confidence rather than
|
|
6
|
+
eliminating a match, because we cannot guarantee every provider's
|
|
7
|
+
algorithm is exactly reproduced here.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import base64
|
|
13
|
+
import binascii
|
|
14
|
+
import calendar
|
|
15
|
+
import datetime as _dt
|
|
16
|
+
import json
|
|
17
|
+
|
|
18
|
+
# ---------------------------------------------------------------------------
|
|
19
|
+
# GitHub token checksum (classic ghp_/gho_/ghu_/ghs_/ghr_ tokens).
|
|
20
|
+
#
|
|
21
|
+
# GitHub tokens are 36 chars after the prefix: a 30-char body plus a 6-char
|
|
22
|
+
# checksum rendered in the token alphabet. Algorithm is publicly documented
|
|
23
|
+
# (GitHub secret-scanning format docs / community reverse engineering):
|
|
24
|
+
# a standard CRC-32 (poly 0xEDB88320, init/xorout 0xFFFFFFFF) over the body,
|
|
25
|
+
# encoded big-endian in base62 over the GitHub token alphabet.
|
|
26
|
+
# ---------------------------------------------------------------------------
|
|
27
|
+
|
|
28
|
+
GITHUB_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def crc32_github(data: bytes) -> int:
|
|
32
|
+
crc = 0xFFFFFFFF
|
|
33
|
+
for byte in data:
|
|
34
|
+
crc ^= byte
|
|
35
|
+
for _ in range(8):
|
|
36
|
+
mask = -(crc & 1)
|
|
37
|
+
crc = (crc >> 1) ^ (0xEDB88320 & mask)
|
|
38
|
+
return ~crc & 0xFFFFFFFF
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _base62_bigendian(value: int, width: int) -> str:
|
|
42
|
+
chars = []
|
|
43
|
+
while value:
|
|
44
|
+
value, rem = divmod(value, 62)
|
|
45
|
+
chars.append(GITHUB_ALPHABET[rem])
|
|
46
|
+
encoded = "".join(reversed(chars))
|
|
47
|
+
return encoded.rjust(width, GITHUB_ALPHABET[0])
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def github_token_checksum(body: str) -> str:
|
|
51
|
+
"""Compute the 6-char checksum for a 30-char GitHub token body."""
|
|
52
|
+
return _base62_bigendian(crc32_github(body.encode()), 6)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def validate_github_token(payload: str) -> bool:
|
|
56
|
+
"""payload = the 36 chars following gh?_ ."""
|
|
57
|
+
if len(payload) != 36:
|
|
58
|
+
return False
|
|
59
|
+
body, check = payload[:30], payload[30:]
|
|
60
|
+
if any(c not in GITHUB_ALPHABET for c in body):
|
|
61
|
+
return False
|
|
62
|
+
return github_token_checksum(body) == check
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
# ---------------------------------------------------------------------------
|
|
66
|
+
# Discord bot tokens: three base64url segments. Segment 1 decodes to the
|
|
67
|
+
# bot user ID (a Discord snowflake); the top 22 bits are a millisecond
|
|
68
|
+
# timestamp that must land after Discord's epoch (2015-01-01) and not in
|
|
69
|
+
# the far future.
|
|
70
|
+
# ---------------------------------------------------------------------------
|
|
71
|
+
|
|
72
|
+
DISCORD_EPOCH_MS = 1420070400000 # 2015-01-01
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def validate_discord_token(token: str) -> bool:
|
|
76
|
+
parts = token.split(".")
|
|
77
|
+
if len(parts) != 3:
|
|
78
|
+
return False
|
|
79
|
+
if len(parts[1]) < 5 or len(parts[2]) < 26:
|
|
80
|
+
return False
|
|
81
|
+
try:
|
|
82
|
+
pad = parts[0] + "=" * (-len(parts[0]) % 4)
|
|
83
|
+
decoded = base64.urlsafe_b64decode(pad)
|
|
84
|
+
# Discord encodes the bot user ID as ASCII digits in most tokens;
|
|
85
|
+
# fall back to raw big-endian bytes for other encodings.
|
|
86
|
+
if decoded and all(48 <= b <= 57 for b in decoded):
|
|
87
|
+
user_id = int(decoded)
|
|
88
|
+
else:
|
|
89
|
+
user_id = int.from_bytes(decoded, "big")
|
|
90
|
+
except (binascii.Error, ValueError):
|
|
91
|
+
return False
|
|
92
|
+
if user_id <= 0 or user_id >> 22 <= 0:
|
|
93
|
+
return False
|
|
94
|
+
ts_ms = (user_id >> 22) + DISCORD_EPOCH_MS
|
|
95
|
+
if ts_ms < DISCORD_EPOCH_MS:
|
|
96
|
+
return False
|
|
97
|
+
now_ms = calendar.timegm(_dt.datetime.now(_dt.UTC).timetuple()) * 1000
|
|
98
|
+
# Bot accounts cannot predate the platform nor be issued in the future.
|
|
99
|
+
return DISCORD_EPOCH_MS <= ts_ms <= now_ms + 86400_000
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def discord_token_timestamp(token: str) -> int | None:
|
|
103
|
+
parts = token.split(".")
|
|
104
|
+
if len(parts) != 3:
|
|
105
|
+
return None
|
|
106
|
+
try:
|
|
107
|
+
pad = parts[0] + "=" * (-len(parts[0]) % 4)
|
|
108
|
+
decoded = base64.urlsafe_b64decode(pad)
|
|
109
|
+
if decoded and all(48 <= b <= 57 for b in decoded):
|
|
110
|
+
user_id = int(decoded)
|
|
111
|
+
else:
|
|
112
|
+
user_id = int.from_bytes(decoded, "big")
|
|
113
|
+
except (binascii.Error, ValueError):
|
|
114
|
+
return None
|
|
115
|
+
return (user_id >> 22) + DISCORD_EPOCH_MS
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
# ---------------------------------------------------------------------------
|
|
119
|
+
# JWT / OIDC tokens: three base64url segments; header must parse as a JSON
|
|
120
|
+
# object carrying an alg. We validate structure only -- signature checking
|
|
121
|
+
# is out of scope for offline attribution.
|
|
122
|
+
# ---------------------------------------------------------------------------
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def validate_jwt(token: str) -> bool:
|
|
126
|
+
parts = token.split(".")
|
|
127
|
+
if len(parts) != 3:
|
|
128
|
+
return False
|
|
129
|
+
try:
|
|
130
|
+
header_b64 = parts[0] + "=" * (-len(parts[0]) % 4)
|
|
131
|
+
header = json.loads(base64.urlsafe_b64decode(header_b64))
|
|
132
|
+
except (binascii.Error, ValueError):
|
|
133
|
+
return False
|
|
134
|
+
return isinstance(header, dict) and isinstance(header.get("alg"), str)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def jwt_header(token: str) -> dict | None:
|
|
138
|
+
parts = token.split(".")
|
|
139
|
+
if len(parts) != 3:
|
|
140
|
+
return None
|
|
141
|
+
try:
|
|
142
|
+
pad = parts[0] + "=" * (-len(parts[0]) % 4)
|
|
143
|
+
return json.loads(base64.urlsafe_b64decode(pad))
|
|
144
|
+
except (binascii.Error, ValueError):
|
|
145
|
+
return None
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# ---------------------------------------------------------------------------
|
|
149
|
+
# Luhn (used by some payment-adjacent test fixtures) and a generic
|
|
150
|
+
# mod-37,2 checksum for formats that use it.
|
|
151
|
+
# ---------------------------------------------------------------------------
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def validate_luhn(digits: str) -> bool:
|
|
155
|
+
if not digits.isdigit():
|
|
156
|
+
return False
|
|
157
|
+
total = 0
|
|
158
|
+
for i, ch in enumerate(reversed(digits)):
|
|
159
|
+
d = int(ch)
|
|
160
|
+
if i % 2 == 1:
|
|
161
|
+
d *= 2
|
|
162
|
+
if d > 9:
|
|
163
|
+
d -= 9
|
|
164
|
+
total += d
|
|
165
|
+
return total % 10 == 0
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
CHECKSUMS = {
|
|
169
|
+
"github": validate_github_token,
|
|
170
|
+
"discord": validate_discord_token,
|
|
171
|
+
"jwt": validate_jwt,
|
|
172
|
+
"luhn": validate_luhn,
|
|
173
|
+
}
|
keyprint/cli.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
"""keyprint command-line interface.
|
|
2
|
+
|
|
3
|
+
Subcommands:
|
|
4
|
+
explain attribute one key from an argument or stdin (offline)
|
|
5
|
+
scan scan files/directories (offline)
|
|
6
|
+
verify authorized liveness check of keys you own (networked, gated)
|
|
7
|
+
fingerprint model fingerprinting plan or run (gated)
|
|
8
|
+
rules list / export the rule corpus
|
|
9
|
+
selftest run the built-in fixture suite against the engine
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import argparse
|
|
15
|
+
import json
|
|
16
|
+
import sys
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from . import __version__, style
|
|
20
|
+
from .engine import Engine
|
|
21
|
+
from .report import RENDERERS
|
|
22
|
+
from .ruleset import load_rules
|
|
23
|
+
from .scanner import scan_git_history, scan_path, scan_stdin
|
|
24
|
+
|
|
25
|
+
from .style import BOLD, CYAN, DIM, GREEN, MAGENTA, RESET, YELLOW, paint
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _engine(args) -> Engine:
|
|
29
|
+
return Engine(load_rules(getattr(args, "rules", None)))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# ---------------------------------------------------------------- explain
|
|
33
|
+
def cmd_explain(args) -> int:
|
|
34
|
+
engine = _engine(args)
|
|
35
|
+
text = args.text if args.text else sys.stdin.read()
|
|
36
|
+
findings = engine.scan_text(text, file="<input>")
|
|
37
|
+
trunc = engine.explain_truncated(text)
|
|
38
|
+
if trunc:
|
|
39
|
+
# truncated attribution outranks the generic unknown fallback
|
|
40
|
+
findings = [f for f in findings if f.provider != "unknown"] + trunc
|
|
41
|
+
if args.format == "text":
|
|
42
|
+
if not findings:
|
|
43
|
+
print("no attribution: input does not match any known credential format "
|
|
44
|
+
"and is not a truncated key.")
|
|
45
|
+
return 1
|
|
46
|
+
for f in findings:
|
|
47
|
+
secret = f.token if args.show_secret else f.redacted
|
|
48
|
+
tok_c, lbl_c = style.tier_colors(f.confidence)
|
|
49
|
+
print(paint(secret, tok_c) + " " + paint(f.title, lbl_c)
|
|
50
|
+
+ paint(f" ({f.confidence})", DIM)
|
|
51
|
+
+ (paint(" [PLACEHOLDER]", MAGENTA) if f.placeholder else ""))
|
|
52
|
+
print(paint(f" evidence: {f.score.render_evidence()}", DIM))
|
|
53
|
+
if f.alternatives:
|
|
54
|
+
print(paint(f" also consistent with: {', '.join(f.alternatives)}", DIM))
|
|
55
|
+
if f.capabilities():
|
|
56
|
+
print(paint(f" capabilities: ", DIM) + paint("; ".join(f.capabilities()), YELLOW))
|
|
57
|
+
if f.financial_exposure():
|
|
58
|
+
print(paint(f" financial exposure: ", DIM) + paint(f.financial_exposure(), YELLOW))
|
|
59
|
+
if f.revoke_url():
|
|
60
|
+
print(paint(" revoke: ", DIM) + paint(f.revoke_url(), GREEN))
|
|
61
|
+
if f.truncated:
|
|
62
|
+
print(paint(" note: truncated key - attribution from prefix + shape; verification impossible", DIM))
|
|
63
|
+
else:
|
|
64
|
+
print(RENDERERS[args.format](findings, args.show_secret))
|
|
65
|
+
return 0
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
# ------------------------------------------------------------------- scan
|
|
69
|
+
def cmd_scan(args) -> int:
|
|
70
|
+
engine = _engine(args)
|
|
71
|
+
findings: list = []
|
|
72
|
+
if args.git_history:
|
|
73
|
+
findings.extend(scan_git_history(engine, args.paths[0]))
|
|
74
|
+
for p in args.paths:
|
|
75
|
+
if p == "-":
|
|
76
|
+
findings.extend(scan_stdin(engine))
|
|
77
|
+
else:
|
|
78
|
+
findings.extend(scan_path(engine, p))
|
|
79
|
+
min_rank = {"placeholder": 0, "unknown": 1, "possible": 2, "likely": 3, "certain": 4}
|
|
80
|
+
floor = min_rank[args.min_confidence]
|
|
81
|
+
findings = [f for f in findings if min_rank.get(f.confidence, 0) >= floor] if not args.all else findings
|
|
82
|
+
print(RENDERERS[args.format](findings, args.show_secret))
|
|
83
|
+
return 1 if (args.fail_on_findings and findings) else 0
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
# ----------------------------------------------------------------- verify
|
|
87
|
+
def cmd_verify(args) -> int:
|
|
88
|
+
from . import verify as V
|
|
89
|
+
keys: list[tuple[str, str]] = [] # (provider, key)
|
|
90
|
+
for item in args.keys:
|
|
91
|
+
if ":" in item and item.split(":", 1)[0] in V.SPECS:
|
|
92
|
+
provider, key = item.split(":", 1)
|
|
93
|
+
elif args.provider:
|
|
94
|
+
provider, key = args.provider, item
|
|
95
|
+
else:
|
|
96
|
+
sys.stderr.write(f"cannot infer provider for key {item[:6]}…; pass --provider or provider:key\n")
|
|
97
|
+
return 2
|
|
98
|
+
keys.append((provider, key))
|
|
99
|
+
V.ownership_gate(len(keys), args.authorized_owner, args.yes, args.i_know_this_is_bulk)
|
|
100
|
+
rc = 0
|
|
101
|
+
for provider, key in keys:
|
|
102
|
+
spec = V.SPECS[provider]
|
|
103
|
+
print(f"[{provider}] about to call: {spec.describe()}")
|
|
104
|
+
try:
|
|
105
|
+
result = V.verify_key(provider, key, basic=args.basic)
|
|
106
|
+
except ConnectionError as e:
|
|
107
|
+
print(f"[{provider}] {e}")
|
|
108
|
+
rc = 1
|
|
109
|
+
continue
|
|
110
|
+
hint = key[:6] + "…" + key[-4:] if len(key) > 12 else "****"
|
|
111
|
+
print(result.render(hint))
|
|
112
|
+
if result.liveness in ("valid",):
|
|
113
|
+
print(" action: no action needed (your key)")
|
|
114
|
+
elif result.liveness in ("revoked-or-invalid",):
|
|
115
|
+
print(" action: rotate if you expected this key to be valid")
|
|
116
|
+
print()
|
|
117
|
+
print(f"audit log (local only): {V.AUDIT_LOG}")
|
|
118
|
+
return rc
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
# ------------------------------------------------------------ fingerprint
|
|
122
|
+
def cmd_fingerprint(args) -> int:
|
|
123
|
+
from . import fingerprint as F
|
|
124
|
+
if args.build_corpus:
|
|
125
|
+
print("corpus builder: collects reference transcripts from official endpoints.")
|
|
126
|
+
print("planned flow: authenticate per provider -> run the probe suite over each")
|
|
127
|
+
print("model id -> hash requests/responses -> sign manifest -> append to bank.")
|
|
128
|
+
print("not implemented in 0.1; see PLAN.md section 8.")
|
|
129
|
+
return 0
|
|
130
|
+
if not args.allow_network:
|
|
131
|
+
print(f"probe plan (offline; nothing will be called): {F.TOTAL_CALLS} requests")
|
|
132
|
+
for p in F.PROBE_PLAN:
|
|
133
|
+
print(f" {p['id']:22s} x{p['calls']} {p['desc']}")
|
|
134
|
+
print(f"\nreference families: {', '.join(F.REFERENCE_BANK)}")
|
|
135
|
+
print(f"note: {F.SEED_NOTE}")
|
|
136
|
+
print("\nto run live: add --allow-network (requires --authorized-owner)")
|
|
137
|
+
return 0
|
|
138
|
+
F.fingerprint_gate(args.authorized_owner, args.allow_network)
|
|
139
|
+
results, egress = F.run_probes(args.endpoint, args.key, args.model)
|
|
140
|
+
verdict = F.score(results, args.claims)
|
|
141
|
+
key_hint = args.key[:6] + "…" + args.key[-4:] if len(args.key) > 12 else "****"
|
|
142
|
+
print(verdict.render(args.endpoint, key_hint))
|
|
143
|
+
return 0 if not verdict.inconclusive else 3
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
# ------------------------------------------------------------------ rules
|
|
147
|
+
def cmd_rules(args) -> int:
|
|
148
|
+
rules = load_rules(args.rules)
|
|
149
|
+
if args.rules_cmd == "list":
|
|
150
|
+
for r in rules:
|
|
151
|
+
cs = f" checksum={r.checksum}" if r.checksum else ""
|
|
152
|
+
ver = f" verifiable" if r.verify else ""
|
|
153
|
+
print(f"{r.provider:16s} {r.id:34s}{cs}{ver}")
|
|
154
|
+
print(f"\n{len(rules)} rules")
|
|
155
|
+
elif args.rules_cmd == "export":
|
|
156
|
+
from .export import export_rules
|
|
157
|
+
print(export_rules(rules, args.format))
|
|
158
|
+
return 0
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
# --------------------------------------------------------------- selftest
|
|
162
|
+
def cmd_selftest(args) -> int:
|
|
163
|
+
engine = _engine(args)
|
|
164
|
+
total = passed = 0
|
|
165
|
+
failures = []
|
|
166
|
+
table = []
|
|
167
|
+
for rule in engine.rules:
|
|
168
|
+
ctx = f"{rule.context[0]}=" if rule.context else ""
|
|
169
|
+
for fx in rule.fixtures.get("valid", []):
|
|
170
|
+
total += 1
|
|
171
|
+
found = engine.scan_text(f"{ctx}{fx}")
|
|
172
|
+
hit = next((f for f in found if f.rule and f.rule.id == rule.id
|
|
173
|
+
and f.confidence in ("certain", "likely")), None)
|
|
174
|
+
if hit:
|
|
175
|
+
passed += 1
|
|
176
|
+
else:
|
|
177
|
+
confs = ", ".join(f"{f.rule.id}:{f.confidence}" if f.rule else "entropy-fallback" for f in found) or "none"
|
|
178
|
+
failures.append(f" MISS {rule.id}: {fx[:20]}… got [{confs}]")
|
|
179
|
+
for fx in rule.fixtures.get("invalid", []):
|
|
180
|
+
total += 1
|
|
181
|
+
found = engine.scan_text(f"{ctx}{fx}")
|
|
182
|
+
bad = next((f for f in found if f.rule and f.rule.id == rule.id
|
|
183
|
+
and f.confidence in ("certain", "likely")), None)
|
|
184
|
+
if not bad:
|
|
185
|
+
passed += 1
|
|
186
|
+
else:
|
|
187
|
+
failures.append(f" FALSE-POSITIVE {rule.id}: {fx[:20]}… scored {bad.confidence}")
|
|
188
|
+
for fx in rule.fixtures.get("truncated", []):
|
|
189
|
+
if not fx:
|
|
190
|
+
continue
|
|
191
|
+
total += 1
|
|
192
|
+
found = engine.explain_truncated(fx)
|
|
193
|
+
hit = next((f for f in found if f.rule and f.rule.id == rule.id), None)
|
|
194
|
+
if hit:
|
|
195
|
+
passed += 1
|
|
196
|
+
else:
|
|
197
|
+
failures.append(f" TRUNC-MISS {rule.id}: {fx[:20]}…")
|
|
198
|
+
table.append((rule.provider, rule.id, bool(rule.checksum), bool(rule.verify)))
|
|
199
|
+
print(f"selftest: {passed}/{total} fixture checks passed ({len(table)} rules)")
|
|
200
|
+
if failures:
|
|
201
|
+
print("failures:")
|
|
202
|
+
print("\n".join(failures))
|
|
203
|
+
return 1
|
|
204
|
+
return 0
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
# ------------------------------------------------------------------- parser
|
|
208
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
209
|
+
p = argparse.ArgumentParser(prog="keyprint",
|
|
210
|
+
description="Offline attribution of API keys and secrets.")
|
|
211
|
+
p.add_argument("--version", action="version", version=f"keyprint {__version__}")
|
|
212
|
+
p.add_argument("--no-color", action="store_true",
|
|
213
|
+
help="disable colored output (also honors NO_COLOR; auto-off when piped)")
|
|
214
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
215
|
+
|
|
216
|
+
def common(sp):
|
|
217
|
+
sp.add_argument("--rules", action="append", default=[],
|
|
218
|
+
help="extra rule file or directory (layered over the bundled corpus)")
|
|
219
|
+
sp.add_argument("--format", choices=["text", "json", "sarif", "markdown"], default="text")
|
|
220
|
+
sp.add_argument("--show-secret", action="store_true",
|
|
221
|
+
help="print full secrets (default: redacted to last 4)")
|
|
222
|
+
|
|
223
|
+
ep = sub.add_parser("explain", help="attribute one key (offline)")
|
|
224
|
+
ep.add_argument("text", nargs="?", help="key or text containing a key; stdin if omitted")
|
|
225
|
+
ep.add_argument("--all", action="store_true", help="include placeholder findings")
|
|
226
|
+
common(ep)
|
|
227
|
+
ep.set_defaults(func=cmd_explain)
|
|
228
|
+
|
|
229
|
+
sp = sub.add_parser("scan", help="scan files/directories (offline)")
|
|
230
|
+
sp.add_argument("paths", nargs="+", help="files or directories; '-' for stdin")
|
|
231
|
+
sp.add_argument("--min-confidence", choices=["placeholder", "unknown", "possible", "likely", "certain"],
|
|
232
|
+
default="possible")
|
|
233
|
+
sp.add_argument("--all", action="store_true", help="report placeholder findings too")
|
|
234
|
+
sp.add_argument("--git-history", action="store_true", help="also scan full git history of the first path")
|
|
235
|
+
sp.add_argument("--fail-on-findings", action="store_true", help="exit 1 when findings above threshold exist (CI)")
|
|
236
|
+
common(sp)
|
|
237
|
+
sp.set_defaults(func=cmd_scan)
|
|
238
|
+
|
|
239
|
+
vp = sub.add_parser("verify", help="authorized liveness check (networked, gated)")
|
|
240
|
+
vp.add_argument("keys", nargs="+", help="KEY or provider:KEY items")
|
|
241
|
+
vp.add_argument("--provider", help="provider for keys given without a provider: prefix")
|
|
242
|
+
vp.add_argument("--basic", help="base64 user:pass for providers needing Basic auth (e.g. twilio)")
|
|
243
|
+
vp.add_argument("--authorized-owner", help="ownership attestation (your identity)")
|
|
244
|
+
vp.add_argument("--yes", action="store_true", help="skip confirmation prompt")
|
|
245
|
+
vp.add_argument("--i-know-this-is-bulk", action="store_true", help="allow >10 verifications per run")
|
|
246
|
+
vp.set_defaults(func=cmd_verify)
|
|
247
|
+
|
|
248
|
+
fp = sub.add_parser("fingerprint", help="model fingerprinting behind an endpoint")
|
|
249
|
+
fp.add_argument("--endpoint", help="OpenAI-compatible base URL")
|
|
250
|
+
fp.add_argument("--key", help="API key for the endpoint")
|
|
251
|
+
fp.add_argument("--model", default="", help="model id to request (if required by endpoint)")
|
|
252
|
+
fp.add_argument("--claims", default=None, help="model name the seller claims to serve")
|
|
253
|
+
fp.add_argument("--authorized-owner", help="ownership attestation")
|
|
254
|
+
fp.add_argument("--allow-network", action="store_true", help="execute live probes (default: plan only)")
|
|
255
|
+
fp.add_argument("--build-corpus", action="store_true", help="reference-corpus builder info")
|
|
256
|
+
fp.set_defaults(func=cmd_fingerprint)
|
|
257
|
+
|
|
258
|
+
rp = sub.add_parser("rules", help="inspect or export the rule corpus")
|
|
259
|
+
rsub = rp.add_subparsers(dest="rules_cmd", required=True)
|
|
260
|
+
lp = rsub.add_parser("list")
|
|
261
|
+
common(lp)
|
|
262
|
+
xp = rsub.add_parser("export")
|
|
263
|
+
xp.add_argument("--format", choices=["gitleaks", "trufflehog", "semgrep", "nuclei", "keyprint"], required=True)
|
|
264
|
+
xp.add_argument("--out", help="write to file instead of stdout")
|
|
265
|
+
xp.add_argument("--rules", action="append", default=[])
|
|
266
|
+
xp.set_defaults(func=cmd_rules, format="text")
|
|
267
|
+
rp.set_defaults(func=cmd_rules)
|
|
268
|
+
|
|
269
|
+
st = sub.add_parser("selftest", help="run built-in fixture checks against the engine")
|
|
270
|
+
common(st)
|
|
271
|
+
st.set_defaults(func=cmd_selftest)
|
|
272
|
+
return p
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def main(argv: list[str] | None = None) -> int:
|
|
276
|
+
args = build_parser().parse_args(argv)
|
|
277
|
+
style.enable_windows_ansi()
|
|
278
|
+
style.set_enabled(style.decide() and not getattr(args, "no_color", False))
|
|
279
|
+
return args.func(args)
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
if __name__ == "__main__":
|
|
283
|
+
sys.exit(main())
|
keyprint/context.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Context fusion and placeholder suppression.
|
|
2
|
+
|
|
3
|
+
Two jobs the regex layer cannot do:
|
|
4
|
+
|
|
5
|
+
1. Placeholder suppression. Documentation samples, ``YOUR_API_KEY``,
|
|
6
|
+
``xxxx…`` and fixture strings are the bulk of false positives in every
|
|
7
|
+
secret scanner. We classify them explicitly instead of reporting them.
|
|
8
|
+
2. Context boosting. A generic shape (``sk-`` + 48 alnum) is only a
|
|
9
|
+
weak signal until the surrounding line names the provider. Context is
|
|
10
|
+
the strongest disambiguator and feeds the scorer.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import math
|
|
16
|
+
import re
|
|
17
|
+
from collections import Counter
|
|
18
|
+
|
|
19
|
+
PLACEHOLDER_PATTERNS = [
|
|
20
|
+
r"(?i)your[_-]?(api[_-]?)?key",
|
|
21
|
+
r"(?i)<[a-z0-9_ -]{3,}>",
|
|
22
|
+
r"(?i)\{\{[^}]{2,}\}\}",
|
|
23
|
+
r"(?i)\$\{[^}]{2,}\}",
|
|
24
|
+
r"(?i)example",
|
|
25
|
+
r"(?i)dummy",
|
|
26
|
+
r"(?i)fake[_-]?key",
|
|
27
|
+
r"(?i)replace[_-]?(me|this|with)",
|
|
28
|
+
r"(?i)insert[_-]?(your|api)",
|
|
29
|
+
r"(?i)xxxxxxxx",
|
|
30
|
+
r"(?i)toke(n|n_here)$",
|
|
31
|
+
]
|
|
32
|
+
|
|
33
|
+
# Strings that are famous documentation samples, not real credentials.
|
|
34
|
+
KNOWN_EXAMPLES = {
|
|
35
|
+
"AKIAIOSFODNN7EXAMPLE",
|
|
36
|
+
"wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
|
|
37
|
+
"AIzaSyA-example-key-not-real-0123456789abcd",
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
_REPS = re.compile(r"(.)\1{6,}") # 7+ repetitions of one char
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def is_placeholder(token: str) -> bool:
|
|
44
|
+
if token in KNOWN_EXAMPLES:
|
|
45
|
+
return True
|
|
46
|
+
if len(set(token)) <= 4 and len(token) >= 12:
|
|
47
|
+
return True
|
|
48
|
+
if _REPS.search(token):
|
|
49
|
+
return True
|
|
50
|
+
if token.lower() in {"test", "none", "null", "undefined", "changeme"}:
|
|
51
|
+
return True
|
|
52
|
+
for p in PLACEHOLDER_PATTERNS:
|
|
53
|
+
if re.search(p, token):
|
|
54
|
+
return True
|
|
55
|
+
return False
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def shannon_entropy(s: str) -> float:
|
|
59
|
+
if not s:
|
|
60
|
+
return 0.0
|
|
61
|
+
counts = Counter(s)
|
|
62
|
+
n = len(s)
|
|
63
|
+
return -sum((c / n) * math.log2(c / n) for c in counts.values())
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def find_context(window: str, rule_contexts: tuple[str, ...]) -> list[str]:
|
|
67
|
+
"""Return the context tokens present in the text window (case-insensitive)."""
|
|
68
|
+
hits = []
|
|
69
|
+
low = window.lower()
|
|
70
|
+
for ctx in rule_contexts:
|
|
71
|
+
if ctx.lower() in low:
|
|
72
|
+
hits.append(ctx)
|
|
73
|
+
return hits
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def classify_charset(s: str) -> str:
|
|
77
|
+
classes = []
|
|
78
|
+
if re.search(r"[a-z]", s):
|
|
79
|
+
classes.append("lower")
|
|
80
|
+
if re.search(r"[A-Z]", s):
|
|
81
|
+
classes.append("upper")
|
|
82
|
+
if re.search(r"[0-9]", s):
|
|
83
|
+
classes.append("digits")
|
|
84
|
+
if re.search(r"[-_]", s):
|
|
85
|
+
classes.append("-_")
|
|
86
|
+
if re.search(r"[+/=]", s):
|
|
87
|
+
classes.append("base64")
|
|
88
|
+
if re.search(r"[^A-Za-z0-9_\-+/=.]", s):
|
|
89
|
+
classes.append("other")
|
|
90
|
+
return "+".join(classes) or "empty"
|