aisbom-cli 1.3.1__tar.gz → 1.3.2__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aisbom-cli
3
- Version: 1.3.1
3
+ Version: 1.3.2
4
4
  Summary: An AI Supply Chain security tool that that detects Pickle bombs and generates CycloneDX SBOMs for Machine Learning models.
5
5
  License-File: LICENSE
6
6
  Author: Ajoy L
@@ -81,7 +81,10 @@ A typical scan against a project with mixed artifacts:
81
81
  │ │ │ __class__, __mro__, __subclasses__) │ │
82
82
  │ exfil.onnx │ ONNX │ CRITICAL (ONNX External Data Escapes Model │ UNKNOWN │
83
83
  │ │ │ Directory: ../../../etc/passwd) │ │
84
+ │ sklearn_pipeline.joblib │ Joblib │ CRITICAL (RCE Detected: posix.system) │ UNKNOWN │
85
+ │ features.npy │ NumPy │ CRITICAL (RCE Detected: builtins.eval) │ UNKNOWN │
84
86
  │ detector.onnx │ ONNX │ LOW │ UNKNOWN │
87
+ │ embeddings.npy │ NumPy │ LOW │ UNKNOWN │
85
88
  │ llama-3-quant.gguf │ GGUF │ LOW │ LEGAL RISK (cc-by-nc-sa-4.0) │
86
89
  │ safe_model.safetensors │ SafeTensors │ LOW │ PASS │
87
90
  │ restricted_model.safetensors │ SafeTensors │ LOW │ LEGAL RISK (cc-by-nc-4.0) │
@@ -94,7 +97,10 @@ A compliant `sbom.json` (CycloneDX v1.6) including SHA256 hashes and license dat
94
97
 
95
98
  | Format | Extensions | What AIsbom looks for |
96
99
  |---|---|---|
97
- | **PyTorch / Pickle** | `.pt` `.pth` `.bin` | Dangerous globals in the pickle opcodes, including indirect-execution gadgets. Concatenated streams are all scanned — a legacy `torch.save` file hides its object behind three header pickles — and non-standard containers (7z, rar, xz…) are flagged. If a file is so full of streams that the walk hits its work limit, the scan says so rather than reporting clean. |
100
+ | **PyTorch / Pickle** | `.pt` `.pth` `.bin` `.pkl` `.pickle` | Dangerous globals in the pickle opcodes, including indirect-execution gadgets. Concatenated streams are all scanned — a legacy `torch.save` file hides its object behind three header pickles — and non-standard containers (7z, rar, xz…) are flagged. If a file is so full of streams that the walk hits its work limit, the scan says so rather than reporting clean. |
101
+ | **joblib** | `.joblib` | The pickle inside the container, whichever codec joblib chose (zlib, gzip, bz2, lzma/xz, and the legacy `ZF` format), plus uncompressed files. A payload placed *after* an array — where a real model puts its weights — is found. |
102
+ | **dill** | `.dill` | Everything the pickle path finds, plus dill's own code-reconstruction globals: a dill'd function or lambda is a marshalled code object rebuilt on load, and is reported as CRITICAL. |
103
+ | **NumPy** | `.npy` `.npz` | The pickle stream behind an `allow_pickle` object array. Each `.npz` member is opened, including ones whose checksum or header has been tampered with. |
98
104
  | **Keras** | `.keras` `.h5` `.hdf5` | `Lambda` layers and embedded marshalled code objects in the model config — an actively exploited RCE vector. |
99
105
  | **GGUF** | `.gguf` | License and architecture metadata, plus the embedded Jinja **chat template**, checked for sandbox-escape constructs. |
100
106
  | **ONNX** | `.onnx` | Producer/opset/IR metadata, custom operators, and external-data paths that point outside the model directory. |
@@ -402,6 +408,17 @@ Attribute names are matched **exactly, never as substrings**, so ordinary global
402
408
 
403
409
  Pickle is not the only way a model file gets code to run. Each of the other formats has its own vector, and each is read as inert data:
404
410
 
411
+ **joblib, dill and NumPy object arrays** (`.joblib`, `.dill`, `.npy`, `.npz`) are pickle underneath — the everyday serialization of scikit-learn and scientific Python, carrying exactly the arbitrary-code-execution risk of a `.pt`, and opened by almost nothing that calls itself an SBOM tool. AIsbom reads them without importing joblib, dill or numpy: the compression is standard-library, the `.npy` header is parsed by hand, and nothing is ever unpickled.
412
+
413
+ Two things about these formats are worth stating plainly:
414
+
415
+ - **A raw array block does not end the scan.** joblib writes its pickle up to an array, dumps the raw buffer inline, then resumes pickling — which stops an opcode disassembly dead a few hundred bytes into the file. Since every real model has weights, "after the first array" is the natural place for a payload. The remaining bytes get a second pass that recovers globals directly, so a dangerous import behind an array block is still reported. That pass reads bytes rather than structure, so it recognises *known* sinks only: in strict mode it does not contribute unrecognized-import findings, and it cannot judge a dual-use constructor like `operator.methodcaller("system")`, because the argument that decides is a stack relationship it has no stack for.
416
+ - **A declared dtype never decides whether to look.** The `.npy` header is attacker-supplied, so a pickle sitting behind a header claiming `'<f8'` would otherwise be a one-line evasion. The data section is disassembled whatever the header says. What the header *does* affect is the reported risk: an array of ordinary numbers with no pickle in it is LOW, not "pickle present".
417
+
418
+ - **No limit ends in a clean verdict.** Four bounds apply here — the file-read budget, the `.npz` member count, the decompressor's output cap, and the disassembler's stream budget — and each one leaves bytes unexamined. Hitting any of them reports `MEDIUM (Pickle Scan Incomplete)` rather than passing the prefix off as the whole file. A limit that reports "clean" is not a safety measure; it is a hiding place with a length attached. A real finding still outranks the marker.
419
+
420
+ joblib's `lz4` and `zstd` codecs have no standard-library decompressor. Following the same reasoning as 7z containers, those are **named but not opened** — `MEDIUM (Unscanned Container: lz4)` — rather than pulling a native dependency into every install and every standalone binary. That is an honest "we did not read these bytes", which is a different answer from a clean scan.
421
+
405
422
  **SafeTensors and GGUF** use binary formats with structured headers — AIsbom parses these directly to extract metadata (artifact names, license info, architecture details) without loading tensor weights.
406
423
 
407
424
  **Keras** (`.keras`, `.h5`, `.hdf5`) carries a different execution vector: a `Lambda` layer stores an arbitrary Python callable in the model config as a base64-encoded marshalled code object, and `load_model` runs it. AIsbom reads the config out of both containers — the `.keras` zip and the legacy HDF5 attribute — and flags `Lambda` layers and embedded code objects as CRITICAL. The payload is identified from its header bytes and **never unmarshalled**. A truncated or corrupted container is still scanned rather than skipped, so damaging a file is not a way to hide a payload.
@@ -56,7 +56,10 @@ A typical scan against a project with mixed artifacts:
56
56
  │ │ │ __class__, __mro__, __subclasses__) │ │
57
57
  │ exfil.onnx │ ONNX │ CRITICAL (ONNX External Data Escapes Model │ UNKNOWN │
58
58
  │ │ │ Directory: ../../../etc/passwd) │ │
59
+ │ sklearn_pipeline.joblib │ Joblib │ CRITICAL (RCE Detected: posix.system) │ UNKNOWN │
60
+ │ features.npy │ NumPy │ CRITICAL (RCE Detected: builtins.eval) │ UNKNOWN │
59
61
  │ detector.onnx │ ONNX │ LOW │ UNKNOWN │
62
+ │ embeddings.npy │ NumPy │ LOW │ UNKNOWN │
60
63
  │ llama-3-quant.gguf │ GGUF │ LOW │ LEGAL RISK (cc-by-nc-sa-4.0) │
61
64
  │ safe_model.safetensors │ SafeTensors │ LOW │ PASS │
62
65
  │ restricted_model.safetensors │ SafeTensors │ LOW │ LEGAL RISK (cc-by-nc-4.0) │
@@ -69,7 +72,10 @@ A compliant `sbom.json` (CycloneDX v1.6) including SHA256 hashes and license dat
69
72
 
70
73
  | Format | Extensions | What AIsbom looks for |
71
74
  |---|---|---|
72
- | **PyTorch / Pickle** | `.pt` `.pth` `.bin` | Dangerous globals in the pickle opcodes, including indirect-execution gadgets. Concatenated streams are all scanned — a legacy `torch.save` file hides its object behind three header pickles — and non-standard containers (7z, rar, xz…) are flagged. If a file is so full of streams that the walk hits its work limit, the scan says so rather than reporting clean. |
75
+ | **PyTorch / Pickle** | `.pt` `.pth` `.bin` `.pkl` `.pickle` | Dangerous globals in the pickle opcodes, including indirect-execution gadgets. Concatenated streams are all scanned — a legacy `torch.save` file hides its object behind three header pickles — and non-standard containers (7z, rar, xz…) are flagged. If a file is so full of streams that the walk hits its work limit, the scan says so rather than reporting clean. |
76
+ | **joblib** | `.joblib` | The pickle inside the container, whichever codec joblib chose (zlib, gzip, bz2, lzma/xz, and the legacy `ZF` format), plus uncompressed files. A payload placed *after* an array — where a real model puts its weights — is found. |
77
+ | **dill** | `.dill` | Everything the pickle path finds, plus dill's own code-reconstruction globals: a dill'd function or lambda is a marshalled code object rebuilt on load, and is reported as CRITICAL. |
78
+ | **NumPy** | `.npy` `.npz` | The pickle stream behind an `allow_pickle` object array. Each `.npz` member is opened, including ones whose checksum or header has been tampered with. |
73
79
  | **Keras** | `.keras` `.h5` `.hdf5` | `Lambda` layers and embedded marshalled code objects in the model config — an actively exploited RCE vector. |
74
80
  | **GGUF** | `.gguf` | License and architecture metadata, plus the embedded Jinja **chat template**, checked for sandbox-escape constructs. |
75
81
  | **ONNX** | `.onnx` | Producer/opset/IR metadata, custom operators, and external-data paths that point outside the model directory. |
@@ -377,6 +383,17 @@ Attribute names are matched **exactly, never as substrings**, so ordinary global
377
383
 
378
384
  Pickle is not the only way a model file gets code to run. Each of the other formats has its own vector, and each is read as inert data:
379
385
 
386
+ **joblib, dill and NumPy object arrays** (`.joblib`, `.dill`, `.npy`, `.npz`) are pickle underneath — the everyday serialization of scikit-learn and scientific Python, carrying exactly the arbitrary-code-execution risk of a `.pt`, and opened by almost nothing that calls itself an SBOM tool. AIsbom reads them without importing joblib, dill or numpy: the compression is standard-library, the `.npy` header is parsed by hand, and nothing is ever unpickled.
387
+
388
+ Two things about these formats are worth stating plainly:
389
+
390
+ - **A raw array block does not end the scan.** joblib writes its pickle up to an array, dumps the raw buffer inline, then resumes pickling — which stops an opcode disassembly dead a few hundred bytes into the file. Since every real model has weights, "after the first array" is the natural place for a payload. The remaining bytes get a second pass that recovers globals directly, so a dangerous import behind an array block is still reported. That pass reads bytes rather than structure, so it recognises *known* sinks only: in strict mode it does not contribute unrecognized-import findings, and it cannot judge a dual-use constructor like `operator.methodcaller("system")`, because the argument that decides is a stack relationship it has no stack for.
391
+ - **A declared dtype never decides whether to look.** The `.npy` header is attacker-supplied, so a pickle sitting behind a header claiming `'<f8'` would otherwise be a one-line evasion. The data section is disassembled whatever the header says. What the header *does* affect is the reported risk: an array of ordinary numbers with no pickle in it is LOW, not "pickle present".
392
+
393
+ - **No limit ends in a clean verdict.** Four bounds apply here — the file-read budget, the `.npz` member count, the decompressor's output cap, and the disassembler's stream budget — and each one leaves bytes unexamined. Hitting any of them reports `MEDIUM (Pickle Scan Incomplete)` rather than passing the prefix off as the whole file. A limit that reports "clean" is not a safety measure; it is a hiding place with a length attached. A real finding still outranks the marker.
394
+
395
+ joblib's `lz4` and `zstd` codecs have no standard-library decompressor. Following the same reasoning as 7z containers, those are **named but not opened** — `MEDIUM (Unscanned Container: lz4)` — rather than pulling a native dependency into every install and every standalone binary. That is an honest "we did not read these bytes", which is a different answer from a clean scan.
396
+
380
397
  **SafeTensors and GGUF** use binary formats with structured headers — AIsbom parses these directly to extract metadata (artifact names, license info, architecture details) without loading tensor weights.
381
398
 
382
399
  **Keras** (`.keras`, `.h5`, `.hdf5`) carries a different execution vector: a `Lambda` layer stores an arbitrary Python callable in the model config as a base64-encoded marshalled code object, and `load_model` runs it. AIsbom reads the config out of both containers — the `.keras` zip and the legacy HDF5 attribute — and flags `Lambda` layers and embedded code objects as CRITICAL. The payload is identified from its header bytes and **never unmarshalled**. A truncated or corrupted container is still scanned rather than skipped, so damaging a file is not a way to hide a payload.
@@ -313,14 +313,6 @@ CASES: tuple[BypassCase, ...] = (
313
313
  "so nothing is scanned. Fixed in picklescan 0.0.22."
314
314
  ),
315
315
  builder=_build_nonstandard_extension,
316
- limitation=(
317
- "The only outright miss in the corpus: the scan reports `No AI models found` "
318
- "and emits zero artifacts, so a user gets a clean run on a file carrying a "
319
- "payload. Nothing subtle blocks this — discovery is extension-driven and "
320
- "`.p` is not on the list. picklescan closed it in 0.0.22 and AIsbom has not, "
321
- "which is precisely why the case stays on the scorecard at "
322
- "`expected=detected`."
323
- ),
324
316
  ),
325
317
  BypassCase(
326
318
  id="cve-2025-1944-zip-filename-tamper",
@@ -0,0 +1,304 @@
1
+ """Locate the pickle stream inside the wrapper formats that carry one.
2
+
3
+ joblib, dill and numpy's object arrays are the everyday serialization formats of
4
+ scientific Python, and every one of them is pickle underneath — the same
5
+ arbitrary-code-execution risk as a bare ``.pkl``, wrapped in a container that
6
+ generic tooling does not open.
7
+
8
+ Nothing in this module imports joblib, numpy or dill. The compression is stdlib,
9
+ the ``.npy`` header is parsed by hand, and the payload is never unpickled — it is
10
+ handed back as bytes for the disassembler to read. That is deliberate twice over:
11
+ a scanner that loads the artifact to inspect it has already lost, and pulling a
12
+ scientific-Python stack into the package would put it into every install and
13
+ every standalone binary for the sake of reading bytes we can read ourselves.
14
+
15
+ Everything here is bounded. A container is an attacker-controlled input, so a
16
+ decompressor is never handed an unbounded output buffer and a declared header
17
+ length is never trusted far enough to allocate against it.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import ast
23
+ import bz2
24
+ import lzma
25
+ import re
26
+ import zlib
27
+ from typing import Any, Dict, Tuple
28
+
29
+ # Fallback ceiling on any single decompressed payload: a compression bomb must
30
+ # cost the same as a large ordinary file, not more. The decompressors below are
31
+ # all incremental and take this as a `max_length`, so the bomb is never expanded
32
+ # in the first place.
33
+ #
34
+ # Callers pass their own budget — the scanner passes the same figure it used to
35
+ # read the file, so a remote scan that fetched 2MB does not then expand 16.
36
+ DECOMPRESS_MAX_BYTES = 16 * 1024 * 1024
37
+
38
+ # `.npy` declares its header length in the file. Cap what we will honour: the
39
+ # real headers are a few dozen bytes, and a declared length is exactly the field
40
+ # an attacker would inflate.
41
+ NPY_MAX_HEADER_BYTES = 1 * 1024 * 1024
42
+
43
+ NPY_MAGIC = b"\x93NUMPY"
44
+
45
+ # joblib's pre-0.10 container: a two-byte tag, a decimal length, then zlib data.
46
+ # Still readable today, and still a way to carry a pickle past a scanner that
47
+ # only knows the modern layout.
48
+ JOBLIB_ZFILE_MAGIC = b"ZF"
49
+
50
+ # Compression formats joblib writes that the standard library can open. The
51
+ # label is what gets reported, so it is the name a user would recognise.
52
+ _GZIP = "gzip"
53
+ _BZ2 = "bz2"
54
+ _LZMA = "lzma"
55
+ _XZ = "xz"
56
+ _ZLIB = "zlib"
57
+
58
+ SUPPORTED_COMPRESSION = (_ZLIB, _GZIP, _BZ2, _LZMA, _XZ)
59
+
60
+ # Formats joblib also supports whose decompressors are not in the standard
61
+ # library. Naming one is not the same as reading it — see `describe_container`.
62
+ _MAGIC_UNSUPPORTED = (
63
+ (b"\x04\x22\x4d\x18", "lz4"),
64
+ (b"\x28\xb5\x2f\xfd", "zstd"),
65
+ )
66
+
67
+ _MAGIC_SUPPORTED = (
68
+ (b"\x1f\x8b", _GZIP),
69
+ (b"BZh", _BZ2),
70
+ (b"\xfd7zXZ\x00", _XZ),
71
+ (b"\x5d\x00\x00", _LZMA),
72
+ )
73
+
74
+
75
+ def _looks_like_zlib(head: bytes) -> bool:
76
+ """True for a zlib stream header (RFC 1950).
77
+
78
+ zlib has no magic number, only a two-byte header with a checksum property:
79
+ the low nibble of the first byte is the compression method (8 = deflate) and
80
+ the 16-bit big-endian pair is a multiple of 31. Testing both is what keeps
81
+ an ordinary binary file that happens to start with 0x78 from being mistaken
82
+ for a compressed container.
83
+ """
84
+ if len(head) < 2:
85
+ return False
86
+ if head[0] & 0x0F != 8:
87
+ return False
88
+ return ((head[0] << 8) | head[1]) % 31 == 0
89
+
90
+
91
+ def detect_compression(head: bytes) -> Tuple[str | None, bool]:
92
+ """Return ``(label, readable)`` for the compression ``head`` begins with.
93
+
94
+ ``readable`` is False for a format we can name but not open, which is a
95
+ materially different answer from "not compressed" and is reported as such
96
+ rather than being quietly treated as a clean scan.
97
+ """
98
+ if not head:
99
+ return None, False
100
+ for magic, label in _MAGIC_SUPPORTED:
101
+ if head.startswith(magic):
102
+ return label, True
103
+ for magic, label in _MAGIC_UNSUPPORTED:
104
+ if head.startswith(magic):
105
+ return label, False
106
+ if _looks_like_zlib(head):
107
+ return _ZLIB, True
108
+ return None, False
109
+
110
+
111
+ def decompress(data: bytes, label: str, limit: int = DECOMPRESS_MAX_BYTES) -> Tuple[bytes | None, bool]:
112
+ """Inflate ``data`` with the named codec; return ``(payload, complete)``.
113
+
114
+ ``complete`` is False when the decompressor stopped before the end of the
115
+ stream — because it hit ``limit``, or because the compressed data itself was
116
+ cut short. That distinction has to reach the caller. A payload placed after
117
+ a large compressible value would otherwise sit in the part we never expanded
118
+ while the prefix scanned clean, and a cap nobody reports is somewhere to hide
119
+ a payload rather than a safety measure.
120
+
121
+ Returns whatever was recovered before an error when a stream is corrupt — a
122
+ damaged tail must not discard the front, the same reasoning that makes a
123
+ broken zip member worth reading anyway. ``(None, False)`` means nothing at
124
+ all could be read.
125
+ """
126
+ if not data:
127
+ return None, False
128
+ try:
129
+ if label == _ZLIB:
130
+ engine = zlib.decompressobj()
131
+ elif label == _GZIP:
132
+ # 16 + MAX_WBITS selects the gzip wrapper.
133
+ engine = zlib.decompressobj(16 + zlib.MAX_WBITS)
134
+ elif label == _BZ2:
135
+ engine = bz2.BZ2Decompressor()
136
+ elif label in (_LZMA, _XZ):
137
+ # FORMAT_AUTO reads both the `.xz` container and the older
138
+ # standalone `.lzma` framing joblib still emits.
139
+ engine = lzma.LZMADecompressor(format=lzma.FORMAT_AUTO)
140
+ else:
141
+ return None, False
142
+
143
+ out = engine.decompress(data, limit)
144
+ # Every one of these decompressors exposes `eof`, which is True only
145
+ # once the stream's own end marker has been consumed.
146
+ return (out or None), bool(getattr(engine, "eof", False))
147
+ except Exception:
148
+ return None, False
149
+
150
+
151
+ def unwrap_zfile(data: bytes, limit: int = DECOMPRESS_MAX_BYTES) -> Tuple[bytes | None, bool]:
152
+ """Inflate joblib's legacy ``ZF`` container; return ``(payload, complete)``.
153
+
154
+ Layout is the tag, a space-padded decimal length, then a zlib stream. The
155
+ declared length is read past rather than trusted — the decompressor stops at
156
+ the real end of the stream, so a lie in that field buys nothing.
157
+ """
158
+ if not data.startswith(JOBLIB_ZFILE_MAGIC):
159
+ return None, False
160
+ # The length field is fixed-width ASCII in every version that wrote it.
161
+ body = data[len(JOBLIB_ZFILE_MAGIC):]
162
+ match = re.match(rb"\s*([0-9]+)\s*", body[:32])
163
+ start = match.end() if match else 0
164
+ return decompress(body[start:], _ZLIB, limit)
165
+
166
+
167
+ def describe_container(data: bytes, limit: int = DECOMPRESS_MAX_BYTES) -> Dict[str, Any]:
168
+ """Unwrap one layer of compression, if any, and say what was found.
169
+
170
+ Returns a dict with ``compression`` (label or None), ``readable`` (whether
171
+ we could open it), ``payload`` (the inner bytes, or None), and ``truncated``
172
+ (whether the decompressor stopped short of the stream's end). An unreadable
173
+ container yields a payload of None with the format still named, so the
174
+ caller can report "we did not read these bytes" instead of "clean" — and a
175
+ truncated one says so rather than passing off a prefix as the whole file.
176
+ """
177
+ result: Dict[str, Any] = {
178
+ "compression": None, "readable": True, "payload": data, "truncated": False,
179
+ }
180
+
181
+ if data.startswith(JOBLIB_ZFILE_MAGIC):
182
+ payload, complete = unwrap_zfile(data, limit)
183
+ result.update(compression="zfile", readable=payload is not None,
184
+ payload=payload, truncated=payload is not None and not complete)
185
+ return result
186
+
187
+ label, readable = detect_compression(data[:16])
188
+ if label is None:
189
+ return result
190
+
191
+ result["compression"] = label
192
+ if not readable:
193
+ result.update(readable=False, payload=None)
194
+ return result
195
+
196
+ payload, complete = decompress(data, label, limit)
197
+ result.update(readable=payload is not None, payload=payload,
198
+ truncated=payload is not None and not complete)
199
+ return result
200
+
201
+
202
+ def parse_npy_header(data: bytes) -> Dict[str, Any] | None:
203
+ """Read a ``.npy`` header, returning where the data section starts.
204
+
205
+ The header is a Python dict *literal* — it is parsed with
206
+ ``ast.literal_eval``, which builds values and cannot call anything, and only
207
+ after the declared length has been bounds-checked. Nothing here evaluates
208
+ the file's contents; a malformed header yields None rather than an
209
+ exception, because a file we cannot parse still gets scanned by the caller.
210
+ """
211
+ if not data.startswith(NPY_MAGIC) or len(data) < 10:
212
+ return None
213
+
214
+ major = data[6]
215
+ if major == 1:
216
+ length_field, header_start = 2, 10
217
+ else:
218
+ # v2 and v3 widened the length field to four bytes.
219
+ length_field, header_start = 4, 12
220
+ if len(data) < header_start:
221
+ return None
222
+
223
+ header_len = int.from_bytes(data[8:8 + length_field], "little")
224
+ if header_len <= 0 or header_len > NPY_MAX_HEADER_BYTES:
225
+ return None
226
+
227
+ raw_header = data[header_start:header_start + header_len]
228
+ if len(raw_header) < header_len:
229
+ # Truncated: the data offset is still known, which is what matters.
230
+ raw_header = data[header_start:]
231
+
232
+ descr: Any = None
233
+ fortran_order = None
234
+ shape = None
235
+ try:
236
+ parsed = ast.literal_eval(raw_header.decode("latin-1").strip())
237
+ if isinstance(parsed, dict):
238
+ descr = parsed.get("descr")
239
+ fortran_order = parsed.get("fortran_order")
240
+ shape = parsed.get("shape")
241
+ except Exception:
242
+ # A header we cannot parse is not a reason to stop: fall back to reading
243
+ # the dtype string out of it, and failing that, carry on with the offset
244
+ # alone. The data section is scanned either way.
245
+ match = re.search(rb"'descr'\s*:\s*'([^']*)'", raw_header)
246
+ if match:
247
+ descr = match.group(1).decode("latin-1")
248
+
249
+ return {
250
+ "version": f"{major}.{data[7]}",
251
+ "descr": descr,
252
+ "fortran_order": fortran_order,
253
+ "shape": shape,
254
+ "data_offset": header_start + header_len,
255
+ "object_dtype": _is_object_dtype(descr),
256
+ }
257
+
258
+
259
+ def _is_object_dtype(descr: Any) -> bool:
260
+ """True if a dtype descriptor carries Python objects anywhere inside it.
261
+
262
+ ``'|O'`` is the plain object array. A structured dtype is a list of
263
+ ``(name, format)`` or ``(name, format, shape)`` entries, and only the
264
+ *format* element is a dtype — searching the whole entry reads field names as
265
+ type codes, so an ordinary ``[('FOO', '<i4')]`` came back True on the
266
+ strength of the letter O in its name.
267
+
268
+ Note this only chooses the reported risk label, never whether to scan: the
269
+ data section is disassembled whatever the header claims, because the header
270
+ is attacker-supplied. Getting this wrong is noise, not a bypass.
271
+ """
272
+ if descr is None:
273
+ return False
274
+ if isinstance(descr, str):
275
+ # Strip the byte-order/size prefix, leaving the type character.
276
+ return "O" in descr.lstrip("|<>=")
277
+ if isinstance(descr, list):
278
+ # Structured: inspect each field's format, never its name or shape.
279
+ return any(
280
+ _is_object_dtype(field[1])
281
+ for field in descr
282
+ if isinstance(field, (list, tuple)) and len(field) >= 2
283
+ )
284
+ if isinstance(descr, tuple) and len(descr) == 2:
285
+ # A subarray format, `(format, shape)` — the dtype is the first element.
286
+ return _is_object_dtype(descr[0])
287
+ return False
288
+
289
+
290
+ def npy_data_section(data: bytes, limit: int = DECOMPRESS_MAX_BYTES) -> Tuple[bytes | None, Dict[str, Any] | None]:
291
+ """Return ``(data_section, header)`` for a ``.npy`` buffer.
292
+
293
+ The data section is returned whatever the declared dtype says. Deciding by
294
+ the header first would mean trusting an attacker-supplied field to tell us
295
+ whether to look — and a pickle behind a header claiming ``'<f8'`` is exactly
296
+ the shape that trick would take.
297
+ """
298
+ header = parse_npy_header(data)
299
+ if header is None:
300
+ return None, None
301
+ offset = header["data_offset"]
302
+ if offset >= len(data):
303
+ return b"", header
304
+ return data[offset:offset + limit], header
@@ -23,8 +23,19 @@ _FRAMEWORK_TO_FORMAT = {
23
23
  "GGUF": "gguf",
24
24
  "Keras": "keras",
25
25
  "ONNX": "onnx",
26
+ # The non-torch pickle carriers. `Pickle` shares PyTorch's token because the
27
+ # format genuinely is the same one; joblib and numpy get their own, because
28
+ # the container is a real difference a consumer may want to filter on.
29
+ "Pickle": "pickle",
30
+ "Joblib": "joblib",
31
+ "NumPy": "numpy",
26
32
  }
27
33
 
34
+ # Formats whose findings are pickle opcodes. They share the `aisbom:pickle:*`
35
+ # vocabulary rather than each inventing a parallel one, so a consumer that knows
36
+ # how to read a threat off a `.pt` reads one off a `.joblib` unchanged.
37
+ _PICKLE_BEARING_FORMATS = {"pickle", "joblib", "numpy"}
38
+
28
39
 
29
40
  def _format_for(art: Dict[str, Any]) -> str | None:
30
41
  return _FRAMEWORK_TO_FORMAT.get(art.get("framework"))
@@ -62,12 +73,49 @@ def build_component_properties(art: Dict[str, Any]) -> List[Tuple[str, str]]:
62
73
  details = art.get("details") or {}
63
74
  props.append(("aisbom:format", fmt))
64
75
 
65
- if fmt == "pickle":
76
+ if fmt in _PICKLE_BEARING_FORMATS:
66
77
  threats = details.get("threats") or []
67
78
  for threat in threats:
68
79
  props.append(("aisbom:pickle:opcode", str(threat)))
69
80
  props.append(("aisbom:pickle:opcode_count", str(len(threats))))
70
81
 
82
+ # The container the stream was found in — `bare`, `npy`, `npz`, or the
83
+ # compression joblib used. Absent for `.pt`, which has its own shape.
84
+ container = details.get("container")
85
+ if container:
86
+ props.append(("aisbom:pickle:container", str(container)))
87
+ if details.get("scan_incomplete"):
88
+ props.append(("aisbom:pickle:scan_incomplete", "true"))
89
+ if details.get("dill_code_objects"):
90
+ props.append(("aisbom:pickle:dill_code_objects", "true"))
91
+
92
+ if fmt == "joblib":
93
+ compression = details.get("compression")
94
+ if compression:
95
+ props.append(("aisbom:joblib:compression", str(compression)))
96
+ decompressed = details.get("decompressed_bytes")
97
+ if decompressed is not None:
98
+ props.append(("aisbom:joblib:decompressed_bytes", str(decompressed)))
99
+
100
+ elif fmt == "numpy":
101
+ dtype = details.get("dtype")
102
+ if dtype:
103
+ props.append(("aisbom:numpy:dtype", str(dtype)))
104
+ if details.get("object_dtype") is not None:
105
+ props.append((
106
+ "aisbom:numpy:object_dtype",
107
+ "true" if details.get("object_dtype") else "false",
108
+ ))
109
+ shape = details.get("shape")
110
+ if shape:
111
+ props.append(("aisbom:numpy:shape", str(shape)))
112
+ npy_version = details.get("npy_version")
113
+ if npy_version:
114
+ props.append(("aisbom:numpy:npy_version", str(npy_version)))
115
+ internal_files = details.get("internal_files")
116
+ if internal_files is not None:
117
+ props.append(("aisbom:numpy:member_count", str(internal_files)))
118
+
71
119
  elif fmt == "safetensors":
72
120
  tensor_count = details.get("tensors")
73
121
  if tensor_count is not None:
@@ -125,6 +125,23 @@ class RemoteStream:
125
125
  self.close()
126
126
 
127
127
 
128
+ def _supported_extensions() -> List[str]:
129
+ """Every extension `DeepScanner` claims, read from the scanner itself.
130
+
131
+ Kept as a derivation rather than a second list, because the two drifting
132
+ apart is not a cosmetic problem: an extension the local walk scans and the
133
+ remote resolver does not is a format that reports every `hf://` model clean.
134
+ """
135
+ from aisbom import scanner # local: `scanner` imports this module
136
+
137
+ return sorted(
138
+ set(scanner.PYTORCH_EXTENSIONS)
139
+ | set(scanner.KERAS_EXTENSIONS)
140
+ | set(scanner.PICKLE_VARIANT_EXTENSIONS)
141
+ | {scanner.SAFETENSORS_EXTENSION, scanner.GGUF_EXTENSION, scanner.ONNX_EXTENSION}
142
+ )
143
+
144
+
128
145
  def resolve_huggingface_repo(repo_id: str) -> List[str]:
129
146
  """
130
147
  Resolve a Hugging Face repo into a list of file URLs for supported model artifacts.
@@ -143,14 +160,13 @@ def resolve_huggingface_repo(repo_id: str) -> List[str]:
143
160
  resp.raise_for_status()
144
161
  data = resp.json()
145
162
 
146
- # Must stay in step with the extensions DeepScanner dispatches on: a format
147
- # missing here is silently skipped for `hf://` scans, so a hostile model in
148
- # that format passes a remote scan without producing an artifact or an error.
149
- supported_exts = (
150
- ".pt", ".pth", ".bin", ".safetensors", ".gguf",
151
- ".keras", ".h5", ".hdf5",
152
- ".onnx",
153
- )
163
+ # Derived from the scanner's own dispatch sets rather than restated here.
164
+ # A format missing from this list is silently skipped for `hf://` scans — a
165
+ # hostile model in that format passes a remote scan producing neither an
166
+ # artifact nor an error — and a hand-maintained copy is exactly how that
167
+ # happens. The import is function-local because `scanner` imports this
168
+ # module, so a module-level one would be circular.
169
+ supported_exts = tuple(_supported_extensions())
154
170
  urls = []
155
171
  for entry in data:
156
172
  path = entry.get("path", "")
@@ -80,6 +80,19 @@ DANGEROUS_GLOBALS = {
80
80
  # Native code loading.
81
81
  "ctypes": {"CDLL", "cdll", "WinDLL", "windll", "PyDLL", "LibraryLoader", "CFUNCTYPE"},
82
82
 
83
+ # dill extends pickle to serialize things pickle cannot: functions, lambdas,
84
+ # classes defined at the prompt. It does that by putting a *marshalled code
85
+ # object* in the stream and rebuilding it on load — the same construct that
86
+ # makes a Keras `Lambda` layer an execution vector, and executable without
87
+ # any further precondition. The names below are the ones that reconstruct or
88
+ # import code.
89
+ #
90
+ # `_create_type`, `_load_type` and `_create_array` are deliberately absent:
91
+ # they name a type or rebuild an array and execute nothing on their own. A
92
+ # dill file holding only data emits none of these entries at all, which is
93
+ # what keeps an ordinary `.dill` scanning clean.
94
+ "dill._dill": {"_create_function", "_create_code", "_import_module", "_get_attr"},
95
+ "dill": {"loads", "load"},
83
96
  }
84
97
 
85
98
  # Callable-construction helpers that are genuinely dual-use. `methodcaller` and
@@ -167,6 +180,18 @@ SAFE_MODULES = {
167
180
  "math",
168
181
  "itertools",
169
182
  "string",
183
+ # Serialization wrappers whose own globals are structural, not executable.
184
+ # A joblib file records its arrays through `joblib.numpy_pickle`, and a dill
185
+ # file records types through `dill._dill`; strict mode flagged both purely
186
+ # for being unrecognized, which made every benign artifact in those formats
187
+ # unscannable in the mode that is supposed to be the careful one.
188
+ #
189
+ # Scoped precisely: `joblib.numpy_pickle`, not `joblib`, so `joblib.parallel`
190
+ # and anything else in the package stays unknown and stays flagged. `dill`
191
+ # is allowlisted as a package, but the DANGEROUS_GLOBALS entries above are
192
+ # checked first and still win — an allowlisted module cannot launder a sink.
193
+ "joblib.numpy_pickle",
194
+ "dill",
170
195
  }
171
196
 
172
197
  SAFE_BUILTINS = {
@@ -290,7 +315,26 @@ def _scan_single_stream(data: bytes, start: int, strict_mode: bool, threats: Lis
290
315
  threats found before that point are still recorded — a corrupt tail must not
291
316
  discard what the front of the stream already revealed.
292
317
  """
293
- memo = [] # recent string literals, for STACK_GLOBAL
318
+ memo = [] # recent string values, for STACK_GLOBAL
319
+ # `STACK_GLOBAL` takes its module and name from the stack, and either can get
320
+ # there from the pickle's *memo table* rather than from a literal immediately
321
+ # before it. A real joblib file does exactly that:
322
+ #
323
+ # SHORT_BINUNICODE 'dtype' <- a dict key
324
+ # BINGET 8 <- pushes 'numpy', memoized much earlier
325
+ # SHORT_BINUNICODE 'dtype'
326
+ # STACK_GLOBAL <- numpy.dtype
327
+ #
328
+ # Watching only the literals resolves that as `dtype.dtype`, which is both a
329
+ # false positive (the real global is allowlisted) and, on other shapes, a
330
+ # false negative — a genuinely dangerous global reached through the memo
331
+ # resolves to a module name that matches nothing in the tables.
332
+ #
333
+ # Tracking the table needs no stack simulation: a memo entry is always the
334
+ # value that was just pushed, so remembering the last push is enough.
335
+ memo_table: Dict[int, Any] = {}
336
+ memo_index = 0 # MEMOIZE assigns indices in order from zero
337
+ last_push: Any = None # the value a MEMOIZE/PUT would record
294
338
  # One buffer is reused across the whole walk; allocating a fresh view per
295
339
  # stream is what made a file of tiny pickles expensive.
296
340
  if stream is None:
@@ -328,13 +372,38 @@ def _scan_single_stream(data: bytes, start: int, strict_mode: bool, threats: Lis
328
372
 
329
373
  try:
330
374
  for opcode, arg, pos in pickletools.genops(stream):
331
- if opcode.name in ("SHORT_BINUNICODE", "UNICODE", "BINUNICODE"):
375
+ if opcode.name in ("SHORT_BINUNICODE", "UNICODE", "BINUNICODE",
376
+ "BINUNICODE8"):
332
377
  memo.append(arg)
333
378
  if len(memo) > 2:
334
379
  memo.pop(0)
380
+ last_push = arg
335
381
  if pending["ctor"] is not None:
336
382
  pending["args"].append(arg)
337
383
 
384
+ elif opcode.name == "MEMOIZE":
385
+ memo_table[memo_index] = last_push
386
+ memo_index += 1
387
+
388
+ elif opcode.name in ("BINPUT", "PUT", "LONG_BINPUT"):
389
+ # Protocol 3 and below name the slot explicitly.
390
+ memo_table[arg] = last_push
391
+
392
+ elif opcode.name in ("BINGET", "GET", "LONG_BINGET"):
393
+ cached = memo_table.get(arg)
394
+ last_push = cached
395
+ if isinstance(cached, str):
396
+ memo.append(cached)
397
+ if len(memo) > 2:
398
+ memo.pop(0)
399
+ if pending["ctor"] is not None:
400
+ pending["args"].append(cached)
401
+
402
+ else:
403
+ # Anything else that reaches the stack is not a string, so a
404
+ # MEMOIZE that follows must not record a stale one.
405
+ last_push = None
406
+
338
407
  if opcode.name == "GLOBAL":
339
408
  # Arg is "module\nname"
340
409
  if isinstance(arg, str) and "\n" in arg:
@@ -374,6 +443,172 @@ def _scan_single_stream(data: bytes, start: int, strict_mode: bool, threats: Lis
374
443
  return None
375
444
 
376
445
 
446
+ # --- SALVAGE PASS: globals in bytes the structural walk could not reach ---
447
+ #
448
+ # A structural disassembly stops dead at the first byte it cannot account for,
449
+ # and joblib guarantees that happens: it writes the pickle up to an array
450
+ # wrapper, then dumps the raw array buffer inline, then resumes pickling. On a
451
+ # real model file `pickletools.genops` therefore dies a couple of hundred bytes
452
+ # in, and everything after the first array — which is where a payload would
453
+ # naturally sit — was never examined. It was not reported as unexamined either:
454
+ # the walk simply returned what it had, and the file read as clean.
455
+ #
456
+ # So the remaining bytes get a second, non-structural pass that looks for the
457
+ # two ways a global can be spelled. It is strictly additive: it can only find
458
+ # globals the structural walk never saw, and it runs only when that walk stopped
459
+ # early.
460
+ #
461
+ # What it deliberately cannot do is judge a dual-use constructor, because the
462
+ # argument that decides is a stack relationship and this pass has no stack.
463
+ # `operator.methodcaller("system")` hidden behind a raw array block is therefore
464
+ # out of reach; there is a test that says so.
465
+
466
+ # `c` + "module\nname\n" — the protocol 0/1 spelling.
467
+ _GLOBAL_OPCODE = re.compile(
468
+ rb"c([A-Za-z_][A-Za-z0-9_.]{0,255})\n([A-Za-z_][A-Za-z0-9_.]{0,255})\n"
469
+ )
470
+
471
+ _STACK_GLOBAL_OPCODE = 0x93
472
+ _SHORT_BINUNICODE_OPCODE = 0x8C
473
+ _BINUNICODE_OPCODE = 0x58
474
+
475
+ # How far back a `STACK_GLOBAL`'s two operands may be spelled out. A module and
476
+ # a name are short; this is generous and keeps the backward walk bounded.
477
+ _SALVAGE_LOOKBACK = 320
478
+
479
+ # Ceilings so that a large adversarial buffer cannot turn the pass into the
480
+ # denial of service that removing the stream cap would have been.
481
+ _SALVAGE_MAX_CANDIDATES = 200_000
482
+ _SALVAGE_MAX_FINDINGS = 50
483
+
484
+
485
+ def _string_ending_at(data: bytes, end: int) -> Tuple[str, int] | None:
486
+ """Read backwards for a unicode push whose bytes finish exactly at ``end``.
487
+
488
+ Returns ``(value, start_offset)``. Anchoring on the end is what makes this
489
+ unambiguous: a length-prefixed string can be identified without knowing
490
+ where it began, because only one starting offset makes its declared length
491
+ land on the byte we already have.
492
+ """
493
+ for size in range(0, min(256, end - 1)):
494
+ start = end - 2 - size
495
+ if start < 0:
496
+ break
497
+ if data[start] == _SHORT_BINUNICODE_OPCODE and data[start + 1] == size:
498
+ try:
499
+ return data[start + 2:end].decode("utf-8"), start
500
+ except UnicodeDecodeError:
501
+ return None
502
+
503
+ for size in range(0, min(_SALVAGE_LOOKBACK, end - 4)):
504
+ start = end - 5 - size
505
+ if start < 0:
506
+ break
507
+ if data[start] == _BINUNICODE_OPCODE:
508
+ declared = int.from_bytes(data[start + 1:start + 5], "little")
509
+ if declared == size:
510
+ try:
511
+ return data[start + 5:end].decode("utf-8"), start
512
+ except UnicodeDecodeError:
513
+ return None
514
+ return None
515
+
516
+
517
+ # A `MEMOIZE` (and, at lower protocols, a `BINPUT`) sits between a string and
518
+ # whatever consumes it, so the operands of a `STACK_GLOBAL` are rarely flush
519
+ # against it. Real bytes look like:
520
+ #
521
+ # \x8c\x05posix \x94 \x8c\x06system \x94 \x93
522
+ #
523
+ # Anchoring strictly on the end byte therefore finds nothing at all. A couple of
524
+ # bytes of slack are allowed instead, and the length check still decides — a
525
+ # candidate only resolves when its declared length lands exactly where it must.
526
+ _SALVAGE_SLACK = 3
527
+
528
+
529
+ def _string_before(data: bytes, end: int) -> Tuple[str, int] | None:
530
+ """``_string_ending_at`` with a few bytes of tolerance for memo opcodes."""
531
+ for back in range(_SALVAGE_SLACK + 1):
532
+ if end - back < 2:
533
+ break
534
+ found = _string_ending_at(data, end - back)
535
+ if found:
536
+ return found
537
+ return None
538
+
539
+
540
+ def salvage_globals(data: bytes, start: int = 0) -> List[Tuple[str, str]]:
541
+ """Recover ``(module, name)`` pairs from a buffer without disassembling it.
542
+
543
+ Used on the region a structural walk could not cross. Both spellings are
544
+ handled: the `GLOBAL` opcode's newline-delimited pair, and `STACK_GLOBAL`
545
+ preceded by two unicode pushes. Order is preserved and duplicates are kept
546
+ out, so a repeating pattern in array data cannot flood the result.
547
+ """
548
+ found: List[Tuple[str, str]] = []
549
+ seen: Set[Tuple[str, str]] = set()
550
+ if start >= len(data):
551
+ return found
552
+ region = data[start:]
553
+
554
+ for match in _GLOBAL_OPCODE.finditer(region):
555
+ pair = (match.group(1).decode("ascii"), match.group(2).decode("ascii"))
556
+ if pair not in seen:
557
+ seen.add(pair)
558
+ found.append(pair)
559
+ if len(found) >= _SALVAGE_MAX_FINDINGS:
560
+ return found
561
+
562
+ cursor = 0
563
+ examined = 0
564
+ while examined < _SALVAGE_MAX_CANDIDATES:
565
+ at = region.find(bytes([_STACK_GLOBAL_OPCODE]), cursor)
566
+ if at == -1:
567
+ break
568
+ cursor = at + 1
569
+ examined += 1
570
+
571
+ name = _string_before(region, at)
572
+ if not name:
573
+ continue
574
+ module = _string_before(region, name[1])
575
+ if not module:
576
+ continue
577
+ pair = (module[0], name[0])
578
+ if pair not in seen:
579
+ seen.add(pair)
580
+ found.append(pair)
581
+ if len(found) >= _SALVAGE_MAX_FINDINGS:
582
+ break
583
+
584
+ return found
585
+
586
+
587
+ def _judge_salvaged(pairs, strict_mode: bool, threats: List[str]) -> None:
588
+ """Judge salvaged pairs against the blocklist only, in either mode.
589
+
590
+ Strict mode's allowlist is deliberately not applied here. Its premise —
591
+ "anything unrecognized is suspicious" — needs names resolved *exactly*, and
592
+ this pass resolves them approximately: with no memo table it cannot see that
593
+ the module operand of a `STACK_GLOBAL` arrived from a `BINGET`, so a real
594
+ `numpy.dtype` reads as `dtype.dtype`. Handing an allowlist a garbled name
595
+ manufactures a false positive on every ordinary joblib file.
596
+
597
+ The blocklist has no such problem: it fires only on an exact match against a
598
+ known sink, and a garbled name matches nothing. The cost is that an
599
+ unrecognized-but-not-blocklisted import hidden behind a raw array block is
600
+ not reported in strict mode; there is a test that says so.
601
+ """
602
+ already = set(threats)
603
+ for module, name in pairs:
604
+ if not is_dangerous_global(module, name):
605
+ continue
606
+ label = f"UNSAFE_IMPORT: {module}.{name}" if strict_mode else f"{module}.{name}"
607
+ if label not in already:
608
+ already.add(label)
609
+ threats.append(label)
610
+
611
+
377
612
  def scan_pickle_stream(data: bytes, strict_mode: bool = False) -> List[str]:
378
613
  """
379
614
  Disassembles a pickle stream and checks for dangerous imports.
@@ -400,6 +635,11 @@ def scan_pickle_stream(data: bytes, strict_mode: bool = False) -> List[str]:
400
635
  # further into the buffer than it began, and the buffer is finite.
401
636
  next_offset = _scan_single_stream(data, offset, strict_mode, threats, buffer)
402
637
  if next_offset is None or next_offset <= offset:
638
+ # The walk stopped without reaching a STOP: either these bytes are
639
+ # not a pickle at all, or one has raw data spliced into it. Both
640
+ # leave the rest of the buffer unread, so it gets the salvage pass
641
+ # rather than being reported as though it had been scanned.
642
+ _judge_salvaged(salvage_globals(data, offset), strict_mode, threats)
403
643
  return threats
404
644
  offset = next_offset
405
645
  if offset >= len(data):
@@ -909,3 +1149,64 @@ def looks_like_pickle_stream(data: bytes) -> bool:
909
1149
  except Exception:
910
1150
  return False
911
1151
  return False
1152
+
1153
+
1154
+ class _NullWriter:
1155
+ """Sink for `pickletools.dis`, which validates by writing a listing."""
1156
+
1157
+ def write(self, _text: str) -> None:
1158
+ pass
1159
+
1160
+
1161
+ def head_looks_like_pickle(data: bytes) -> tuple[bool, bool]:
1162
+ """Does the head of a file begin with a genuinely valid pickle?
1163
+
1164
+ Used by discovery on files no extension claimed, where the question is not
1165
+ "what does this pickle import" but the earlier one: is this a pickle at
1166
+ all? Getting that wrong in either direction is expensive — miss it and a
1167
+ payload is invisible, over-claim it and every SBOM fills with phantom
1168
+ components — so the bar here is deliberately higher than elsewhere.
1169
+
1170
+ Parsing as opcodes is *not* enough, and assuming it was is a trap worth
1171
+ recording: `.` is the STOP opcode, so on a "reaches STOP" test every CSS
1172
+ file that opens with a class selector is a pickle. Measured against a real
1173
+ `node_modules`, that rule claimed JavaScript, stylesheets, TypeScript
1174
+ declarations and a man page.
1175
+
1176
+ So the head must *validate*: `pickletools.dis` walks the stack, and a
1177
+ pickle that pops from an empty stack or ends holding anything other than
1178
+ one object is rejected. Validation runs against the prefix ending at the
1179
+ first STOP rather than the whole buffer, so a payload followed by a corrupt
1180
+ tail — the nullifAI shape — is still recognized instead of being thrown
1181
+ out along with its own garbage.
1182
+
1183
+ Returns `(is_pickle, may_be_truncated)`. The second flag is the caller's
1184
+ escalation signal: opcodes parsed cleanly but no STOP appeared, which is
1185
+ what a real pickle larger than the read window looks like.
1186
+
1187
+ Disassembly only. The stream is never unpickled.
1188
+ """
1189
+ if not data:
1190
+ return (False, False)
1191
+
1192
+ stop_at = None
1193
+ parsed = 0
1194
+ try:
1195
+ for opcode, _arg, pos in pickletools.genops(io.BytesIO(data)):
1196
+ parsed += 1
1197
+ if opcode.name == "STOP":
1198
+ stop_at = pos + 1
1199
+ break
1200
+ except Exception:
1201
+ pass
1202
+
1203
+ if stop_at is None:
1204
+ # No complete pickle in view. Worth a bigger read only if something
1205
+ # actually parsed; a file that yielded nothing is simply not a pickle.
1206
+ return (False, parsed > 0)
1207
+
1208
+ try:
1209
+ pickletools.dis(io.BytesIO(data[:stop_at]), out=_NullWriter())
1210
+ except Exception:
1211
+ return (False, False)
1212
+ return (True, False)
@@ -8,10 +8,12 @@ import hashlib
8
8
  from typing import List, Dict, Any
9
9
  from pathlib import Path
10
10
  from pip_requirements_parser import RequirementsFile
11
+ from aisbom import pickle_containers as pc
11
12
  from aisbom import protobuf_reader as pb
12
13
  from aisbom.safety import (
13
14
  PICKLE_SCAN_INCOMPLETE,
14
15
  _threat_kind as _jinja_threat_kind,
16
+ head_looks_like_pickle,
15
17
  jinja_threats_are_critical,
16
18
  looks_like_pickle_stream,
17
19
  onnx_domain_is_custom,
@@ -28,6 +30,39 @@ SAFETENSORS_EXTENSION = '.safetensors'
28
30
  GGUF_EXTENSION = '.gguf'
29
31
  KERAS_EXTENSIONS = {'.keras', '.h5', '.hdf5'}
30
32
  ONNX_EXTENSION = '.onnx'
33
+
34
+ # The serialization formats of everyday scientific Python. Every one of them is
35
+ # a pickle stream under a wrapper, so each carries the same arbitrary-code
36
+ # -execution risk as a `.pt` — and generic SBOM tooling opens none of them.
37
+ #
38
+ # `.pkl`/`.pickle` are here because the bare pickle was never discovered at all:
39
+ # the README documents `aisbom scan model.pkl --strict`, and until now that
40
+ # scanned nothing and exited 0.
41
+ PICKLE_VARIANT_EXTENSIONS = {'.pkl', '.pickle', '.joblib', '.dill', '.npy', '.npz'}
42
+
43
+ # Local reads get the same budget as the other formats; a remote read pays one
44
+ # HTTP Range request per call and gets the tighter one.
45
+ PICKLE_VARIANT_MAX_SCAN_BYTES = 16 * 1024 * 1024
46
+ PICKLE_VARIANT_MAX_REMOTE_SCAN_BYTES = 2 * 1024 * 1024
47
+
48
+ # Discovery by content, for files no extension claims (CVE-2025-1889). The
49
+ # attacker names the file, so the suffix cannot be the thing that decides
50
+ # whether we look inside it. Every unclaimed file gets its head disassembled.
51
+ #
52
+ # The first read is small because it is paid on *every* unclaimed file in a
53
+ # tree — the READMEs, the parquet, the images. Non-pickles are rejected here
54
+ # for a few kilobytes: they hold no valid pickle and are never re-read.
55
+ PICKLE_SNIFF_BYTES = 64 * 1024
56
+ # A head that *did* parse opcodes cleanly and then ran out of data may be a
57
+ # real pickle whose STOP sits past the window, so it earns a larger read. The
58
+ # ceiling is the variant inspector's own budget on purpose: discovery is
59
+ # exactly as far-sighted as the inspection that follows it, never further.
60
+ PICKLE_SNIFF_MAX_BYTES = PICKLE_VARIANT_MAX_SCAN_BYTES
61
+
62
+ # How many members of an `.npz` are opened. An archive is attacker-controlled,
63
+ # so the member count is bounded like every other declared length.
64
+ NPZ_MAX_MEMBERS = 512
65
+
31
66
  REQUIREMENTS_FILENAME = 'requirements.txt'
32
67
 
33
68
  # --- ONNX protobuf field numbers ---
@@ -230,6 +265,11 @@ class DeepScanner:
230
265
  elif ext == ONNX_EXTENSION:
231
266
  with RemoteStream(url) as stream:
232
267
  self.artifacts.append(self._inspect_onnx(stream, Path(url).name, is_remote=True))
268
+ elif ext in PICKLE_VARIANT_EXTENSIONS:
269
+ with RemoteStream(url) as stream:
270
+ self.artifacts.append(
271
+ self._inspect_pickle_variant(stream, Path(url).name, is_remote=True)
272
+ )
233
273
  except Exception as e:
234
274
  self._record_fetch_error(url, e)
235
275
  continue
@@ -296,12 +336,63 @@ class DeepScanner:
296
336
  self.artifacts.append(self._inspect_keras(full_path))
297
337
  elif ext == ONNX_EXTENSION:
298
338
  self.artifacts.append(self._inspect_onnx(full_path))
339
+ elif ext in PICKLE_VARIANT_EXTENSIONS:
340
+ self.artifacts.append(self._inspect_pickle_variant(full_path))
299
341
  elif full_path.name == REQUIREMENTS_FILENAME:
300
342
  self._parse_requirements(full_path)
343
+ elif self._sniff_is_pickle(full_path):
344
+ # Nothing claimed this file by name, but its bytes read as a
345
+ # pickle. This is the CVE-2025-1889 class: `config.p`, `weights.dat`,
346
+ # a file with no extension at all. The inspector below already
347
+ # decides what a file *is* from its contents rather than its
348
+ # suffix — only discovery was still trusting the name.
349
+ self.artifacts.append(self._inspect_pickle_variant(full_path))
301
350
  else:
302
351
  return False
303
352
  return True
304
353
 
354
+ def _sniff_is_pickle(self, full_path: Path) -> bool:
355
+ """Decide by content whether an unclaimed file is a pickle.
356
+
357
+ Reads a small head first and gives up on it unless opcodes actually
358
+ parsed, which is what keeps a walk over a tree full of parquet and PNGs
359
+ cheap: those yield zero opcodes and are never opened a second time.
360
+
361
+ Known limit, stated rather than hidden: a pickle whose *first* opcode
362
+ carries an argument longer than the whole sniff budget parses zero
363
+ opcodes here and is not discovered by content. Reaching that requires
364
+ a single 16MB-plus literal ahead of the payload. Files carrying a
365
+ recognized model extension are unaffected — they never reach this path.
366
+ """
367
+ try:
368
+ size = full_path.stat().st_size
369
+ except OSError:
370
+ return False
371
+ if not size:
372
+ return False
373
+
374
+ budget = PICKLE_SNIFF_BYTES
375
+ while True:
376
+ try:
377
+ with open(full_path, "rb") as handle:
378
+ head = handle.read(min(budget, PICKLE_SNIFF_MAX_BYTES))
379
+ except OSError:
380
+ return False
381
+
382
+ verdict, truncated = head_looks_like_pickle(head)
383
+ if verdict:
384
+ return True
385
+ # Settled: either the head held a complete pickle and it failed
386
+ # validation, or nothing parsed at all. Reading more cannot change
387
+ # the answer. This is the branch nearly every file in a real
388
+ # repository takes.
389
+ if not truncated:
390
+ return False
391
+ # We saw the whole file, or spent the budget.
392
+ if len(head) >= size or budget >= PICKLE_SNIFF_MAX_BYTES:
393
+ return False
394
+ budget *= 8
395
+
305
396
  def _record_target_error(self, target: str, message: str) -> None:
306
397
  """Record an unusable scan target as a structured, non-fatal error.
307
398
 
@@ -567,6 +658,204 @@ class DeepScanner:
567
658
  pass
568
659
  return meta
569
660
 
661
+ def _npy_member_threats(self, blob: bytes, details: Dict[str, Any]):
662
+ """Scan one `.npy` buffer; return ``(threats, carries_pickle)``.
663
+
664
+ The data section is disassembled whatever the declared dtype says. The
665
+ header is an attacker-supplied field, so using it to decide *whether* to
666
+ look would make `descr: '<f8'` a one-line way to hide a pickle.
667
+
668
+ Whether the file *carries* one is a separate question, answered from the
669
+ bytes: an array of ordinary numbers is a real, fully-read file with no
670
+ pickle in it, and reporting it as "pickle present" would be noise on
671
+ every checkpoint directory that holds one.
672
+ """
673
+ section, header = pc.npy_data_section(blob)
674
+ if header is not None:
675
+ details["npy_version"] = header["version"]
676
+ details["dtype"] = str(header["descr"]) if header["descr"] is not None else None
677
+ details["object_dtype"] = header["object_dtype"]
678
+ if header["shape"] is not None:
679
+ details["shape"] = str(header["shape"])
680
+ if section is None:
681
+ # Not a `.npy` after all — scan the whole buffer as a pickle rather
682
+ # than declining, since the extension is not what decides here.
683
+ section = blob
684
+ threats = scan_pickle_stream(section, strict_mode=self.strict_mode)
685
+ carries_pickle = bool(
686
+ threats
687
+ or (header or {}).get("object_dtype")
688
+ or looks_like_pickle_stream(section)
689
+ )
690
+ return threats, carries_pickle
691
+
692
+ def _inspect_pickle_variant(self, source, name: str | None = None,
693
+ is_remote: bool = False) -> Dict[str, Any]:
694
+ """Scan the pickle-bearing serialization formats that are not `.pt`.
695
+
696
+ joblib (plain, compressed, and the legacy `ZF` container), dill, bare
697
+ `.pkl`, and numpy's `.npy`/`.npz` object arrays all reduce to the same
698
+ question — what does the pickle stream inside import — so they share one
699
+ inspector and the disassembler the rest of the scanner uses.
700
+
701
+ What the file *is* comes from its bytes, not its extension. A `.npy`
702
+ holding a bare pickle is reported as a pickle, and a `.joblib` that is
703
+ really a zip is opened as one, because the attacker picks the extension.
704
+ """
705
+ local_path = None
706
+ if isinstance(source, (str, Path)):
707
+ local_path = Path(source)
708
+ name = name or local_path.name
709
+ is_remote = False
710
+ name = name or getattr(source, "name", "unknown")
711
+
712
+ meta = {
713
+ "name": name,
714
+ "type": "machine-learning-model",
715
+ "framework": "Pickle",
716
+ "risk_level": "UNKNOWN",
717
+ "license": "Unknown", # none of these containers carry license metadata
718
+ "legal_status": "UNKNOWN",
719
+ "hash": "remote_unhashed" if is_remote else self._calculate_hash(local_path),
720
+ "details": {},
721
+ }
722
+ details = meta["details"]
723
+
724
+ stream = None
725
+ try:
726
+ stream = open(local_path, "rb") if local_path else source
727
+ budget = (PICKLE_VARIANT_MAX_SCAN_BYTES if local_path
728
+ else PICKLE_VARIANT_MAX_REMOTE_SCAN_BYTES)
729
+
730
+ threats: List[str] = []
731
+ carries_pickle = False
732
+ unreadable = None # a container we could name but not open
733
+ # Set whenever bytes went unexamined for a reason other than the
734
+ # disassembler's own stream budget. Every one of these is a place a
735
+ # payload could sit, so none of them may end in a clean verdict.
736
+ unexamined = False
737
+
738
+ if zipfile.is_zipfile(stream):
739
+ # `.npz` is a zip of `.npy` members. Compressed or stored, and
740
+ # damaged either way, it goes through the same reader the
741
+ # PyTorch path uses, so tampering with a CRC or a member name
742
+ # does not buy silence here either.
743
+ meta["framework"] = "NumPy"
744
+ details["container"] = "npz"
745
+ stream.seek(0)
746
+ with zipfile.ZipFile(stream, "r") as z:
747
+ all_members = z.namelist()
748
+ members = all_members[:NPZ_MAX_MEMBERS]
749
+ details["internal_files"] = len(all_members)
750
+ if len(all_members) > NPZ_MAX_MEMBERS:
751
+ # 512 benign numeric arrays followed by an object array
752
+ # would otherwise leave every later member unopened and
753
+ # the archive reported LOW.
754
+ details["members_capped"] = NPZ_MAX_MEMBERS
755
+ unexamined = True
756
+ read_notes = []
757
+ for member in members:
758
+ blob, note = self._read_zip_member(z, member, stream)
759
+ if note:
760
+ read_notes.append(f"{member}: {note}")
761
+ if blob is None:
762
+ unreadable = unreadable or "npz member"
763
+ continue
764
+ member_threats, member_pickle = self._npy_member_threats(blob, details)
765
+ threats.extend(member_threats)
766
+ carries_pickle = carries_pickle or member_pickle
767
+ if read_notes:
768
+ details["member_read"] = read_notes
769
+ else:
770
+ stream.seek(0)
771
+ blob = stream.read(budget)
772
+ if not isinstance(blob, bytes):
773
+ blob = bytes(blob)
774
+ if len(blob) >= budget:
775
+ # The read stopped at the budget with bytes still on disk.
776
+ # A valid pickle can carry a large BINBYTES value ahead of
777
+ # its payload, so the prefix can disassemble clean while the
778
+ # part that matters was never read.
779
+ details["truncated"] = True
780
+ unexamined = True
781
+ else:
782
+ details["truncated"] = False
783
+
784
+ if blob.startswith(pc.NPY_MAGIC):
785
+ meta["framework"] = "NumPy"
786
+ details["container"] = "npy"
787
+ threats, carries_pickle = self._npy_member_threats(blob, details)
788
+ else:
789
+ # The decompression budget is the read budget: a remote
790
+ # scan pays per byte and must not expand 16MB after
791
+ # fetching 2. Passed explicitly rather than left to the
792
+ # default, which binds once at import and so ignores both
793
+ # the remote case and any override.
794
+ wrapper = pc.describe_container(blob, limit=budget)
795
+ if wrapper["compression"]:
796
+ meta["framework"] = "Joblib"
797
+ details["container"] = wrapper["compression"]
798
+ details["compression"] = wrapper["compression"]
799
+ if wrapper["payload"] is None:
800
+ # Named, not opened. lz4 and zstd are the joblib
801
+ # codecs with no standard-library decompressor, and
802
+ # pulling one in would put it into every install and
803
+ # every standalone binary. Reporting the limit is
804
+ # the honest answer; claiming a clean scan is not.
805
+ unreadable = wrapper["compression"]
806
+ else:
807
+ carries_pickle = True
808
+ threats = scan_pickle_stream(
809
+ wrapper["payload"], strict_mode=self.strict_mode
810
+ )
811
+ details["decompressed_bytes"] = len(wrapper["payload"])
812
+ if wrapper["truncated"]:
813
+ # The decompressor stopped before the stream's
814
+ # end marker: either it hit the output cap or
815
+ # the compressed data was itself cut short.
816
+ details["decompression_truncated"] = True
817
+ unexamined = True
818
+ else:
819
+ details["container"] = "bare"
820
+ threats = scan_pickle_stream(blob, strict_mode=self.strict_mode)
821
+ carries_pickle = looks_like_pickle_stream(blob) or bool(threats)
822
+ self._apply_lint(meta, blob)
823
+
824
+ threats, incomplete = self._split_scan_incomplete(threats)
825
+ # De-duplicate across `.npz` members while keeping the order, so one
826
+ # payload repeated in every array is reported once.
827
+ threats = list(dict.fromkeys(threats))
828
+ details["threats"] = threats
829
+ if any(t.startswith("dill.") or t.startswith("UNSAFE_IMPORT: dill.")
830
+ for t in threats):
831
+ # dill puts a marshalled code object in the stream and rebuilds
832
+ # it on load. Worth naming: "RCE detected" reads very
833
+ # differently once you know the file is a serialized function.
834
+ details["dill_code_objects"] = True
835
+
836
+ if threats:
837
+ meta["risk_level"] = f"CRITICAL (RCE Detected: {', '.join(threats)})"
838
+ elif incomplete or unexamined:
839
+ details["scan_incomplete"] = True
840
+ meta["risk_level"] = "MEDIUM (Pickle Scan Incomplete)"
841
+ elif unreadable:
842
+ meta["risk_level"] = f"MEDIUM (Unscanned Container: {unreadable})"
843
+ elif carries_pickle:
844
+ meta["risk_level"] = "MEDIUM (Pickle Present)"
845
+ else:
846
+ # A `.npy` of ordinary numbers reaches here: a real file, fully
847
+ # read, carrying no pickle at all.
848
+ meta["risk_level"] = "LOW"
849
+ except Exception as e:
850
+ meta["error"] = str(e)
851
+ finally:
852
+ if local_path and stream:
853
+ try:
854
+ stream.close()
855
+ except Exception:
856
+ pass
857
+ return meta
858
+
570
859
  def _inspect_safetensors(self, source, name: str | None = None, is_remote: bool = False) -> Dict[str, Any]:
571
860
  """Reads Safetensors header for Metadata/License."""
572
861
  local_path = None
@@ -1,6 +1,6 @@
1
1
  [tool.poetry]
2
2
  name = "aisbom-cli"
3
- version = "1.3.1"
3
+ version = "1.3.2"
4
4
  description = "An AI Supply Chain security tool that that detects Pickle bombs and generates CycloneDX SBOMs for Machine Learning models."
5
5
  authors = ["Ajoy L <lab700xdev@gmail.com>"]
6
6
  readme = "README.md"
@@ -26,6 +26,14 @@ pyinstaller = {version = "^6.18.0", python = "<3.15"}
26
26
  py7zr = "^1.1.3"
27
27
  h5py = "^3.12"
28
28
  onnx = "^1.17"
29
+ # Fixture builders only. The scanner never imports these: joblib containers are
30
+ # decompressed with the stdlib and .npy headers are parsed by hand, precisely so
31
+ # the shipped wheel and the standalone binaries stay free of them. They exist
32
+ # here to generate realistic artifacts and to cross-validate the hand-written
33
+ # parsers in both directions.
34
+ joblib = "^1.4"
35
+ dill = "^0.3.8"
36
+ numpy = "^2.0"
29
37
  [build-system]
30
38
  requires = ["poetry-core"]
31
39
  build-backend = "poetry.core.masonry.api"
File without changes
File without changes
File without changes
File without changes