forgottenvaultkeys 0.2.0__tar.gz

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,105 @@
1
+ Metadata-Version: 2.4
2
+ Name: forgottenvaultkeys
3
+ Version: 0.2.0
4
+ Summary: Stopping & remediating Idiot-in-the-Middle (IitM) leaks before and after push
5
+ Author: DevSpecOps
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/DevSpecOps/forgottenvaultkeys
8
+ Project-URL: Repository, https://github.com/DevSpecOps/forgottenvaultkeys
9
+ Project-URL: Issues, https://github.com/DevSpecOps/forgottenvaultkeys/issues
10
+ Keywords: security,devsecops,secret-scanner,pre-commit,cryptography,remediation,sarif
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Security
18
+ Requires-Python: >=3.9
19
+ Description-Content-Type: text/markdown
20
+
21
+ # ForgottenVaultKeys (`fvk`)
22
+
23
+ > **Stopping & remediating Idiot-in-the-Middle before and after push.**
24
+
25
+ While tech headlines speculate about frontier AI models or planetary-scale quantum computers breaking RSA-2048 and lattice-based cryptography, **over 99% of real-world breaches still occur via the *Idiot-in-the-Middle (IitM)* attack vector**:
26
+ * `.env` files and cloud credentials accidentally pushed to public repositories;
27
+ * Weak hardcoded passwords (`password`, `qwerty`, `123456`) left in staging configs;
28
+ * `chmod 777` applied "temporarily" to fix a deployment blocker; <!-- fvk:ignore -->
29
+ * Redis, PostgreSQL, or Elasticsearch instances bound to `0.0.0.0` without authentication.
30
+
31
+ **ForgottenVaultKeys** is a zero-dependency CLI scanner, `pre-commit` guardrail, and **active remediation engine** that not only detects leaks in local files and pushed Git histories, but immediately patches code, exports 4-class CSPRNG replacement secrets outside Git, and generates history-purge scripts.
32
+
33
+ *(For a formal analysis of why asymptotic cryptographic breakthroughs rarely translate into practical threat models—and why operational hygiene dominates security economics—see [THEORY.md](THEORY.md).)*
34
+
35
+ ## Quick Start
36
+
37
+ ### Installation
38
+ ```bash
39
+ git clone https://github.com
40
+ cd ForgottenVaultKeys
41
+ pip install .
42
+ ```
43
+
44
+ ### Core Commands
45
+ ```bash
46
+ # 1. Scan current directory with sarcastic security engineer commentary
47
+ fvk . --roast
48
+
49
+ # 2. Scan both working tree AND full local Git commit history
50
+ fvk . --git-history --roast
51
+
52
+ # 3. Clone and audit an already-pushed remote repository URL
53
+ fvk --remote https://github.com --roast
54
+
55
+ # 4. Active Remediation: patch code, export 4-class CSPRNG secrets outside Git & generate purge script
56
+ fvk . --roast --remediate --secret-length 32
57
+ ```
58
+
59
+ ## Test Drive: Try It in 30 Seconds
60
+
61
+ Want to see `fvk` catch classic junior mistakes and auto-remediate them? Run this sandbox test in a temporary directory:
62
+
63
+ ```bash
64
+ mkdir /tmp/fvk-sandbox && cd /tmp/fvk-sandbox
65
+
66
+ # Create a vulnerable config with classic weak passwords
67
+ cat << 'EOF' > vulnerable_app.py
68
+ DB_PASSWORD = "password" <!-- fvk:ignore -->
69
+ ADMIN_PASS = "qwerty" <!-- fvk:ignore -->
70
+ BACKUP_PIN = "123456"
71
+ EOF
72
+
73
+ # Step 1: Detect the leaks
74
+ fvk . --roast
75
+
76
+ # Step 2: Run Active Remediation (patches file, hardens .gitignore, exports CSPRNG keys to ~/.fvk-vault/)
77
+ fvk . --roast --remediate
78
+
79
+ # Step 3: Inspect the patched code and your new external vault
80
+ cat vulnerable_app.py
81
+ cat ~/.fvk-vault/fvk-sandbox/rotated_secrets.env
82
+ ```
83
+
84
+ ### What `--remediate` Does Under the Hood
85
+ 1. **4-Class CSPRNG Secret Generation:** Generates high-entropy replacement secrets enforcing all 4 character classes (uppercase, lowercase, digits, special symbols) shuffled via `secrets.SystemRandom()` (Fisher-Yates).
86
+ 2. **Out-of-Band Vault Export:** Writes rotated credentials to `~/.fvk-vault/<project>/rotated_secrets.env` with strict `chmod 600` permissions—completely outside Git coverage.
87
+ 3. **Code & `.gitignore` Hardening:** Rewrites hardcoded Python assignments to `os.environ.get("...")` and appends `.env`, `*.pem`, and `*.key` to `.gitignore`.
88
+ 4. **History Purge Script:** Generates an executable `~/.fvk-vault/<project>/purge_git_history.sh` wrapper around `git-filter-repo` to scrub already-pushed commits.
89
+
90
+ ## Pre-Commit Integration
91
+
92
+ Add the following to your repository's `.pre-commit-config.yaml`:
93
+
94
+ ```yaml
95
+ repos:
96
+ - repo: https://github.com
97
+ rev: v0.2.0
98
+ hooks:
99
+ - id: forgotten-vault-keys
100
+ ```
101
+
102
+ Install the hook:
103
+ ```bash
104
+ pre-commit install
105
+ ```
@@ -0,0 +1,85 @@
1
+ # ForgottenVaultKeys (`fvk`)
2
+
3
+ > **Stopping & remediating Idiot-in-the-Middle before and after push.**
4
+
5
+ While tech headlines speculate about frontier AI models or planetary-scale quantum computers breaking RSA-2048 and lattice-based cryptography, **over 99% of real-world breaches still occur via the *Idiot-in-the-Middle (IitM)* attack vector**:
6
+ * `.env` files and cloud credentials accidentally pushed to public repositories;
7
+ * Weak hardcoded passwords (`password`, `qwerty`, `123456`) left in staging configs;
8
+ * `chmod 777` applied "temporarily" to fix a deployment blocker; <!-- fvk:ignore -->
9
+ * Redis, PostgreSQL, or Elasticsearch instances bound to `0.0.0.0` without authentication.
10
+
11
+ **ForgottenVaultKeys** is a zero-dependency CLI scanner, `pre-commit` guardrail, and **active remediation engine** that not only detects leaks in local files and pushed Git histories, but immediately patches code, exports 4-class CSPRNG replacement secrets outside Git, and generates history-purge scripts.
12
+
13
+ *(For a formal analysis of why asymptotic cryptographic breakthroughs rarely translate into practical threat models—and why operational hygiene dominates security economics—see [THEORY.md](THEORY.md).)*
14
+
15
+ ## Quick Start
16
+
17
+ ### Installation
18
+ ```bash
19
+ git clone https://github.com
20
+ cd ForgottenVaultKeys
21
+ pip install .
22
+ ```
23
+
24
+ ### Core Commands
25
+ ```bash
26
+ # 1. Scan current directory with sarcastic security engineer commentary
27
+ fvk . --roast
28
+
29
+ # 2. Scan both working tree AND full local Git commit history
30
+ fvk . --git-history --roast
31
+
32
+ # 3. Clone and audit an already-pushed remote repository URL
33
+ fvk --remote https://github.com --roast
34
+
35
+ # 4. Active Remediation: patch code, export 4-class CSPRNG secrets outside Git & generate purge script
36
+ fvk . --roast --remediate --secret-length 32
37
+ ```
38
+
39
+ ## Test Drive: Try It in 30 Seconds
40
+
41
+ Want to see `fvk` catch classic junior mistakes and auto-remediate them? Run this sandbox test in a temporary directory:
42
+
43
+ ```bash
44
+ mkdir /tmp/fvk-sandbox && cd /tmp/fvk-sandbox
45
+
46
+ # Create a vulnerable config with classic weak passwords
47
+ cat << 'EOF' > vulnerable_app.py
48
+ DB_PASSWORD = "password" <!-- fvk:ignore -->
49
+ ADMIN_PASS = "qwerty" <!-- fvk:ignore -->
50
+ BACKUP_PIN = "123456"
51
+ EOF
52
+
53
+ # Step 1: Detect the leaks
54
+ fvk . --roast
55
+
56
+ # Step 2: Run Active Remediation (patches file, hardens .gitignore, exports CSPRNG keys to ~/.fvk-vault/)
57
+ fvk . --roast --remediate
58
+
59
+ # Step 3: Inspect the patched code and your new external vault
60
+ cat vulnerable_app.py
61
+ cat ~/.fvk-vault/fvk-sandbox/rotated_secrets.env
62
+ ```
63
+
64
+ ### What `--remediate` Does Under the Hood
65
+ 1. **4-Class CSPRNG Secret Generation:** Generates high-entropy replacement secrets enforcing all 4 character classes (uppercase, lowercase, digits, special symbols) shuffled via `secrets.SystemRandom()` (Fisher-Yates).
66
+ 2. **Out-of-Band Vault Export:** Writes rotated credentials to `~/.fvk-vault/<project>/rotated_secrets.env` with strict `chmod 600` permissions—completely outside Git coverage.
67
+ 3. **Code & `.gitignore` Hardening:** Rewrites hardcoded Python assignments to `os.environ.get("...")` and appends `.env`, `*.pem`, and `*.key` to `.gitignore`.
68
+ 4. **History Purge Script:** Generates an executable `~/.fvk-vault/<project>/purge_git_history.sh` wrapper around `git-filter-repo` to scrub already-pushed commits.
69
+
70
+ ## Pre-Commit Integration
71
+
72
+ Add the following to your repository's `.pre-commit-config.yaml`:
73
+
74
+ ```yaml
75
+ repos:
76
+ - repo: https://github.com
77
+ rev: v0.2.0
78
+ hooks:
79
+ - id: forgotten-vault-keys
80
+ ```
81
+
82
+ Install the hook:
83
+ ```bash
84
+ pre-commit install
85
+ ```
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.4
2
+ Name: forgottenvaultkeys
3
+ Version: 0.2.0
4
+ Summary: Stopping & remediating Idiot-in-the-Middle (IitM) leaks before and after push
5
+ Author: DevSpecOps
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/DevSpecOps/forgottenvaultkeys
8
+ Project-URL: Repository, https://github.com/DevSpecOps/forgottenvaultkeys
9
+ Project-URL: Issues, https://github.com/DevSpecOps/forgottenvaultkeys/issues
10
+ Keywords: security,devsecops,secret-scanner,pre-commit,cryptography,remediation,sarif
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Security
18
+ Requires-Python: >=3.9
19
+ Description-Content-Type: text/markdown
20
+
21
+ # ForgottenVaultKeys (`fvk`)
22
+
23
+ > **Stopping & remediating Idiot-in-the-Middle before and after push.**
24
+
25
+ While tech headlines speculate about frontier AI models or planetary-scale quantum computers breaking RSA-2048 and lattice-based cryptography, **over 99% of real-world breaches still occur via the *Idiot-in-the-Middle (IitM)* attack vector**:
26
+ * `.env` files and cloud credentials accidentally pushed to public repositories;
27
+ * Weak hardcoded passwords (`password`, `qwerty`, `123456`) left in staging configs;
28
+ * `chmod 777` applied "temporarily" to fix a deployment blocker; <!-- fvk:ignore -->
29
+ * Redis, PostgreSQL, or Elasticsearch instances bound to `0.0.0.0` without authentication.
30
+
31
+ **ForgottenVaultKeys** is a zero-dependency CLI scanner, `pre-commit` guardrail, and **active remediation engine** that not only detects leaks in local files and pushed Git histories, but immediately patches code, exports 4-class CSPRNG replacement secrets outside Git, and generates history-purge scripts.
32
+
33
+ *(For a formal analysis of why asymptotic cryptographic breakthroughs rarely translate into practical threat models—and why operational hygiene dominates security economics—see [THEORY.md](THEORY.md).)*
34
+
35
+ ## Quick Start
36
+
37
+ ### Installation
38
+ ```bash
39
+ git clone https://github.com
40
+ cd ForgottenVaultKeys
41
+ pip install .
42
+ ```
43
+
44
+ ### Core Commands
45
+ ```bash
46
+ # 1. Scan current directory with sarcastic security engineer commentary
47
+ fvk . --roast
48
+
49
+ # 2. Scan both working tree AND full local Git commit history
50
+ fvk . --git-history --roast
51
+
52
+ # 3. Clone and audit an already-pushed remote repository URL
53
+ fvk --remote https://github.com --roast
54
+
55
+ # 4. Active Remediation: patch code, export 4-class CSPRNG secrets outside Git & generate purge script
56
+ fvk . --roast --remediate --secret-length 32
57
+ ```
58
+
59
+ ## Test Drive: Try It in 30 Seconds
60
+
61
+ Want to see `fvk` catch classic junior mistakes and auto-remediate them? Run this sandbox test in a temporary directory:
62
+
63
+ ```bash
64
+ mkdir /tmp/fvk-sandbox && cd /tmp/fvk-sandbox
65
+
66
+ # Create a vulnerable config with classic weak passwords
67
+ cat << 'EOF' > vulnerable_app.py
68
+ DB_PASSWORD = "password" <!-- fvk:ignore -->
69
+ ADMIN_PASS = "qwerty" <!-- fvk:ignore -->
70
+ BACKUP_PIN = "123456"
71
+ EOF
72
+
73
+ # Step 1: Detect the leaks
74
+ fvk . --roast
75
+
76
+ # Step 2: Run Active Remediation (patches file, hardens .gitignore, exports CSPRNG keys to ~/.fvk-vault/)
77
+ fvk . --roast --remediate
78
+
79
+ # Step 3: Inspect the patched code and your new external vault
80
+ cat vulnerable_app.py
81
+ cat ~/.fvk-vault/fvk-sandbox/rotated_secrets.env
82
+ ```
83
+
84
+ ### What `--remediate` Does Under the Hood
85
+ 1. **4-Class CSPRNG Secret Generation:** Generates high-entropy replacement secrets enforcing all 4 character classes (uppercase, lowercase, digits, special symbols) shuffled via `secrets.SystemRandom()` (Fisher-Yates).
86
+ 2. **Out-of-Band Vault Export:** Writes rotated credentials to `~/.fvk-vault/<project>/rotated_secrets.env` with strict `chmod 600` permissions—completely outside Git coverage.
87
+ 3. **Code & `.gitignore` Hardening:** Rewrites hardcoded Python assignments to `os.environ.get("...")` and appends `.env`, `*.pem`, and `*.key` to `.gitignore`.
88
+ 4. **History Purge Script:** Generates an executable `~/.fvk-vault/<project>/purge_git_history.sh` wrapper around `git-filter-repo` to scrub already-pushed commits.
89
+
90
+ ## Pre-Commit Integration
91
+
92
+ Add the following to your repository's `.pre-commit-config.yaml`:
93
+
94
+ ```yaml
95
+ repos:
96
+ - repo: https://github.com
97
+ rev: v0.2.0
98
+ hooks:
99
+ - id: forgotten-vault-keys
100
+ ```
101
+
102
+ Install the hook:
103
+ ```bash
104
+ pre-commit install
105
+ ```
@@ -0,0 +1,16 @@
1
+ README.md
2
+ pyproject.toml
3
+ forgottenvaultkeys.egg-info/PKG-INFO
4
+ forgottenvaultkeys.egg-info/SOURCES.txt
5
+ forgottenvaultkeys.egg-info/dependency_links.txt
6
+ forgottenvaultkeys.egg-info/entry_points.txt
7
+ forgottenvaultkeys.egg-info/top_level.txt
8
+ fvk/__init__.py
9
+ fvk/attestation.py
10
+ fvk/auditor.py
11
+ fvk/blast_radius.py
12
+ fvk/git_shield.py
13
+ fvk/ml_filter.py
14
+ fvk/runtime.py
15
+ fvk/scanner.py
16
+ tests/test_scanner.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ fvk = fvk.scanner:main
@@ -0,0 +1,52 @@
1
+ """
2
+ ForgottenVaultKeys (fvk) — Zero-dependency programmatic API & CLI for secret
3
+ detection, ML false-positive suppression, AST blast-radius analysis, runtime
4
+ secret injection, and cryptographic commit attestation.
5
+ """
6
+
7
+ from fvk.attestation import (
8
+ compute_merkle_root,
9
+ detect_semantic_drift,
10
+ generate_attestation,
11
+ verify_attestation,
12
+ )
13
+ from fvk.auditor import audit_local_machine, inspect_jwt
14
+ from fvk.blast_radius import analyze_blast_radius
15
+ from fvk.git_shield import build_commit_trailer, verify_head_commit
16
+ from fvk.ml_filter import is_likely_secret, markov_log_likelihood
17
+ from fvk.runtime import load_vault_env, run_with_vault
18
+ from fvk.scanner import (
19
+ apply_remediation,
20
+ export_sarif,
21
+ generate_strong_secret,
22
+ scan_directory,
23
+ scan_file,
24
+ scan_git_history,
25
+ shannon_entropy,
26
+ )
27
+
28
+ __version__ = "0.2.0"
29
+
30
+ __all__ = [
31
+ "__version__",
32
+ "analyze_blast_radius",
33
+ "apply_remediation",
34
+ "audit_local_machine",
35
+ "build_commit_trailer",
36
+ "compute_merkle_root",
37
+ "detect_semantic_drift",
38
+ "export_sarif",
39
+ "generate_attestation",
40
+ "generate_strong_secret",
41
+ "inspect_jwt",
42
+ "is_likely_secret",
43
+ "load_vault_env",
44
+ "markov_log_likelihood",
45
+ "run_with_vault",
46
+ "scan_directory",
47
+ "scan_file",
48
+ "scan_git_history",
49
+ "shannon_entropy",
50
+ "verify_attestation",
51
+ "verify_head_commit",
52
+ ]
@@ -0,0 +1,216 @@
1
+ """
2
+ Zero-Leak Cryptographic Attestation & Semantic Security Drift (`fvk attest` / `fvk drift`).
3
+ """
4
+
5
+ import ast
6
+ import hashlib
7
+ import hmac
8
+ import json
9
+ import os
10
+ import time
11
+ from pathlib import Path
12
+
13
+ from fvk.blast_radius import analyze_blast_radius
14
+ from fvk.scanner import IGNORED_DIRS, IGNORED_EXTS, scan_directory
15
+
16
+
17
+ class _SecurityPostureVisitor(ast.NodeVisitor):
18
+ """Detect weak cryptographic primitives and TLS verification bypasses in Python AST."""
19
+
20
+ def __init__(self) -> None:
21
+ self.weak_crypto_calls: list[str] = []
22
+ self.tls_bypass_calls: list[str] = []
23
+
24
+ def visit_Call(self, node: ast.Call) -> None:
25
+ if isinstance(node.func, ast.Attribute) and node.func.attr in {"md5", "sha1"}:
26
+ self.weak_crypto_calls.append(f"{node.func.attr}@line:{node.lineno}")
27
+
28
+ for kw in node.keywords:
29
+ if (
30
+ kw.arg == "verify"
31
+ and isinstance(kw.value, ast.Constant)
32
+ and kw.value.value is False
33
+ ):
34
+ self.tls_bypass_calls.append(f"verify=False@line:{node.lineno}")
35
+
36
+ self.generic_visit(node)
37
+
38
+
39
+ def compute_merkle_root(project_root: Path) -> tuple[str, int]:
40
+ """Compute a deterministic SHA-256 Merkle tree root over all scannable files."""
41
+ leaf_hashes: list[str] = []
42
+
43
+ if project_root.is_file():
44
+ files_to_hash = [project_root]
45
+ base_dir = project_root.parent
46
+ else:
47
+ files_to_hash = []
48
+ base_dir = project_root
49
+ for root, dirs, files in os.walk(project_root):
50
+ dirs[:] = sorted(d for d in dirs if d not in IGNORED_DIRS)
51
+ for fname in sorted(files):
52
+ fpath = Path(root) / fname
53
+ if fpath.suffix.lower() not in IGNORED_EXTS:
54
+ files_to_hash.append(fpath)
55
+
56
+ for fpath in sorted(files_to_hash, key=lambda p: p.relative_to(base_dir).as_posix()):
57
+ rel_posix = fpath.relative_to(base_dir).as_posix().encode("utf-8")
58
+ content_bytes = fpath.read_bytes()
59
+ leaf = hashlib.sha256(rel_posix + b"\x00" + content_bytes).hexdigest()
60
+ leaf_hashes.append(leaf)
61
+
62
+ if not leaf_hashes:
63
+ return hashlib.sha256(b"EMPTY_TREE").hexdigest(), 0
64
+
65
+ file_count = len(leaf_hashes)
66
+ level = leaf_hashes
67
+ while len(level) > 1:
68
+ next_level: list[str] = []
69
+ for i in range(0, len(level), 2):
70
+ left = level[i]
71
+ right = level[i + 1] if i + 1 < len(level) else left
72
+ combined = hashlib.sha256((left + right).encode("utf-8")).hexdigest()
73
+ next_level.append(combined)
74
+ level = next_level
75
+
76
+ return level[int(0)], file_count
77
+
78
+
79
+ def _extract_ast_posture(project_root: Path) -> dict:
80
+ """Summarize AST security invariants across all Python files."""
81
+ blast_items = analyze_blast_radius(project_root)
82
+ env_isolated = sum(1 for i in blast_items if i["source_kind"] == "env_lookup")
83
+ hardcoded = sum(1 for i in blast_items if i["source_kind"] == "hardcoded_literal")
84
+
85
+ weak_crypto: list[str] = []
86
+ tls_bypasses: list[str] = []
87
+
88
+ py_files = (
89
+ [project_root]
90
+ if project_root.is_file() and project_root.suffix == ".py"
91
+ else list(project_root.rglob("*.py"))
92
+ )
93
+ for py_file in py_files:
94
+ if any(part in IGNORED_DIRS for part in py_file.parts):
95
+ continue
96
+ try:
97
+ tree = ast.parse(py_file.read_text(encoding="utf-8", errors="ignore"))
98
+ except SyntaxError:
99
+ continue
100
+ visitor = _SecurityPostureVisitor()
101
+ visitor.visit(tree)
102
+ weak_crypto.extend(visitor.weak_crypto_calls)
103
+ tls_bypasses.extend(visitor.tls_bypass_calls)
104
+
105
+ return {
106
+ "env_isolated_secrets": env_isolated,
107
+ "hardcoded_secrets": hardcoded,
108
+ "weak_crypto_count": len(weak_crypto),
109
+ "tls_bypass_count": len(tls_bypasses),
110
+ }
111
+
112
+
113
+ def generate_attestation(
114
+ project_root: Path,
115
+ signing_key: str | None = None,
116
+ output_path: Path | None = None,
117
+ ) -> dict:
118
+ """Generate a Zero-Leak Cryptographic Hygiene Attestation JSON document."""
119
+ findings = scan_directory(project_root)
120
+ merkle_root, file_count = compute_merkle_root(project_root)
121
+ posture = _extract_ast_posture(project_root)
122
+
123
+ status = (
124
+ "PASS_ZERO_LEAK"
125
+ if len(findings) == 0
126
+ and posture["hardcoded_secrets"] == 0
127
+ and posture["tls_bypass_count"] == 0
128
+ else "FAIL_HYGIENE_VIOLATION"
129
+ )
130
+
131
+ payload = {
132
+ "schema": "fvk-attestation-v1",
133
+ "tool_version": "0.2.0",
134
+ "timestamp_utc": int(time.time()),
135
+ "project": project_root.resolve().name,
136
+ "status": status,
137
+ "merkle_root_sha256": merkle_root,
138
+ "files_hashed": file_count,
139
+ "findings_count": len(findings),
140
+ "ast_security_posture": posture,
141
+ }
142
+
143
+ canonical = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8")
144
+ if signing_key:
145
+ sig = hmac.new(signing_key.encode("utf-8"), canonical, hashlib.sha256).hexdigest()
146
+ payload["signature"] = {"algorithm": "HMAC-SHA256", "value": sig}
147
+ else:
148
+ payload["signature"] = {
149
+ "algorithm": "SHA256-UNKEYED-DIGEST",
150
+ "value": hashlib.sha256(canonical).hexdigest(),
151
+ }
152
+
153
+ if output_path:
154
+ output_path.write_text(json.dumps(payload, indent=2), encoding="utf-8")
155
+
156
+ return payload
157
+
158
+
159
+ def verify_attestation(
160
+ attestation: dict, project_root: Path, signing_key: str | None = None
161
+ ) -> tuple[bool, list[str]]:
162
+ """Verify cryptographic signature and current directory Merkle root."""
163
+ errors: list[str] = []
164
+ sig_block = attestation.get("signature", {})
165
+ payload_copy = {k: v for k, v in attestation.items() if k != "signature"}
166
+ canonical = json.dumps(payload_copy, sort_keys=True, separators=(",", ":")).encode("utf-8")
167
+
168
+ alg = sig_block.get("algorithm")
169
+ expected_sig = sig_block.get("value", "")
170
+
171
+ if alg == "HMAC-SHA256":
172
+ if not signing_key:
173
+ errors.append("Attestation requires an HMAC signing key for verification.")
174
+ else:
175
+ actual_sig = hmac.new(signing_key.encode("utf-8"), canonical, hashlib.sha256).hexdigest()
176
+ if not hmac.compare_digest(actual_sig, expected_sig):
177
+ errors.append("HMAC-SHA256 signature mismatch — attestation was tampered with!")
178
+ else:
179
+ actual_digest = hashlib.sha256(canonical).hexdigest()
180
+ if not hmac.compare_digest(actual_digest, expected_sig):
181
+ errors.append("SHA-256 digest mismatch — attestation payload was altered!")
182
+
183
+ current_root, _ = compute_merkle_root(project_root)
184
+ if current_root != attestation.get("merkle_root_sha256"):
185
+ errors.append("Merkle root mismatch — repository files have changed since attestation!")
186
+
187
+ if attestation.get("status") != "PASS_ZERO_LEAK":
188
+ errors.append(f"Attestation status is {attestation.get('status')} (not PASS_ZERO_LEAK).")
189
+
190
+ return len(errors) == 0, errors
191
+
192
+
193
+ def detect_semantic_drift(baseline_attestation: dict, candidate_attestation: dict) -> list[str]:
194
+ """Compare two attestations to detect silent security posture degradation."""
195
+ drifts: list[str] = []
196
+ base_p = baseline_attestation.get("ast_security_posture", {})
197
+ cand_p = candidate_attestation.get("ast_security_posture", {})
198
+
199
+ if cand_p.get("hardcoded_secrets", 0) > base_p.get("hardcoded_secrets", 0):
200
+ drifts.append(
201
+ f"DRIFT [CRITICAL]: Hardcoded secrets increased ({base_p.get('hardcoded_secrets')} -> {cand_p.get('hardcoded_secrets')})."
202
+ )
203
+ if cand_p.get("env_isolated_secrets", 0) < base_p.get("env_isolated_secrets", 0):
204
+ drifts.append(
205
+ f"DRIFT [HIGH]: Environment-isolated secrets dropped ({base_p.get('env_isolated_secrets')} -> {cand_p.get('env_isolated_secrets')})."
206
+ )
207
+ if cand_p.get("tls_bypass_count", 0) > base_p.get("tls_bypass_count", 0):
208
+ drifts.append(
209
+ f"DRIFT [CRITICAL]: TLS verification bypasses ('verify=False') introduced ({base_p.get('tls_bypass_count')} -> {cand_p.get('tls_bypass_count')})."
210
+ )
211
+ if cand_p.get("weak_crypto_count", 0) > base_p.get("weak_crypto_count", 0):
212
+ drifts.append(
213
+ f"DRIFT [MEDIUM]: Weak hash primitives (MD5/SHA1) increased ({base_p.get('weak_crypto_count')} -> {cand_p.get('weak_crypto_count')})."
214
+ )
215
+
216
+ return drifts
@@ -0,0 +1,89 @@
1
+ """
2
+ Offline Cryptographic Hygiene Auditor (`fvk audit`).
3
+ Inspects JWT tokens and local developer keystores (~/.ssh, ~/.aws) for staleness.
4
+ """
5
+
6
+ import base64
7
+ import json
8
+ import re
9
+ import time
10
+ from pathlib import Path
11
+
12
+ JWT_PATTERN = re.compile(r"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]*\b")
13
+
14
+
15
+ def _b64url_decode(segment: str) -> bytes:
16
+ padding = "=" * ((4 - len(segment) % 4) % 4)
17
+ return base64.urlsafe_b64decode(segment + padding)
18
+
19
+
20
+ def inspect_jwt(token: str) -> list[str]:
21
+ """Decode JWT header & payload offline and flag security/lifecycle issues."""
22
+ issues: list[str] = []
23
+ parts = token.split(".")
24
+ if len(parts) < 2:
25
+ return issues
26
+
27
+ try:
28
+ header = json.loads(_b64url_decode(parts[0]).decode("utf-8"))
29
+ payload = json.loads(_b64url_decode(parts[1]).decode("utf-8"))
30
+ except Exception:
31
+ return issues
32
+
33
+ alg = str(header.get("alg", "")).lower()
34
+ if alg == "none" or not alg:
35
+ issues.append("CRITICAL: JWT uses unsigned 'alg: none' — trivial signature forgery.")
36
+
37
+ now = int(time.time())
38
+ exp = payload.get("exp")
39
+ iat = payload.get("iat")
40
+
41
+ if exp is None:
42
+ issues.append("HIGH: JWT has no 'exp' claim — immortal token risk.")
43
+ elif isinstance(exp, (int, float)) and exp < now:
44
+ days_expired = int((now - exp) // 86400)
45
+ issues.append(f"INFO: Expired JWT left in codebase (expired {days_expired}d ago).")
46
+
47
+ if isinstance(iat, (int, float)) and (now - iat) > 90 * 86400:
48
+ age_days = int((now - iat) // 86400)
49
+ issues.append(f"WARN: Forgotten JWT issued {age_days} days ago (>90d rotation policy).")
50
+
51
+ return issues
52
+
53
+
54
+ def audit_local_machine(max_age_days: int = 90) -> list[dict]:
55
+ """Audit ~/.ssh and ~/.aws on the local workstation for stale, unrotated keys."""
56
+ findings: list[dict] = []
57
+ now = time.time()
58
+ max_age_sec = max_age_days * 86400
59
+
60
+ ssh_dir = Path.home() / ".ssh"
61
+ if ssh_dir.is_dir():
62
+ for key_file in ssh_dir.iterdir():
63
+ if (
64
+ not key_file.is_file()
65
+ or key_file.suffix == ".pub"
66
+ or key_file.name in {"config", "known_hosts", "authorized_keys"}
67
+ ):
68
+ continue
69
+ age_days = int((now - key_file.stat().st_mtime) // 86400)
70
+ if (now - key_file.stat().st_mtime) > max_age_sec:
71
+ findings.append(
72
+ {
73
+ "target": str(key_file),
74
+ "issue": f"Forgotten SSH private key unrotated for {age_days} days (threshold: {max_age_days}d).",
75
+ }
76
+ )
77
+
78
+ aws_creds = Path.home() / ".aws" / "credentials"
79
+ if aws_creds.is_file():
80
+ age_days = int((now - aws_creds.stat().st_mtime) // 86400)
81
+ if (now - aws_creds.stat().st_mtime) > max_age_sec:
82
+ findings.append(
83
+ {
84
+ "target": str(aws_creds),
85
+ "issue": f"Local AWS credentials untouched for {age_days} days — rotate IAM keys.",
86
+ }
87
+ )
88
+
89
+ return findings