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.
- modelbom/__init__.py +9 -0
- modelbom/__main__.py +5 -0
- modelbom/artifacts.py +696 -0
- modelbom/attack_paths.py +202 -0
- modelbom/cli.py +202 -0
- modelbom/code_rules.py +642 -0
- modelbom/deps.py +461 -0
- modelbom/discovery.py +126 -0
- modelbom/graph.py +257 -0
- modelbom/models.py +201 -0
- modelbom/pickle_scan.py +417 -0
- modelbom/py.typed +0 -0
- modelbom/report/__init__.py +16 -0
- modelbom/report/cyclonedx.py +219 -0
- modelbom/report/jsonfmt.py +78 -0
- modelbom/report/sarif.py +110 -0
- modelbom/report/text.py +60 -0
- modelbom/rules.py +350 -0
- modelbom/scanner.py +77 -0
- modelbom-0.1.0.dist-info/METADATA +265 -0
- modelbom-0.1.0.dist-info/RECORD +25 -0
- modelbom-0.1.0.dist-info/WHEEL +4 -0
- modelbom-0.1.0.dist-info/entry_points.txt +2 -0
- modelbom-0.1.0.dist-info/licenses/LICENSE +202 -0
- modelbom-0.1.0.dist-info/licenses/NOTICE +14 -0
modelbom/pickle_scan.py
ADDED
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
"""Static pickle analysis built on :func:`pickletools.genops`.
|
|
2
|
+
|
|
3
|
+
Nothing here ever unpickles data. The opcode stream is decoded and a small stack machine
|
|
4
|
+
tracks enough state to resolve which callables (``GLOBAL``, ``INST``, ``STACK_GLOBAL``) a pickle
|
|
5
|
+
would import when loaded. Those imports are then classified as dangerous, allowlisted,
|
|
6
|
+
framework classes (low risk) or unknown.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import io
|
|
12
|
+
import pickletools
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
|
|
15
|
+
from .models import Severity
|
|
16
|
+
|
|
17
|
+
_MARK = object()
|
|
18
|
+
_ANY = object()
|
|
19
|
+
|
|
20
|
+
_STRING_OPS = frozenset(
|
|
21
|
+
{
|
|
22
|
+
"STRING",
|
|
23
|
+
"BINSTRING",
|
|
24
|
+
"SHORT_BINSTRING",
|
|
25
|
+
"UNICODE",
|
|
26
|
+
"BINUNICODE",
|
|
27
|
+
"SHORT_BINUNICODE",
|
|
28
|
+
"BINUNICODE8",
|
|
29
|
+
}
|
|
30
|
+
)
|
|
31
|
+
_MEMO_PUT_OPS = frozenset({"PUT", "BINPUT", "LONG_BINPUT"})
|
|
32
|
+
_MEMO_GET_OPS = frozenset({"GET", "BINGET", "LONG_BINGET"})
|
|
33
|
+
_CALL_OPS = frozenset({"REDUCE", "BUILD", "NEWOBJ", "NEWOBJ_EX", "OBJ", "INST"})
|
|
34
|
+
|
|
35
|
+
# --- classification tables -------------------------------------------------------------------
|
|
36
|
+
|
|
37
|
+
_DANGEROUS_MODULES = frozenset(
|
|
38
|
+
{
|
|
39
|
+
"os",
|
|
40
|
+
"posix",
|
|
41
|
+
"nt",
|
|
42
|
+
"subprocess",
|
|
43
|
+
"sys",
|
|
44
|
+
"socket",
|
|
45
|
+
"shutil",
|
|
46
|
+
"runpy",
|
|
47
|
+
"pty",
|
|
48
|
+
"importlib",
|
|
49
|
+
"imp",
|
|
50
|
+
"ctypes",
|
|
51
|
+
"marshal",
|
|
52
|
+
"webbrowser",
|
|
53
|
+
"requests",
|
|
54
|
+
"urllib",
|
|
55
|
+
"urllib2",
|
|
56
|
+
"urllib3",
|
|
57
|
+
"httpx",
|
|
58
|
+
"http",
|
|
59
|
+
"aiohttp",
|
|
60
|
+
"ftplib",
|
|
61
|
+
"smtplib",
|
|
62
|
+
"telnetlib",
|
|
63
|
+
"paramiko",
|
|
64
|
+
"pickle",
|
|
65
|
+
"_pickle",
|
|
66
|
+
"cPickle",
|
|
67
|
+
"dill",
|
|
68
|
+
"cloudpickle",
|
|
69
|
+
"code",
|
|
70
|
+
"codeop",
|
|
71
|
+
"commands",
|
|
72
|
+
"popen2",
|
|
73
|
+
"multiprocessing",
|
|
74
|
+
"pdb",
|
|
75
|
+
"bdb",
|
|
76
|
+
"timeit",
|
|
77
|
+
"cProfile",
|
|
78
|
+
"profile",
|
|
79
|
+
"trace",
|
|
80
|
+
"zipimport",
|
|
81
|
+
"pkgutil",
|
|
82
|
+
"asyncio",
|
|
83
|
+
"signal",
|
|
84
|
+
"shelve",
|
|
85
|
+
"pexpect",
|
|
86
|
+
}
|
|
87
|
+
)
|
|
88
|
+
_DANGEROUS_MODULE_PREFIXES = ("torch.hub",)
|
|
89
|
+
_DANGEROUS_BUILTINS = frozenset(
|
|
90
|
+
{
|
|
91
|
+
"eval",
|
|
92
|
+
"exec",
|
|
93
|
+
"compile",
|
|
94
|
+
"open",
|
|
95
|
+
"__import__",
|
|
96
|
+
"getattr",
|
|
97
|
+
"setattr",
|
|
98
|
+
"delattr",
|
|
99
|
+
"globals",
|
|
100
|
+
"locals",
|
|
101
|
+
"vars",
|
|
102
|
+
"input",
|
|
103
|
+
"breakpoint",
|
|
104
|
+
"exit",
|
|
105
|
+
"quit",
|
|
106
|
+
}
|
|
107
|
+
)
|
|
108
|
+
_DANGEROUS_CALLABLES = frozenset(
|
|
109
|
+
{
|
|
110
|
+
("operator", "attrgetter"),
|
|
111
|
+
("operator", "methodcaller"),
|
|
112
|
+
("_operator", "attrgetter"),
|
|
113
|
+
("_operator", "methodcaller"),
|
|
114
|
+
("types", "FunctionType"),
|
|
115
|
+
("types", "CodeType"),
|
|
116
|
+
("types", "LambdaType"),
|
|
117
|
+
("io", "open"),
|
|
118
|
+
("_io", "open"),
|
|
119
|
+
("io", "FileIO"),
|
|
120
|
+
("_io", "FileIO"),
|
|
121
|
+
("torch", "load"),
|
|
122
|
+
("torch.serialization", "load"),
|
|
123
|
+
("numpy", "load"),
|
|
124
|
+
("numpy.lib.npyio", "load"),
|
|
125
|
+
("joblib", "load"),
|
|
126
|
+
("joblib.numpy_pickle", "load"),
|
|
127
|
+
("pandas", "read_pickle"),
|
|
128
|
+
("pandas.io.pickle", "read_pickle"),
|
|
129
|
+
}
|
|
130
|
+
)
|
|
131
|
+
_REVIEW_CALLABLES = {
|
|
132
|
+
("functools", "partial"): "can wrap arbitrary callables",
|
|
133
|
+
("_functools", "partial"): "can wrap arbitrary callables",
|
|
134
|
+
("torch.storage", "_load_from_bytes"): "performs a nested torch deserialization",
|
|
135
|
+
("builtins", "type"): "can construct new classes",
|
|
136
|
+
}
|
|
137
|
+
_SAFE_EXACT = frozenset(
|
|
138
|
+
{
|
|
139
|
+
("collections", "OrderedDict"),
|
|
140
|
+
("collections", "defaultdict"),
|
|
141
|
+
("collections", "deque"),
|
|
142
|
+
("collections", "Counter"),
|
|
143
|
+
("copyreg", "_reconstructor"),
|
|
144
|
+
("copy_reg", "_reconstructor"),
|
|
145
|
+
("copyreg", "__newobj__"),
|
|
146
|
+
("copyreg", "__newobj_ex__"),
|
|
147
|
+
("numpy", "ndarray"),
|
|
148
|
+
("numpy", "dtype"),
|
|
149
|
+
("numpy.core.multiarray", "_reconstruct"),
|
|
150
|
+
("numpy._core.multiarray", "_reconstruct"),
|
|
151
|
+
("numpy.core.multiarray", "scalar"),
|
|
152
|
+
("numpy._core.multiarray", "scalar"),
|
|
153
|
+
("numpy.core.numeric", "_frombuffer"),
|
|
154
|
+
("numpy._core.numeric", "_frombuffer"),
|
|
155
|
+
("torch", "Size"),
|
|
156
|
+
("torch", "device"),
|
|
157
|
+
("torch", "dtype"),
|
|
158
|
+
("torch.serialization", "_get_layout"),
|
|
159
|
+
("decimal", "Decimal"),
|
|
160
|
+
("fractions", "Fraction"),
|
|
161
|
+
("uuid", "UUID"),
|
|
162
|
+
("pathlib", "PosixPath"),
|
|
163
|
+
("pathlib", "WindowsPath"),
|
|
164
|
+
("pathlib", "PurePosixPath"),
|
|
165
|
+
("pathlib", "PureWindowsPath"),
|
|
166
|
+
}
|
|
167
|
+
)
|
|
168
|
+
_SAFE_BUILTINS = frozenset(
|
|
169
|
+
{
|
|
170
|
+
"set",
|
|
171
|
+
"frozenset",
|
|
172
|
+
"bytearray",
|
|
173
|
+
"bytes",
|
|
174
|
+
"slice",
|
|
175
|
+
"complex",
|
|
176
|
+
"range",
|
|
177
|
+
"list",
|
|
178
|
+
"dict",
|
|
179
|
+
"tuple",
|
|
180
|
+
"str",
|
|
181
|
+
"int",
|
|
182
|
+
"float",
|
|
183
|
+
"bool",
|
|
184
|
+
"object",
|
|
185
|
+
}
|
|
186
|
+
)
|
|
187
|
+
_SAFE_MODULE_PREFIXES = ("datetime", "numpy.dtypes")
|
|
188
|
+
_LOW_EXACT = {("_codecs", "encode"): "used by NumPy pickles to encode raw bytes", ("re", "_compile"): ""}
|
|
189
|
+
_FRAMEWORK_ROOTS = frozenset(
|
|
190
|
+
{
|
|
191
|
+
"torch",
|
|
192
|
+
"numpy",
|
|
193
|
+
"sklearn",
|
|
194
|
+
"xgboost",
|
|
195
|
+
"lightgbm",
|
|
196
|
+
"catboost",
|
|
197
|
+
"scipy",
|
|
198
|
+
"pandas",
|
|
199
|
+
"joblib",
|
|
200
|
+
"transformers",
|
|
201
|
+
"tokenizers",
|
|
202
|
+
}
|
|
203
|
+
)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
@dataclass
|
|
207
|
+
class PickleImport:
|
|
208
|
+
module: str
|
|
209
|
+
name: str
|
|
210
|
+
position: int
|
|
211
|
+
severity: Severity | None # None = allowlisted
|
|
212
|
+
reason: str
|
|
213
|
+
|
|
214
|
+
@property
|
|
215
|
+
def qualname(self) -> str:
|
|
216
|
+
return f"{self.module}.{self.name}" if self.name else self.module
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
@dataclass
|
|
220
|
+
class PickleReport:
|
|
221
|
+
imports: list[PickleImport] = field(default_factory=list)
|
|
222
|
+
pickles: int = 0
|
|
223
|
+
protocol: int | None = None
|
|
224
|
+
calls: int = 0
|
|
225
|
+
error: str | None = None
|
|
226
|
+
truncated: bool = False
|
|
227
|
+
bytes_analyzed: int = 0
|
|
228
|
+
|
|
229
|
+
@property
|
|
230
|
+
def dangerous(self) -> list[PickleImport]:
|
|
231
|
+
return [i for i in self.imports if i.severity == Severity.CRITICAL]
|
|
232
|
+
|
|
233
|
+
@property
|
|
234
|
+
def unknown(self) -> list[PickleImport]:
|
|
235
|
+
return [i for i in self.imports if i.severity == Severity.MEDIUM]
|
|
236
|
+
|
|
237
|
+
@property
|
|
238
|
+
def low(self) -> list[PickleImport]:
|
|
239
|
+
return [i for i in self.imports if i.severity == Severity.LOW]
|
|
240
|
+
|
|
241
|
+
def to_details(self) -> dict[str, object]:
|
|
242
|
+
return {
|
|
243
|
+
"pickles": self.pickles,
|
|
244
|
+
"protocol": self.protocol,
|
|
245
|
+
"calls": self.calls,
|
|
246
|
+
"imports": sorted({i.qualname for i in self.imports}),
|
|
247
|
+
"dangerous_imports": sorted({i.qualname for i in self.dangerous}),
|
|
248
|
+
"unknown_imports": sorted({i.qualname for i in self.unknown}),
|
|
249
|
+
"bytes_analyzed": self.bytes_analyzed,
|
|
250
|
+
"truncated": self.truncated,
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def classify(module: str, name: str) -> tuple[Severity | None, str]:
|
|
255
|
+
"""Return ``(severity, reason)``; severity ``None`` means allowlisted."""
|
|
256
|
+
if module == "__builtin__":
|
|
257
|
+
module = "builtins"
|
|
258
|
+
root = module.split(".", 1)[0]
|
|
259
|
+
if module == "builtins":
|
|
260
|
+
if name in _DANGEROUS_BUILTINS:
|
|
261
|
+
return Severity.CRITICAL, "evaluates code or accesses arbitrary attributes/files"
|
|
262
|
+
if name in _SAFE_BUILTINS:
|
|
263
|
+
return None, "builtin container type"
|
|
264
|
+
if (module, name) in _DANGEROUS_CALLABLES:
|
|
265
|
+
return Severity.CRITICAL, "loads or executes further code"
|
|
266
|
+
if root in _DANGEROUS_MODULES or module.startswith(_DANGEROUS_MODULE_PREFIXES):
|
|
267
|
+
return Severity.CRITICAL, f"module '{module}' can execute commands, code or network I/O"
|
|
268
|
+
if (module, name) in _REVIEW_CALLABLES:
|
|
269
|
+
return Severity.MEDIUM, _REVIEW_CALLABLES[(module, name)]
|
|
270
|
+
if (module, name) in _SAFE_EXACT or module.startswith(_SAFE_MODULE_PREFIXES):
|
|
271
|
+
return None, "allowlisted"
|
|
272
|
+
if module in ("torch._utils", "torch._tensor") and name.startswith("_rebuild"):
|
|
273
|
+
return None, "tensor reconstruction helper"
|
|
274
|
+
if module == "torch" and name.endswith("Storage"):
|
|
275
|
+
return None, "tensor storage type"
|
|
276
|
+
if (module, name) in _LOW_EXACT:
|
|
277
|
+
return Severity.LOW, _LOW_EXACT[(module, name)] or "allowlisted with review"
|
|
278
|
+
if root in _FRAMEWORK_ROOTS:
|
|
279
|
+
return Severity.LOW, "framework class (its own reconstruction code runs on load)"
|
|
280
|
+
return Severity.MEDIUM, "not on the allowlist"
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def _record(report: PickleReport, module: str, name: str, pos: int) -> None:
|
|
284
|
+
sev, reason = classify(module, name)
|
|
285
|
+
report.imports.append(PickleImport(module, name, pos, sev, reason))
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
def _pop(stack: list[object]) -> object:
|
|
289
|
+
return stack.pop() if stack else _ANY
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _apply_generic(stack: list[object], op: pickletools.OpcodeInfo) -> None:
|
|
293
|
+
before = op.stack_before
|
|
294
|
+
if pickletools.markobject in before:
|
|
295
|
+
idx = before.index(pickletools.markobject)
|
|
296
|
+
while stack and stack[-1] is not _MARK:
|
|
297
|
+
stack.pop()
|
|
298
|
+
if stack:
|
|
299
|
+
stack.pop()
|
|
300
|
+
for _ in range(idx):
|
|
301
|
+
_pop(stack)
|
|
302
|
+
else:
|
|
303
|
+
for _ in before:
|
|
304
|
+
_pop(stack)
|
|
305
|
+
for item in op.stack_after:
|
|
306
|
+
stack.append(_MARK if item is pickletools.markobject else _ANY)
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _split_global(arg: object) -> tuple[str, str]:
|
|
310
|
+
text = str(arg)
|
|
311
|
+
module, _, name = text.partition(" ")
|
|
312
|
+
return module.strip(), name.strip()
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
def _scan_one(stream: io.BytesIO, report: PickleReport, scratch: PickleReport) -> int:
|
|
316
|
+
"""Decode one pickle from the current stream position into ``scratch``.
|
|
317
|
+
|
|
318
|
+
Returns the offset just past ``STOP`` (or -1 if the stream ended first). Imports recorded
|
|
319
|
+
before an exception stay in ``scratch``: a real unpickler would already have executed them.
|
|
320
|
+
"""
|
|
321
|
+
stack: list[object] = []
|
|
322
|
+
memo: dict[int, object] = {}
|
|
323
|
+
end = -1
|
|
324
|
+
for op, arg, pos in pickletools.genops(stream):
|
|
325
|
+
name = op.name
|
|
326
|
+
position = pos if pos is not None else -1
|
|
327
|
+
if name == "PROTO":
|
|
328
|
+
if report.protocol is None and isinstance(arg, int):
|
|
329
|
+
report.protocol = arg
|
|
330
|
+
elif name in _STRING_OPS:
|
|
331
|
+
stack.append(arg if isinstance(arg, str) else _ANY)
|
|
332
|
+
elif name == "MEMOIZE":
|
|
333
|
+
memo[len(memo)] = stack[-1] if stack else _ANY
|
|
334
|
+
elif name in _MEMO_PUT_OPS:
|
|
335
|
+
memo[int(arg)] = stack[-1] if stack else _ANY
|
|
336
|
+
elif name in _MEMO_GET_OPS:
|
|
337
|
+
stack.append(memo.get(int(arg), _ANY))
|
|
338
|
+
elif name == "DUP":
|
|
339
|
+
stack.append(stack[-1] if stack else _ANY)
|
|
340
|
+
elif name == "GLOBAL":
|
|
341
|
+
module, gname = _split_global(arg)
|
|
342
|
+
_record(scratch, module, gname, position)
|
|
343
|
+
stack.append(_ANY)
|
|
344
|
+
elif name == "INST":
|
|
345
|
+
module, gname = _split_global(arg)
|
|
346
|
+
_record(scratch, module, gname, position)
|
|
347
|
+
_apply_generic(stack, op)
|
|
348
|
+
elif name == "STACK_GLOBAL":
|
|
349
|
+
gname = _pop(stack)
|
|
350
|
+
module = _pop(stack)
|
|
351
|
+
if isinstance(module, str) and isinstance(gname, str):
|
|
352
|
+
_record(scratch, module, gname, position)
|
|
353
|
+
else:
|
|
354
|
+
scratch.imports.append(
|
|
355
|
+
PickleImport(
|
|
356
|
+
"<dynamic>",
|
|
357
|
+
"",
|
|
358
|
+
position,
|
|
359
|
+
Severity.MEDIUM,
|
|
360
|
+
"STACK_GLOBAL operands could not be resolved statically",
|
|
361
|
+
)
|
|
362
|
+
)
|
|
363
|
+
stack.append(_ANY)
|
|
364
|
+
elif name in ("EXT1", "EXT2", "EXT4"):
|
|
365
|
+
scratch.imports.append(
|
|
366
|
+
PickleImport(
|
|
367
|
+
f"<extension:{arg}>",
|
|
368
|
+
"",
|
|
369
|
+
position,
|
|
370
|
+
Severity.MEDIUM,
|
|
371
|
+
"copyreg extension code resolves to a callable at load time",
|
|
372
|
+
)
|
|
373
|
+
)
|
|
374
|
+
stack.append(_ANY)
|
|
375
|
+
elif name == "STOP":
|
|
376
|
+
end = position + 1
|
|
377
|
+
break
|
|
378
|
+
else:
|
|
379
|
+
_apply_generic(stack, op)
|
|
380
|
+
if name in _CALL_OPS:
|
|
381
|
+
report.calls += 1
|
|
382
|
+
return end
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
def analyze_pickle(data: bytes, *, truncated: bool = False, max_pickles: int = 32) -> PickleReport:
|
|
386
|
+
"""Statically analyze one or more concatenated pickle streams in ``data``."""
|
|
387
|
+
report = PickleReport(truncated=truncated, bytes_analyzed=len(data))
|
|
388
|
+
stream = io.BytesIO(data)
|
|
389
|
+
offset = 0
|
|
390
|
+
while offset < len(data) and report.pickles < max_pickles:
|
|
391
|
+
if report.pickles > 0 and data[offset : offset + 1] != b"\x80":
|
|
392
|
+
break # trailing raw data (for example tensor storage in legacy torch files)
|
|
393
|
+
stream.seek(offset)
|
|
394
|
+
scratch = PickleReport()
|
|
395
|
+
plausible = report.pickles == 0 or looks_like_pickle(data[offset : offset + 2])
|
|
396
|
+
try:
|
|
397
|
+
end = _scan_one(stream, report, scratch)
|
|
398
|
+
except Exception as exc: # pickletools raises ValueError and friends on bad input
|
|
399
|
+
if plausible:
|
|
400
|
+
report.imports.extend(scratch.imports)
|
|
401
|
+
if report.pickles == 0:
|
|
402
|
+
report.error = f"{type(exc).__name__}: {exc}"
|
|
403
|
+
break
|
|
404
|
+
if plausible:
|
|
405
|
+
report.imports.extend(scratch.imports)
|
|
406
|
+
if end <= offset:
|
|
407
|
+
if report.pickles == 0:
|
|
408
|
+
report.error = "pickle stream ended without STOP"
|
|
409
|
+
break
|
|
410
|
+
report.pickles += 1
|
|
411
|
+
offset = end
|
|
412
|
+
return report
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def looks_like_pickle(head: bytes) -> bool:
|
|
416
|
+
"""Cheap check for a protocol 2+ pickle header."""
|
|
417
|
+
return len(head) >= 2 and head[0] == 0x80 and 2 <= head[1] <= 5
|
modelbom/py.typed
ADDED
|
File without changes
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""Report renderers: text, JSON, SARIF 2.1.0 and CycloneDX 1.6."""
|
|
2
|
+
|
|
3
|
+
from .cyclonedx import render_cyclonedx, to_cyclonedx
|
|
4
|
+
from .jsonfmt import render_json, to_dict
|
|
5
|
+
from .sarif import render_sarif, to_sarif
|
|
6
|
+
from .text import render_text
|
|
7
|
+
|
|
8
|
+
__all__ = [
|
|
9
|
+
"render_cyclonedx",
|
|
10
|
+
"render_json",
|
|
11
|
+
"render_sarif",
|
|
12
|
+
"render_text",
|
|
13
|
+
"to_cyclonedx",
|
|
14
|
+
"to_dict",
|
|
15
|
+
"to_sarif",
|
|
16
|
+
]
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""CycloneDX 1.6 AI-BOM (ML-BOM) output.
|
|
2
|
+
|
|
3
|
+
Components:
|
|
4
|
+
|
|
5
|
+
* ``machine-learning-model`` for local model artifacts and for hub / torch.hub references in code
|
|
6
|
+
* ``data`` for dataset files and hub datasets
|
|
7
|
+
* ``file`` for model configuration files (``config.json``, tokenizer configs, chat templates)
|
|
8
|
+
* ``library`` for Python dependencies (``pkg:pypi`` purls)
|
|
9
|
+
|
|
10
|
+
Findings attached to a component are emitted in the ``vulnerabilities`` section.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import posixpath
|
|
17
|
+
import uuid
|
|
18
|
+
from datetime import UTC, datetime
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from .. import __version__
|
|
22
|
+
from ..models import Artifact, ModelRef, ScanResult, Severity
|
|
23
|
+
from ..rules import get_rule
|
|
24
|
+
|
|
25
|
+
SPEC_VERSION = "1.6"
|
|
26
|
+
_REPO = "https://github.com/rajyavardhan01/modelbom"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _props(**values: Any) -> list[dict[str, str]]:
|
|
30
|
+
return [
|
|
31
|
+
{"name": f"modelbom:{k.replace('_', '-')}", "value": str(v)}
|
|
32
|
+
for k, v in values.items()
|
|
33
|
+
if v not in (None, "", [], {})
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _artifact_component(a: Artifact, risk: str | None) -> dict[str, Any]:
|
|
38
|
+
ctype = {"model": "machine-learning-model", "data": "data", "config": "file"}.get(a.kind, "file")
|
|
39
|
+
comp: dict[str, Any] = {
|
|
40
|
+
"type": ctype,
|
|
41
|
+
"bom-ref": a.ref,
|
|
42
|
+
"name": posixpath.basename(a.path),
|
|
43
|
+
}
|
|
44
|
+
if a.sha256:
|
|
45
|
+
comp["hashes"] = [{"alg": "SHA-256", "content": a.sha256}]
|
|
46
|
+
if ctype == "data":
|
|
47
|
+
comp["data"] = [{"type": "dataset", "name": posixpath.basename(a.path)}]
|
|
48
|
+
general = a.details.get("general") if isinstance(a.details.get("general"), dict) else {}
|
|
49
|
+
arch = general.get("general.architecture") if general else None
|
|
50
|
+
if ctype == "machine-learning-model" and arch:
|
|
51
|
+
comp["modelCard"] = {"modelParameters": {"modelArchitecture": str(arch)}}
|
|
52
|
+
comp["properties"] = _props(
|
|
53
|
+
path=a.path,
|
|
54
|
+
format=a.format,
|
|
55
|
+
serialization=a.serialization,
|
|
56
|
+
size=a.size,
|
|
57
|
+
parameters=a.details.get("parameters"),
|
|
58
|
+
tensors=a.details.get("tensors"),
|
|
59
|
+
risk=risk,
|
|
60
|
+
)
|
|
61
|
+
return comp
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _ref_component(ref: ModelRef, referenced_by: list[str], risk: str | None) -> dict[str, Any]:
|
|
65
|
+
is_dataset = ref.kind == "dataset"
|
|
66
|
+
comp: dict[str, Any] = {
|
|
67
|
+
"type": "data" if is_dataset else "machine-learning-model",
|
|
68
|
+
"bom-ref": ref.ref,
|
|
69
|
+
"name": ref.name,
|
|
70
|
+
"version": ref.revision if ref.pinned else "unpinned",
|
|
71
|
+
}
|
|
72
|
+
if ref.source == "huggingface":
|
|
73
|
+
base = "https://huggingface.co/" + ("datasets/" if is_dataset else "")
|
|
74
|
+
comp["externalReferences"] = [{"type": "distribution", "url": base + ref.name}]
|
|
75
|
+
if not is_dataset:
|
|
76
|
+
purl = "pkg:huggingface/" + ref.name.lower()
|
|
77
|
+
if ref.pinned and ref.revision and ref.revision != "<dynamic>":
|
|
78
|
+
purl += "@" + ref.revision.lower()
|
|
79
|
+
comp["purl"] = purl
|
|
80
|
+
else:
|
|
81
|
+
comp["externalReferences"] = [{"type": "vcs", "url": "https://github.com/" + ref.name}]
|
|
82
|
+
comp["purl"] = "pkg:github/" + ref.name.lower() + (f"@{ref.revision}" if ref.revision else "")
|
|
83
|
+
if is_dataset:
|
|
84
|
+
comp["data"] = [{"type": "dataset", "name": ref.name}]
|
|
85
|
+
comp["properties"] = _props(
|
|
86
|
+
source=ref.source,
|
|
87
|
+
pinned=str(ref.pinned).lower(),
|
|
88
|
+
trust_remote_code=str(ref.trust_remote_code).lower() if ref.trust_remote_code else None,
|
|
89
|
+
referenced_by=", ".join(referenced_by),
|
|
90
|
+
risk=risk,
|
|
91
|
+
)
|
|
92
|
+
return comp
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def to_cyclonedx(
|
|
96
|
+
result: ScanResult, *, serial: str | None = None, timestamp: str | None = None
|
|
97
|
+
) -> dict[str, Any]:
|
|
98
|
+
risk: dict[str, Severity] = {}
|
|
99
|
+
|
|
100
|
+
def bump(ref: str, sev: Severity) -> None:
|
|
101
|
+
if sev > Severity.INFO and (ref not in risk or risk[ref] < sev):
|
|
102
|
+
risk[ref] = sev
|
|
103
|
+
|
|
104
|
+
affects: list[tuple[str, Any]] = []
|
|
105
|
+
for f in result.reportable():
|
|
106
|
+
target = None
|
|
107
|
+
if f.details.get("artifact"):
|
|
108
|
+
target = f"artifact:{f.details['artifact']}"
|
|
109
|
+
elif f.details.get("ref"):
|
|
110
|
+
target = str(f.details["ref"])
|
|
111
|
+
elif f.details.get("package"):
|
|
112
|
+
target = f"pkg-component:{f.details['package']}"
|
|
113
|
+
if target:
|
|
114
|
+
bump(target, f.severity)
|
|
115
|
+
affects.append((target, f))
|
|
116
|
+
|
|
117
|
+
components: list[dict[str, Any]] = []
|
|
118
|
+
for a in result.artifacts:
|
|
119
|
+
r = risk.get(a.ref)
|
|
120
|
+
components.append(_artifact_component(a, r.label if r else None))
|
|
121
|
+
|
|
122
|
+
refs: dict[str, ModelRef] = {}
|
|
123
|
+
users: dict[str, list[str]] = {}
|
|
124
|
+
for ref in result.model_refs:
|
|
125
|
+
refs.setdefault(ref.ref, ref)
|
|
126
|
+
users.setdefault(ref.ref, []).append(f"{ref.path}:{ref.line}" if ref.line else ref.path)
|
|
127
|
+
for key, ref in refs.items():
|
|
128
|
+
r = risk.get(key)
|
|
129
|
+
components.append(_ref_component(ref, sorted(set(users[key])), r.label if r else None))
|
|
130
|
+
|
|
131
|
+
libs: dict[str, dict[str, Any]] = {}
|
|
132
|
+
for d in result.dependencies:
|
|
133
|
+
entry = libs.setdefault(d.name, {"versions": set(), "specs": set(), "sources": set()})
|
|
134
|
+
if d.version:
|
|
135
|
+
entry["versions"].add(d.version)
|
|
136
|
+
if d.specifier and d.kind == "declared":
|
|
137
|
+
entry["specs"].add(d.specifier)
|
|
138
|
+
entry["sources"].add(d.source)
|
|
139
|
+
lib_refs: dict[str, str] = {}
|
|
140
|
+
for name in sorted(libs):
|
|
141
|
+
entry = libs[name]
|
|
142
|
+
version = sorted(entry["versions"])[0] if entry["versions"] else None
|
|
143
|
+
purl = f"pkg:pypi/{name}" + (f"@{version}" if version else "")
|
|
144
|
+
lib_refs[name] = purl
|
|
145
|
+
comp: dict[str, Any] = {"type": "library", "bom-ref": purl, "name": name, "purl": purl}
|
|
146
|
+
if version:
|
|
147
|
+
comp["version"] = version
|
|
148
|
+
r = risk.get(f"pkg-component:{name}")
|
|
149
|
+
comp["properties"] = _props(
|
|
150
|
+
declared=", ".join(sorted(entry["specs"])),
|
|
151
|
+
sources=", ".join(sorted(entry["sources"])),
|
|
152
|
+
risk=r.label if r else None,
|
|
153
|
+
)
|
|
154
|
+
components.append(comp)
|
|
155
|
+
|
|
156
|
+
def resolve(target: str) -> str | None:
|
|
157
|
+
if target.startswith("pkg-component:"):
|
|
158
|
+
return lib_refs.get(target.split(":", 1)[1])
|
|
159
|
+
return target if any(c["bom-ref"] == target for c in components) else None
|
|
160
|
+
|
|
161
|
+
vulnerabilities: list[dict[str, Any]] = []
|
|
162
|
+
for target, f in affects:
|
|
163
|
+
bom_ref = resolve(target)
|
|
164
|
+
if bom_ref is None:
|
|
165
|
+
continue
|
|
166
|
+
rule = get_rule(f.rule_id)
|
|
167
|
+
vuln: dict[str, Any] = {
|
|
168
|
+
"bom-ref": f"vuln:{f.rule_id}:{f.fingerprint}",
|
|
169
|
+
"id": str(f.details.get("vuln_id") or f.rule_id),
|
|
170
|
+
"source": (
|
|
171
|
+
{"name": "OSV", "url": f"https://osv.dev/vulnerability/{f.details['vuln_id']}"}
|
|
172
|
+
if f.details.get("vuln_id")
|
|
173
|
+
else {"name": "modelbom", "url": rule.help_uri}
|
|
174
|
+
),
|
|
175
|
+
"ratings": [{"severity": f.severity.label, "method": "other"}],
|
|
176
|
+
"description": rule.title,
|
|
177
|
+
"detail": f.message,
|
|
178
|
+
"recommendation": rule.remediation,
|
|
179
|
+
"affects": [{"ref": bom_ref}],
|
|
180
|
+
}
|
|
181
|
+
cwes = [int(c.split("-", 1)[1]) for c in rule.cwe if c.startswith("CWE-")]
|
|
182
|
+
if cwes:
|
|
183
|
+
vuln["cwes"] = cwes
|
|
184
|
+
vulnerabilities.append(vuln)
|
|
185
|
+
|
|
186
|
+
project = "project"
|
|
187
|
+
root_name = posixpath.basename(result.root.rstrip("/\\").replace("\\", "/")) or "project"
|
|
188
|
+
bom: dict[str, Any] = {
|
|
189
|
+
"bomFormat": "CycloneDX",
|
|
190
|
+
"specVersion": SPEC_VERSION,
|
|
191
|
+
"serialNumber": serial or f"urn:uuid:{uuid.uuid4()}",
|
|
192
|
+
"version": 1,
|
|
193
|
+
"metadata": {
|
|
194
|
+
"timestamp": timestamp
|
|
195
|
+
or datetime.now(UTC).isoformat(timespec="seconds").replace("+00:00", "Z"),
|
|
196
|
+
"tools": {
|
|
197
|
+
"components": [
|
|
198
|
+
{
|
|
199
|
+
"type": "application",
|
|
200
|
+
"name": "modelbom",
|
|
201
|
+
"version": __version__,
|
|
202
|
+
"externalReferences": [{"type": "vcs", "url": _REPO}],
|
|
203
|
+
}
|
|
204
|
+
]
|
|
205
|
+
},
|
|
206
|
+
"component": {"type": "application", "bom-ref": project, "name": root_name},
|
|
207
|
+
},
|
|
208
|
+
"components": components,
|
|
209
|
+
"dependencies": [
|
|
210
|
+
{"ref": project, "dependsOn": [c["bom-ref"] for c in components]},
|
|
211
|
+
],
|
|
212
|
+
}
|
|
213
|
+
if vulnerabilities:
|
|
214
|
+
bom["vulnerabilities"] = vulnerabilities
|
|
215
|
+
return bom
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def render_cyclonedx(result: ScanResult) -> str:
|
|
219
|
+
return json.dumps(to_cyclonedx(result), indent=2) + "\n"
|