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/engine.py ADDED
@@ -0,0 +1,390 @@
1
+ """The attribution engine.
2
+
3
+ Pipeline per text input:
4
+
5
+ prefix candidates -> per-rule full-pattern match -> checksum validation
6
+ -> context fusion -> placeholder suppression -> weighted scoring
7
+ -> evidence-annotated Finding (never a bare label).
8
+
9
+ Design notes:
10
+ - "certain" requires converging evidence; "possible" covers prefix-only
11
+ attribution (truncated keys), the workflow researchers actually have.
12
+ - Ambiguity is reported: when multiple providers claim the same shape the
13
+ winner carries an `ambiguous` penalty and every claimant is listed.
14
+ - Strings no rule claims but that look credential-shaped fall through to
15
+ an honest high-entropy "unknown" with classified alternatives.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import re
21
+ from dataclasses import dataclass, field
22
+
23
+ from . import checksum
24
+ from .context import classify_charset, find_context, is_placeholder, shannon_entropy
25
+ from .redact import redact_inline
26
+ from .ruleset import Rule
27
+ from .scoring import Evidence, Score, WEIGHTS, tier_for
28
+
29
+ # Distinctive prefix: long enough to name a provider on its own.
30
+ _DISTINCTIVE_PREFIX = 5
31
+
32
+ _TOKEN_RE = re.compile(r"[A-Za-z0-9_\-/+=.:@$&]{16,}")
33
+
34
+
35
+ @dataclass
36
+ class Finding:
37
+ token: str
38
+ rule: Rule | None
39
+ provider: str
40
+ title: str
41
+ confidence: str
42
+ score: Score
43
+ evidence: list[Evidence]
44
+ line_number: int
45
+ column: int
46
+ file: str = "<input>"
47
+ context_hits: list[str] = field(default_factory=list)
48
+ placeholder: bool = False
49
+ truncated: bool = False
50
+ alternatives: list[str] = field(default_factory=list)
51
+ claims: list[dict] = field(default_factory=list)
52
+
53
+ @property
54
+ def redacted(self) -> str:
55
+ return redact_inline(self.token)
56
+
57
+ @property
58
+ def display(self) -> str:
59
+ label = self.title
60
+ conf = self.confidence + (" [placeholder]" if self.placeholder else "")
61
+ return f"{self.redacted} {label} ({conf})"
62
+
63
+ def capabilities(self) -> tuple[str, ...]:
64
+ return self.rule.capabilities if self.rule else ()
65
+
66
+ def revoke_url(self) -> str | None:
67
+ return self.rule.revoke_url if self.rule else None
68
+
69
+ def docs_url(self) -> str | None:
70
+ return self.rule.docs_url if self.rule else None
71
+
72
+ def verify_key(self) -> str | None:
73
+ return self.rule.verify if self.rule else None
74
+
75
+ def financial_exposure(self) -> str | None:
76
+ return self.rule.financial_exposure if self.rule else None
77
+
78
+ def to_dict(self, redact_secret: bool = True) -> dict:
79
+ out = {
80
+ "file": self.file,
81
+ "line": self.line_number,
82
+ "column": self.column,
83
+ "provider": self.provider,
84
+ "rule": self.rule.id if self.rule else None,
85
+ "title": self.title,
86
+ "confidence": self.confidence,
87
+ "score": self.score.value,
88
+ "evidence": [e.render() for e in self.evidence],
89
+ "context": self.context_hits,
90
+ "placeholder": self.placeholder,
91
+ "truncated": self.truncated,
92
+ "capabilities": list(self.capabilities()),
93
+ "revoke_url": self.revoke_url(),
94
+ "docs_url": self.docs_url(),
95
+ "verify_supported": self.verify_key(),
96
+ "financial_exposure": self.financial_exposure(),
97
+ "secret": None if redact_secret else self.token,
98
+ "secret_redacted": self.redacted,
99
+ }
100
+ if self.alternatives:
101
+ out["alternatives"] = self.alternatives
102
+ return out
103
+
104
+
105
+ class Engine:
106
+ def __init__(self, rules: list[Rule]):
107
+ self.rules = rules
108
+ self._by_id = {r.id: r for r in rules}
109
+ self._prefix_index: dict[str, list[Rule]] = {}
110
+ for r in rules:
111
+ for p in r.prefixes:
112
+ self._prefix_index.setdefault(p, []).append(r)
113
+ # longest prefixes first for truncated attribution
114
+ self._prefixes = sorted(self._prefix_index, key=len, reverse=True)
115
+ self._prefix_alt = re.compile("|".join(re.escape(p) for p in self._prefixes)) if self._prefixes else None
116
+
117
+ # ------------------------------------------------------------------
118
+ # full-fidelity matching on a block of text
119
+ # ------------------------------------------------------------------
120
+ def scan_text(self, text: str, file: str = "<input>", context_window: int = 2) -> list[Finding]:
121
+ findings: list[Finding] = []
122
+ lines = text.splitlines()
123
+
124
+ for i, line in enumerate(lines):
125
+ window = "\n".join(lines[max(0, i - context_window): i + context_window + 1])
126
+ claimed_spans: list[tuple[int, int]] = []
127
+ for rule in self.rules:
128
+ for m in rule.compiled.finditer(line):
129
+ token = m.group(0)
130
+ start = m.start()
131
+ if any(s <= start and start < e for s, e in claimed_spans):
132
+ continue
133
+ if rule.requires_context and not any(
134
+ c.lower() in window.lower() for c in rule.requires_context):
135
+ continue # shape fits but no naming context: not reportable
136
+ findings.append(
137
+ self._score_match(rule, token, line, window, i + 1, start + 1, file, truncated=False)
138
+ )
139
+ claimed_spans.append((start, start + len(token)))
140
+
141
+ findings.extend(self._entropy_fallback(lines, claimed_spans, file))
142
+ return self._dedupe(findings)
143
+
144
+ def _score_match(
145
+ self, rule: Rule, token: str, line: str, window: str,
146
+ line_number: int, column: int, file: str, truncated: bool,
147
+ ) -> Finding:
148
+ evidence: list[Evidence] = []
149
+ value = 0
150
+ placeholder = is_placeholder(token)
151
+ context_hits = find_context(window, rule.context)
152
+
153
+ best_prefix = max((p for p in rule.prefixes if token.startswith(p)), key=len, default=None)
154
+
155
+ checksum_ok = False
156
+ if rule.checksum:
157
+ checksum_ok = self._validate_checksum(rule.checksum, token) and not placeholder
158
+
159
+ # a checksum-bearing format validates the prefix as much as the prefix
160
+ # validates the checksum: either one makes the format distinctive
161
+ distinctive = (best_prefix is not None and
162
+ (len(best_prefix) >= _DISTINCTIVE_PREFIX
163
+ or getattr(rule, "distinctive", False)
164
+ or checksum_ok))
165
+ if best_prefix and distinctive:
166
+ value += WEIGHTS["distinctive_prefix"]
167
+ evidence.append(Evidence("prefix", WEIGHTS["distinctive_prefix"], best_prefix))
168
+ elif best_prefix:
169
+ value += WEIGHTS["generic_prefix"]
170
+ evidence.append(Evidence("prefix", WEIGHTS["generic_prefix"], f"{best_prefix} (short, collision-prone)"))
171
+
172
+ value += WEIGHTS["structure_match"]
173
+ evidence.append(Evidence("structure", WEIGHTS["structure_match"],
174
+ f"length {len(token)}{f', charset {classify_charset(token)}' if not truncated else ''}"))
175
+
176
+ if rule.checksum:
177
+ if checksum_ok:
178
+ value += WEIGHTS["checksum_valid"]
179
+ evidence.append(Evidence("checksum", WEIGHTS["checksum_valid"], f"{rule.checksum} valid"))
180
+ elif placeholder and self._validate_checksum(rule.checksum, token):
181
+ evidence.append(Evidence("checksum", 0, f"{rule.checksum} valid (but placeholder shape)"))
182
+ else:
183
+ value += WEIGHTS["checksum_failed"]
184
+ evidence.append(Evidence("checksum", WEIGHTS["checksum_failed"], f"{rule.checksum} invalid"))
185
+
186
+ if context_hits:
187
+ value += WEIGHTS["context_boost"]
188
+ evidence.append(Evidence("context", WEIGHTS["context_boost"], ", ".join(context_hits[:3])))
189
+ if rule.requires_context and any(c.lower() in window.lower() for c in rule.requires_context):
190
+ value += WEIGHTS["required_context"]
191
+ evidence.append(Evidence("required-context", WEIGHTS["required_context"], ""))
192
+
193
+ if placeholder:
194
+ evidence.append(Evidence("placeholder", 0, "documentation/dummy shape"))
195
+ return Finding(
196
+ token=token, rule=rule, provider=rule.provider, title=rule.title,
197
+ confidence="placeholder", score=Score("placeholder", value, evidence),
198
+ evidence=evidence, line_number=line_number, column=column, file=file,
199
+ context_hits=context_hits, placeholder=True, truncated=truncated,
200
+ )
201
+
202
+ tier = "possible" if truncated else tier_for(max(value, 0))
203
+ return Finding(
204
+ token=token, rule=rule, provider=rule.provider, title=rule.title,
205
+ confidence=tier, score=Score(tier, value, evidence),
206
+ evidence=evidence, line_number=line_number, column=column, file=file,
207
+ context_hits=context_hits, truncated=truncated,
208
+ )
209
+
210
+ def _validate_checksum(self, kind: str, token: str) -> bool:
211
+ if kind == "github":
212
+ prefix, _, payload = token.partition("_")
213
+ return checksum.validate_github_token(payload)
214
+ if kind == "discord":
215
+ return checksum.validate_discord_token(token)
216
+ if kind == "jwt":
217
+ return checksum.validate_jwt(token)
218
+ if kind == "luhn":
219
+ return checksum.validate_luhn(token)
220
+ return False
221
+
222
+ # ------------------------------------------------------------------
223
+ # high-entropy fallback for strings no rule claims
224
+ # ------------------------------------------------------------------
225
+ def _entropy_fallback(self, lines: list[str], claimed: list[tuple[int, int]], file: str) -> list[Finding]:
226
+ def overlaps(start: int, end: int) -> bool:
227
+ return any(not (end <= s or start >= e) for s, e in claimed)
228
+
229
+ out = []
230
+ for i, line in enumerate(lines):
231
+ for m in _TOKEN_RE.finditer(line):
232
+ start = m.start()
233
+ if overlaps(start, start + len(m.group(0))):
234
+ continue
235
+ token = m.group(0)
236
+ if is_placeholder(token) or len(token) < 20:
237
+ continue
238
+ if shannon_entropy(token) < 3.0:
239
+ continue
240
+ evidence = [
241
+ Evidence("no-rule", 0, "no provider rule claims this shape"),
242
+ Evidence("entropy", 0, f"{shannon_entropy(token):.2f} bits/char, charset {classify_charset(token)}"),
243
+ ]
244
+ alts = self._suggest_alternatives(token)
245
+ out.append(Finding(
246
+ token=token, rule=None, provider="unknown", title=f"unknown credential-shaped string ({len(token)} chars)",
247
+ confidence="unknown", score=Score("unknown", 0, evidence),
248
+ evidence=evidence, line_number=i + 1, column=start + 1, file=file,
249
+ alternatives=alts,
250
+ ))
251
+ return out
252
+
253
+ def _suggest_alternatives(self, token: str) -> list[str]:
254
+ alts = []
255
+ n = len(token)
256
+ for r in self.rules:
257
+ if not r.requires_context:
258
+ continue
259
+ if r.min_length and r.max_length and r.min_length <= n <= r.max_length:
260
+ # only plausible if the shape itself fits (prefix/charset),
261
+ # not merely the length
262
+ if r.compiled.search(token):
263
+ alts.append(f"{r.provider} ({r.id}, requires context: {', '.join(r.requires_context[:2])})")
264
+ if not alts:
265
+ alts.append("no known format fits - vendor-specific or opaque token")
266
+ return alts[:4]
267
+
268
+ # ------------------------------------------------------------------
269
+ # truncated attribution: prefix + partial shape, no full match
270
+ # ------------------------------------------------------------------
271
+ def explain_truncated(self, text: str) -> list[Finding]:
272
+ """Identify partial/truncated keys from prefix and visible shape."""
273
+ findings: list[Finding] = []
274
+ stripped = text.strip().strip("'\"`")
275
+ if self._prefix_alt:
276
+ for m in self._prefix_alt.finditer(stripped):
277
+ prefix = m.group(0)
278
+ rest = stripped[m.start():].strip()
279
+ for rule in self._prefix_index.get(prefix, []):
280
+ full = rule.compiled.fullmatch(rest)
281
+ if full:
282
+ continue # fully matched; scan path handles it
283
+ # shape check on what is visible: charset must be plausible
284
+ visible = rest[len(prefix):].rstrip(".…")
285
+ ok_chars = all(ch.isalnum() or ch in "-_+/=$." for ch in visible)
286
+ if not ok_chars and visible:
287
+ continue
288
+ # length plausibility: visible portion cannot exceed max
289
+ if rule.max_length and len(rest) > rule.max_length:
290
+ continue
291
+ evidence = [
292
+ Evidence("prefix", 15, f"{prefix} (truncated attribution)"),
293
+ Evidence("visible-shape", 0, f"{len(visible)} chars visible, charset plausible"),
294
+ ]
295
+ context_hits = find_context(stripped, rule.context)
296
+ if context_hits:
297
+ evidence.append(Evidence("context", WEIGHTS["context_boost"], ", ".join(context_hits[:3])))
298
+ tier = "likely" if (context_hits and len(prefix) >= 10) else "possible"
299
+ findings.append(Finding(
300
+ token=rest, rule=rule, provider=rule.provider, title=rule.title,
301
+ confidence=tier, score=Score(tier, 0, evidence),
302
+ evidence=evidence, line_number=1, column=m.start() + 1,
303
+ context_hits=context_hits, truncated=True,
304
+ ))
305
+ # partial-structure specials: JWT and Discord tokens are attributable
306
+ # from their decodable first segment alone.
307
+ if stripped.startswith("eyJ"):
308
+ first_seg = stripped.split(".")[0]
309
+ try:
310
+ import base64 as _b64
311
+ import json as _json
312
+ pad = first_seg + "=" * (-len(first_seg) % 4)
313
+ hdr = _json.loads(_b64.urlsafe_b64decode(pad))
314
+ if isinstance(hdr, dict) and isinstance(hdr.get("alg"), str):
315
+ rule = self._by_id.get("jwt-oidc-token")
316
+ if rule:
317
+ evidence = [Evidence("partial-jwt", 20, f"decodable header, alg={hdr['alg']}")]
318
+ findings.append(Finding(
319
+ token=stripped, rule=rule, provider=rule.provider, title=rule.title,
320
+ confidence="possible", score=Score("possible", 0, evidence),
321
+ evidence=evidence, line_number=1, column=1, truncated=True,
322
+ ))
323
+ except Exception:
324
+ pass
325
+ if 1 <= stripped.count(".") <= 2 and " " not in stripped:
326
+ try:
327
+ import base64 as _b64
328
+ first_seg = stripped.split(".")[0]
329
+ if len(first_seg) >= 10 and all(ch.isalnum() or ch in "-_" for ch in first_seg):
330
+ pad = first_seg + "=" * (-len(first_seg) % 4)
331
+ decoded = _b64.urlsafe_b64decode(pad)
332
+ if all(48 <= b <= 57 for b in decoded): # ASCII-digit id (Discord's actual encoding)
333
+ user_id = int(decoded)
334
+ else:
335
+ user_id = int.from_bytes(decoded, "big")
336
+ ts = (user_id >> 22) + checksum.DISCORD_EPOCH_MS
337
+ if ts >= checksum.DISCORD_EPOCH_MS:
338
+ rule = self._by_id.get("discord-bot-token")
339
+ if rule:
340
+ evidence = [Evidence("partial-discord", 20, "decodable snowflake segment")]
341
+ findings.append(Finding(
342
+ token=stripped, rule=rule, provider=rule.provider, title=rule.title,
343
+ confidence="possible", score=Score("possible", 0, evidence),
344
+ evidence=evidence, line_number=1, column=1, truncated=True,
345
+ ))
346
+ except Exception:
347
+ pass
348
+ return self._dedupe(findings)
349
+
350
+ # ------------------------------------------------------------------
351
+ def _dedupe(self, findings: list[Finding]) -> list[Finding]:
352
+ seen: dict[tuple, Finding] = {}
353
+ for f in findings:
354
+ key = (f.file, f.line_number, f.column, f.rule.id if f.rule else "unknown")
355
+ if key not in seen or _rank(f) > _rank(seen[key]):
356
+ seen[key] = f
357
+ ordered = list(seen.values())
358
+
359
+ # ambiguity pass: same span claimed by multiple rules
360
+ by_span: dict[tuple, list[Finding]] = {}
361
+ for f in ordered:
362
+ by_span.setdefault((f.file, f.line_number, f.token), []).append(f)
363
+ for group in by_span.values():
364
+ if len(group) < 2:
365
+ continue
366
+ group.sort(key=_rank, reverse=True)
367
+ winner = group[0]
368
+ others = [g for g in group[1:] if g.confidence != "placeholder"]
369
+ if others:
370
+ winner.alternatives = [f"{g.provider} ({g.rule.id})" for g in others]
371
+ winner.claims = [{"provider": g.provider, "rule": g.rule.id, "score": g.score.value} for g in group]
372
+ evidence = Evidence("ambiguous", WEIGHTS["ambiguous"],
373
+ "also claimed by: " + ", ".join(winner.alternatives))
374
+ winner.score = Score(winner.score.tier, winner.score.value + WEIGHTS["ambiguous"],
375
+ winner.score.evidence + [evidence])
376
+ winner.evidence = winner.score.evidence
377
+ # re-tier after penalty
378
+ if not winner.truncated:
379
+ winner.confidence = tier_for(max(winner.score.value, 0))
380
+ winner.score.tier = winner.confidence
381
+ return ordered
382
+
383
+
384
+ def _rank(f: Finding) -> int:
385
+ return f.score.value
386
+
387
+
388
+ def default_engine() -> Engine:
389
+ from .ruleset import load_rules
390
+ return Engine(load_rules())
keyprint/export.py ADDED
@@ -0,0 +1,80 @@
1
+ """Rule export to scanners people already run.
2
+
3
+ keyprint as upstream: one rule corpus, four export formats. Every export
4
+ carries provenance in its description field so downstream users know the
5
+ rules came from (and can update from) keyprint.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import json
11
+ import re
12
+
13
+
14
+ def _clean(pattern: str) -> str:
15
+ # gitleaks wants an anchor-free pattern that matches the secret substring;
16
+ # our patterns are already substring-friendly (they do not use ^ $).
17
+ return pattern
18
+
19
+
20
+ def export_rules(rules, fmt: str) -> str:
21
+ if fmt == "keyprint":
22
+ return json.dumps({"schema_version": 1,
23
+ "rules": [r.to_dict() for r in rules]}, indent=2)
24
+ if fmt == "gitleaks":
25
+ out = [{"id": r.id,
26
+ "description": f"{r.title} (keyprint:{r.id})",
27
+ "regex": _clean(r.pattern),
28
+ "keywords": list(r.prefixes),
29
+ "tags": [r.provider, r.category, "keyprint"]}
30
+ for r in rules]
31
+ return json.dumps(out, indent=2)
32
+ if fmt == "trufflehog":
33
+ out = []
34
+ for r in rules:
35
+ if not r.verify:
36
+ continue
37
+ out.append({"name": f"keyprint-{r.id}",
38
+ "verification_endpoint": r.verify,
39
+ "regex": {"pattern": _clean(r.pattern)},
40
+ "keywords": list(r.prefixes),
41
+ "note": "verification handled by keyprint specs"})
42
+ return json.dumps(out, indent=2)
43
+ if fmt == "semgrep":
44
+ rules_out = []
45
+ for r in rules:
46
+ if not r.prefixes:
47
+ continue
48
+ prefix = re.escape(r.prefixes[0])
49
+ rules_out.append({
50
+ "id": f"keyprint.{r.id}",
51
+ "patterns": [{"pattern-regex": _clean(r.pattern)}],
52
+ "message": f"{r.title} - potential {r.provider} secret",
53
+ "languages": ["generic"],
54
+ "severity": "ERROR",
55
+ "metadata": {"provider": r.provider, "source": "keyprint"},
56
+ })
57
+ return json.dumps({"rules": rules_out}, indent=2)
58
+ if fmt == "nuclei":
59
+ tmpl = []
60
+ for r in rules:
61
+ if not r.prefixes:
62
+ continue
63
+ tmpl.append(f"""id: {r.id}
64
+ info:
65
+ name: {r.title}
66
+ author: keyprint
67
+ severity: high
68
+ tags: keyprint,{r.provider}
69
+ metadata:
70
+ provenance: keyprint-rules
71
+ file:
72
+ extensions:
73
+ - all
74
+ extractors:
75
+ - type: regex
76
+ name: {r.id}
77
+ regex:
78
+ - "{_clean(r.pattern)}" """)
79
+ return "\n---\n".join(tmpl)
80
+ raise ValueError(f"unknown export format: {fmt}")