modelsieve 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,580 @@
1
+ Metadata-Version: 2.4
2
+ Name: modelsieve
3
+ Version: 0.1.0
4
+ Summary: Static security scanner for GGUF / Hugging Face / MLX model artifacts: chat-template SSTI and prompt injection, parser attacks, pickle and remote-code hooks, weight anomalies. Parses, never loads.
5
+ Author: Redveil Industry
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/redveil-industry/modelsieve
8
+ Project-URL: Issues, https://github.com/redveil-industry/modelsieve/issues
9
+ Keywords: llm-security,gguf,mlx,safetensors,jinja2,ssti,prompt-injection,pickle,static-analysis
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Information Technology
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Security
17
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
18
+ Requires-Python: >=3.9
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: jinja2>=3.1.6
22
+ Provides-Extra: deep
23
+ Requires-Dist: numpy>=1.24; extra == "deep"
24
+ Provides-Extra: test
25
+ Requires-Dist: pytest>=7; extra == "test"
26
+ Requires-Dist: numpy>=1.24; extra == "test"
27
+ Dynamic: license-file
28
+
29
+ # ModelSieve
30
+
31
+ [![CI](https://github.com/redveil-industry/modelsieve/actions/workflows/ci.yml/badge.svg)](https://github.com/redveil-industry/modelsieve/actions/workflows/ci.yml)
32
+ ![Python 3.9–3.13](https://img.shields.io/badge/python-3.9%E2%80%933.13-blue)
33
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE)
34
+
35
+ ModelSieve is a static security scanner for local LLM files: **GGUF** files and **Hugging Face / MLX model directories** (safetensors weights plus their tokenizer and config JSON). It looks for ways a model file can attack the machine or the conversation **at inference time**, before you load it:
36
+
37
+ - malicious **Jinja2 chat templates**, covering both sandbox escape (SSTI → code execution) and behavioural prompt injection (hidden instructions, trigger words, invisible unicode);
38
+ - **malformed containers** built to exploit loader parsers (out-of-bounds offsets, integer-overflow counts, duplicate keys, hidden bytes);
39
+ - **code-execution side channels**: pickle files, `trust_remote_code` hooks, and mlx-lm import hooks;
40
+ - **corrupted or anomalous float weights**: NaN/Inf, all-zero tensors, outlier layers, and tampered HF cache blobs.
41
+
42
+ ![ModelSieve flagging a malicious GGUF: SSTI gadget, trigger-word branch, injected instruction, hidden trailing bytes](demo/modelsieve-demo.gif)
43
+
44
+ > **Core rule: parse, never load.** ModelSieve never imports `gguf`, `safetensors`, `transformers` or `mlx`. It never renders a template, never unpickles and never imports model code. Loading is the attack surface, so the scanner reads raw bytes with its own bounds-checked readers.
45
+
46
+ > **What it cannot do:** prove that a model has **no trained-in backdoor**. Static inspection cannot detect behaviour learned into the weights. The verdict therefore always reads *"no findings from the checks run"* and lists what was **not** checked. It never says "clean".
47
+
48
+ ---
49
+
50
+ ## Table of contents
51
+
52
+ 1. [Quick start](#quick-start)
53
+ 2. [Requirements and installation](#requirements-and-installation)
54
+ 3. [Usage](#usage)
55
+ 4. [Reading the results](#reading-the-results)
56
+ 5. [Architecture](#architecture)
57
+ 6. [Threat model](#threat-model)
58
+ 7. [Check reference](#check-reference)
59
+ 8. [CI / automation](#ci--automation)
60
+ 9. [Testing](#testing)
61
+ 10. [Known limitations](#known-limitations)
62
+ 11. [Troubleshooting](#troubleshooting)
63
+ 12. [Project layout](#project-layout)
64
+ 13. [Design decisions](#design-decisions)
65
+
66
+ ---
67
+
68
+ ## Quick start
69
+
70
+ ```bash
71
+ pipx install git+https://github.com/redveil-industry/modelsieve
72
+
73
+ modelsieve ~/models/Qwen3-8B-Q5_K_M.gguf # one GGUF file
74
+ modelsieve --deep ~/models/Qwen-MLX-4bit # MLX / HF dir, plus float weight values
75
+ modelsieve ~/models ~/more-models # every model under these folders
76
+ modelsieve ./Some-Model-finetune --baseline ./Original-Model # diff a fine-tune's template vs the original
77
+ ```
78
+
79
+ The installed `modelsieve` command is safe to run from inside a downloaded model folder. A console script puts its own `bin/` directory on `sys.path`, not the current directory, so a planted `json.py` or `struct.py` in the model folder is never imported. This was verified by running the installed command in a folder containing both: they were ignored, and the planted `.py` was itself reported as `code.python_file`. When running **from source**, always use `python3 -I modelsieve.py …` (isolated mode) for the same protection.
80
+
81
+ ---
82
+
83
+ ## Requirements and installation
84
+
85
+ | Requirement | Why | Verified with |
86
+ |---|---|---|
87
+ | Python ≥ 3.9 | `math.prod`, walrus operator | CI: 3.10–3.13 on Ubuntu and macOS, 3.9 on macOS only (no 3.9 runner build for Ubuntu 26.04) |
88
+ | `jinja2` ≥ 3.1.6 | used **only** to parse templates into an AST, never to render | 3.1.6 |
89
+ | `numpy` (optional, `deep` extra) | only for `--deep` (imported lazily) | 2.4.6 |
90
+ | `pytest` (optional, `test` extra) | only to run the test suite | 9.1.1 |
91
+
92
+ ### Install with pipx (recommended)
93
+
94
+ ```bash
95
+ pipx install git+https://github.com/redveil-industry/modelsieve # base scanner
96
+ pipx inject modelsieve numpy # add --deep support
97
+ ```
98
+
99
+ ### Run from source
100
+
101
+ ```bash
102
+ git clone https://github.com/redveil-industry/modelsieve ~/tools/modelsieve
103
+ python3 -m pip install "jinja2>=3.1.6" numpy pytest
104
+ python3 -I ~/tools/modelsieve/modelsieve.py --help
105
+ ```
106
+
107
+ `modelsieve.py` is a single self-contained file, so you can also copy just that file to an air-gapped machine.
108
+
109
+ If the installed jinja2 is older than 3.1.6, the scanner prints a warning. The scanner itself is not at risk, because it only parses, but any *loader* on that host that renders templates with that jinja2 is exposed to CVE-2024-56326 and CVE-2025-27516.
110
+
111
+ ### Shell shortcut (fish, source checkout)
112
+
113
+ You don't need this with the pipx install. For a source checkout, `~/.config/fish/functions/modelsieve.fish` gives you the same `modelsieve` command:
114
+
115
+ ```fish
116
+ function modelsieve --description 'ModelSieve: static security scan of GGUF/HF/MLX models (parses, never loads)'
117
+ # -I: isolated mode, so a planted json.py in a model folder (cwd) can't shadow the stdlib
118
+ python3 -I ~/tools/modelsieve/modelsieve.py $argv
119
+ end
120
+ ```
121
+
122
+ All flags and the exit code (`$status` in fish) pass through unchanged.
123
+
124
+ ---
125
+
126
+ ## Usage
127
+
128
+ ```
129
+ usage: modelsieve.py [-h] [--deep] [--baseline BASELINE]
130
+ [--fail-on {INFO,LOW,MEDIUM,HIGH,CRITICAL}] [--json] [-v]
131
+ [--trust-root TRUST_ROOT]
132
+ paths [paths ...]
133
+ ```
134
+
135
+ | Argument | Meaning |
136
+ |---|---|
137
+ | `paths` | One or more of: `.gguf`, `.safetensors`, a pickle file (`.bin .pt .pth .pkl .pickle .ckpt .joblib .dat`), a `.jinja` template, or a **directory**, which is walked recursively. |
138
+ | `--deep` | Also read float tensor values (F32/F16/BF16/F64) for NaN/Inf, all-zero and outlier checks, and verify each HF cache blob's sha256 against its file name. This step is slower on large models; a 6 GB 4-bit MLX model took about 4 s because only its float tensors are read. |
139
+ | `--baseline PATH` | A known-good model (directory, `.gguf` or `.jinja`). Every chat template is diffed against the template of the same name in the baseline. This is the strongest check against a re-uploaded model whose prompt was "tuned". |
140
+ | `--fail-on SEV` | Exit code 1 if any finding is at or above `SEV`. The default is `HIGH`. |
141
+ | `--json` | Machine-readable output (see below). |
142
+ | `-v`, `--verbose` | Also show `INFO` findings, such as the inventory of natural-language text each template injects. |
143
+ | `--trust-root DIR` | A directory that model symlinks may legitimately point into, for example a model manager's shim folder whose files link into a central model store. Repeatable. Without it, those links are reported as `fs.symlink_escape`. |
144
+
145
+ ### What a directory walk picks up
146
+
147
+ ```mermaid
148
+ flowchart LR
149
+ D[directory argument] -->|os.walk, no symlinked dirs| W{each folder}
150
+ W -->|*.gguf| G[GGUF scan]
151
+ W -->|config.json / tokenizer_config.json /<br/>chat_template.jinja / tokenizer.json / *.safetensors| H[HF/MLX directory scan]
152
+ W -.->|skipped| X[.git, blobs, refs, .locks]
153
+ ```
154
+
155
+ HF cache layouts (`models--org--name/snapshots/<rev>/`) work as-is. Snapshot files are symlinks into `models--*/blobs/` or the hub-level `hub/blobs/<2hex>/<sha256>`, and both are accepted as legitimate link targets.
156
+
157
+ ---
158
+
159
+ ## Reading the results
160
+
161
+ ### Text output (default)
162
+
163
+ Real output from scanning a deliberately malicious test GGUF (paths shortened):
164
+
165
+ ```
166
+ == ModelSieve 0.1.0: /models/evil.gguf
167
+ CRITICAL template.ssti_underscore_attr /models/evil.gguf::tokenizer.chat_template
168
+ underscore attribute access (sandbox-escape gadget)
169
+ x2: __globals__ | __init__
170
+ HIGH template.content_trigger /models/evil.gguf::tokenizer.chat_template
171
+ branch on a literal phrase in message content (trigger-word backdoor pattern)
172
+ x1: ['open sesame']
173
+ HIGH template.dangerous_name /models/evil.gguf::tokenizer.chat_template
174
+ reference to a global with no legitimate chat-template use
175
+ x1: cycler
176
+ HIGH template.injected_instruction /models/evil.gguf::tokenizer.chat_template
177
+ override/exfiltration phrase hard-coded in template
178
+ x1: Ignore all previous instructions.
179
+ MEDIUM gguf.trailing_data /models/evil.gguf
180
+ 200 bytes after last tensor (hidden payload / appended data)
181
+ LOW template.unknown_method /models/evil.gguf::tokenizer.chat_template
182
+ method call outside allowlist
183
+ x2: popen | read
184
+
185
+ Coverage: {"gguf_files": 1, "templates_analysed": 1, "tensors_total": 1}
186
+ Findings: CRITICAL=1, HIGH=3, MEDIUM=1, LOW=1, INFO=0
187
+ Verdict: findings up to CRITICAL from the checks run. Not checked: trained-in weight backdoors (not statically detectable); weight values (run with --deep); template wording vs a known-good original (use --baseline; review INFO literal_text with -v).
188
+ ```
189
+
190
+ Each finding has the following fields:
191
+
192
+ | Field | Meaning |
193
+ |---|---|
194
+ | severity | `CRITICAL` > `HIGH` > `MEDIUM` > `LOW` > `INFO` (INFO is hidden unless you pass `-v`) |
195
+ | check id | stable `area.name` identifier; see the [check reference](#check-reference) |
196
+ | source | `file`, `file::metadata-key`, `file::tensor-name` or `archive!member` |
197
+ | message | what was found and why it matters |
198
+ | evidence | `xN:` how many times it occurred, then the unique values (truncated at 400 chars) |
199
+
200
+ The three footer lines matter as much as the findings:
201
+
202
+ - **Coverage** is what was actually examined: file, template and tensor counts. It includes `tensors_not_analysed_by_dtype` (for example `{"U32": 250, "Q4_K": 169}`), the packed or quantized tensors whose values were **not** inspected, and `templates_missing`, the artifacts that carry no chat template.
203
+ - **Findings** gives counts per severity.
204
+ - **Verdict** gives the worst severity and an explicit **Not checked** list.
205
+
206
+ ### Save findings to a file
207
+
208
+ ```bash
209
+ modelsieve ~/models -v > ~/scans/scan.txt
210
+ ```
211
+
212
+ ### JSON output
213
+
214
+ ```bash
215
+ modelsieve ~/models --json > ~/scans/scan.json
216
+ ```
217
+
218
+ Schema: one object per path argument.
219
+
220
+ ```json
221
+ [
222
+ {
223
+ "path": "/home/me/models",
224
+ "version": "0.1.0",
225
+ "findings": [
226
+ {"severity": "MEDIUM", "check": "template.concealment_instruction",
227
+ "source": ".../chat_template.jinja", "message": "...", "evidence": "x1: ..."}
228
+ ],
229
+ "coverage": {"hf_dirs": 4, "templates_analysed": 4, "tensors_total": 6503},
230
+ "errors": [],
231
+ "verdict": "Verdict: findings up to MEDIUM from the checks run. Not checked: ..."
232
+ }
233
+ ]
234
+ ```
235
+
236
+ Useful `jq` one-liners:
237
+
238
+ ```bash
239
+ # HIGH and CRITICAL only
240
+ jq -r '.[].findings[] | select(.severity=="HIGH" or .severity=="CRITICAL") | "\(.severity) \(.check) \(.source)\n \(.evidence)"' scan.json
241
+
242
+ # count findings per check
243
+ jq -r '.[].findings[].check' scan.json | sort | uniq -c | sort -rn
244
+
245
+ # what was NOT analysed
246
+ jq '.[].coverage.tensors_not_analysed_by_dtype' scan.json
247
+ ```
248
+
249
+ ### Exit codes
250
+
251
+ | Code | Meaning |
252
+ |---|---|
253
+ | `0` | no finding at or above `--fail-on` (default HIGH) |
254
+ | `1` | at least one finding at or above `--fail-on` |
255
+ | `2` | scan error: missing path, unsupported file, I/O error, or a file that crashed the scanner. Results for that path are incomplete. Errors are listed as `ERROR:` lines or in `"errors"`. |
256
+
257
+ A crash on one file never aborts the rest of a multi-path run. It is recorded as an error and the walk continues.
258
+
259
+ ---
260
+
261
+ ## Architecture
262
+
263
+ ### Components and data flow
264
+
265
+ ```mermaid
266
+ flowchart TB
267
+ CLI["main()<br/>argparse, --trust-root, jinja2 version check"] --> BASE["baseline_templates()<br/>template inventory of --baseline"]
268
+ CLI --> SCAN["scan(path)<br/>dispatch by file type / os.walk"]
269
+
270
+ SCAN --> GG["scan_gguf()"]
271
+ SCAN --> HF["scan_hf_dir()"]
272
+ SCAN --> STF["scan_safetensors()"]
273
+ SCAN --> PK["scan_pickle()"]
274
+
275
+ GG --> PG["_parse_gguf() + _R<br/>bounded mmap reader"]
276
+ HF --> STF
277
+ HF --> PK
278
+ HF --> TJ["_scan_tokenizer_json()"]
279
+ HF --> IDX["_check_index()<br/>model.safetensors.index.json"]
280
+ HF --> HT["hf_templates()<br/>collect every template source"]
281
+
282
+ PG --> AT
283
+ HT --> AT["analyse_templates()<br/>dedupe · divergence · baseline diff"]
284
+ AT --> A1["analyse_template()<br/>Jinja2 AST walk"]
285
+
286
+ STF -->|--deep| WS["tensor_stats()<br/>chunked mmap, numpy"]
287
+ PG -->|--deep| WS
288
+ WS --> WF["weight_findings()<br/>NaN/Inf, zero, sibling-layer z-score"]
289
+
290
+ PK --> PGL["pickle_globals()<br/>pickletools.genops, never unpickles"]
291
+
292
+ A1 & WF & PGL & IDX & TJ --> REP["Report<br/>findings + coverage + errors"]
293
+ REP --> OUT["render() text / --json<br/>verdict() + exit code"]
294
+ ```
295
+
296
+ Everything lives in one file, `modelsieve.py` (about 1.2k lines). The sections inside it, in order:
297
+
298
+ | Section | Responsibility |
299
+ |---|---|
300
+ | `Finding`, `Report`, `Malformed` | result model: findings, coverage counters, scan errors |
301
+ | unicode / text | `hidden_unicode()` detects zero-width, bidi, variation-selector and **Unicode tag** characters, and decodes tag-smuggled ASCII |
302
+ | templates | `analyse_template()` (AST rules) and `analyse_templates()` (dedupe, divergence, baseline) |
303
+ | GGUF | `GGML_TYPES` block-size table, the `_R` bounded reader, `_parse_gguf()` and `scan_gguf()` |
304
+ | safetensors | `scan_safetensors()`: header cap, duplicate-key JSON hook, span validation |
305
+ | weights | `tensor_stats()` (chunked, BF16 handled manually) and `weight_findings()` |
306
+ | pickle | `pickle_globals()` opcode scan and `scan_pickle()` (zip/torch, raw, npy/npz) |
307
+ | HF / MLX directory | `scan_hf_dir()`: symlinks, configs, code files, tokenizer.json, index, templates |
308
+ | driver | `scan()`, `_isolated()` crash isolation, `baseline_templates()`, `render()`, `verdict()`, `main()` |
309
+
310
+ ### Trust boundary
311
+
312
+ ```mermaid
313
+ flowchart LR
314
+ subgraph UNTRUSTED["Untrusted: everything under the scanned path"]
315
+ F1[GGUF bytes] --- F2[safetensors header] --- F3[JSON configs] --- F4[templates] --- F5[pickles] --- F6[symlinks]
316
+ end
317
+ subgraph SCANNER["ModelSieve process (console script, or python3 -I from source)"]
318
+ R["bounded readers<br/>every length checked vs file size<br/>before any allocation"]
319
+ P["jinja2 parse only<br/>bounded constant folding"]
320
+ O["pickletools.genops<br/>opcode listing only"]
321
+ end
322
+ UNTRUSTED -->|read-only mmap / read| R
323
+ UNTRUSTED --> P
324
+ UNTRUSTED --> O
325
+ SCANNER -->|findings only| USER[operator]
326
+ ```
327
+
328
+ The scanner enforces these invariants:
329
+
330
+ - **No execution of model content:** templates are never rendered, pickles are never unpickled, and no model module is imported.
331
+ - **No unbounded allocation:** GGUF string, array and count fields are checked against the remaining file size before being read. The safetensors header is capped at 100 MB before `json.loads`. Template constant folding stops at 10k chars and depth 16. ModelSieve deliberately never calls `jinja2.nodes.Node.as_const()`, because that **evaluates** expressions: `'a' * 10**10` would exhaust memory in the scanner.
332
+ - **Symlinks:** a symlink that resolves outside the model root (or the HF blob store, or a `--trust-root`) is reported and **not read**, so a link to `~/.ssh/id_rsa` never reaches the report. A dangling link is reported as not analysed.
333
+
334
+ ### How the template analysis works
335
+
336
+ 1. **Inventory.** Every source a loader might use is collected:
337
+ - GGUF: `tokenizer.chat_template` and `tokenizer.chat_template.<name>`, plus any other metadata string containing `{%` or `{{`;
338
+ - HF/MLX: `chat_template.jinja`, `additional_chat_templates/*.jinja`, and the `chat_template` field (string or named list) of `tokenizer_config.json`, `chat_template.json` and `processor_config.json`.
339
+ 2. **Divergence.** If two sources hold different text under the same name, which one runs depends on the loader, and that gap is an attack path. Real MLX folders ship the template twice (`chat_template.jinja` and `tokenizer_config.json`).
340
+ 3. **Parse** in an environment that mirrors transformers' chat-template environment: `loopcontrols`, a parse-only `{% generation %}` tag, `trim_blocks` and `lstrip_blocks`. This was verified against `transformers/utils/chat_template_utils.py` in transformers 5.23.
341
+ 4. **Resolve one hop of indirection.** `{% set k = '__cla' ~ 'ss__' %}` constants are folded and substituted. "Contains user content" taint is propagated through `{% set %}` and `{% for %}` targets.
342
+ 5. **AST rules:**
343
+ - **Execution:** underscore or dunder attributes, items and strings, `|attr`, private attribute names passed to filters (`selectattr('__class__')`), introspection attributes, `str.format` references, dangerous globals (`lipsum`, `cycler`, `self`, …), and calls, filters or tests outside the HF allowlist.
344
+ - **Behaviour:** override or exfiltration phrases, concealment phrases, URLs, hidden unicode, branches on literal phrases in message content (trigger words), and an INFO inventory of injected natural-language text.
345
+ - **DoS:** `range(>1e6)`, large multiplications, parser recursion.
346
+ 6. **Baseline diff** (optional): a unified diff against the same-named template of a known-good model.
347
+
348
+ ### How the container checks work
349
+
350
+ ```mermaid
351
+ flowchart TB
352
+ H["GGUF header<br/>magic, version 2/3, n_tensors, n_kv"] -->|counts x minimal size <= file size?| KV[KV pairs]
353
+ KV -->|duplicate / empty key, bad UTF-8| TI["tensor infos<br/>n_dims <= GGML_MAX_DIMS (4)"]
354
+ TI --> AL["data start = align(general.alignment)"]
355
+ AL --> SP["per tensor:<br/>type known? elements % block == 0?<br/>offset aligned? start+nbytes <= EOF?"]
356
+ SP --> LAY["layout:<br/>contiguous in header order (llama.cpp rule)<br/>no overlap · no trailing bytes"]
357
+ ```
358
+
359
+ The GGUF type and block-size table comes from llama.cpp `gguf-py/gguf/constants.py`, including types local to the unsloth fork. The contiguity rule (llama.cpp `ggml/src/gguf.cpp`: *"tensor has offset X, expected Y"*) means any file with gaps or reordering is rejected by llama.cpp but may be accepted by other readers. That makes it a **parser differential**, and ModelSieve reports it.
360
+
361
+ Safetensors goes through the same pipeline: an 8-byte length that must fit the file, a header that must be UTF-8 JSON with no duplicate keys, a known dtype for every tensor, `end - begin == prod(shape) x sizeof(dtype)`, and spans that must tile the data region with no holes, overlaps or trailing bytes. `model.safetensors.index.json` is cross-checked against the shard headers, including path traversal in shard names.
362
+
363
+ ---
364
+
365
+ ## Threat model
366
+
367
+ | Asset | Entry point | Abuse case | Checks |
368
+ |---|---|---|---|
369
+ | Host running the loader | chat template (GGUF KV, tokenizer_config, `.jinja`, chat_template.json, processor_config) | SSTI sandbox escape → RCE. Real precedent: **CVE-2024-34359** (llama-cpp-python rendered GGUF templates unsandboxed, fixed in 0.2.72), **CVE-2024-56326** (Jinja indirect `str.format`, fixed in 3.1.5), **CVE-2025-27516** (Jinja `\|attr` → format, fixed in 3.1.6) | `template.ssti_*`, `attr_filter`, `dunder_string`, `format_reference`, `dangerous_name`, `unknown_*` |
370
+ | Model behaviour / user data | same | hidden system instructions, trigger-word backdoors, invisible or bidi or tag-unicode smuggling, a "tuned" re-upload | `injected_instruction`, `concealment_instruction`, `content_trigger*`, `hidden_unicode`, `url`, `divergent_sources`, `baseline_diff` |
371
+ | Loader memory safety | GGUF header, KVs and tensor infos; safetensors header | integer overflow, OOB reads, parser differentials, hidden payloads | `gguf.*`, `st.*` |
372
+ | Host | `*.py`, `config.json:auto_map`, mlx-lm `model_file`, pickle files | remote code under `trust_remote_code=True`; pickle `__reduce__` RCE | `code.*` |
373
+ | Host / mlx-lm | `model_type`, `chat_template_type`, `tool_parser_type` | the value flows into `importlib.import_module("mlx_lm.<pkg>.<value>")` (verified in the mlx-lm source) | `code.import_injection` |
374
+ | User input integrity | `tokenizer.json` normalizer / pre-tokenizer, special tokens | rules that silently rewrite the user's words, look-alike special tokens | `tokenizer.*` |
375
+ | Output integrity | float tensors, HF blobs, generation_config | NaN poisoning, ablated or edited layers, tampering after download, forced tokens | `weights.*`, `fs.blob_hash_mismatch`, `gen.logit_manipulation` |
376
+
377
+ ---
378
+
379
+ ## Check reference
380
+
381
+ Severity guide: **CRITICAL** = code execution or memory-safety primitive present. **HIGH** = strong attack indicator or loader-rejected structure. **MEDIUM** = suspicious, review it. **LOW** = coverage gap or weak signal. **INFO** = inventory.
382
+
383
+ ### Templates (`template.*`)
384
+
385
+ | Check | Severity | Meaning |
386
+ |---|---|---|
387
+ | `ssti_underscore_attr` | CRITICAL | `x.__class__`-style attribute access |
388
+ | `ssti_underscore_item` | CRITICAL | `x['__class__']`, including folded or `{% set %}`-resolved keys |
389
+ | `ssti_filter_arg` | CRITICAL | a filter argument names a private attribute (`selectattr('__class__')`, `map(attribute='__x__')`) |
390
+ | `dunder_string` | CRITICAL | any string constant containing `__name__` (gadget staged for indirection) |
391
+ | `attr_filter` | CRITICAL / HIGH | `\|attr(...)`: CRITICAL when the argument is private or `format` (CVE-2025-27516) |
392
+ | `indirect_filter` | CRITICAL / MEDIUM | `map('attr', …)` or `map` into a non-allowlisted filter |
393
+ | `ssti_introspection` | HIGH | `mro`, `f_globals`, `gi_frame`, … |
394
+ | `format_reference` | HIGH | `.format` referenced without being called (CVE-2024-56326 pattern) |
395
+ | `dangerous_name` | HIGH | `lipsum`, `cycler`, `joiner`, `self`, `config`, `request`, `os`, … |
396
+ | `external_load` | HIGH | `include`, `import` or `extends` |
397
+ | `content_trigger` | HIGH | branch on a literal phrase found in message content |
398
+ | `injected_instruction` | HIGH | "ignore previous…", exfiltration, `curl -`, `<script`, api key, password |
399
+ | `parse_dos` | HIGH | nesting exhausts parser recursion |
400
+ | `hidden_unicode` | HIGH / MEDIUM | HIGH for bidi or tag characters (decoded text shown), MEDIUM for zero-width |
401
+ | `content_trigger_markup` | MEDIUM | branch on a tag-like literal (`'<deploy>'`) that the template never emits |
402
+ | `concealment_instruction` | MEDIUM | "do not tell the user…"; upstream Qwen tool prompts trigger this |
403
+ | `url` | MEDIUM | URL hard-coded in the template |
404
+ | `computed_key` | MEDIUM | subscript key built from string expressions or filters |
405
+ | `str_format` | MEDIUM | direct `.format()` call |
406
+ | `unknown_filter`, `unknown_test`, `unknown_callable` | MEDIUM | outside the HF chat-template environment |
407
+ | `dos_range`, `dos_mul` | MEDIUM | render-time resource blow-up |
408
+ | `parse_error` | MEDIUM | does not parse; loaders may disagree |
409
+ | `divergent_sources` | MEDIUM | the same template name has different text in different files |
410
+ | `baseline_diff` | MEDIUM | differs from `--baseline` (diff in evidence) |
411
+ | `unknown_method`, `indirect_call` | LOW | method or call outside the allowlist |
412
+ | `baseline_missing` | LOW | the baseline has no template with this name |
413
+ | `literal_text`, `baseline_match`, `none` | INFO | inventory |
414
+
415
+ ### GGUF (`gguf.*`)
416
+
417
+ | Check | Severity | Meaning |
418
+ |---|---|---|
419
+ | `malformed` | CRITICAL | header does not parse within bounds: bad magic, v1, counts that cannot fit the file, a string or array past EOF |
420
+ | `tensor_oob` | CRITICAL | tensor data runs past EOF |
421
+ | `element_overflow` | CRITICAL | element count ≥ 2^62 |
422
+ | `duplicate_key` | HIGH | llama.cpp rejects the file; other readers pick first or last (template smuggling) |
423
+ | `empty_key`, `bad_alignment`, `block_misaligned`, `duplicate_tensor`, `tensor_overlap`, `noncontiguous` | HIGH | loader-rejected or loader-dependent structure |
424
+ | `trailing_data`, `tensor_unaligned`, `unknown_type`, `template_like_metadata`, `bad_utf8` | MEDIUM | hidden bytes, unverifiable sizes, Jinja in odd places |
425
+ | `hidden_unicode_metadata` | HIGH / MEDIUM | invisible unicode in a metadata string |
426
+
427
+ ### Safetensors (`st.*`)
428
+
429
+ | Check | Severity | Meaning |
430
+ |---|---|---|
431
+ | `malformed`, `tensor_oob` | CRITICAL | length prefix past EOF, non-JSON header, span outside the data region |
432
+ | `header_too_large`, `duplicate_key`, `bad_entry`, `size_mismatch`, `tensor_overlap`, `index_path_traversal` | HIGH | |
433
+ | `hidden_gap`, `trailing_data`, `unknown_dtype`, `bad_metadata`, `template_like_metadata`, `index_*` | MEDIUM | |
434
+ | `unindexed_tensors` | LOW | tensors that loaders ignore |
435
+
436
+ ### Code and filesystem (`code.*`, `fs.*`, `tokenizer.*`, `gen.*`)
437
+
438
+ | Check | Severity | Meaning |
439
+ |---|---|---|
440
+ | `code.pickle_import` | CRITICAL / HIGH | the pickle imports a non-allowlisted callable. CRITICAL for `os`, `subprocess`, `builtins.eval`, … All protocols 0–5 are handled. |
441
+ | `fs.blob_hash_mismatch` | CRITICAL | HF blob content ≠ its sha256 name (`--deep`) |
442
+ | `code.auto_map`, `code.model_file`, `code.import_injection`, `code.npy_object`, `code.pickle_unparseable`, `code.pickle_unreadable` | HIGH | |
443
+ | `fs.symlink_escape`, `fs.native_binary` | HIGH | |
444
+ | `tokenizer.hidden_unicode_special_token` | HIGH | a special or control token contains invisible characters |
445
+ | `code.pickle_present`, `code.python_file`, `tokenizer.replace_rule`, `fs.bad_json` | MEDIUM | |
446
+ | `code.pickle_unrecognised`, `fs.dangling_symlink`, `gen.logit_manipulation` | LOW | not analysed / review intent |
447
+ | `code.mlx_module_hook` | INFO | |
448
+
449
+ ### Weights (`weights.*`, `--deep` only)
450
+
451
+ | Check | Severity | Meaning |
452
+ |---|---|---|
453
+ | `nonfinite` | HIGH | NaN or Inf values |
454
+ | `all_zero` | LOW | tensor of ≥1024 elements is entirely zero |
455
+ | `layer_outlier` | LOW | tensor std deviates from ≥8 sibling layers (robust z > 8); can be benign |
456
+
457
+ Only F32, F16, BF16 and F64 tensors are analysed. MLX packed `U32` weights and GGUF K-quants appear under `tensors_not_analysed_by_dtype` and are never counted as passed.
458
+
459
+ ---
460
+
461
+ ## CI / automation
462
+
463
+ ```bash
464
+ #!/usr/bin/env bash
465
+ # gate a model before it enters the shared model store
466
+ set -u
467
+ modelsieve --deep --fail-on HIGH --json "$1" > "scan-$(basename "$1").json"
468
+ rc=$?
469
+ case $rc in
470
+ 0) echo "no HIGH+ findings from checks run" ;;
471
+ 1) echo "BLOCKED: HIGH+ findings"; jq -r '.[].findings[] | select(.severity=="HIGH" or .severity=="CRITICAL") | "\(.severity) \(.check) \(.source)"' "scan-$(basename "$1").json"; exit 1 ;;
472
+ *) echo "scan error, treat as blocked"; exit 2 ;;
473
+ esac
474
+ ```
475
+
476
+ Treat exit code 2 as **fail closed**: an incomplete scan is not a pass.
477
+
478
+ ---
479
+
480
+ ## Testing
481
+
482
+ ```bash
483
+ cd ~/tools/modelsieve
484
+ python3 -I -m pytest -q test_modelsieve.py
485
+ ```
486
+
487
+ The suite has 72 tests and runs in under 1 s. Every fixture is generated in-test by small GGUF and safetensors writers (`make_gguf`, `make_st`); no binary blobs are committed. The coverage pattern is one synthetic attack per check class plus benign negatives:
488
+
489
+ - SSTI gadgets and their one-hop bypasses (`{% set k='__class__' %}{{ x[k] }}`, `'_'*2 ~ 'class' ~ '_'*2`, `selectattr('__class__')`, `groupby('_…')`, `|attr('format')`);
490
+ - trigger words, including through `{% set c = m['content'] %}` and `{% for line in m.content.split() %}`;
491
+ - tag-character smuggling, with the decoded text asserted;
492
+ - GGUF and safetensors parser attacks (count overflow, string length bomb, OOB, overlap, gap, duplicate keys, header bomb);
493
+ - pickles of protocols 0–5 with an `os.system` `__reduce__` (serialised only, never loaded);
494
+ - an HF directory combining `auto_map`, `model_file`, import injection, a `Replace` rule, symlink escape, dangling link, index path traversal and divergent templates;
495
+ - crash isolation, `--trust-root`, exit codes and JSON output;
496
+ - a **benign Qwen-style template** that must produce no MEDIUM+ finding, and a guard that constant folding stays bounded (< 1 s on `'a' * 10**10`).
497
+
498
+ **CI.** `.github/workflows/ci.yml` runs the suite and a console-script smoke test on every push and PR, across Python 3.10–3.13 on Ubuntu and macOS plus 3.9 on macOS (9 jobs). All Actions are pinned to commit SHAs and run with read-only `contents` permission.
499
+
500
+ **False-positive gate.** Every check change is re-run against a corpus of real downloaded models. The last run, on 2026-11-28, covered 29 GGUF and 9 HF dirs, 10,524 tensor headers and 16 templates (mostly Qwen-family). The result was **0 HIGH/CRITICAL**: 4 MEDIUM upstream-Qwen concealment phrases and 1 LOW non-pickle `model.bin` (CTranslate2).
501
+
502
+ ---
503
+
504
+ ## Known limitations
505
+
506
+ | Limitation | Effect | Planned fix |
507
+ |---|---|---|
508
+ | Trained-in weight backdoors | not detectable statically, by design | none possible statically; use behavioural evals |
509
+ | Quantized or packed tensor values (GGUF K-quants, MLX U32) | not analysed; reported in coverage | read quant block scales (Q8_0/Q4_K `d` fields) |
510
+ | One-word lowercase triggers (`'xyzzy' in content`) | treated as key/type checks, so missed | opt-in sandboxed render-diff (`--render`) |
511
+ | Markup-like triggers that the template also emits | exempt, so missed | `--render` |
512
+ | Indirection deeper than one `{% set %}` hop, or through macro arguments | not resolved | `--render` |
513
+ | Python `jinja2` vs llama.cpp's C++ template engine | parse differences not yet tested | differential fixtures |
514
+ | Pickle `STACK_GLOBAL` | resolved from the two most recent string pushes, not a full stack emulator | stack emulator if evasion matters |
515
+ | Pickle size | only the first 64 MiB of a raw pickle is inspected | raise the cap for large legacy checkpoints |
516
+ | Template gate corpus | 16 templates, mostly Qwen | add Llama, Gemma, Mistral, Phi and GLM templates |
517
+
518
+ ---
519
+
520
+ ## Troubleshooting
521
+
522
+ ```mermaid
523
+ flowchart TD
524
+ A[Unexpected result] --> B{Exit code 2?}
525
+ B -->|yes| C["Read ERROR: lines.<br/>'no such path' → check the path.<br/>'unsupported file type' → pass the directory instead.<br/>'scanner crashed' → keep the file, it is a test case for a bug."]
526
+ B -->|no| D{Many fs.symlink_escape?}
527
+ D -->|yes| E["Model-manager shim folder?<br/>add --trust-root <central model store>"]
528
+ D -->|no| F{fs.dangling_symlink?}
529
+ F -->|yes| G["Link targets were deleted; nothing behind them was scanned.<br/>Re-download or scan the real files."]
530
+ F -->|no| H{Coverage shows 0 templates?}
531
+ H -->|yes| I["The model ships no chat template; the loader default applies.<br/>See templates_missing."]
532
+ H -->|no| J["Re-run with -v to see INFO inventory;<br/>add --baseline ORIGINAL to diff wording"]
533
+ ```
534
+
535
+ - **The warning `jinja2 < 3.1.6`** means: upgrade jinja2 on this host. Your *loaders* are exposed even though ModelSieve is not.
536
+ - **`template.concealment_instruction` on Qwen models** is expected. The upstream tool-calling prompt says "do not tell the user about function calls".
537
+ - **`weights.layer_outlier`** can be benign; first and last layers often differ. Confirm with `--baseline` on an untouched original, or with a behavioural test.
538
+
539
+ ---
540
+
541
+ ## Project layout
542
+
543
+ ```
544
+ modelsieve/
545
+ ├── README.md ← this file
546
+ ├── LICENSE ← MIT
547
+ ├── pyproject.toml ← packaging: console script `modelsieve`, extras `deep` and `test`
548
+ ├── .gitignore
549
+ ├── modelsieve.py ← the scanner (single file, stdlib + jinja2, numpy for --deep)
550
+ ├── test_modelsieve.py ← 72 tests, in-test fixture writers
551
+ ├── demo/
552
+ │ ├── make_demo_model.py ← writes the deliberately malicious demo GGUF
553
+ │ ├── demo.tape ← vhs script; re-record with `vhs demo/demo.tape`
554
+ │ └── modelsieve-demo.gif ← the README demo (real output)
555
+ └── .github/workflows/
556
+ ├── ci.yml ← tests on Python 3.9–3.13 (Ubuntu + macOS; 3.9 macOS only)
557
+ └── publish.yml ← PyPI release via Trusted Publishing (OIDC, no stored token)
558
+ ```
559
+
560
+ Never commit scan outputs (`--json` files, saved text reports): they list your local model paths and file names. `.gitignore` excludes `scan*.json`, `scan*.txt` and `out/`.
561
+
562
+ ---
563
+
564
+ ## Design decisions
565
+
566
+ | Decision | Rationale | Trade-off |
567
+ |---|---|---|
568
+ | Own bounded parsers instead of the `gguf` / `safetensors` libraries | the libraries trust header values; loading is the attack surface | a type table to keep in sync with llama.cpp |
569
+ | AST analysis, never rendering | rendering an untrusted template *is* the exploit | misses behaviour only visible at render time (see limitations) |
570
+ | Allowlists for calls, filters and tests; denylists only for attribute names | namespace attributes are arbitrary, so calls can be allowlisted but reads can't | some LOW noise on unusual string methods |
571
+ | "No findings from checks run" instead of "clean" | static scanning cannot prove absence | less comforting output, and accurate |
572
+ | Single file | easy to audit, copy to an air-gapped box and run with `python3 -I` | a long file; sections are clearly delimited |
573
+ | GitHub Actions pinned to full commit SHAs; PyPI via Trusted Publishing | a security tool's own supply chain must not hinge on mutable tags or a long-lived token | SHAs need manual bumps |
574
+ | `--deep` opt-in | float-stat passes on 50 GB BF16 models are slow | the default run doesn't inspect weight values (stated in the verdict) |
575
+
576
+ ---
577
+
578
+ ## License
579
+
580
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,7 @@
1
+ modelsieve.py,sha256=G4MCEb87cGUhDJnC4erW-o6t7vmY20bLpSz44nREKU4,58104
2
+ modelsieve-0.1.0.dist-info/licenses/LICENSE,sha256=uMZm924JuleppM8lMINGwWjY2h5KVyjYf4Zqbao2uRE,1073
3
+ modelsieve-0.1.0.dist-info/METADATA,sha256=wMO3h_FC40mwnXa5U15kDE6IRtSOEQ8SNLGc1PYPmjM,34199
4
+ modelsieve-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
5
+ modelsieve-0.1.0.dist-info/entry_points.txt,sha256=LpIeaTT2bO7aeYKqd5m-IYbzFt_-GO47YnXVwp9f7ok,47
6
+ modelsieve-0.1.0.dist-info/top_level.txt,sha256=cgvZPOuYevOoXovAAM4N3LVgtE8-VHF2DKhWA9aRAFc,11
7
+ modelsieve-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ modelsieve = modelsieve:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Redveil Industry
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ modelsieve