cbomly 0.2.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.
- cbomly/__init__.py +3 -0
- cbomly/__main__.py +5 -0
- cbomly/algorithms.py +218 -0
- cbomly/cbom.py +216 -0
- cbomly/cbom_names.py +35 -0
- cbomly/cli.py +191 -0
- cbomly/detect/__init__.py +1 -0
- cbomly/detect/deps.py +81 -0
- cbomly/detect/keys.py +319 -0
- cbomly/detect/services.py +69 -0
- cbomly/detect/source.py +358 -0
- cbomly/findings.py +29 -0
- cbomly/inventory.py +150 -0
- cbomly/packs/au.toml +45 -0
- cbomly/packs/baseline.toml +110 -0
- cbomly/packs/ca.toml +61 -0
- cbomly/packs/eu.toml +117 -0
- cbomly/packs/india.toml +102 -0
- cbomly/packs/jp.toml +44 -0
- cbomly/packs/pci-dss.toml +55 -0
- cbomly/packs/sg.toml +45 -0
- cbomly/packs/uk.toml +47 -0
- cbomly/packs/us-cnsa2.toml +97 -0
- cbomly/packs/us-fda.toml +63 -0
- cbomly/packs/us.toml +145 -0
- cbomly/report.py +188 -0
- cbomly/rules.py +235 -0
- cbomly/sbom.py +54 -0
- cbomly/scanner.py +77 -0
- cbomly/upload.py +96 -0
- cbomly-0.2.0.dist-info/METADATA +202 -0
- cbomly-0.2.0.dist-info/RECORD +37 -0
- cbomly-0.2.0.dist-info/WHEEL +5 -0
- cbomly-0.2.0.dist-info/entry_points.txt +2 -0
- cbomly-0.2.0.dist-info/licenses/LICENSE +202 -0
- cbomly-0.2.0.dist-info/licenses/NOTICE +4 -0
- cbomly-0.2.0.dist-info/top_level.txt +1 -0
cbomly/cli.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
"""Command-line interface: `cbomly scan`, `cbomly upload`, `cbomly rules`, `cbomly doctor`."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import sys
|
|
9
|
+
from datetime import UTC, datetime
|
|
10
|
+
from pathlib import Path
|
|
11
|
+
|
|
12
|
+
from . import __version__, algorithms, cbom, inventory, report, rules, sbom, scanner
|
|
13
|
+
from .detect import deps
|
|
14
|
+
from .rules import SEVERITIES
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _parser() -> argparse.ArgumentParser:
|
|
18
|
+
p = argparse.ArgumentParser(prog="cbomly", description="Find the cryptography in your software and check it is quantum-safe.")
|
|
19
|
+
p.add_argument("--version", action="version", version=f"cbomly {__version__}")
|
|
20
|
+
sub = p.add_subparsers(dest="cmd", required=True)
|
|
21
|
+
|
|
22
|
+
s = sub.add_parser("scan", help="scan a folder and write a CBOM plus a readable report")
|
|
23
|
+
s.add_argument("path", nargs="?", default=".", help="folder (or file) to scan; default: current folder")
|
|
24
|
+
s.add_argument("-r", "--rules", default="baseline", help="rule pack(s), comma-separated, e.g. india (default: baseline)")
|
|
25
|
+
s.add_argument("--rules-dir", action="append", default=[], help="extra folder of .toml rule packs")
|
|
26
|
+
s.add_argument("-o", "--out", default="cbomly-out", help="output folder (default: ./cbomly-out)")
|
|
27
|
+
s.add_argument("--name", help="product name to put in the reports (default: folder name)")
|
|
28
|
+
s.add_argument("--no-sbom", action="store_true", help="skip the Syft software list; crypto only")
|
|
29
|
+
s.add_argument("--syft", help="path to the syft binary (default: from PATH or $CBOMLY_SYFT)")
|
|
30
|
+
s.add_argument("--exclude", action="append", default=[], help="extra file/folder name pattern to skip (repeatable)")
|
|
31
|
+
s.add_argument("--include-vendored", action="store_true", help="also scan node_modules, vendor, venv and build folders")
|
|
32
|
+
s.add_argument("--fail-on", choices=SEVERITIES[:-1], help="exit with code 1 if any issue is this severe or worse (for CI)")
|
|
33
|
+
s.add_argument("-q", "--quiet", action="store_true", help="print nothing except errors")
|
|
34
|
+
s.add_argument("--no-color", action="store_true")
|
|
35
|
+
|
|
36
|
+
r = sub.add_parser("rules", help="list or show rule packs")
|
|
37
|
+
r.add_argument("pack", nargs="?", help="show the rules in this pack")
|
|
38
|
+
r.add_argument("--rules-dir", action="append", default=[])
|
|
39
|
+
|
|
40
|
+
u = sub.add_parser("upload", help="send scan results (findings only, never source code) to your cbomly.com dashboard")
|
|
41
|
+
u.add_argument("out", nargs="?", default="cbomly-out", help="folder written by `cbomly scan` (default: ./cbomly-out)")
|
|
42
|
+
u.add_argument("--key", help="project API key (default: $CBOMLY_API_KEY)")
|
|
43
|
+
u.add_argument("--url", help="dashboard address (default: $CBOMLY_URL or https://app.cbomly.com)")
|
|
44
|
+
u.add_argument("--gate", action="store_true",
|
|
45
|
+
help="exit with code 1 if your project's release gate fails (e.g. new RSA or ECC was added)")
|
|
46
|
+
u.add_argument("--dry-run", action="store_true", help="print exactly what would be sent, and send nothing")
|
|
47
|
+
|
|
48
|
+
sub.add_parser("doctor", help="check that helper tools are installed")
|
|
49
|
+
return p
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def cmd_scan(a) -> int:
|
|
53
|
+
target = Path(a.path)
|
|
54
|
+
if not target.exists():
|
|
55
|
+
print(f"cbomly: {a.path}: no such file or folder", file=sys.stderr)
|
|
56
|
+
return 2
|
|
57
|
+
name = a.name or target.resolve().name
|
|
58
|
+
try:
|
|
59
|
+
packs = rules.resolve([x.strip() for x in a.rules.split(",") if x.strip()], a.rules_dir)
|
|
60
|
+
except ValueError as e:
|
|
61
|
+
print(f"cbomly: {e}", file=sys.stderr)
|
|
62
|
+
return 2
|
|
63
|
+
log = (lambda *m: None) if a.quiet else (lambda *m: print(*m, file=sys.stderr))
|
|
64
|
+
notes: list[str] = []
|
|
65
|
+
|
|
66
|
+
base = [".git", ".hg", ".svn", "cbomly-out"] if a.include_vendored else list(scanner.DEFAULT_EXCLUDES)
|
|
67
|
+
excludes = base + a.exclude + [Path(a.out).name]
|
|
68
|
+
|
|
69
|
+
log(f"Scanning {target} for cryptography…")
|
|
70
|
+
findings, stats = scanner.scan_path(target, excludes)
|
|
71
|
+
log(f" {stats.files_scanned} files read, {len(findings)} crypto uses found")
|
|
72
|
+
|
|
73
|
+
sb = None
|
|
74
|
+
tool_versions = {}
|
|
75
|
+
if not a.no_sbom:
|
|
76
|
+
syft = sbom.find_syft(a.syft)
|
|
77
|
+
if not syft:
|
|
78
|
+
log(sbom.INSTALL_HINT)
|
|
79
|
+
notes.append("Syft was not installed, so no software list (SBOM) was produced.")
|
|
80
|
+
else:
|
|
81
|
+
log("Building the software list with Syft…")
|
|
82
|
+
try:
|
|
83
|
+
sb = sbom.generate(str(target), syft)
|
|
84
|
+
v = sbom.syft_version(syft)
|
|
85
|
+
if v:
|
|
86
|
+
tool_versions["syft"] = v
|
|
87
|
+
except sbom.SyftError as e:
|
|
88
|
+
log(f" Syft failed: {e}")
|
|
89
|
+
notes.append(f"Syft failed, so no software list (SBOM) was produced: {str(e)[:200]}")
|
|
90
|
+
|
|
91
|
+
libs = deps.crypto_libraries(sb)
|
|
92
|
+
ev = rules.evaluate(packs, findings, sb)
|
|
93
|
+
bom = cbom.build(findings, sb, name, libs, tool_versions, stats.services)
|
|
94
|
+
n_sw = len(sb.get("components", [])) if sb else None
|
|
95
|
+
|
|
96
|
+
out = Path(a.out)
|
|
97
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
98
|
+
(out / "cbom.cdx.json").write_text(json.dumps(bom, indent=2) + "\n")
|
|
99
|
+
(out / "summary.md").write_text(report.markdown(name, findings, ev, libs, n_sw, notes, stats.services))
|
|
100
|
+
(out / "findings.json").write_text(json.dumps(results_doc(name, findings, ev, libs, n_sw, stats), indent=2) + "\n")
|
|
101
|
+
|
|
102
|
+
if not a.quiet:
|
|
103
|
+
color = sys.stdout.isatty() and not a.no_color and not os.environ.get("NO_COLOR")
|
|
104
|
+
print(report.terminal(findings, ev, str(out), color))
|
|
105
|
+
|
|
106
|
+
if a.fail_on:
|
|
107
|
+
worst = ev.worst_severity()
|
|
108
|
+
if worst and SEVERITIES.index(worst) <= SEVERITIES.index(a.fail_on):
|
|
109
|
+
return 1
|
|
110
|
+
return 0
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def results_doc(name, findings, ev, libs, n_sw, stats) -> dict:
|
|
114
|
+
"""findings.json: everything the reports need, so `cbomly upload` never has to re-scan."""
|
|
115
|
+
def fd(f):
|
|
116
|
+
alg = algorithms.get(f.algorithm)
|
|
117
|
+
return {**f.to_dict(), "name": cbom.display_name(f), "quantum": alg.quantum, "classical": alg.classical,
|
|
118
|
+
"primitive": alg.primitive, "replacement": alg.replacement}
|
|
119
|
+
inv = inventory.build(findings)
|
|
120
|
+
rule_keys = ("title", "severity", "message", "action", "references", "due", "positive")
|
|
121
|
+
return {
|
|
122
|
+
"schema": "cbomly-findings/2",
|
|
123
|
+
"tool": {"name": "cbomly", "version": __version__},
|
|
124
|
+
"target": name,
|
|
125
|
+
"generated_at": datetime.now(UTC).isoformat(timespec="seconds"),
|
|
126
|
+
"packs": [{"id": p.id, "name": p.name, "version": p.version, "review_status": p.review_status}
|
|
127
|
+
for p in ev.packs],
|
|
128
|
+
"findings": [fd(f) for f in findings],
|
|
129
|
+
"rules": [{"id": r.rule["id"], "pack": r.pack, **{k: r.rule[k] for k in rule_keys if k in r.rule},
|
|
130
|
+
"triggered": r.triggered, "count": len(r.findings),
|
|
131
|
+
"matched": sorted({cbom.display_name(f) for f in r.findings})} for r in ev.rules],
|
|
132
|
+
"checks": [{"id": c.check["id"], "pack": c.pack, "title": c.check.get("title", ""),
|
|
133
|
+
"severity": c.check.get("severity", "info"), "message": c.check.get("message", ""),
|
|
134
|
+
"references": c.check.get("references", []), "status": c.status, "detail": c.detail}
|
|
135
|
+
for c in ev.checks],
|
|
136
|
+
"references": ev.references,
|
|
137
|
+
"crypto_libraries": libs,
|
|
138
|
+
"inventory": inv,
|
|
139
|
+
"vendors": inventory.vendors(inv, libs, stats.services),
|
|
140
|
+
"sbom_components": n_sw,
|
|
141
|
+
"worst_severity": ev.worst_severity(),
|
|
142
|
+
"stats": {"files_seen": stats.files_seen, "files_scanned": stats.files_scanned,
|
|
143
|
+
"skipped_large": stats.skipped_large, "errors": stats.errors},
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def cmd_upload(a) -> int:
|
|
148
|
+
from . import upload
|
|
149
|
+
return upload.run(a)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def cmd_rules(a) -> int:
|
|
153
|
+
avail = rules.available_packs(a.rules_dir)
|
|
154
|
+
if not a.pack:
|
|
155
|
+
for pid, path in sorted(avail.items()):
|
|
156
|
+
p = rules.load_pack(path)
|
|
157
|
+
ext = f" (extends {', '.join(p.extends)})" if p.extends else ""
|
|
158
|
+
print(f"{pid:<12} {p.name}{ext} [{p.review_status}]")
|
|
159
|
+
return 0
|
|
160
|
+
try:
|
|
161
|
+
for p in rules.resolve([a.pack], a.rules_dir):
|
|
162
|
+
print(f"\n{p.name} v{p.version} [{p.review_status}]\n{p.summary}\n")
|
|
163
|
+
for r in p.rules:
|
|
164
|
+
print(f" {r['id']:<12} {r.get('severity', 'info'):<8} {r['title']}")
|
|
165
|
+
for c in p.checks:
|
|
166
|
+
print(f" {c['id']:<12} {c.get('severity', 'info'):<8} {c['title']} (check)")
|
|
167
|
+
except ValueError as e:
|
|
168
|
+
print(f"cbomly: {e}", file=sys.stderr)
|
|
169
|
+
return 2
|
|
170
|
+
return 0
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def cmd_doctor(_a) -> int:
|
|
174
|
+
syft = sbom.find_syft()
|
|
175
|
+
print(f"cbomly {__version__}")
|
|
176
|
+
print(f"python {sys.version.split()[0]}")
|
|
177
|
+
if syft:
|
|
178
|
+
print(f"syft {sbom.syft_version(syft) or 'found'} ({syft})")
|
|
179
|
+
else:
|
|
180
|
+
print("syft NOT FOUND")
|
|
181
|
+
print(sbom.INSTALL_HINT)
|
|
182
|
+
return 0 if syft else 1
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def main(argv: list[str] | None = None) -> int:
|
|
186
|
+
a = _parser().parse_args(argv)
|
|
187
|
+
return {"scan": cmd_scan, "rules": cmd_rules, "doctor": cmd_doctor, "upload": cmd_upload}[a.cmd](a)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
if __name__ == "__main__":
|
|
191
|
+
sys.exit(main())
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Detectors: each one finds crypto in a different kind of file."""
|
cbomly/detect/deps.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Spot crypto libraries in the dependency list (the SBOM).
|
|
2
|
+
|
|
3
|
+
A crypto library on its own does not tell us which algorithms are used, but
|
|
4
|
+
it tells a buyer where crypto comes from, and some versions are known to
|
|
5
|
+
support post-quantum algorithms. That is useful for the upgrade plan.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
|
|
12
|
+
# (purl name regex, display name, PQC-ready from version, PQC note)
|
|
13
|
+
LIBRARIES: list[tuple[str, str, str | None, str]] = [
|
|
14
|
+
(r"^pkg:(?:deb|rpm|apk|generic|conan|brew)/(?:[^/]+/)?(?:openssl|libssl\d*(?:\.\d+)*(?:t64)?|openssl-libs)@",
|
|
15
|
+
"OpenSSL", "3.5.0", "OpenSSL 3.5+ ships ML-KEM, ML-DSA and SLH-DSA."),
|
|
16
|
+
(r"^pkg:maven/org\.bouncycastle/bc(?:prov|pkix|fips)[\w-]*@", "Bouncy Castle", "1.79",
|
|
17
|
+
"Bouncy Castle 1.79+ includes the final NIST ML-KEM, ML-DSA and SLH-DSA."),
|
|
18
|
+
(r"^pkg:golang/stdlib@|^pkg:golang/go@", "Go standard library crypto", "1.24.0",
|
|
19
|
+
"Go 1.24+ has crypto/mlkem and enables X25519MLKEM768 in TLS by default."),
|
|
20
|
+
(r"^pkg:golang/golang\.org/x/crypto@", "golang.org/x/crypto", None, ""),
|
|
21
|
+
(r"^pkg:(?:generic|conan|deb|github)/(?:[^/]+/)?liboqs@|^pkg:pypi/liboqs-python@|^pkg:\w+/(?:[^/]+/)?oqs[\w-]*@",
|
|
22
|
+
"liboqs (Open Quantum Safe)", "0.0.0", "Provides post-quantum algorithms."),
|
|
23
|
+
(r"^pkg:pypi/cryptography@", "pyca/cryptography", None, ""),
|
|
24
|
+
(r"^pkg:pypi/pycryptodomex?@", "PyCryptodome", None, ""),
|
|
25
|
+
(r"^pkg:pypi/(?:rsa|ecdsa|pynacl|pyjwt|python-jose|paramiko)@", "Python crypto package", None, ""),
|
|
26
|
+
(r"^pkg:npm/(?:node-forge|jsonwebtoken|jose|node-rsa|elliptic|tweetnacl|crypto-js|@noble/[\w-]+)@",
|
|
27
|
+
"JavaScript crypto package", None, ""),
|
|
28
|
+
(r"^pkg:npm/@noble/post-quantum@", "noble post-quantum", "0.0.0", "Provides ML-KEM, ML-DSA, SLH-DSA."),
|
|
29
|
+
(r"^pkg:maven/(?:io\.jsonwebtoken|com\.nimbusds|com\.auth0)/[\w.-]+@", "Java JWT/JOSE library", None, ""),
|
|
30
|
+
(r"^pkg:cargo/(?:ring|rustls|rsa|p256|p384|ed25519-dalek|x25519-dalek|openssl)@", "Rust crypto crate", None, ""),
|
|
31
|
+
(r"^pkg:cargo/(?:ml-kem|ml-dsa|pqcrypto[\w-]*|oqs)@", "Rust post-quantum crate", "0.0.0", "Provides post-quantum algorithms."),
|
|
32
|
+
(r"^pkg:nuget/(?:BouncyCastle[\w.]*|Portable\.BouncyCastle|System\.Security\.Cryptography[\w.]*)@",
|
|
33
|
+
".NET crypto package", None, ""),
|
|
34
|
+
(r"^pkg:gem/(?:openssl|jwt|rbnacl)@", "Ruby crypto gem", None, ""),
|
|
35
|
+
]
|
|
36
|
+
VENDORS = {
|
|
37
|
+
"OpenSSL": "OpenSSL Foundation",
|
|
38
|
+
"Bouncy Castle": "Legion of the Bouncy Castle",
|
|
39
|
+
"Go standard library crypto": "The Go Authors",
|
|
40
|
+
"golang.org/x/crypto": "The Go Authors",
|
|
41
|
+
"liboqs (Open Quantum Safe)": "Open Quantum Safe (PQCA)",
|
|
42
|
+
"pyca/cryptography": "Python Cryptographic Authority",
|
|
43
|
+
"PyCryptodome": "PyCryptodome project",
|
|
44
|
+
"noble post-quantum": "Paul Miller (noble)",
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
_COMPILED = [(re.compile(rx, re.IGNORECASE), n, v, note) for rx, n, v, note in LIBRARIES]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _vtuple(v: str) -> tuple:
|
|
51
|
+
nums = re.findall(r"\d+", v.split("-")[0].split("+")[0])
|
|
52
|
+
return tuple(int(x) for x in nums[:3]) or (0,)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def crypto_libraries(sbom: dict | None) -> list[dict]:
|
|
56
|
+
"""Return crypto libraries found among the SBOM components."""
|
|
57
|
+
if not sbom:
|
|
58
|
+
return []
|
|
59
|
+
out = []
|
|
60
|
+
for c in sbom.get("components", []):
|
|
61
|
+
purl = c.get("purl") or ""
|
|
62
|
+
for rx, name, pqc_from, note in _COMPILED:
|
|
63
|
+
if rx.search(purl):
|
|
64
|
+
version = c.get("version") or ""
|
|
65
|
+
pqc = None
|
|
66
|
+
if pqc_from is not None and version:
|
|
67
|
+
pqc = _vtuple(version) >= _vtuple(pqc_from)
|
|
68
|
+
out.append({
|
|
69
|
+
"library": name, "component": c.get("name"), "version": version, "purl": purl,
|
|
70
|
+
"bom-ref": c.get("bom-ref"), "vendor": VENDORS.get(name) or _supplier(c), "pqc_ready": pqc, "pqc_from": pqc_from, "note": note,
|
|
71
|
+
})
|
|
72
|
+
break
|
|
73
|
+
return out
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _supplier(c: dict) -> str | None:
|
|
77
|
+
"""Fall back to whatever the SBOM says about who makes the component."""
|
|
78
|
+
sup = c.get("supplier") or {}
|
|
79
|
+
if isinstance(sup, dict) and sup.get("name"):
|
|
80
|
+
return sup["name"]
|
|
81
|
+
return c.get("publisher") or c.get("author") or None
|
cbomly/detect/keys.py
ADDED
|
@@ -0,0 +1,319 @@
|
|
|
1
|
+
"""Find keys and certificates stored in the codebase.
|
|
2
|
+
|
|
3
|
+
Reads PEM blocks (-----BEGIN ...-----), raw DER certificate files and SSH
|
|
4
|
+
public keys, then decodes just enough ASN.1 to learn the algorithm, key
|
|
5
|
+
size or curve, and certificate validity dates. Nothing here needs OpenSSL.
|
|
6
|
+
|
|
7
|
+
A private key committed to a repository is also a secret leak, so those
|
|
8
|
+
findings are marked material="private-key" and rule packs can flag them.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import base64
|
|
14
|
+
import re
|
|
15
|
+
import struct
|
|
16
|
+
from datetime import UTC, datetime
|
|
17
|
+
|
|
18
|
+
from .. import algorithms
|
|
19
|
+
from ..findings import Finding
|
|
20
|
+
|
|
21
|
+
PEM_RE = re.compile(
|
|
22
|
+
r"-----BEGIN (?P<label>[A-Z0-9 ]+)-----\s*(?P<body>[A-Za-z0-9+/=\s:\-,]*?)-----END (?P=label)-----",
|
|
23
|
+
re.DOTALL,
|
|
24
|
+
)
|
|
25
|
+
SSH_PUB_RE = re.compile(
|
|
26
|
+
r"(?m)^(?:[^\s#]+\s+)?(?P<type>ssh-rsa|ssh-dss|ssh-ed25519|ecdsa-sha2-nistp(?:256|384|521)|sk-ssh-ed25519@openssh\.com)\s+(?P<b64>AAAA[A-Za-z0-9+/=]+)"
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
KEY_EXTS = {".pem", ".crt", ".cer", ".der", ".key", ".pub", ".csr", ".p7b", ".cert"}
|
|
30
|
+
SSH_NAMES = {"authorized_keys", "known_hosts", "id_rsa", "id_ecdsa", "id_ed25519", "id_dsa"}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# ---------------------------------------------------------------- DER ----
|
|
34
|
+
class DER:
|
|
35
|
+
"""A tiny DER reader: enough to walk certificates and keys."""
|
|
36
|
+
|
|
37
|
+
def __init__(self, data: bytes):
|
|
38
|
+
self.data = data
|
|
39
|
+
|
|
40
|
+
def read(self, pos: int) -> tuple[int, int, int, int]:
|
|
41
|
+
"""Return (tag, content_start, content_end, next_pos)."""
|
|
42
|
+
d = self.data
|
|
43
|
+
tag = d[pos]
|
|
44
|
+
ln = d[pos + 1]
|
|
45
|
+
p = pos + 2
|
|
46
|
+
if ln & 0x80:
|
|
47
|
+
n = ln & 0x7F
|
|
48
|
+
if n == 0 or n > 4:
|
|
49
|
+
raise ValueError("unsupported length")
|
|
50
|
+
ln = int.from_bytes(d[p:p + n], "big")
|
|
51
|
+
p += n
|
|
52
|
+
end = p + ln
|
|
53
|
+
if end > len(d):
|
|
54
|
+
raise ValueError("truncated")
|
|
55
|
+
return tag, p, end, end
|
|
56
|
+
|
|
57
|
+
def children(self, start: int, end: int):
|
|
58
|
+
p = start
|
|
59
|
+
while p < end:
|
|
60
|
+
tag, cs, ce, p = self.read(p)
|
|
61
|
+
yield tag, cs, ce
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def decode_oid(b: bytes) -> str:
|
|
65
|
+
if not b:
|
|
66
|
+
return ""
|
|
67
|
+
first = b[0]
|
|
68
|
+
parts = [str(min(first // 40, 2)), str(first - 40 * min(first // 40, 2))]
|
|
69
|
+
v = 0
|
|
70
|
+
for byte in b[1:]:
|
|
71
|
+
v = (v << 7) | (byte & 0x7F)
|
|
72
|
+
if not byte & 0x80:
|
|
73
|
+
parts.append(str(v))
|
|
74
|
+
v = 0
|
|
75
|
+
return ".".join(parts)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _first_oid(der: DER, start: int, end: int) -> str | None:
|
|
79
|
+
for tag, cs, ce in der.children(start, end):
|
|
80
|
+
if tag == 0x06:
|
|
81
|
+
return decode_oid(der.data[cs:ce])
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def parse_spki(der: DER, start: int, end: int) -> tuple[str | None, str | None]:
|
|
86
|
+
"""SubjectPublicKeyInfo -> (algorithm id, params such as '2048' or 'P-256')."""
|
|
87
|
+
kids = list(der.children(start, end))
|
|
88
|
+
if len(kids) < 2 or kids[0][0] != 0x30:
|
|
89
|
+
return None, None
|
|
90
|
+
_, acs, ace = kids[0]
|
|
91
|
+
alg_kids = list(der.children(acs, ace))
|
|
92
|
+
if not alg_kids or alg_kids[0][0] != 0x06:
|
|
93
|
+
return None, None
|
|
94
|
+
oid = decode_oid(der.data[alg_kids[0][1]:alg_kids[0][2]])
|
|
95
|
+
alg, hint = algorithms.OIDS.get(oid, (None, None))
|
|
96
|
+
params = hint
|
|
97
|
+
if alg == "ec" and len(alg_kids) > 1 and alg_kids[1][0] == 0x06:
|
|
98
|
+
curve_oid = decode_oid(der.data[alg_kids[1][1]:alg_kids[1][2]])
|
|
99
|
+
params = algorithms.CURVE_OIDS.get(curve_oid, curve_oid)
|
|
100
|
+
if alg == "rsa":
|
|
101
|
+
# BIT STRING -> SEQUENCE { INTEGER modulus, INTEGER exponent }
|
|
102
|
+
tag, bcs, _bce = kids[1]
|
|
103
|
+
if tag == 0x03:
|
|
104
|
+
try:
|
|
105
|
+
_, scs, sce, _ = der.read(bcs + 1)
|
|
106
|
+
_mtag, mcs, mce = next(der.children(scs, sce))
|
|
107
|
+
modulus = der.data[mcs:mce].lstrip(b"\x00")
|
|
108
|
+
params = str(_round_bits(len(modulus) * 8))
|
|
109
|
+
except (ValueError, StopIteration, IndexError):
|
|
110
|
+
pass
|
|
111
|
+
return alg, params
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _round_bits(bits: int) -> int:
|
|
115
|
+
for std in (512, 768, 1024, 1536, 2048, 3072, 4096, 7680, 8192, 15360):
|
|
116
|
+
if abs(bits - std) <= 8:
|
|
117
|
+
return std
|
|
118
|
+
return bits
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _parse_time(der: DER, tag: int, cs: int, ce: int) -> str | None:
|
|
122
|
+
s = der.data[cs:ce].decode("ascii", "replace")
|
|
123
|
+
try:
|
|
124
|
+
if tag == 0x17: # UTCTime
|
|
125
|
+
dt = datetime.strptime(s, "%y%m%d%H%M%SZ")
|
|
126
|
+
else: # GeneralizedTime
|
|
127
|
+
dt = datetime.strptime(s, "%Y%m%d%H%M%SZ")
|
|
128
|
+
return dt.replace(tzinfo=UTC).isoformat().replace("+00:00", "Z")
|
|
129
|
+
except ValueError:
|
|
130
|
+
return None
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _name_cn(der: DER, cs: int, ce: int) -> str | None:
|
|
134
|
+
"""Pull the CN (or O) out of an X.501 Name, for display only."""
|
|
135
|
+
found = {}
|
|
136
|
+
try:
|
|
137
|
+
for _, scs, sce in der.children(cs, ce): # SET
|
|
138
|
+
for _, acs, ace in der.children(scs, sce): # SEQUENCE
|
|
139
|
+
kids = list(der.children(acs, ace))
|
|
140
|
+
if len(kids) == 2 and kids[0][0] == 0x06:
|
|
141
|
+
oid = decode_oid(der.data[kids[0][1]:kids[0][2]])
|
|
142
|
+
found[oid] = der.data[kids[1][1]:kids[1][2]].decode("utf-8", "replace")
|
|
143
|
+
except ValueError:
|
|
144
|
+
return None
|
|
145
|
+
return found.get("2.5.4.3") or found.get("2.5.4.10")
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def parse_certificate(data: bytes) -> dict | None:
|
|
149
|
+
der = DER(data)
|
|
150
|
+
try:
|
|
151
|
+
_, cs, ce, _ = der.read(0)
|
|
152
|
+
top = list(der.children(cs, ce)) # tbs, sigAlg, sig
|
|
153
|
+
if len(top) < 3:
|
|
154
|
+
return None
|
|
155
|
+
_, tcs, tce = top[0]
|
|
156
|
+
tbs = list(der.children(tcs, tce))
|
|
157
|
+
i = 1 if tbs and tbs[0][0] == 0xA0 else 0 # optional [0] version
|
|
158
|
+
sig_oid = _first_oid(der, top[1][1], top[1][2])
|
|
159
|
+
issuer = tbs[i + 2]
|
|
160
|
+
validity = tbs[i + 3]
|
|
161
|
+
subject = tbs[i + 4]
|
|
162
|
+
spki = tbs[i + 5]
|
|
163
|
+
times = list(der.children(validity[1], validity[2]))
|
|
164
|
+
key_alg, key_params = parse_spki(der, spki[1], spki[2])
|
|
165
|
+
except (ValueError, IndexError):
|
|
166
|
+
return None
|
|
167
|
+
sig_alg, sig_hint = algorithms.OIDS.get(sig_oid or "", (None, None))
|
|
168
|
+
return {
|
|
169
|
+
"subject": _name_cn(der, subject[1], subject[2]),
|
|
170
|
+
"issuer": _name_cn(der, issuer[1], issuer[2]),
|
|
171
|
+
"not_before": _parse_time(der, *times[0]) if times else None,
|
|
172
|
+
"not_after": _parse_time(der, *times[1]) if len(times) > 1 else None,
|
|
173
|
+
"signature_algorithm": sig_alg, "signature_hash": sig_hint, "signature_oid": sig_oid,
|
|
174
|
+
"key_algorithm": key_alg, "key_params": key_params,
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def parse_pkcs8(data: bytes) -> tuple[str | None, str | None]:
|
|
179
|
+
der = DER(data)
|
|
180
|
+
try:
|
|
181
|
+
_, cs, ce, _ = der.read(0)
|
|
182
|
+
kids = list(der.children(cs, ce)) # version, AlgorithmIdentifier, privateKey
|
|
183
|
+
_, acs, ace = kids[1]
|
|
184
|
+
alg_kids = list(der.children(acs, ace))
|
|
185
|
+
oid = decode_oid(der.data[alg_kids[0][1]:alg_kids[0][2]])
|
|
186
|
+
alg, params = algorithms.OIDS.get(oid, (None, None))
|
|
187
|
+
if alg == "ec" and len(alg_kids) > 1 and alg_kids[1][0] == 0x06:
|
|
188
|
+
c = decode_oid(der.data[alg_kids[1][1]:alg_kids[1][2]])
|
|
189
|
+
params = algorithms.CURVE_OIDS.get(c, c)
|
|
190
|
+
if alg == "rsa":
|
|
191
|
+
# privateKey OCTET STRING -> RSAPrivateKey SEQUENCE { version, modulus, ... }
|
|
192
|
+
_, ocs, _oce = kids[2]
|
|
193
|
+
_, scs, sce, _ = der.read(ocs)
|
|
194
|
+
ints = list(der.children(scs, sce))
|
|
195
|
+
params = str(_round_bits(len(der.data[ints[1][1]:ints[1][2]].lstrip(b"\x00")) * 8))
|
|
196
|
+
return alg, params
|
|
197
|
+
except (ValueError, IndexError):
|
|
198
|
+
return None, None
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def parse_pkcs1_rsa_private(data: bytes) -> str | None:
|
|
202
|
+
der = DER(data)
|
|
203
|
+
try:
|
|
204
|
+
_, cs, ce, _ = der.read(0)
|
|
205
|
+
ints = list(der.children(cs, ce))
|
|
206
|
+
return str(_round_bits(len(der.data[ints[1][1]:ints[1][2]].lstrip(b"\x00")) * 8))
|
|
207
|
+
except (ValueError, IndexError):
|
|
208
|
+
return None
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def parse_ssh_pub(b64: str) -> str | None:
|
|
212
|
+
"""Return the RSA modulus size of an ssh-rsa key."""
|
|
213
|
+
try:
|
|
214
|
+
blob = base64.b64decode(b64)
|
|
215
|
+
parts = []
|
|
216
|
+
p = 0
|
|
217
|
+
while p < len(blob) and len(parts) < 3:
|
|
218
|
+
(n,) = struct.unpack(">I", blob[p:p + 4])
|
|
219
|
+
parts.append(blob[p + 4:p + 4 + n])
|
|
220
|
+
p += 4 + n
|
|
221
|
+
if parts and parts[0] == b"ssh-rsa" and len(parts) == 3:
|
|
222
|
+
return str(_round_bits(len(parts[2].lstrip(b"\x00")) * 8))
|
|
223
|
+
except (ValueError, struct.error):
|
|
224
|
+
pass
|
|
225
|
+
return None
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
SSH_TYPES = {
|
|
229
|
+
"ssh-rsa": ("rsa", None), "ssh-dss": ("dsa", None), "ssh-ed25519": ("ed25519", None),
|
|
230
|
+
"sk-ssh-ed25519@openssh.com": ("ed25519", None),
|
|
231
|
+
"ecdsa-sha2-nistp256": ("ecdsa", "P-256"), "ecdsa-sha2-nistp384": ("ecdsa", "P-384"),
|
|
232
|
+
"ecdsa-sha2-nistp521": ("ecdsa", "P-521"),
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
# ------------------------------------------------------------ scanning ----
|
|
237
|
+
def scan_text(rel: str, text: str) -> list[Finding]:
|
|
238
|
+
out: list[Finding] = []
|
|
239
|
+
for m in PEM_RE.finditer(text):
|
|
240
|
+
label = m.group("label")
|
|
241
|
+
line = text.count("\n", 0, m.start()) + 1
|
|
242
|
+
body = "".join(l for l in m.group("body").splitlines() if ":" not in l)
|
|
243
|
+
try:
|
|
244
|
+
raw = base64.b64decode(body, validate=False)
|
|
245
|
+
except ValueError:
|
|
246
|
+
raw = b""
|
|
247
|
+
out.extend(_from_pem(rel, line, label, raw, encrypted="ENCRYPTED" in m.group("body")))
|
|
248
|
+
for m in SSH_PUB_RE.finditer(text):
|
|
249
|
+
alg, params = SSH_TYPES[m.group("type")]
|
|
250
|
+
if alg == "rsa":
|
|
251
|
+
params = parse_ssh_pub(m.group("b64"))
|
|
252
|
+
out.append(Finding(alg, rel, text.count("\n", 0, m.start()) + 1, m.group("type") + " AAAA…",
|
|
253
|
+
"key-file", "high", params, "verify", "public-key"))
|
|
254
|
+
return out
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def scan_der(rel: str, data: bytes) -> list[Finding]:
|
|
258
|
+
cert = parse_certificate(data)
|
|
259
|
+
if cert:
|
|
260
|
+
return _from_cert(rel, None, cert)
|
|
261
|
+
return []
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def _from_pem(rel: str, line: int, label: str, raw: bytes, encrypted: bool) -> list[Finding]:
|
|
265
|
+
snippet = f"-----BEGIN {label}-----"
|
|
266
|
+
if label in ("CERTIFICATE", "TRUSTED CERTIFICATE", "X509 CERTIFICATE"):
|
|
267
|
+
cert = parse_certificate(raw)
|
|
268
|
+
return _from_cert(rel, line, cert) if cert else [
|
|
269
|
+
Finding("rsa", rel, line, snippet, "certificate", "low", material="certificate")]
|
|
270
|
+
if label == "RSA PRIVATE KEY":
|
|
271
|
+
return [Finding("rsa", rel, line, snippet, "key-file", "high",
|
|
272
|
+
None if encrypted else parse_pkcs1_rsa_private(raw), "keygen", "private-key")]
|
|
273
|
+
if label == "EC PRIVATE KEY":
|
|
274
|
+
return [Finding("ec", rel, line, snippet, "key-file", "high", None, "keygen", "private-key")]
|
|
275
|
+
if label == "DSA PRIVATE KEY":
|
|
276
|
+
return [Finding("dsa", rel, line, snippet, "key-file", "high", None, "keygen", "private-key")]
|
|
277
|
+
if label == "OPENSSH PRIVATE KEY":
|
|
278
|
+
alg, params = "rsa", None
|
|
279
|
+
for t, (a, prm) in SSH_TYPES.items():
|
|
280
|
+
if t.encode() in raw:
|
|
281
|
+
alg, params = a, prm
|
|
282
|
+
break
|
|
283
|
+
return [Finding(alg, rel, line, snippet, "key-file", "medium", params, "keygen", "private-key")]
|
|
284
|
+
if label == "PRIVATE KEY":
|
|
285
|
+
alg, params = parse_pkcs8(raw)
|
|
286
|
+
return [Finding(alg or "rsa", rel, line, snippet, "key-file", "high" if alg else "low",
|
|
287
|
+
params, "keygen", "private-key")]
|
|
288
|
+
if label == "ENCRYPTED PRIVATE KEY":
|
|
289
|
+
return [Finding("rsa", rel, line, snippet, "key-file", "low", None, "keygen", "private-key",
|
|
290
|
+
{"note": "encrypted; algorithm not readable"})]
|
|
291
|
+
if label in ("PUBLIC KEY",):
|
|
292
|
+
alg, params = parse_spki(DER(raw), *DER(raw).read(0)[1:3]) if raw else (None, None)
|
|
293
|
+
return [Finding(alg or "rsa", rel, line, snippet, "key-file", "high" if alg else "low",
|
|
294
|
+
params, "verify", "public-key")]
|
|
295
|
+
if label == "RSA PUBLIC KEY":
|
|
296
|
+
return [Finding("rsa", rel, line, snippet, "key-file", "high", None, "verify", "public-key")]
|
|
297
|
+
if label == "DH PARAMETERS":
|
|
298
|
+
return [Finding("dh", rel, line, snippet, "key-file", "high", None, "keyderive")]
|
|
299
|
+
if label == "CERTIFICATE REQUEST":
|
|
300
|
+
return [Finding("rsa", rel, line, snippet, "certificate", "low", material="csr")]
|
|
301
|
+
return []
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def _from_cert(rel: str, line: int | None, cert: dict) -> list[Finding]:
|
|
305
|
+
out = []
|
|
306
|
+
subject = cert.get("subject") or "unknown"
|
|
307
|
+
extra = {k: cert[k] for k in ("subject", "issuer", "not_before", "not_after") if cert.get(k)}
|
|
308
|
+
if cert.get("key_algorithm"):
|
|
309
|
+
out.append(Finding(cert["key_algorithm"], rel, line, f"certificate key: {subject}", "certificate",
|
|
310
|
+
"high", cert.get("key_params"), "verify", "certificate", dict(extra)))
|
|
311
|
+
if cert.get("signature_algorithm"):
|
|
312
|
+
out.append(Finding(cert["signature_algorithm"], rel, line, f"certificate signature: {subject}",
|
|
313
|
+
"certificate", "high", cert.get("signature_hash"), "sign", "certificate-signature",
|
|
314
|
+
dict(extra)))
|
|
315
|
+
if cert.get("signature_hash") in ("SHA-1", "MD5"):
|
|
316
|
+
out.append(Finding("sha1" if cert["signature_hash"] == "SHA-1" else "md5", rel, line,
|
|
317
|
+
f"certificate signature hash: {subject}", "certificate", "high", None,
|
|
318
|
+
"digest", "certificate-signature", dict(extra)))
|
|
319
|
+
return out
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Find third-party crypto services the code relies on.
|
|
2
|
+
|
|
3
|
+
These are vendors that hold or use keys on your behalf: cloud key
|
|
4
|
+
management (KMS), hardware security modules (HSMs), secret stores and
|
|
5
|
+
certificate authorities. They belong in the inventory because a buyer
|
|
6
|
+
will ask who controls the keys.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from dataclasses import dataclass
|
|
13
|
+
|
|
14
|
+
from .source import ALL
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@dataclass(frozen=True)
|
|
18
|
+
class Service:
|
|
19
|
+
vendor: str
|
|
20
|
+
service: str
|
|
21
|
+
kind: str # kms | hsm | secrets | ca | certificates
|
|
22
|
+
regex: re.Pattern
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def S(vendor, service, kind, rx):
|
|
26
|
+
return Service(vendor, service, kind, re.compile(rx, re.IGNORECASE))
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
SERVICES = [
|
|
30
|
+
S("Amazon Web Services", "AWS KMS", "kms",
|
|
31
|
+
r"kms\.[\w-]+\.amazonaws\.com|boto3\.client\(\s*[\"']kms[\"']|@aws-sdk/client-kms|\bKmsClient\b|"
|
|
32
|
+
r"\baws_kms_key\b|service/kms\"|aws-sdk-go[\w/-]*/kms\b|arn:aws:kms:"),
|
|
33
|
+
S("Amazon Web Services", "AWS CloudHSM", "hsm", r"\bcloudhsm\b|\baws_cloudhsm_v2_cluster\b"),
|
|
34
|
+
S("Amazon Web Services", "AWS Certificate Manager", "certificates",
|
|
35
|
+
r"boto3\.client\(\s*[\"']acm[\"']|@aws-sdk/client-acm\b|\baws_acm_certificate\b|arn:aws:acm:"),
|
|
36
|
+
S("Amazon Web Services", "AWS Secrets Manager", "secrets",
|
|
37
|
+
r"boto3\.client\(\s*[\"']secretsmanager[\"']|@aws-sdk/client-secrets-manager|\baws_secretsmanager_secret\b"),
|
|
38
|
+
S("Google Cloud", "Google Cloud KMS", "kms",
|
|
39
|
+
r"cloudkms\.googleapis\.com|google\.cloud\s*import\s+kms|google\.cloud\.kms|@google-cloud/kms|"
|
|
40
|
+
r"\bKeyManagementServiceClient\b|\bgoogle_kms_crypto_key\b|cloud\.google\.com/go/kms"),
|
|
41
|
+
S("Google Cloud", "Google Secret Manager", "secrets",
|
|
42
|
+
r"secretmanager\.googleapis\.com|google\.cloud\.secretmanager|@google-cloud/secret-manager|\bgoogle_secret_manager_secret\b"),
|
|
43
|
+
S("Microsoft Azure", "Azure Key Vault", "kms",
|
|
44
|
+
r"\.vault\.azure\.net|azure\.keyvault|@azure/keyvault-|Azure\.Security\.KeyVault|\bazurerm_key_vault\w*\b|azure-sdk-for-go/sdk/security/keyvault"),
|
|
45
|
+
S("HashiCorp", "HashiCorp Vault", "secrets",
|
|
46
|
+
r"\bhvac\.Client\(|github\.com/hashicorp/vault/api|\bVAULT_ADDR\b|[\"']node-vault[\"']|/transit/(?:encrypt|decrypt|sign|keys)/"),
|
|
47
|
+
S("Thales", "Thales Luna HSM", "hsm", r"\blibCryptoki2\w*\b|\bChrystoki\b|\bLunaProvider\b"),
|
|
48
|
+
S("Yubico", "YubiHSM", "hsm", r"\byubihsm\w*\b"),
|
|
49
|
+
S("Fortanix", "Fortanix DSM", "kms", r"\bfortanix\b|\bsdkms\b"),
|
|
50
|
+
S("Unknown (PKCS#11)", "PKCS#11 hardware security module", "hsm",
|
|
51
|
+
r"\bPyKCS11\b|\bpython-pkcs11\b|\bimport\s+pkcs11\b|\bSunPKCS11\b|\bC_Initialize\s*\(|\bpkcs11:"),
|
|
52
|
+
S("Internet Security Research Group", "Let's Encrypt", "ca",
|
|
53
|
+
r"acme-v02\.api\.letsencrypt\.org|\bcertbot\b|\bletsencrypt\b"),
|
|
54
|
+
S("eMudhra", "eMudhra digital signatures", "ca", r"\bemudhra\b"),
|
|
55
|
+
]
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def scan_text(rel: str, text: str, ext: str) -> list[dict]:
|
|
59
|
+
if ext not in ALL:
|
|
60
|
+
return []
|
|
61
|
+
out: list[dict] = []
|
|
62
|
+
seen: set[str] = set()
|
|
63
|
+
for svc in SERVICES:
|
|
64
|
+
m = svc.regex.search(text)
|
|
65
|
+
if m and svc.service not in seen:
|
|
66
|
+
seen.add(svc.service)
|
|
67
|
+
line = text.count("\n", 0, m.start()) + 1
|
|
68
|
+
out.append({"vendor": svc.vendor, "service": svc.service, "kind": svc.kind, "file": rel, "line": line})
|
|
69
|
+
return out
|