modelbom 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,202 @@
1
+ """Attack-path engine.
2
+
3
+ Each path rule states a precondition (what the adversary must be able to do), the findings that
4
+ must co-occur (the exploitation steps) and the postcondition (impact). This mirrors attack-graph
5
+ generation where edges are state transitions enabled by specific weaknesses: a path is reported
6
+ only when every step is present in the scan.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections import defaultdict
12
+
13
+ from .graph import Link
14
+ from .models import AttackPath, AttackStep, Finding, ModelRef, ScanResult, Severity
15
+
16
+ _LOADERS = ("MB103", "MB104", "MB105")
17
+
18
+
19
+ def _step(f: Finding, description: str | None = None) -> AttackStep:
20
+ return AttackStep(f.rule_id, f.location, description or f.message, f.fingerprint)
21
+
22
+
23
+ class _Builder:
24
+ def __init__(self) -> None:
25
+ self.paths: list[AttackPath] = []
26
+ self._seen: set[tuple[str, tuple[str, ...]]] = set()
27
+
28
+ def add(
29
+ self,
30
+ kind: str,
31
+ title: str,
32
+ severity: Severity,
33
+ precondition: str,
34
+ steps: list[AttackStep],
35
+ impact: str,
36
+ nodes: list[str],
37
+ ) -> None:
38
+ key = (kind, tuple(s.fingerprint for s in steps))
39
+ if key in self._seen:
40
+ return
41
+ self._seen.add(key)
42
+ self.paths.append(AttackPath("", kind, title, severity, precondition, steps, impact, nodes))
43
+
44
+
45
+ def derive_attack_paths(result: ScanResult, links: list[Link]) -> list[AttackPath]:
46
+ active = [f for f in result.reportable() if f.severity > Severity.INFO]
47
+ by_rule: dict[str, list[Finding]] = defaultdict(list)
48
+ by_file: dict[str, list[Finding]] = defaultdict(list)
49
+ for f in active:
50
+ by_rule[f.rule_id].append(f)
51
+ by_file[f.path].append(f)
52
+ refs: dict[str, ModelRef] = {r.ref: r for r in result.model_refs}
53
+ b = _Builder()
54
+
55
+ # 1. Unpinned hub repository + trust_remote_code -> code execution at load time.
56
+ for rc in by_rule["MB101"]:
57
+ for up in by_rule["MB102"]:
58
+ same_call = (
59
+ up.path == rc.path
60
+ and up.line == rc.line
61
+ and up.details.get("cell") == rc.details.get("cell")
62
+ )
63
+ if not same_call:
64
+ continue
65
+ hub_id = up.details.get("hub_id", "the repository")
66
+ b.add(
67
+ "remote-code-on-load",
68
+ "Upstream repository change executes code at load time",
69
+ Severity.CRITICAL,
70
+ f"adversary can push to, take over or impersonate '{hub_id}'",
71
+ [_step(up), _step(rc)],
72
+ f"arbitrary code execution in the process that runs {rc.path}",
73
+ [str(up.details.get("ref")), f"file:{rc.path}"],
74
+ )
75
+
76
+ # 2. Dangerous artifact + code that loads it.
77
+ artifact_rules = {"MB201": Severity.CRITICAL, "MB204": Severity.HIGH, "MB207": Severity.HIGH}
78
+ for rule_id, sev in artifact_rules.items():
79
+ for af in by_rule[rule_id]:
80
+ target = str(af.details.get("artifact", af.path))
81
+ for link in links:
82
+ if link.target != target:
83
+ continue
84
+ loaders = [f for f in by_file[link.source] if f.rule_id in _LOADERS]
85
+ if link.label != "loads" and not loaders:
86
+ continue
87
+ steps = [_step(af)]
88
+ if loaders:
89
+ steps.append(_step(loaders[0]))
90
+ path_sev = sev
91
+ if rule_id == "MB204" and any(f.rule_id == "MB105" for f in loaders):
92
+ path_sev = Severity.CRITICAL
93
+ b.add(
94
+ "malicious-artifact-loaded",
95
+ f"Unsafe artifact {target} is loaded by {link.source}",
96
+ path_sev,
97
+ f"{target} was produced or replaced by an untrusted party",
98
+ steps,
99
+ f"code embedded in {target} runs when {link.source} executes",
100
+ [f"artifact:{target}", f"file:{link.source}"],
101
+ )
102
+
103
+ # 3. Unverified download + unsafe deserialization in the same file.
104
+ for dl in by_rule["MB107"]:
105
+ loaders = [f for f in by_file[dl.path] if f.rule_id in _LOADERS]
106
+ if loaders:
107
+ b.add(
108
+ "unverified-download-deserialized",
109
+ "Unverified download is deserialized",
110
+ Severity.HIGH,
111
+ "adversary controls the download host, a mirror, DNS or the network path",
112
+ [_step(dl), _step(loaders[0])],
113
+ f"arbitrary code execution when {dl.path} unpickles the substituted file",
114
+ [f"file:{dl.path}"],
115
+ )
116
+
117
+ # 4. Unpinned file download from a hub + unsafe deserialization in the same file.
118
+ for up in by_rule["MB102"]:
119
+ ref = refs.get(str(up.details.get("ref")))
120
+ if ref is None or ref.kind != "model" or not ref.call.endswith(("hf_hub_download", "snapshot_download")):
121
+ continue
122
+ loaders = [f for f in by_file[up.path] if f.rule_id in _LOADERS]
123
+ if loaders:
124
+ b.add(
125
+ "upstream-file-swap-deserialized",
126
+ "Upstream model file swap is deserialized",
127
+ Severity.HIGH,
128
+ f"adversary can push a new revision to '{ref.name}'",
129
+ [_step(up), _step(loaders[0])],
130
+ f"arbitrary code execution when {up.path} unpickles the downloaded file",
131
+ [ref.ref, f"file:{up.path}"],
132
+ )
133
+
134
+ # 5. Unpinned dataset -> silent training-data poisoning.
135
+ for up in by_rule["MB102"]:
136
+ if up.details.get("kind") != "dataset":
137
+ continue
138
+ hub_id = up.details.get("hub_id", "the dataset")
139
+ b.add(
140
+ "dataset-poisoning",
141
+ "Upstream dataset change poisons training data",
142
+ Severity.HIGH,
143
+ f"adversary can push a new revision to dataset '{hub_id}'",
144
+ [_step(up)],
145
+ "poisoned or backdoored samples flow into models trained by " + up.path,
146
+ [str(up.details.get("ref")), f"file:{up.path}"],
147
+ )
148
+
149
+ # 6. Pickled vector index -> code execution in the retrieval service.
150
+ for vf in by_rule["MB109"]:
151
+ b.add(
152
+ "poisoned-vector-index",
153
+ "Poisoned vector index executes code",
154
+ Severity.HIGH,
155
+ "adversary can write the stored index or poison the pipeline that builds it",
156
+ [_step(vf)],
157
+ f"arbitrary code execution in the retrieval service running {vf.path}",
158
+ [f"file:{vf.path}"],
159
+ )
160
+
161
+ # 7. torch.hub repository code from a moving branch.
162
+ for hf in by_rule["MB108"]:
163
+ if hf.severity < Severity.HIGH:
164
+ continue
165
+ hub_id = hf.details.get("hub_id", "the repository")
166
+ b.add(
167
+ "remote-hub-code",
168
+ "torch.hub repository change executes code",
169
+ Severity.HIGH,
170
+ f"adversary can push to or take over the GitHub repository '{hub_id}'",
171
+ [_step(hf)],
172
+ f"hubconf.py runs inside the process that executes {hf.path}",
173
+ [str(hf.details.get("ref")), f"file:{hf.path}"],
174
+ )
175
+
176
+ # 8. Known-vulnerable dependency imported by code (one path per package and importer).
177
+ importers: dict[str, list[str]] = defaultdict(list)
178
+ for cf in result.code_files:
179
+ for module in cf.imports:
180
+ importers[module.replace("_", "-").lower()].append(cf.path)
181
+ vulns_by_pkg: dict[str, list[Finding]] = defaultdict(list)
182
+ for vf in by_rule["MB302"]:
183
+ vulns_by_pkg[str(vf.details.get("package", ""))].append(vf)
184
+ for package, vulns in sorted(vulns_by_pkg.items()):
185
+ vulns.sort(key=lambda f: -int(f.severity))
186
+ count = len(vulns)
187
+ label = f"{count} advisor{'y' if count == 1 else 'ies'}"
188
+ for path in sorted(set(importers.get(package, []))):
189
+ b.add(
190
+ "vulnerable-dependency-imported",
191
+ f"Vulnerable {package} ({label}) is imported by {path}",
192
+ vulns[0].severity,
193
+ f"a published vulnerability in {package} is reachable through code that imports it",
194
+ [_step(v) for v in vulns[:3]],
195
+ f"{path} runs with a dependency that has {label}",
196
+ [f"pkg:{package}", f"file:{path}"],
197
+ )
198
+
199
+ ordered = sorted(b.paths, key=lambda p: (-int(p.severity), p.kind, p.title))
200
+ for i, p in enumerate(ordered, start=1):
201
+ p.id = f"AP-{i}"
202
+ return ordered
modelbom/cli.py ADDED
@@ -0,0 +1,202 @@
1
+ """Command-line interface.
2
+
3
+ Exit codes:
4
+ 0 success (``scan``: no unsuppressed finding at or above ``--fail-on``)
5
+ 1 ``scan`` found at least one unsuppressed finding at or above ``--fail-on``
6
+ 2 usage error (bad arguments, missing path)
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import sys
15
+ from collections.abc import Sequence
16
+ from pathlib import Path
17
+
18
+ from . import __version__
19
+ from .artifacts import DEFAULT_MAX_BYTES
20
+ from .graph import build_graph, build_links, to_dot, to_json, to_mermaid
21
+ from .models import ScanResult, Severity
22
+ from .report import render_cyclonedx, render_json, render_sarif, render_text
23
+ from .rules import all_rules
24
+ from .scanner import scan
25
+
26
+ _SEVERITIES = [s.label for s in Severity]
27
+
28
+
29
+ def _add_common(p: argparse.ArgumentParser) -> None:
30
+ p.add_argument("path", help="directory or file to scan")
31
+ p.add_argument(
32
+ "--exclude",
33
+ action="append",
34
+ default=[],
35
+ metavar="GLOB",
36
+ help="exclude paths matching GLOB (repeatable; .modelbomignore is also honored)",
37
+ )
38
+ p.add_argument("--no-hash", action="store_true", help="skip SHA-256 hashing of artifacts")
39
+ p.add_argument(
40
+ "--max-bytes",
41
+ type=int,
42
+ default=DEFAULT_MAX_BYTES,
43
+ metavar="N",
44
+ help=f"per-artifact analysis limit in bytes (default {DEFAULT_MAX_BYTES})",
45
+ )
46
+ p.add_argument("-o", "--output", metavar="FILE", help="write the report to FILE instead of stdout")
47
+
48
+
49
+ def build_parser() -> argparse.ArgumentParser:
50
+ parser = argparse.ArgumentParser(
51
+ prog="modelbom",
52
+ description=(
53
+ "Find unsafe model loading, poisoned artifacts and unpinned AI dependencies, "
54
+ "and emit a CycloneDX AI-BOM. Never loads what it scans."
55
+ ),
56
+ )
57
+ parser.add_argument("--version", action="version", version=f"modelbom {__version__}")
58
+ sub = parser.add_subparsers(dest="command", metavar="COMMAND")
59
+
60
+ p_scan = sub.add_parser("scan", help="scan code, artifacts and dependencies")
61
+ _add_common(p_scan)
62
+ p_scan.add_argument("--format", choices=["text", "json", "sarif"], default="text")
63
+ p_scan.add_argument(
64
+ "--fail-on",
65
+ choices=_SEVERITIES,
66
+ default="high",
67
+ help="exit 1 if a finding at or above this severity exists (default: high)",
68
+ )
69
+ p_scan.add_argument("--online", action="store_true", help="query OSV.dev for known vulnerabilities")
70
+ p_scan.add_argument("--verbose", action="store_true", help="also list inventory records (MB206)")
71
+ p_scan.add_argument("--no-color", action="store_true", help="disable ANSI colors")
72
+
73
+ p_bom = sub.add_parser("bom", help="write a CycloneDX 1.6 AI-BOM")
74
+ _add_common(p_bom)
75
+ p_bom.add_argument("--online", action="store_true", help="include OSV.dev vulnerabilities")
76
+
77
+ p_graph = sub.add_parser("graph", help="export the dependency and attack-path graph")
78
+ _add_common(p_graph)
79
+ p_graph.add_argument("--format", choices=["mermaid", "dot", "json"], default="mermaid")
80
+
81
+ p_rules = sub.add_parser("rules", help="list rules and their standard mappings")
82
+ p_rules.add_argument("--format", choices=["text", "json", "markdown"], default="text")
83
+
84
+ sub.add_parser("version", help="print the version")
85
+ return parser
86
+
87
+
88
+ def _write(text: str, output: str | None) -> None:
89
+ if output:
90
+ Path(output).write_text(text, encoding="utf-8")
91
+ else:
92
+ sys.stdout.write(text)
93
+
94
+
95
+ def _run_scan(args: argparse.Namespace) -> ScanResult:
96
+ return scan(
97
+ args.path,
98
+ excludes=args.exclude,
99
+ online=getattr(args, "online", False),
100
+ hash_files=not args.no_hash,
101
+ max_bytes=args.max_bytes,
102
+ )
103
+
104
+
105
+ def _rules_text(fmt: str) -> str:
106
+ rules = all_rules()
107
+ if fmt == "json":
108
+ payload = [
109
+ {
110
+ "id": r.id,
111
+ "title": r.title,
112
+ "severity": r.severity.label,
113
+ "category": r.category,
114
+ "description": r.description,
115
+ "remediation": r.remediation,
116
+ "references": r.references(),
117
+ "help_uri": r.help_uri,
118
+ }
119
+ for r in rules
120
+ ]
121
+ return json.dumps(payload, indent=2) + "\n"
122
+ if fmt == "markdown":
123
+ out = [
124
+ "| Rule | Severity | Title | OWASP LLM / Agentic | MITRE ATLAS | CWE |",
125
+ "|---|---|---|---|---|---|",
126
+ ]
127
+ for r in rules:
128
+ owasp = ", ".join(r.owasp_llm + r.owasp_agentic) or "—"
129
+ out.append(
130
+ f"| [{r.id}](#{r.id.lower()}) | {r.severity.label} | {r.title} | {owasp} | "
131
+ f"{', '.join(r.atlas) or '—'} | {', '.join(r.cwe) or '—'} |"
132
+ )
133
+ out.append("")
134
+ for r in rules:
135
+ out.append(f"### {r.id}")
136
+ out.append("")
137
+ out.append(f"**{r.title}** · default severity `{r.severity.label}` · {r.category}")
138
+ out.append("")
139
+ out.append(r.description)
140
+ out.append("")
141
+ out.append(f"**Remediation:** {r.remediation}")
142
+ out.append("")
143
+ return "\n".join(out)
144
+ lines = []
145
+ for r in rules:
146
+ refs = ", ".join(r.owasp_llm + r.owasp_agentic + r.atlas + r.cwe)
147
+ lines.append(f"{r.id} {r.severity.label:<8} {r.title}")
148
+ if refs:
149
+ lines.append(f" {refs}")
150
+ return "\n".join(lines) + "\n"
151
+
152
+
153
+ def main(argv: Sequence[str] | None = None) -> int:
154
+ parser = build_parser()
155
+ args = parser.parse_args(argv)
156
+ if args.command is None:
157
+ parser.print_help(sys.stderr)
158
+ return 2
159
+ if args.command == "version":
160
+ print(f"modelbom {__version__}")
161
+ return 0
162
+ if args.command == "rules":
163
+ sys.stdout.write(_rules_text(args.format))
164
+ return 0
165
+ if not Path(args.path).exists():
166
+ print(f"modelbom: error: no such file or directory: {args.path}", file=sys.stderr)
167
+ return 2
168
+ if args.max_bytes <= 0:
169
+ print("modelbom: error: --max-bytes must be positive", file=sys.stderr)
170
+ return 2
171
+ result = _run_scan(args)
172
+
173
+ if args.command == "bom":
174
+ _write(render_cyclonedx(result), args.output)
175
+ return 0
176
+ if args.command == "graph":
177
+ links = build_links(result)
178
+ graph = build_graph(result, links)
179
+ render = {"mermaid": to_mermaid, "dot": to_dot, "json": to_json}[args.format]
180
+ _write(render(graph, result.attack_paths), args.output)
181
+ return 0
182
+
183
+ if args.format == "json":
184
+ text = render_json(result)
185
+ elif args.format == "sarif":
186
+ text = render_sarif(result)
187
+ else:
188
+ color = (
189
+ not args.no_color
190
+ and not args.output
191
+ and sys.stdout.isatty()
192
+ and "NO_COLOR" not in os.environ
193
+ )
194
+ text = render_text(result, color=color, verbose=args.verbose)
195
+ _write(text, args.output)
196
+ threshold = Severity.parse(args.fail_on)
197
+ failing = [f for f in result.reportable() if f.severity >= threshold]
198
+ return 1 if failing else 0
199
+
200
+
201
+ if __name__ == "__main__": # pragma: no cover
202
+ raise SystemExit(main())