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/rules.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""The rules engine: turns raw findings into compliance results.
|
|
2
|
+
|
|
3
|
+
Rules live in "rule packs", plain TOML files under cbomly/packs/ (or any
|
|
4
|
+
folder you point --rules-dir at). The engine itself knows nothing about any
|
|
5
|
+
country. A pack says which findings matter, how serious they are, what to
|
|
6
|
+
do about them, and which regulation asks for it. That keeps India, EU and
|
|
7
|
+
US requirements swappable: add a file, not code.
|
|
8
|
+
|
|
9
|
+
Pack layout:
|
|
10
|
+
|
|
11
|
+
[pack] id, name, version, jurisdiction, extends = ["baseline"], summary
|
|
12
|
+
[references.<id>] title, issuer, date, url, status
|
|
13
|
+
[[rules]] id, title, severity, match = {...}, message, action, references, due
|
|
14
|
+
[[checks]] id, title, severity, type, ... (document-level checks on the SBOM/CBOM)
|
|
15
|
+
|
|
16
|
+
Match keys (all optional, all must hold): algorithm, quantum, classical,
|
|
17
|
+
primitive, material, detector (lists), max_key_bits, min_confidence,
|
|
18
|
+
expired (bool).
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import tomllib
|
|
24
|
+
from dataclasses import dataclass, field
|
|
25
|
+
from datetime import UTC, datetime
|
|
26
|
+
from importlib import resources
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
|
|
29
|
+
from . import algorithms
|
|
30
|
+
from .findings import Finding
|
|
31
|
+
|
|
32
|
+
SEVERITIES = ["critical", "high", "medium", "low", "info"]
|
|
33
|
+
CONF_ORDER = {"low": 0, "medium": 1, "high": 2}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
@dataclass
|
|
37
|
+
class Pack:
|
|
38
|
+
id: str
|
|
39
|
+
name: str
|
|
40
|
+
version: str
|
|
41
|
+
jurisdiction: str
|
|
42
|
+
summary: str
|
|
43
|
+
extends: list[str]
|
|
44
|
+
references: dict[str, dict]
|
|
45
|
+
rules: list[dict]
|
|
46
|
+
checks: list[dict]
|
|
47
|
+
review_status: str = "draft"
|
|
48
|
+
path: str = ""
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
@dataclass
|
|
52
|
+
class RuleResult:
|
|
53
|
+
rule: dict
|
|
54
|
+
pack: str
|
|
55
|
+
findings: list[Finding] = field(default_factory=list)
|
|
56
|
+
|
|
57
|
+
@property
|
|
58
|
+
def triggered(self) -> bool:
|
|
59
|
+
return bool(self.findings)
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@dataclass
|
|
63
|
+
class CheckResult:
|
|
64
|
+
check: dict
|
|
65
|
+
pack: str
|
|
66
|
+
status: str # pass | warn | fail
|
|
67
|
+
detail: str
|
|
68
|
+
data: dict = field(default_factory=dict)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
@dataclass
|
|
72
|
+
class Evaluation:
|
|
73
|
+
packs: list[Pack]
|
|
74
|
+
rules: list[RuleResult]
|
|
75
|
+
checks: list[CheckResult]
|
|
76
|
+
references: dict[str, dict]
|
|
77
|
+
|
|
78
|
+
def worst_severity(self) -> str | None:
|
|
79
|
+
sev = [r.rule.get("severity", "info") for r in self.rules if r.triggered and not r.rule.get("positive")]
|
|
80
|
+
sev += [c.check.get("severity", "info") for c in self.checks if c.status == "fail"]
|
|
81
|
+
return min(sev, key=SEVERITIES.index) if sev else None
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
# ------------------------------------------------------------ loading ----
|
|
85
|
+
def _pack_dirs(extra: list[str] | None) -> list[Path]:
|
|
86
|
+
dirs = [Path(d) for d in (extra or [])]
|
|
87
|
+
dirs.append(Path(str(resources.files("cbomly") / "packs")))
|
|
88
|
+
return dirs
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def available_packs(extra_dirs: list[str] | None = None) -> dict[str, Path]:
|
|
92
|
+
found: dict[str, Path] = {}
|
|
93
|
+
for d in reversed(_pack_dirs(extra_dirs)): # user dirs override built-ins
|
|
94
|
+
if d.is_dir():
|
|
95
|
+
for p in sorted(d.glob("*.toml")):
|
|
96
|
+
found[p.stem] = p
|
|
97
|
+
return found
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def load_pack(path: Path) -> Pack:
|
|
101
|
+
with open(path, "rb") as fh:
|
|
102
|
+
data = tomllib.load(fh)
|
|
103
|
+
meta = data.get("pack", {})
|
|
104
|
+
pid = meta.get("id") or path.stem
|
|
105
|
+
for r in data.get("rules", []):
|
|
106
|
+
unknown = set(r.get("match", {})) - {"algorithm", "quantum", "classical", "primitive", "material",
|
|
107
|
+
"detector", "max_key_bits", "min_confidence", "expired"}
|
|
108
|
+
if unknown:
|
|
109
|
+
raise ValueError(f"{path}: rule {r.get('id')} has unknown match keys {sorted(unknown)}")
|
|
110
|
+
if r.get("severity", "info") not in SEVERITIES:
|
|
111
|
+
raise ValueError(f"{path}: rule {r.get('id')} has bad severity {r.get('severity')}")
|
|
112
|
+
for a in r.get("match", {}).get("algorithm", []):
|
|
113
|
+
if a not in algorithms.CATALOG:
|
|
114
|
+
raise ValueError(f"{path}: rule {r.get('id')} names unknown algorithm {a!r}")
|
|
115
|
+
return Pack(
|
|
116
|
+
id=pid, name=meta.get("name", pid), version=str(meta.get("version", "")),
|
|
117
|
+
jurisdiction=meta.get("jurisdiction", "global"), summary=meta.get("summary", ""),
|
|
118
|
+
extends=list(meta.get("extends", [])), references=data.get("references", {}),
|
|
119
|
+
rules=data.get("rules", []), checks=data.get("checks", []),
|
|
120
|
+
review_status=meta.get("review_status", "draft"), path=str(path),
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def resolve(pack_ids: list[str], extra_dirs: list[str] | None = None) -> list[Pack]:
|
|
125
|
+
"""Load the named packs plus everything they extend, parents first."""
|
|
126
|
+
avail = available_packs(extra_dirs)
|
|
127
|
+
order: list[Pack] = []
|
|
128
|
+
seen: set[str] = set()
|
|
129
|
+
|
|
130
|
+
def visit(pid: str, stack: tuple = ()):
|
|
131
|
+
if pid in seen:
|
|
132
|
+
return
|
|
133
|
+
if pid in stack:
|
|
134
|
+
raise ValueError(f"rule pack cycle: {' -> '.join(stack + (pid,))}")
|
|
135
|
+
if pid not in avail:
|
|
136
|
+
raise ValueError(f"unknown rule pack {pid!r}. Available: {', '.join(sorted(avail))}")
|
|
137
|
+
pack = load_pack(avail[pid])
|
|
138
|
+
for parent in pack.extends:
|
|
139
|
+
visit(parent, stack + (pid,))
|
|
140
|
+
seen.add(pid)
|
|
141
|
+
order.append(pack)
|
|
142
|
+
|
|
143
|
+
for pid in pack_ids:
|
|
144
|
+
visit(pid)
|
|
145
|
+
return order
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
# --------------------------------------------------------- evaluating ----
|
|
149
|
+
def matches(f: Finding, m: dict, now: datetime | None = None) -> bool:
|
|
150
|
+
alg = algorithms.get(f.algorithm)
|
|
151
|
+
if "algorithm" in m and f.algorithm not in m["algorithm"]:
|
|
152
|
+
return False
|
|
153
|
+
if "quantum" in m and alg.quantum not in m["quantum"]:
|
|
154
|
+
return False
|
|
155
|
+
if "classical" in m and alg.classical not in m["classical"]:
|
|
156
|
+
return False
|
|
157
|
+
if "primitive" in m and alg.primitive not in m["primitive"]:
|
|
158
|
+
return False
|
|
159
|
+
if "material" in m and (f.material or "") not in m["material"]:
|
|
160
|
+
return False
|
|
161
|
+
if "detector" in m and f.detector not in m["detector"]:
|
|
162
|
+
return False
|
|
163
|
+
if "max_key_bits" in m and (f.key_bits is None or f.key_bits > m["max_key_bits"]):
|
|
164
|
+
return False
|
|
165
|
+
if "min_confidence" in m and CONF_ORDER[f.confidence] < CONF_ORDER[m["min_confidence"]]:
|
|
166
|
+
return False
|
|
167
|
+
if "expired" in m:
|
|
168
|
+
na = f.extra.get("not_after")
|
|
169
|
+
if not na:
|
|
170
|
+
return False
|
|
171
|
+
is_expired = datetime.fromisoformat(na) < (now or datetime.now(UTC))
|
|
172
|
+
if is_expired != m["expired"]:
|
|
173
|
+
return False
|
|
174
|
+
return True
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def evaluate(packs: list[Pack], findings: list[Finding], sbom: dict | None) -> Evaluation:
|
|
178
|
+
rules: list[RuleResult] = []
|
|
179
|
+
checks: list[CheckResult] = []
|
|
180
|
+
refs: dict[str, dict] = {}
|
|
181
|
+
for pack in packs:
|
|
182
|
+
refs.update(pack.references)
|
|
183
|
+
for r in pack.rules:
|
|
184
|
+
rr = RuleResult(r, pack.id, [f for f in findings if matches(f, r.get("match", {}))])
|
|
185
|
+
rules.append(rr)
|
|
186
|
+
for c in pack.checks:
|
|
187
|
+
checks.append(run_check(c, pack.id, findings, sbom))
|
|
188
|
+
# A child pack can override a parent's rule by reusing its id.
|
|
189
|
+
by_id: dict[str, RuleResult] = {}
|
|
190
|
+
for rr in rules:
|
|
191
|
+
by_id[rr.rule["id"]] = rr
|
|
192
|
+
return Evaluation(packs, list(by_id.values()), checks, refs)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def run_check(c: dict, pack: str, findings: list[Finding], sbom: dict | None) -> CheckResult:
|
|
196
|
+
kind = c.get("type")
|
|
197
|
+
comps = [x for x in (sbom or {}).get("components", []) if x.get("type") != "cryptographic-asset"]
|
|
198
|
+
if kind == "sbom-present":
|
|
199
|
+
if sbom is None:
|
|
200
|
+
return CheckResult(c, pack, "fail", "No software list (SBOM) was generated. Install Syft and re-run.")
|
|
201
|
+
return CheckResult(c, pack, "pass", f"SBOM generated with {len(comps)} components.")
|
|
202
|
+
if kind == "sbom-fields":
|
|
203
|
+
if not comps:
|
|
204
|
+
return CheckResult(c, pack, "fail" if sbom is None else "warn", "No components to check.")
|
|
205
|
+
cov = {}
|
|
206
|
+
for fld in c.get("fields", []):
|
|
207
|
+
cov[fld] = sum(1 for x in comps if _has_field(x, fld)) / len(comps)
|
|
208
|
+
threshold = float(c.get("min_coverage", 0.8))
|
|
209
|
+
low = {k: v for k, v in cov.items() if v < threshold}
|
|
210
|
+
detail = ", ".join(f"{k} {v:.0%}" for k, v in cov.items())
|
|
211
|
+
status = "pass" if not low else "warn"
|
|
212
|
+
return CheckResult(c, pack, status, f"Field coverage: {detail}", {"coverage": cov, "threshold": threshold})
|
|
213
|
+
if kind == "dependencies-present":
|
|
214
|
+
deps = (sbom or {}).get("dependencies", [])
|
|
215
|
+
n = sum(1 for d in deps if d.get("dependsOn"))
|
|
216
|
+
if sbom is None:
|
|
217
|
+
return CheckResult(c, pack, "fail", "No SBOM, so no dependency relationships.")
|
|
218
|
+
return CheckResult(c, pack, "pass" if n else "warn",
|
|
219
|
+
f"{n} components list their dependencies." if n else "No dependency relationships recorded.")
|
|
220
|
+
if kind == "crypto-inventory":
|
|
221
|
+
n = len({(f.algorithm, f.params) for f in findings})
|
|
222
|
+
return CheckResult(c, pack, "pass", f"CBOM lists {n} distinct cryptographic assets with file and line evidence.")
|
|
223
|
+
raise ValueError(f"check {c.get('id')}: unknown type {kind!r}")
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _has_field(comp: dict, fld: str) -> bool:
|
|
227
|
+
if fld == "supplier":
|
|
228
|
+
return bool(comp.get("supplier") or comp.get("publisher") or comp.get("author") or comp.get("authors"))
|
|
229
|
+
if fld == "licenses":
|
|
230
|
+
return bool(comp.get("licenses"))
|
|
231
|
+
if fld == "hashes":
|
|
232
|
+
return bool(comp.get("hashes"))
|
|
233
|
+
if fld == "unique-id":
|
|
234
|
+
return bool(comp.get("purl") or comp.get("cpe") or comp.get("swid"))
|
|
235
|
+
return bool(comp.get(fld))
|
cbomly/sbom.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
"""Build the software list (SBOM) by running Syft.
|
|
2
|
+
|
|
3
|
+
Syft (https://github.com/anchore/syft) is a widely used open-source SBOM
|
|
4
|
+
generator from Anchore. We call it rather than writing our own, because it
|
|
5
|
+
already understands dozens of package ecosystems.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import shutil
|
|
13
|
+
import subprocess
|
|
14
|
+
|
|
15
|
+
INSTALL_HINT = (
|
|
16
|
+
"Syft is not installed, so the software list (SBOM) was skipped.\n"
|
|
17
|
+
" macOS: brew install syft\n"
|
|
18
|
+
" Linux: curl -sSfL https://raw.githubusercontent.com/anchore/syft/main/install.sh | sh -s -- -b ~/.local/bin\n"
|
|
19
|
+
"Then run the scan again. Use --no-sbom to silence this message."
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class SyftError(RuntimeError):
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def find_syft(explicit: str | None = None) -> str | None:
|
|
28
|
+
if explicit:
|
|
29
|
+
return explicit if os.path.exists(explicit) else shutil.which(explicit)
|
|
30
|
+
return os.environ.get("CBOMLY_SYFT") or shutil.which("syft")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def syft_version(syft: str) -> str | None:
|
|
34
|
+
try:
|
|
35
|
+
out = subprocess.run([syft, "version", "-o", "json"], check=False, capture_output=True, text=True, timeout=30)
|
|
36
|
+
return json.loads(out.stdout).get("version")
|
|
37
|
+
except (OSError, ValueError, subprocess.SubprocessError):
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def generate(target: str, syft: str, timeout: int = 900) -> dict:
|
|
42
|
+
"""Run Syft on a directory, container image or archive; return CycloneDX JSON."""
|
|
43
|
+
src = target if ":" in target and not os.path.exists(target) else f"dir:{target}" if os.path.isdir(target) else f"file:{target}"
|
|
44
|
+
cmd = [syft, "scan", src, "-o", "cyclonedx-json", "-q"]
|
|
45
|
+
try:
|
|
46
|
+
proc = subprocess.run(cmd, check=False, capture_output=True, text=True, timeout=timeout)
|
|
47
|
+
except subprocess.TimeoutExpired as e:
|
|
48
|
+
raise SyftError(f"Syft timed out after {timeout}s") from e
|
|
49
|
+
if proc.returncode != 0:
|
|
50
|
+
raise SyftError((proc.stderr or proc.stdout).strip()[:2000] or f"syft exited {proc.returncode}")
|
|
51
|
+
try:
|
|
52
|
+
return json.loads(proc.stdout)
|
|
53
|
+
except ValueError as e:
|
|
54
|
+
raise SyftError("Syft did not return valid JSON") from e
|
cbomly/scanner.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Walk a folder and run every detector on it."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import fnmatch
|
|
6
|
+
import os
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
from .detect import keys, services, source
|
|
11
|
+
from .findings import Finding
|
|
12
|
+
|
|
13
|
+
DEFAULT_EXCLUDES = [
|
|
14
|
+
".git", ".hg", ".svn", "node_modules", "vendor", "third_party", ".venv", "venv", "env",
|
|
15
|
+
"__pycache__", ".tox", ".mypy_cache", ".pytest_cache", "dist", "build", "target", ".gradle",
|
|
16
|
+
".idea", ".vscode", "Pods", ".terraform", "site-packages", "cbomly-out",
|
|
17
|
+
]
|
|
18
|
+
MAX_TEXT_BYTES = 2 * 1024 * 1024
|
|
19
|
+
DER_EXTS = {".der", ".cer", ".crt"}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass
|
|
23
|
+
class ScanStats:
|
|
24
|
+
files_seen: int = 0
|
|
25
|
+
files_scanned: int = 0
|
|
26
|
+
skipped_large: int = 0
|
|
27
|
+
errors: list[str] = field(default_factory=list)
|
|
28
|
+
services: list[dict] = field(default_factory=list) # third-party crypto services (KMS, HSM, CA)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def iter_files(root: Path, excludes: list[str]):
|
|
32
|
+
for dirpath, dirnames, filenames in os.walk(root):
|
|
33
|
+
dirnames[:] = [d for d in dirnames if not any(fnmatch.fnmatch(d, pat) for pat in excludes)]
|
|
34
|
+
for name in filenames:
|
|
35
|
+
if any(fnmatch.fnmatch(name, pat) for pat in excludes):
|
|
36
|
+
continue
|
|
37
|
+
yield Path(dirpath) / name
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def scan_path(root: str | Path, excludes: list[str] | None = None) -> tuple[list[Finding], ScanStats]:
|
|
41
|
+
root = Path(root).resolve()
|
|
42
|
+
stats = ScanStats()
|
|
43
|
+
findings: list[Finding] = []
|
|
44
|
+
ex = DEFAULT_EXCLUDES if excludes is None else excludes
|
|
45
|
+
paths = [root] if root.is_file() else iter_files(root, ex)
|
|
46
|
+
for path in paths:
|
|
47
|
+
stats.files_seen += 1
|
|
48
|
+
ext = path.suffix.lower()
|
|
49
|
+
name = path.name
|
|
50
|
+
is_key = ext in keys.KEY_EXTS or name in keys.SSH_NAMES
|
|
51
|
+
is_src = source.applies_to(path)
|
|
52
|
+
if not (is_key or is_src):
|
|
53
|
+
continue
|
|
54
|
+
rel = path.name if root.is_file() else path.relative_to(root).as_posix()
|
|
55
|
+
try:
|
|
56
|
+
size = path.stat().st_size
|
|
57
|
+
if size > MAX_TEXT_BYTES:
|
|
58
|
+
stats.skipped_large += 1
|
|
59
|
+
continue
|
|
60
|
+
data = path.read_bytes()
|
|
61
|
+
except OSError as e:
|
|
62
|
+
stats.errors.append(f"{rel}: {e}")
|
|
63
|
+
continue
|
|
64
|
+
stats.files_scanned += 1
|
|
65
|
+
if ext in DER_EXTS and not data.lstrip().startswith(b"-----"):
|
|
66
|
+
findings.extend(keys.scan_der(rel, data))
|
|
67
|
+
continue
|
|
68
|
+
if b"\x00" in data[:4096]:
|
|
69
|
+
continue # binary
|
|
70
|
+
text = data.decode("utf-8", "replace")
|
|
71
|
+
if "-----BEGIN " in text or "AAAA" in text:
|
|
72
|
+
findings.extend(keys.scan_text(rel, text))
|
|
73
|
+
if is_src:
|
|
74
|
+
findings.extend(source.scan_text(rel, text, ext))
|
|
75
|
+
stats.services.extend(services.scan_text(rel, text, ext))
|
|
76
|
+
findings.sort(key=lambda f: (f.file, f.line or 0, f.algorithm))
|
|
77
|
+
return findings, stats
|
cbomly/upload.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""`cbomly upload`: send scan results to the cbomly.com dashboard.
|
|
2
|
+
|
|
3
|
+
Only findings leave the machine: algorithm, file path, line number and rule results, plus the
|
|
4
|
+
software list. Code snippets are removed before anything is sent, and `--dry-run` shows the
|
|
5
|
+
exact payload. Uses only the standard library.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import os
|
|
12
|
+
import sys
|
|
13
|
+
import urllib.error
|
|
14
|
+
import urllib.request
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from . import __version__
|
|
18
|
+
|
|
19
|
+
DEFAULT_URL = "https://app.cbomly.com"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def ci_metadata(env=os.environ) -> dict:
|
|
23
|
+
"""Commit, branch and run link from GitHub Actions or GitLab CI, if present."""
|
|
24
|
+
if env.get("GITHUB_ACTIONS"):
|
|
25
|
+
server, repo = env.get("GITHUB_SERVER_URL", "https://github.com"), env.get("GITHUB_REPOSITORY", "")
|
|
26
|
+
return {"ci": "github", "repo": repo, "commit": env.get("GITHUB_SHA"), "ref": env.get("GITHUB_REF_NAME"),
|
|
27
|
+
"run_url": f"{server}/{repo}/actions/runs/{env.get('GITHUB_RUN_ID')}" if env.get("GITHUB_RUN_ID") else None}
|
|
28
|
+
if env.get("GITLAB_CI"):
|
|
29
|
+
return {"ci": "gitlab", "repo": env.get("CI_PROJECT_PATH"), "commit": env.get("CI_COMMIT_SHA"),
|
|
30
|
+
"ref": env.get("CI_COMMIT_REF_NAME"), "run_url": env.get("CI_JOB_URL")}
|
|
31
|
+
return {"ci": None}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def build_payload(out: Path, env=os.environ) -> dict:
|
|
35
|
+
results = json.loads((out / "findings.json").read_text())
|
|
36
|
+
if results.get("schema") != "cbomly-findings/2":
|
|
37
|
+
raise ValueError(f"{out}/findings.json is from an older cbomly. Run `cbomly scan` again.")
|
|
38
|
+
for f in results["findings"]:
|
|
39
|
+
f.pop("snippet", None)
|
|
40
|
+
cbom = None
|
|
41
|
+
if (out / "cbom.cdx.json").exists():
|
|
42
|
+
cbom = json.loads((out / "cbom.cdx.json").read_text())
|
|
43
|
+
for comp in cbom.get("components", []):
|
|
44
|
+
for occ in comp.get("evidence", {}).get("occurrences", []):
|
|
45
|
+
occ.pop("additionalContext", None)
|
|
46
|
+
return {"client": {"name": "cbomly", "version": __version__}, "meta": ci_metadata(env),
|
|
47
|
+
"results": results, "cbom": cbom}
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def run(a) -> int:
|
|
51
|
+
out = Path(a.out)
|
|
52
|
+
if not (out / "findings.json").exists():
|
|
53
|
+
print(f"cbomly: {out}/findings.json not found. Run `cbomly scan` first.", file=sys.stderr)
|
|
54
|
+
return 2
|
|
55
|
+
try:
|
|
56
|
+
payload = build_payload(out)
|
|
57
|
+
except ValueError as e:
|
|
58
|
+
print(f"cbomly: {e}", file=sys.stderr)
|
|
59
|
+
return 2
|
|
60
|
+
if a.dry_run:
|
|
61
|
+
print(json.dumps(payload, indent=2))
|
|
62
|
+
return 0
|
|
63
|
+
key = a.key or os.environ.get("CBOMLY_API_KEY")
|
|
64
|
+
if not key:
|
|
65
|
+
print("cbomly: no API key. Create one in your dashboard and set CBOMLY_API_KEY.", file=sys.stderr)
|
|
66
|
+
return 2
|
|
67
|
+
url = (a.url or os.environ.get("CBOMLY_URL") or DEFAULT_URL).rstrip("/") + "/api/v1/scans"
|
|
68
|
+
req = urllib.request.Request(url, data=json.dumps(payload).encode(), method="POST", headers={
|
|
69
|
+
"Authorization": f"Bearer {key}", "Content-Type": "application/json",
|
|
70
|
+
"User-Agent": f"cbomly/{__version__}"})
|
|
71
|
+
try:
|
|
72
|
+
with urllib.request.urlopen(req, timeout=60) as r:
|
|
73
|
+
res = json.loads(r.read())
|
|
74
|
+
except urllib.error.HTTPError as e:
|
|
75
|
+
try:
|
|
76
|
+
msg = json.loads(e.read()).get("error", "")
|
|
77
|
+
except ValueError:
|
|
78
|
+
msg = ""
|
|
79
|
+
print(f"cbomly: upload failed ({e.code}) {msg}", file=sys.stderr)
|
|
80
|
+
return 2
|
|
81
|
+
except urllib.error.URLError as e:
|
|
82
|
+
print(f"cbomly: could not reach {url}: {e.reason}", file=sys.stderr)
|
|
83
|
+
return 2
|
|
84
|
+
|
|
85
|
+
print(f"Uploaded. Report: {res.get('url')}")
|
|
86
|
+
new = res.get("new_vulnerable") or []
|
|
87
|
+
if new:
|
|
88
|
+
print(f" {len(new)} new quantum-vulnerable item(s) since the last scan:")
|
|
89
|
+
for n in new[:10]:
|
|
90
|
+
print(f" ● {n['name']} {n['file']}:{n.get('line') or '-'}")
|
|
91
|
+
gate = res.get("gate") or {}
|
|
92
|
+
if gate.get("enabled"):
|
|
93
|
+
print(f" Release gate: {'FAILED' if gate.get('failed') else 'passed'}. {gate.get('reason', '')}")
|
|
94
|
+
if a.gate and gate.get("failed"):
|
|
95
|
+
return 1
|
|
96
|
+
return 0
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cbomly
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Find the cryptography in your software, write a CycloneDX CBOM, and check it is quantum-safe.
|
|
5
|
+
Author-email: Cbomly <team@cbomly.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://cbomly.com
|
|
8
|
+
Project-URL: Source, https://github.com/Cbomly/cbomly-scanner
|
|
9
|
+
Project-URL: Issues, https://github.com/Cbomly/cbomly-scanner/issues
|
|
10
|
+
Keywords: cbom,sbom,cyclonedx,post-quantum,pqc,cryptography,cert-in,compliance
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
13
|
+
Classifier: Operating System :: MacOS
|
|
14
|
+
Classifier: Topic :: Security :: Cryptography
|
|
15
|
+
Classifier: Environment :: Console
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Requires-Python: >=3.11
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
License-File: NOTICE
|
|
21
|
+
Provides-Extra: dev
|
|
22
|
+
Requires-Dist: pytest>=8; extra == "dev"
|
|
23
|
+
Requires-Dist: jsonschema>=4.21; extra == "dev"
|
|
24
|
+
Requires-Dist: ruff>=0.6; extra == "dev"
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
# Cbomly
|
|
28
|
+
|
|
29
|
+
**Find the cryptography in your software, and check it is ready for quantum computers.**
|
|
30
|
+
|
|
31
|
+
Cbomly scans a codebase and writes a **CBOM** (cryptographic bill of materials): a list of every
|
|
32
|
+
algorithm, key and certificate your product uses, with the file and line where it was found. It also
|
|
33
|
+
writes the normal software list (**SBOM**) and a plain-English report that says what a future quantum
|
|
34
|
+
computer would break, and what to replace it with.
|
|
35
|
+
|
|
36
|
+
It runs locally on Linux and macOS. Nothing is uploaded unless you run `cbomly upload` to keep your
|
|
37
|
+
reports in a free dashboard at [app.cbomly.com](https://app.cbomly.com), and even then only findings are
|
|
38
|
+
sent, never source code.
|
|
39
|
+
|
|
40
|
+
```
|
|
41
|
+
$ cbomly scan ./my-product --rules india
|
|
42
|
+
|
|
43
|
+
Cbomly scan complete
|
|
44
|
+
|
|
45
|
+
14 quantum-vulnerable algorithm(s) 0 weakened 2 quantum-safe
|
|
46
|
+
37 crypto use(s) in 13 file(s)
|
|
47
|
+
|
|
48
|
+
● ECDSA (SHA-256) svc/Signer.java:14
|
|
49
|
+
● RSA-2048 certs/server.crt:1 (+4 more)
|
|
50
|
+
...
|
|
51
|
+
[CRITICAL] BASE-K-001: Private key stored in the codebase
|
|
52
|
+
[HIGH ] IN-PQC-002: Quantum-vulnerable digital signatures (first in line for migration)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Why this matters
|
|
56
|
+
|
|
57
|
+
Large quantum computers will break RSA, elliptic-curve cryptography (ECDSA, ECDH, Ed25519, X25519),
|
|
58
|
+
DSA and Diffie-Hellman. Governments are setting deadlines to move to the new NIST post-quantum
|
|
59
|
+
standards (ML-KEM, ML-DSA, SLH-DSA), and buyers are starting to ask their software suppliers for a
|
|
60
|
+
CBOM and a migration plan:
|
|
61
|
+
|
|
62
|
+
- **US:** NIST IR 8547 (Oct 2026) deprecates RSA and elliptic curves after 2030 and disallows them
|
|
63
|
+
after 2035; EO 14412 sets federal PQC key exchange by end of 2030 and signatures by end of 2031;
|
|
64
|
+
NSA's CNSA 2.0 sets 2030-2033 deadlines for national security systems; EO 14028 and FDA section
|
|
65
|
+
524B ask for SBOMs.
|
|
66
|
+
- **EU:** the Cyber Resilience Act requires an SBOM from 11 December 2027 (reporting since
|
|
67
|
+
11 September 2026); the EU PQC roadmap says start by end of 2026 and finish high-risk uses by 2030.
|
|
68
|
+
- **UK, Canada, Australia, Singapore, Japan:** national PQC timelines between 2030 (Australia) and
|
|
69
|
+
2035, each starting with a cryptographic inventory.
|
|
70
|
+
- **India:** CERT-In's BOM guidelines v2.0 (July 2025) define SBOM and CBOM; SEBI's CSCRF (Aug 2024)
|
|
71
|
+
requires regulated entities to obtain SBOMs; the DST post-quantum roadmap (Feb 2026) asks vendors
|
|
72
|
+
for CBOMs from FY 2027-28.
|
|
73
|
+
- **Payments:** PCI DSS v4.0.1 requires a yearly reviewed inventory of cipher suites, keys and
|
|
74
|
+
certificates (since 31 March 2025).
|
|
75
|
+
|
|
76
|
+
## Install
|
|
77
|
+
|
|
78
|
+
Cbomly needs Python 3.11 or newer. [Syft](https://github.com/anchore/syft) is optional but recommended:
|
|
79
|
+
it builds the software list.
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
# macOS
|
|
83
|
+
brew install pipx syft
|
|
84
|
+
pipx install cbomly
|
|
85
|
+
|
|
86
|
+
# Linux
|
|
87
|
+
python3 -m pip install --user pipx
|
|
88
|
+
pipx install cbomly
|
|
89
|
+
curl -sSfL https://raw.githubusercontent.com/anchore/syft/main/install.sh | sh -s -- -b ~/.local/bin
|
|
90
|
+
|
|
91
|
+
cbomly doctor # checks everything is in place
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Use
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
cbomly scan # scan the current folder with the baseline rules
|
|
98
|
+
cbomly scan ./src --rules india # use the India rule pack (includes baseline)
|
|
99
|
+
cbomly scan . --fail-on high # exit code 1 if anything high or critical is found (for CI)
|
|
100
|
+
cbomly scan . --exclude 'testdata' # skip folders or files by name pattern
|
|
101
|
+
cbomly rules # list rule packs
|
|
102
|
+
cbomly rules india # show the rules in a pack
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Output goes to `./cbomly-out/`:
|
|
106
|
+
|
|
107
|
+
| File | What it is |
|
|
108
|
+
|---|---|
|
|
109
|
+
| `cbom.cdx.json` | CycloneDX 1.6 BOM: the software components from Syft, one `cryptographic-asset` per algorithm, key, certificate and protocol (each with file and line evidence and a `cbomly:status`), and crypto services (KMS, HSM, CA) under `services` |
|
|
110
|
+
| `summary.md` | The readable report: what is quantum-vulnerable, where, what to do, the full crypto inventory, and vendors |
|
|
111
|
+
| `findings.json` | Findings, rule results, inventory and vendors, for scripts and `cbomly upload` |
|
|
112
|
+
|
|
113
|
+
## Dashboard and CI
|
|
114
|
+
|
|
115
|
+
```bash
|
|
116
|
+
export CBOMLY_API_KEY=cbk_... # from your project page on app.cbomly.com
|
|
117
|
+
cbomly upload # sends ./cbomly-out (findings only; code snippets removed)
|
|
118
|
+
cbomly upload --dry-run # prints exactly what would be sent
|
|
119
|
+
cbomly upload --gate # exit code 1 if the project's release gate fails (Pro)
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
GitHub Actions:
|
|
123
|
+
|
|
124
|
+
```yaml
|
|
125
|
+
- uses: actions/checkout@v4
|
|
126
|
+
- uses: Cbomly/cbomly-scanner@v0
|
|
127
|
+
with:
|
|
128
|
+
api-key: ${{ secrets.CBOMLY_API_KEY }}
|
|
129
|
+
rules: india
|
|
130
|
+
gate: true
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
GitLab CI: include [`ci/gitlab/cbomly.yml`](ci/gitlab/cbomly.yml) and extend `.cbomly`.
|
|
134
|
+
|
|
135
|
+
Free accounts get a basic report for every scan. Pro adds the signed compliance pack, the upgrade plan,
|
|
136
|
+
the trend view, alerts for new RSA/ECC and the release gate.
|
|
137
|
+
|
|
138
|
+
## What it detects
|
|
139
|
+
|
|
140
|
+
| Where | How |
|
|
141
|
+
|---|---|
|
|
142
|
+
| Source code: Python, Java/Kotlin, Go, JavaScript/TypeScript, C/C++, C#, Ruby, PHP, Rust, Swift | Known crypto API calls (e.g. `KeyPairGenerator.getInstance("RSA")`, `rsa.generate_private_key`, `crypto.subtle`, OpenSSL `EVP_*`), including key sizes and curves where written in the code |
|
|
143
|
+
| Config files: nginx/Apache, YAML, TOML, properties, JSON | TLS versions, cipher suites, JWT algorithms (`RS256`, `ES256`) |
|
|
144
|
+
| Keys and certificates: PEM, DER, SSH keys | Algorithm, key size, curve, signature hash, subject and validity dates. Private keys are flagged as leaks |
|
|
145
|
+
| Dependencies (via Syft) | Crypto libraries such as OpenSSL, Bouncy Castle and Go's standard library, and whether the version supports post-quantum algorithms |
|
|
146
|
+
| Post-quantum use | ML-KEM, ML-DSA, SLH-DSA and hybrid X25519MLKEM768 are recognised and reported as good news |
|
|
147
|
+
| Third-party crypto services | AWS KMS, CloudHSM, Certificate Manager and Secrets Manager, Google Cloud KMS and Secret Manager, Azure Key Vault, HashiCorp Vault, Thales Luna, YubiHSM, Fortanix, PKCS#11 HSMs, Let's Encrypt and eMudhra, listed as vendors |
|
|
148
|
+
| Safe crypto | AES (with key size and mode), ChaCha20-Poly1305, SHA-2, SHA-3, BLAKE2, HMAC, key derivation (PBKDF2, HKDF, scrypt, Argon2, bcrypt) and secure random number generators. Listed in the CBOM and marked quantum-safe, so the inventory is complete. AES-128 is marked "weakened by quantum" |
|
|
149
|
+
|
|
150
|
+
Every algorithm, certificate, key and protocol gets one status: **broken**, **deprecated**,
|
|
151
|
+
**quantum-vulnerable**, **weakened** (by quantum attacks, e.g. AES-128) or **safe**. Certificates also
|
|
152
|
+
show issuer, public key, signature and expiry. Keys show size or curve. The **Vendors** section lists
|
|
153
|
+
who supplies or controls your crypto: library makers, certificate issuers, and key management services.
|
|
154
|
+
|
|
155
|
+
Detection is pattern-based, so it is fast and needs no build, but it can miss crypto hidden inside
|
|
156
|
+
compiled binaries or wrapper functions, and it can report false positives. Findings carry a
|
|
157
|
+
confidence level (high, medium, low).
|
|
158
|
+
|
|
159
|
+
## Rule packs
|
|
160
|
+
|
|
161
|
+
The scanner itself is country-neutral. Requirements live in small TOML files called rule packs, so
|
|
162
|
+
a new country or standard is a new file, not new code. Built-in packs:
|
|
163
|
+
|
|
164
|
+
| Pack | Status | Covers |
|
|
165
|
+
|---|---|---|
|
|
166
|
+
| `baseline` | stable | Quantum-vulnerable crypto, broken and deprecated algorithms, short RSA keys, committed private keys, expired certificates |
|
|
167
|
+
| `us` | draft | NIST IR 8547, EO 14412 / OMB M-26-15, CISA PQC product categories, EO 14028 and NTIA SBOM |
|
|
168
|
+
| `us-cnsa2` | draft | NSA CNSA 2.0 and CNSSP 15 for national security systems (includes `us`) |
|
|
169
|
+
| `us-fda` | draft | FD&C Act section 524B SBOM and FDA premarket cybersecurity guidance (medical devices) |
|
|
170
|
+
| `eu` | draft | Cyber Resilience Act SBOM and crypto, EU PQC roadmap, NIS2, DORA |
|
|
171
|
+
| `uk` | draft | NCSC PQC migration timelines (2028 / 2031 / 2035) |
|
|
172
|
+
| `ca` | draft | Government of Canada PQC roadmap and TBS SPIN, OSFI quantum readiness |
|
|
173
|
+
| `au` | draft | ASD ISM: stop traditional asymmetric crypto by end of 2030 |
|
|
174
|
+
| `sg` | draft | MAS quantum advisory and proposed 2030 / 2034 migration timelines |
|
|
175
|
+
| `jp` | draft | National Cybersecurity Office 2035 target, FSA guidance for banks |
|
|
176
|
+
| `india` | draft | CERT-In BOM guidelines (SBOM + CBOM), SEBI CSCRF, DST post-quantum roadmap milestones |
|
|
177
|
+
| `pci-dss` | draft | PCI DSS v4.0.1 cipher suite, key and certificate inventory (12.3.3, 4.2.1.1, 6.3.2) |
|
|
178
|
+
|
|
179
|
+
Combine packs for the markets you sell to, e.g. `--rules eu,us,india`.
|
|
180
|
+
|
|
181
|
+
See [docs/rule-packs.md](docs/rule-packs.md) to write your own and load it with `--rules-dir`.
|
|
182
|
+
|
|
183
|
+
The regional packs are marked **draft**: each reference says how far its summary was checked
|
|
184
|
+
against the official documents, and anything not confirmed is labelled UNVERIFIED or NOT re-checked. The reports are informational, not legal advice.
|
|
185
|
+
|
|
186
|
+
## Development
|
|
187
|
+
|
|
188
|
+
```bash
|
|
189
|
+
python3 -m venv .venv && . .venv/bin/activate
|
|
190
|
+
pip install -e ".[dev]" "cyclonedx-python-lib[json-validation]"
|
|
191
|
+
pytest
|
|
192
|
+
ruff check src tests
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
Every key and certificate under `tests/fixtures/` is a throwaway test fixture.
|
|
196
|
+
|
|
197
|
+
Contributions are welcome: see [CONTRIBUTING.md](CONTRIBUTING.md). To report a security problem,
|
|
198
|
+
see [SECURITY.md](SECURITY.md).
|
|
199
|
+
|
|
200
|
+
## Licence
|
|
201
|
+
|
|
202
|
+
Apache-2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
|