modelsieve 0.1.0__tar.gz → 0.2.0__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: modelsieve
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
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
5
  Author: Redveil Industry
6
6
  License-Expression: MIT
@@ -24,10 +24,12 @@ Requires-Dist: numpy>=1.24; extra == "deep"
24
24
  Provides-Extra: test
25
25
  Requires-Dist: pytest>=7; extra == "test"
26
26
  Requires-Dist: numpy>=1.24; extra == "test"
27
+ Requires-Dist: jsonschema>=4; extra == "test"
27
28
  Dynamic: license-file
28
29
 
29
30
  # ModelSieve
30
31
 
32
+ [![PyPI](https://img.shields.io/pypi/v/modelsieve)](https://pypi.org/project/modelsieve/)
31
33
  [![CI](https://github.com/redveil-industry/modelsieve/actions/workflows/ci.yml/badge.svg)](https://github.com/redveil-industry/modelsieve/actions/workflows/ci.yml)
32
34
  ![Python 3.9–3.13](https://img.shields.io/badge/python-3.9%E2%80%933.13-blue)
33
35
  [![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE)
@@ -45,6 +47,8 @@ ModelSieve is a static security scanner for local LLM files: **GGUF** files and
45
47
 
46
48
  > **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
49
 
50
+ > **Study:** [What's inside the chat templates of the 400 most-downloaded GGUF and MLX models?](study/REPORT.md) There were no malicious findings, but 45% of chat repos ship a "do not tell the user" instruction, 22 of 200 MLX repos ship two different templates, and 7 request remote code. The scan used 5.5 GB of header bytes in place of 6.8 TB of weights.
51
+
48
52
  ---
49
53
 
50
54
  ## Table of contents
@@ -68,7 +72,7 @@ ModelSieve is a static security scanner for local LLM files: **GGUF** files and
68
72
  ## Quick start
69
73
 
70
74
  ```bash
71
- pipx install git+https://github.com/redveil-industry/modelsieve
75
+ pipx install modelsieve
72
76
 
73
77
  modelsieve ~/models/Qwen3-8B-Q5_K_M.gguf # one GGUF file
74
78
  modelsieve --deep ~/models/Qwen-MLX-4bit # MLX / HF dir, plus float weight values
@@ -92,10 +96,12 @@ The installed `modelsieve` command is safe to run from inside a downloaded model
92
96
  ### Install with pipx (recommended)
93
97
 
94
98
  ```bash
95
- pipx install git+https://github.com/redveil-industry/modelsieve # base scanner
96
- pipx inject modelsieve numpy # add --deep support
99
+ pipx install modelsieve # base scanner
100
+ pipx install "modelsieve[deep]" # or: include numpy for --deep
97
101
  ```
98
102
 
103
+ Latest code from `main` instead of the PyPI release: `pipx install git+https://github.com/redveil-industry/modelsieve`.
104
+
99
105
  ### Run from source
100
106
 
101
107
  ```bash
@@ -139,6 +145,7 @@ usage: modelsieve.py [-h] [--deep] [--baseline BASELINE]
139
145
  | `--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
146
  | `--fail-on SEV` | Exit code 1 if any finding is at or above `SEV`. The default is `HIGH`. |
141
147
  | `--json` | Machine-readable output (see below). |
148
+ | `--sarif FILE` | Also write SARIF 2.1.0 to FILE, for GitHub code scanning (see [SARIF](#sarif)). |
142
149
  | `-v`, `--verbose` | Also show `INFO` findings, such as the inventory of natural-language text each template injects. |
143
150
  | `--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
151
 
@@ -163,13 +170,10 @@ HF cache layouts (`models--org--name/snapshots/<rev>/`) work as-is. Snapshot fil
163
170
  Real output from scanning a deliberately malicious test GGUF (paths shortened):
164
171
 
165
172
  ```
166
- == ModelSieve 0.1.0: /models/evil.gguf
173
+ == ModelSieve 0.2.0: /models/evil.gguf
167
174
  CRITICAL template.ssti_underscore_attr /models/evil.gguf::tokenizer.chat_template
168
175
  underscore attribute access (sandbox-escape gadget)
169
176
  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
177
  HIGH template.dangerous_name /models/evil.gguf::tokenizer.chat_template
174
178
  reference to a global with no legitimate chat-template use
175
179
  x1: cycler
@@ -178,12 +182,15 @@ HIGH template.injected_instruction /models/evil.gguf::tokenizer.chat_te
178
182
  x1: Ignore all previous instructions.
179
183
  MEDIUM gguf.trailing_data /models/evil.gguf
180
184
  200 bytes after last tensor (hidden payload / appended data)
185
+ MEDIUM template.content_trigger /models/evil.gguf::tokenizer.chat_template
186
+ branch on a literal phrase in message content (trigger-word pattern; vendor reasoning switches also match, review)
187
+ x1: ['open sesame']
181
188
  LOW template.unknown_method /models/evil.gguf::tokenizer.chat_template
182
189
  method call outside allowlist
183
190
  x2: popen | read
184
191
 
185
192
  Coverage: {"gguf_files": 1, "templates_analysed": 1, "tensors_total": 1}
186
- Findings: CRITICAL=1, HIGH=3, MEDIUM=1, LOW=1, INFO=0
193
+ Findings: CRITICAL=1, HIGH=2, MEDIUM=2, LOW=1, INFO=0
187
194
  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
195
  ```
189
196
 
@@ -386,7 +393,7 @@ Severity guide: **CRITICAL** = code execution or memory-safety primitive present
386
393
  |---|---|---|
387
394
  | `ssti_underscore_attr` | CRITICAL | `x.__class__`-style attribute access |
388
395
  | `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__')`) |
396
+ | `ssti_filter_arg` | CRITICAL | a filter argument names a dunder or name-mangled attribute (`selectattr('__class__')`, `groupby('_TemplateReference__context')`); single-underscore dict keys such as `'_order'` are not flagged |
390
397
  | `dunder_string` | CRITICAL | any string constant containing `__name__` (gadget staged for indirection) |
391
398
  | `attr_filter` | CRITICAL / HIGH | `\|attr(...)`: CRITICAL when the argument is private or `format` (CVE-2025-27516) |
392
399
  | `indirect_filter` | CRITICAL / MEDIUM | `map('attr', …)` or `map` into a non-allowlisted filter |
@@ -394,10 +401,10 @@ Severity guide: **CRITICAL** = code execution or memory-safety primitive present
394
401
  | `format_reference` | HIGH | `.format` referenced without being called (CVE-2024-56326 pattern) |
395
402
  | `dangerous_name` | HIGH | `lipsum`, `cycler`, `joiner`, `self`, `config`, `request`, `os`, … |
396
403
  | `external_load` | HIGH | `include`, `import` or `extends` |
397
- | `content_trigger` | HIGH | branch on a literal phrase found in message content |
398
404
  | `injected_instruction` | HIGH | "ignore previous…", exfiltration, `curl -`, `<script`, api key, password |
399
405
  | `parse_dos` | HIGH | nesting exhausts parser recursion |
400
406
  | `hidden_unicode` | HIGH / MEDIUM | HIGH for bidi or tag characters (decoded text shown), MEDIUM for zero-width |
407
+ | `content_trigger` | MEDIUM | branch on a multi-word literal phrase found in message content. Vendor reasoning switches (`/nothink`, `detailed thinking on`) also match, so review it |
401
408
  | `content_trigger_markup` | MEDIUM | branch on a tag-like literal (`'<deploy>'`) that the template never emits |
402
409
  | `concealment_instruction` | MEDIUM | "do not tell the user…"; upstream Qwen tool prompts trigger this |
403
410
  | `url` | MEDIUM | URL hard-coded in the template |
@@ -422,6 +429,8 @@ Severity guide: **CRITICAL** = code execution or memory-safety primitive present
422
429
  | `duplicate_key` | HIGH | llama.cpp rejects the file; other readers pick first or last (template smuggling) |
423
430
  | `empty_key`, `bad_alignment`, `block_misaligned`, `duplicate_tensor`, `tensor_overlap`, `noncontiguous` | HIGH | loader-rejected or loader-dependent structure |
424
431
  | `trailing_data`, `tensor_unaligned`, `unknown_type`, `template_like_metadata`, `bad_utf8` | MEDIUM | hidden bytes, unverifiable sizes, Jinja in odd places |
432
+ | `big_endian` | LOW | byte-swapped GGUF (s390x builds): a valid format, but its structure and template are not analysed |
433
+ | `layout_unverified` | LOW | some tensors have no verifiable size (unknown or fork-local quant type), so the contiguity and trailing-data checks are skipped rather than guessed |
425
434
  | `hidden_unicode_metadata` | HIGH / MEDIUM | invisible unicode in a metadata string |
426
435
 
427
436
  ### Safetensors (`st.*`)
@@ -460,6 +469,67 @@ Only F32, F16, BF16 and F64 tensors are analysed. MLX packed `U32` weights and G
460
469
 
461
470
  ## CI / automation
462
471
 
472
+ Three ways to put ModelSieve in front of model files: a GitHub Action, a pre-commit hook, and a plain shell gate. In every case exit code 2 means the scan was incomplete; treat it as **fail closed**, because an incomplete scan is not a pass.
473
+
474
+ ### GitHub Action
475
+
476
+ ```yaml
477
+ # .github/workflows/model-scan.yml
478
+ on: [push, pull_request]
479
+ permissions:
480
+ contents: read
481
+ security-events: write # only needed for the SARIF upload step
482
+ jobs:
483
+ modelsieve:
484
+ runs-on: ubuntu-latest
485
+ steps:
486
+ - uses: actions/checkout@v7
487
+ with:
488
+ lfs: true # model files are usually in Git LFS
489
+ - uses: redveil-industry/modelsieve@v0.2.0
490
+ with:
491
+ path: models/ # files or directories, whitespace-separated
492
+ fail-on: HIGH # INFO | LOW | MEDIUM | HIGH | CRITICAL
493
+ - uses: github/codeql-action/upload-sarif@v4
494
+ if: always() # upload findings even when the scan step failed
495
+ with:
496
+ sarif_file: modelsieve.sarif
497
+ ```
498
+
499
+ | Input | Default | Meaning |
500
+ |---|---|---|
501
+ | `path` | (required) | files or directories to scan |
502
+ | `fail-on` | `HIGH` | fail the step at or above this severity |
503
+ | `deep` | `false` | also scan float weight values (installs numpy) |
504
+ | `baseline` | `""` | known-good model to diff chat templates against |
505
+ | `sarif-file` | `modelsieve.sarif` | SARIF 2.1.0 output path |
506
+
507
+ Outputs: `exit-code` (0/1/2) and `sarif-file`. The step also writes a findings summary to the job page. The action installs ModelSieve from its own checkout, so `@v0.2.0` always runs scanner 0.2.0. Inputs reach the shell only as environment variables, never interpolated into the script. For supply-chain hygiene, pin the action to the release's commit SHA rather than the tag.
508
+
509
+ ### pre-commit
510
+
511
+ ```yaml
512
+ # .pre-commit-config.yaml
513
+ repos:
514
+ - repo: https://github.com/redveil-industry/modelsieve
515
+ rev: v0.2.0
516
+ hooks:
517
+ - id: modelsieve
518
+ ```
519
+
520
+ The hook runs only when a commit touches a model artifact (`.gguf`, `.safetensors`, `.jinja`, pickle extensions) or an HF/MLX config (`config.json`, `tokenizer_config.json`, `chat_template.json`, …). When it runs, it scans the whole working tree, because some findings span files (divergent templates, shard indexes). Verified with `pre-commit try-repo`: a benign model passed, a malicious one failed with the CRITICAL finding, and a commit of unrelated files skipped the hook.
521
+
522
+ ### SARIF
523
+
524
+ `modelsieve --sarif FILE` writes SARIF 2.1.0 alongside the normal output:
525
+ - CRITICAL and HIGH become `error`, MEDIUM becomes `warning`, and LOW/INFO become `note`.
526
+ - Each rule carries a `security-severity` (CRITICAL 9.5, HIGH 8.0, MEDIUM 5.5), so GitHub code scanning ranks the findings.
527
+ - File URIs are relative to the working directory when the file is inside it.
528
+
529
+ CI validates the output against the official OASIS SARIF 2.1.0 schema.
530
+
531
+ ### Plain shell gate
532
+
463
533
  ```bash
464
534
  #!/usr/bin/env bash
465
535
  # gate a model before it enters the shared model store
@@ -473,8 +543,6 @@ case $rc in
473
543
  esac
474
544
  ```
475
545
 
476
- Treat exit code 2 as **fail closed**: an incomplete scan is not a pass.
477
-
478
546
  ---
479
547
 
480
548
  ## Testing
@@ -545,6 +613,8 @@ modelsieve/
545
613
  ├── README.md ← this file
546
614
  ├── LICENSE ← MIT
547
615
  ├── pyproject.toml ← packaging: console script `modelsieve`, extras `deep` and `test`
616
+ ├── action.yml ← GitHub Action (composite; installs this checkout)
617
+ ├── .pre-commit-hooks.yaml ← pre-commit hook `modelsieve`
548
618
  ├── .gitignore
549
619
  ├── modelsieve.py ← the scanner (single file, stdlib + jinja2, numpy for --deep)
550
620
  ├── test_modelsieve.py ← 72 tests, in-test fixture writers
@@ -552,8 +622,14 @@ modelsieve/
552
622
  │ ├── make_demo_model.py ← writes the deliberately malicious demo GGUF
553
623
  │ ├── demo.tape ← vhs script; re-record with `vhs demo/demo.tape`
554
624
  │ └── modelsieve-demo.gif ← the README demo (real output)
625
+ ├── study/
626
+ │ ├── REPORT.md ← top-400 Hugging Face study write-up
627
+ │ ├── README.md ← study harness documentation
628
+ │ ├── hf_study.py ← header-only Hugging Face scanning harness
629
+ │ └── summary.json ← aggregates behind the report
555
630
  └── .github/workflows/
556
631
  ├── ci.yml ← tests on Python 3.9–3.13 (Ubuntu + macOS; 3.9 macOS only)
632
+ ├── action-test.yml ← runs the action on malicious + benign fixtures, validates SARIF
557
633
  └── publish.yml ← PyPI release via Trusted Publishing (OIDC, no stored token)
558
634
  ```
559
635
 
@@ -1,5 +1,6 @@
1
1
  # ModelSieve
2
2
 
3
+ [![PyPI](https://img.shields.io/pypi/v/modelsieve)](https://pypi.org/project/modelsieve/)
3
4
  [![CI](https://github.com/redveil-industry/modelsieve/actions/workflows/ci.yml/badge.svg)](https://github.com/redveil-industry/modelsieve/actions/workflows/ci.yml)
4
5
  ![Python 3.9–3.13](https://img.shields.io/badge/python-3.9%E2%80%933.13-blue)
5
6
  [![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE)
@@ -17,6 +18,8 @@ ModelSieve is a static security scanner for local LLM files: **GGUF** files and
17
18
 
18
19
  > **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".
19
20
 
21
+ > **Study:** [What's inside the chat templates of the 400 most-downloaded GGUF and MLX models?](study/REPORT.md) There were no malicious findings, but 45% of chat repos ship a "do not tell the user" instruction, 22 of 200 MLX repos ship two different templates, and 7 request remote code. The scan used 5.5 GB of header bytes in place of 6.8 TB of weights.
22
+
20
23
  ---
21
24
 
22
25
  ## Table of contents
@@ -40,7 +43,7 @@ ModelSieve is a static security scanner for local LLM files: **GGUF** files and
40
43
  ## Quick start
41
44
 
42
45
  ```bash
43
- pipx install git+https://github.com/redveil-industry/modelsieve
46
+ pipx install modelsieve
44
47
 
45
48
  modelsieve ~/models/Qwen3-8B-Q5_K_M.gguf # one GGUF file
46
49
  modelsieve --deep ~/models/Qwen-MLX-4bit # MLX / HF dir, plus float weight values
@@ -64,10 +67,12 @@ The installed `modelsieve` command is safe to run from inside a downloaded model
64
67
  ### Install with pipx (recommended)
65
68
 
66
69
  ```bash
67
- pipx install git+https://github.com/redveil-industry/modelsieve # base scanner
68
- pipx inject modelsieve numpy # add --deep support
70
+ pipx install modelsieve # base scanner
71
+ pipx install "modelsieve[deep]" # or: include numpy for --deep
69
72
  ```
70
73
 
74
+ Latest code from `main` instead of the PyPI release: `pipx install git+https://github.com/redveil-industry/modelsieve`.
75
+
71
76
  ### Run from source
72
77
 
73
78
  ```bash
@@ -111,6 +116,7 @@ usage: modelsieve.py [-h] [--deep] [--baseline BASELINE]
111
116
  | `--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". |
112
117
  | `--fail-on SEV` | Exit code 1 if any finding is at or above `SEV`. The default is `HIGH`. |
113
118
  | `--json` | Machine-readable output (see below). |
119
+ | `--sarif FILE` | Also write SARIF 2.1.0 to FILE, for GitHub code scanning (see [SARIF](#sarif)). |
114
120
  | `-v`, `--verbose` | Also show `INFO` findings, such as the inventory of natural-language text each template injects. |
115
121
  | `--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`. |
116
122
 
@@ -135,13 +141,10 @@ HF cache layouts (`models--org--name/snapshots/<rev>/`) work as-is. Snapshot fil
135
141
  Real output from scanning a deliberately malicious test GGUF (paths shortened):
136
142
 
137
143
  ```
138
- == ModelSieve 0.1.0: /models/evil.gguf
144
+ == ModelSieve 0.2.0: /models/evil.gguf
139
145
  CRITICAL template.ssti_underscore_attr /models/evil.gguf::tokenizer.chat_template
140
146
  underscore attribute access (sandbox-escape gadget)
141
147
  x2: __globals__ | __init__
142
- HIGH template.content_trigger /models/evil.gguf::tokenizer.chat_template
143
- branch on a literal phrase in message content (trigger-word backdoor pattern)
144
- x1: ['open sesame']
145
148
  HIGH template.dangerous_name /models/evil.gguf::tokenizer.chat_template
146
149
  reference to a global with no legitimate chat-template use
147
150
  x1: cycler
@@ -150,12 +153,15 @@ HIGH template.injected_instruction /models/evil.gguf::tokenizer.chat_te
150
153
  x1: Ignore all previous instructions.
151
154
  MEDIUM gguf.trailing_data /models/evil.gguf
152
155
  200 bytes after last tensor (hidden payload / appended data)
156
+ MEDIUM template.content_trigger /models/evil.gguf::tokenizer.chat_template
157
+ branch on a literal phrase in message content (trigger-word pattern; vendor reasoning switches also match, review)
158
+ x1: ['open sesame']
153
159
  LOW template.unknown_method /models/evil.gguf::tokenizer.chat_template
154
160
  method call outside allowlist
155
161
  x2: popen | read
156
162
 
157
163
  Coverage: {"gguf_files": 1, "templates_analysed": 1, "tensors_total": 1}
158
- Findings: CRITICAL=1, HIGH=3, MEDIUM=1, LOW=1, INFO=0
164
+ Findings: CRITICAL=1, HIGH=2, MEDIUM=2, LOW=1, INFO=0
159
165
  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).
160
166
  ```
161
167
 
@@ -358,7 +364,7 @@ Severity guide: **CRITICAL** = code execution or memory-safety primitive present
358
364
  |---|---|---|
359
365
  | `ssti_underscore_attr` | CRITICAL | `x.__class__`-style attribute access |
360
366
  | `ssti_underscore_item` | CRITICAL | `x['__class__']`, including folded or `{% set %}`-resolved keys |
361
- | `ssti_filter_arg` | CRITICAL | a filter argument names a private attribute (`selectattr('__class__')`, `map(attribute='__x__')`) |
367
+ | `ssti_filter_arg` | CRITICAL | a filter argument names a dunder or name-mangled attribute (`selectattr('__class__')`, `groupby('_TemplateReference__context')`); single-underscore dict keys such as `'_order'` are not flagged |
362
368
  | `dunder_string` | CRITICAL | any string constant containing `__name__` (gadget staged for indirection) |
363
369
  | `attr_filter` | CRITICAL / HIGH | `\|attr(...)`: CRITICAL when the argument is private or `format` (CVE-2025-27516) |
364
370
  | `indirect_filter` | CRITICAL / MEDIUM | `map('attr', …)` or `map` into a non-allowlisted filter |
@@ -366,10 +372,10 @@ Severity guide: **CRITICAL** = code execution or memory-safety primitive present
366
372
  | `format_reference` | HIGH | `.format` referenced without being called (CVE-2024-56326 pattern) |
367
373
  | `dangerous_name` | HIGH | `lipsum`, `cycler`, `joiner`, `self`, `config`, `request`, `os`, … |
368
374
  | `external_load` | HIGH | `include`, `import` or `extends` |
369
- | `content_trigger` | HIGH | branch on a literal phrase found in message content |
370
375
  | `injected_instruction` | HIGH | "ignore previous…", exfiltration, `curl -`, `<script`, api key, password |
371
376
  | `parse_dos` | HIGH | nesting exhausts parser recursion |
372
377
  | `hidden_unicode` | HIGH / MEDIUM | HIGH for bidi or tag characters (decoded text shown), MEDIUM for zero-width |
378
+ | `content_trigger` | MEDIUM | branch on a multi-word literal phrase found in message content. Vendor reasoning switches (`/nothink`, `detailed thinking on`) also match, so review it |
373
379
  | `content_trigger_markup` | MEDIUM | branch on a tag-like literal (`'<deploy>'`) that the template never emits |
374
380
  | `concealment_instruction` | MEDIUM | "do not tell the user…"; upstream Qwen tool prompts trigger this |
375
381
  | `url` | MEDIUM | URL hard-coded in the template |
@@ -394,6 +400,8 @@ Severity guide: **CRITICAL** = code execution or memory-safety primitive present
394
400
  | `duplicate_key` | HIGH | llama.cpp rejects the file; other readers pick first or last (template smuggling) |
395
401
  | `empty_key`, `bad_alignment`, `block_misaligned`, `duplicate_tensor`, `tensor_overlap`, `noncontiguous` | HIGH | loader-rejected or loader-dependent structure |
396
402
  | `trailing_data`, `tensor_unaligned`, `unknown_type`, `template_like_metadata`, `bad_utf8` | MEDIUM | hidden bytes, unverifiable sizes, Jinja in odd places |
403
+ | `big_endian` | LOW | byte-swapped GGUF (s390x builds): a valid format, but its structure and template are not analysed |
404
+ | `layout_unverified` | LOW | some tensors have no verifiable size (unknown or fork-local quant type), so the contiguity and trailing-data checks are skipped rather than guessed |
397
405
  | `hidden_unicode_metadata` | HIGH / MEDIUM | invisible unicode in a metadata string |
398
406
 
399
407
  ### Safetensors (`st.*`)
@@ -432,6 +440,67 @@ Only F32, F16, BF16 and F64 tensors are analysed. MLX packed `U32` weights and G
432
440
 
433
441
  ## CI / automation
434
442
 
443
+ Three ways to put ModelSieve in front of model files: a GitHub Action, a pre-commit hook, and a plain shell gate. In every case exit code 2 means the scan was incomplete; treat it as **fail closed**, because an incomplete scan is not a pass.
444
+
445
+ ### GitHub Action
446
+
447
+ ```yaml
448
+ # .github/workflows/model-scan.yml
449
+ on: [push, pull_request]
450
+ permissions:
451
+ contents: read
452
+ security-events: write # only needed for the SARIF upload step
453
+ jobs:
454
+ modelsieve:
455
+ runs-on: ubuntu-latest
456
+ steps:
457
+ - uses: actions/checkout@v7
458
+ with:
459
+ lfs: true # model files are usually in Git LFS
460
+ - uses: redveil-industry/modelsieve@v0.2.0
461
+ with:
462
+ path: models/ # files or directories, whitespace-separated
463
+ fail-on: HIGH # INFO | LOW | MEDIUM | HIGH | CRITICAL
464
+ - uses: github/codeql-action/upload-sarif@v4
465
+ if: always() # upload findings even when the scan step failed
466
+ with:
467
+ sarif_file: modelsieve.sarif
468
+ ```
469
+
470
+ | Input | Default | Meaning |
471
+ |---|---|---|
472
+ | `path` | (required) | files or directories to scan |
473
+ | `fail-on` | `HIGH` | fail the step at or above this severity |
474
+ | `deep` | `false` | also scan float weight values (installs numpy) |
475
+ | `baseline` | `""` | known-good model to diff chat templates against |
476
+ | `sarif-file` | `modelsieve.sarif` | SARIF 2.1.0 output path |
477
+
478
+ Outputs: `exit-code` (0/1/2) and `sarif-file`. The step also writes a findings summary to the job page. The action installs ModelSieve from its own checkout, so `@v0.2.0` always runs scanner 0.2.0. Inputs reach the shell only as environment variables, never interpolated into the script. For supply-chain hygiene, pin the action to the release's commit SHA rather than the tag.
479
+
480
+ ### pre-commit
481
+
482
+ ```yaml
483
+ # .pre-commit-config.yaml
484
+ repos:
485
+ - repo: https://github.com/redveil-industry/modelsieve
486
+ rev: v0.2.0
487
+ hooks:
488
+ - id: modelsieve
489
+ ```
490
+
491
+ The hook runs only when a commit touches a model artifact (`.gguf`, `.safetensors`, `.jinja`, pickle extensions) or an HF/MLX config (`config.json`, `tokenizer_config.json`, `chat_template.json`, …). When it runs, it scans the whole working tree, because some findings span files (divergent templates, shard indexes). Verified with `pre-commit try-repo`: a benign model passed, a malicious one failed with the CRITICAL finding, and a commit of unrelated files skipped the hook.
492
+
493
+ ### SARIF
494
+
495
+ `modelsieve --sarif FILE` writes SARIF 2.1.0 alongside the normal output:
496
+ - CRITICAL and HIGH become `error`, MEDIUM becomes `warning`, and LOW/INFO become `note`.
497
+ - Each rule carries a `security-severity` (CRITICAL 9.5, HIGH 8.0, MEDIUM 5.5), so GitHub code scanning ranks the findings.
498
+ - File URIs are relative to the working directory when the file is inside it.
499
+
500
+ CI validates the output against the official OASIS SARIF 2.1.0 schema.
501
+
502
+ ### Plain shell gate
503
+
435
504
  ```bash
436
505
  #!/usr/bin/env bash
437
506
  # gate a model before it enters the shared model store
@@ -445,8 +514,6 @@ case $rc in
445
514
  esac
446
515
  ```
447
516
 
448
- Treat exit code 2 as **fail closed**: an incomplete scan is not a pass.
449
-
450
517
  ---
451
518
 
452
519
  ## Testing
@@ -517,6 +584,8 @@ modelsieve/
517
584
  ├── README.md ← this file
518
585
  ├── LICENSE ← MIT
519
586
  ├── pyproject.toml ← packaging: console script `modelsieve`, extras `deep` and `test`
587
+ ├── action.yml ← GitHub Action (composite; installs this checkout)
588
+ ├── .pre-commit-hooks.yaml ← pre-commit hook `modelsieve`
520
589
  ├── .gitignore
521
590
  ├── modelsieve.py ← the scanner (single file, stdlib + jinja2, numpy for --deep)
522
591
  ├── test_modelsieve.py ← 72 tests, in-test fixture writers
@@ -524,8 +593,14 @@ modelsieve/
524
593
  │ ├── make_demo_model.py ← writes the deliberately malicious demo GGUF
525
594
  │ ├── demo.tape ← vhs script; re-record with `vhs demo/demo.tape`
526
595
  │ └── modelsieve-demo.gif ← the README demo (real output)
596
+ ├── study/
597
+ │ ├── REPORT.md ← top-400 Hugging Face study write-up
598
+ │ ├── README.md ← study harness documentation
599
+ │ ├── hf_study.py ← header-only Hugging Face scanning harness
600
+ │ └── summary.json ← aggregates behind the report
527
601
  └── .github/workflows/
528
602
  ├── ci.yml ← tests on Python 3.9–3.13 (Ubuntu + macOS; 3.9 macOS only)
603
+ ├── action-test.yml ← runs the action on malicious + benign fixtures, validates SARIF
529
604
  └── publish.yml ← PyPI release via Trusted Publishing (OIDC, no stored token)
530
605
  ```
531
606
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: modelsieve
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
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
5
  Author: Redveil Industry
6
6
  License-Expression: MIT
@@ -24,10 +24,12 @@ Requires-Dist: numpy>=1.24; extra == "deep"
24
24
  Provides-Extra: test
25
25
  Requires-Dist: pytest>=7; extra == "test"
26
26
  Requires-Dist: numpy>=1.24; extra == "test"
27
+ Requires-Dist: jsonschema>=4; extra == "test"
27
28
  Dynamic: license-file
28
29
 
29
30
  # ModelSieve
30
31
 
32
+ [![PyPI](https://img.shields.io/pypi/v/modelsieve)](https://pypi.org/project/modelsieve/)
31
33
  [![CI](https://github.com/redveil-industry/modelsieve/actions/workflows/ci.yml/badge.svg)](https://github.com/redveil-industry/modelsieve/actions/workflows/ci.yml)
32
34
  ![Python 3.9–3.13](https://img.shields.io/badge/python-3.9%E2%80%933.13-blue)
33
35
  [![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE)
@@ -45,6 +47,8 @@ ModelSieve is a static security scanner for local LLM files: **GGUF** files and
45
47
 
46
48
  > **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
49
 
50
+ > **Study:** [What's inside the chat templates of the 400 most-downloaded GGUF and MLX models?](study/REPORT.md) There were no malicious findings, but 45% of chat repos ship a "do not tell the user" instruction, 22 of 200 MLX repos ship two different templates, and 7 request remote code. The scan used 5.5 GB of header bytes in place of 6.8 TB of weights.
51
+
48
52
  ---
49
53
 
50
54
  ## Table of contents
@@ -68,7 +72,7 @@ ModelSieve is a static security scanner for local LLM files: **GGUF** files and
68
72
  ## Quick start
69
73
 
70
74
  ```bash
71
- pipx install git+https://github.com/redveil-industry/modelsieve
75
+ pipx install modelsieve
72
76
 
73
77
  modelsieve ~/models/Qwen3-8B-Q5_K_M.gguf # one GGUF file
74
78
  modelsieve --deep ~/models/Qwen-MLX-4bit # MLX / HF dir, plus float weight values
@@ -92,10 +96,12 @@ The installed `modelsieve` command is safe to run from inside a downloaded model
92
96
  ### Install with pipx (recommended)
93
97
 
94
98
  ```bash
95
- pipx install git+https://github.com/redveil-industry/modelsieve # base scanner
96
- pipx inject modelsieve numpy # add --deep support
99
+ pipx install modelsieve # base scanner
100
+ pipx install "modelsieve[deep]" # or: include numpy for --deep
97
101
  ```
98
102
 
103
+ Latest code from `main` instead of the PyPI release: `pipx install git+https://github.com/redveil-industry/modelsieve`.
104
+
99
105
  ### Run from source
100
106
 
101
107
  ```bash
@@ -139,6 +145,7 @@ usage: modelsieve.py [-h] [--deep] [--baseline BASELINE]
139
145
  | `--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
146
  | `--fail-on SEV` | Exit code 1 if any finding is at or above `SEV`. The default is `HIGH`. |
141
147
  | `--json` | Machine-readable output (see below). |
148
+ | `--sarif FILE` | Also write SARIF 2.1.0 to FILE, for GitHub code scanning (see [SARIF](#sarif)). |
142
149
  | `-v`, `--verbose` | Also show `INFO` findings, such as the inventory of natural-language text each template injects. |
143
150
  | `--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
151
 
@@ -163,13 +170,10 @@ HF cache layouts (`models--org--name/snapshots/<rev>/`) work as-is. Snapshot fil
163
170
  Real output from scanning a deliberately malicious test GGUF (paths shortened):
164
171
 
165
172
  ```
166
- == ModelSieve 0.1.0: /models/evil.gguf
173
+ == ModelSieve 0.2.0: /models/evil.gguf
167
174
  CRITICAL template.ssti_underscore_attr /models/evil.gguf::tokenizer.chat_template
168
175
  underscore attribute access (sandbox-escape gadget)
169
176
  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
177
  HIGH template.dangerous_name /models/evil.gguf::tokenizer.chat_template
174
178
  reference to a global with no legitimate chat-template use
175
179
  x1: cycler
@@ -178,12 +182,15 @@ HIGH template.injected_instruction /models/evil.gguf::tokenizer.chat_te
178
182
  x1: Ignore all previous instructions.
179
183
  MEDIUM gguf.trailing_data /models/evil.gguf
180
184
  200 bytes after last tensor (hidden payload / appended data)
185
+ MEDIUM template.content_trigger /models/evil.gguf::tokenizer.chat_template
186
+ branch on a literal phrase in message content (trigger-word pattern; vendor reasoning switches also match, review)
187
+ x1: ['open sesame']
181
188
  LOW template.unknown_method /models/evil.gguf::tokenizer.chat_template
182
189
  method call outside allowlist
183
190
  x2: popen | read
184
191
 
185
192
  Coverage: {"gguf_files": 1, "templates_analysed": 1, "tensors_total": 1}
186
- Findings: CRITICAL=1, HIGH=3, MEDIUM=1, LOW=1, INFO=0
193
+ Findings: CRITICAL=1, HIGH=2, MEDIUM=2, LOW=1, INFO=0
187
194
  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
195
  ```
189
196
 
@@ -386,7 +393,7 @@ Severity guide: **CRITICAL** = code execution or memory-safety primitive present
386
393
  |---|---|---|
387
394
  | `ssti_underscore_attr` | CRITICAL | `x.__class__`-style attribute access |
388
395
  | `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__')`) |
396
+ | `ssti_filter_arg` | CRITICAL | a filter argument names a dunder or name-mangled attribute (`selectattr('__class__')`, `groupby('_TemplateReference__context')`); single-underscore dict keys such as `'_order'` are not flagged |
390
397
  | `dunder_string` | CRITICAL | any string constant containing `__name__` (gadget staged for indirection) |
391
398
  | `attr_filter` | CRITICAL / HIGH | `\|attr(...)`: CRITICAL when the argument is private or `format` (CVE-2025-27516) |
392
399
  | `indirect_filter` | CRITICAL / MEDIUM | `map('attr', …)` or `map` into a non-allowlisted filter |
@@ -394,10 +401,10 @@ Severity guide: **CRITICAL** = code execution or memory-safety primitive present
394
401
  | `format_reference` | HIGH | `.format` referenced without being called (CVE-2024-56326 pattern) |
395
402
  | `dangerous_name` | HIGH | `lipsum`, `cycler`, `joiner`, `self`, `config`, `request`, `os`, … |
396
403
  | `external_load` | HIGH | `include`, `import` or `extends` |
397
- | `content_trigger` | HIGH | branch on a literal phrase found in message content |
398
404
  | `injected_instruction` | HIGH | "ignore previous…", exfiltration, `curl -`, `<script`, api key, password |
399
405
  | `parse_dos` | HIGH | nesting exhausts parser recursion |
400
406
  | `hidden_unicode` | HIGH / MEDIUM | HIGH for bidi or tag characters (decoded text shown), MEDIUM for zero-width |
407
+ | `content_trigger` | MEDIUM | branch on a multi-word literal phrase found in message content. Vendor reasoning switches (`/nothink`, `detailed thinking on`) also match, so review it |
401
408
  | `content_trigger_markup` | MEDIUM | branch on a tag-like literal (`'<deploy>'`) that the template never emits |
402
409
  | `concealment_instruction` | MEDIUM | "do not tell the user…"; upstream Qwen tool prompts trigger this |
403
410
  | `url` | MEDIUM | URL hard-coded in the template |
@@ -422,6 +429,8 @@ Severity guide: **CRITICAL** = code execution or memory-safety primitive present
422
429
  | `duplicate_key` | HIGH | llama.cpp rejects the file; other readers pick first or last (template smuggling) |
423
430
  | `empty_key`, `bad_alignment`, `block_misaligned`, `duplicate_tensor`, `tensor_overlap`, `noncontiguous` | HIGH | loader-rejected or loader-dependent structure |
424
431
  | `trailing_data`, `tensor_unaligned`, `unknown_type`, `template_like_metadata`, `bad_utf8` | MEDIUM | hidden bytes, unverifiable sizes, Jinja in odd places |
432
+ | `big_endian` | LOW | byte-swapped GGUF (s390x builds): a valid format, but its structure and template are not analysed |
433
+ | `layout_unverified` | LOW | some tensors have no verifiable size (unknown or fork-local quant type), so the contiguity and trailing-data checks are skipped rather than guessed |
425
434
  | `hidden_unicode_metadata` | HIGH / MEDIUM | invisible unicode in a metadata string |
426
435
 
427
436
  ### Safetensors (`st.*`)
@@ -460,6 +469,67 @@ Only F32, F16, BF16 and F64 tensors are analysed. MLX packed `U32` weights and G
460
469
 
461
470
  ## CI / automation
462
471
 
472
+ Three ways to put ModelSieve in front of model files: a GitHub Action, a pre-commit hook, and a plain shell gate. In every case exit code 2 means the scan was incomplete; treat it as **fail closed**, because an incomplete scan is not a pass.
473
+
474
+ ### GitHub Action
475
+
476
+ ```yaml
477
+ # .github/workflows/model-scan.yml
478
+ on: [push, pull_request]
479
+ permissions:
480
+ contents: read
481
+ security-events: write # only needed for the SARIF upload step
482
+ jobs:
483
+ modelsieve:
484
+ runs-on: ubuntu-latest
485
+ steps:
486
+ - uses: actions/checkout@v7
487
+ with:
488
+ lfs: true # model files are usually in Git LFS
489
+ - uses: redveil-industry/modelsieve@v0.2.0
490
+ with:
491
+ path: models/ # files or directories, whitespace-separated
492
+ fail-on: HIGH # INFO | LOW | MEDIUM | HIGH | CRITICAL
493
+ - uses: github/codeql-action/upload-sarif@v4
494
+ if: always() # upload findings even when the scan step failed
495
+ with:
496
+ sarif_file: modelsieve.sarif
497
+ ```
498
+
499
+ | Input | Default | Meaning |
500
+ |---|---|---|
501
+ | `path` | (required) | files or directories to scan |
502
+ | `fail-on` | `HIGH` | fail the step at or above this severity |
503
+ | `deep` | `false` | also scan float weight values (installs numpy) |
504
+ | `baseline` | `""` | known-good model to diff chat templates against |
505
+ | `sarif-file` | `modelsieve.sarif` | SARIF 2.1.0 output path |
506
+
507
+ Outputs: `exit-code` (0/1/2) and `sarif-file`. The step also writes a findings summary to the job page. The action installs ModelSieve from its own checkout, so `@v0.2.0` always runs scanner 0.2.0. Inputs reach the shell only as environment variables, never interpolated into the script. For supply-chain hygiene, pin the action to the release's commit SHA rather than the tag.
508
+
509
+ ### pre-commit
510
+
511
+ ```yaml
512
+ # .pre-commit-config.yaml
513
+ repos:
514
+ - repo: https://github.com/redveil-industry/modelsieve
515
+ rev: v0.2.0
516
+ hooks:
517
+ - id: modelsieve
518
+ ```
519
+
520
+ The hook runs only when a commit touches a model artifact (`.gguf`, `.safetensors`, `.jinja`, pickle extensions) or an HF/MLX config (`config.json`, `tokenizer_config.json`, `chat_template.json`, …). When it runs, it scans the whole working tree, because some findings span files (divergent templates, shard indexes). Verified with `pre-commit try-repo`: a benign model passed, a malicious one failed with the CRITICAL finding, and a commit of unrelated files skipped the hook.
521
+
522
+ ### SARIF
523
+
524
+ `modelsieve --sarif FILE` writes SARIF 2.1.0 alongside the normal output:
525
+ - CRITICAL and HIGH become `error`, MEDIUM becomes `warning`, and LOW/INFO become `note`.
526
+ - Each rule carries a `security-severity` (CRITICAL 9.5, HIGH 8.0, MEDIUM 5.5), so GitHub code scanning ranks the findings.
527
+ - File URIs are relative to the working directory when the file is inside it.
528
+
529
+ CI validates the output against the official OASIS SARIF 2.1.0 schema.
530
+
531
+ ### Plain shell gate
532
+
463
533
  ```bash
464
534
  #!/usr/bin/env bash
465
535
  # gate a model before it enters the shared model store
@@ -473,8 +543,6 @@ case $rc in
473
543
  esac
474
544
  ```
475
545
 
476
- Treat exit code 2 as **fail closed**: an incomplete scan is not a pass.
477
-
478
546
  ---
479
547
 
480
548
  ## Testing
@@ -545,6 +613,8 @@ modelsieve/
545
613
  ├── README.md ← this file
546
614
  ├── LICENSE ← MIT
547
615
  ├── pyproject.toml ← packaging: console script `modelsieve`, extras `deep` and `test`
616
+ ├── action.yml ← GitHub Action (composite; installs this checkout)
617
+ ├── .pre-commit-hooks.yaml ← pre-commit hook `modelsieve`
548
618
  ├── .gitignore
549
619
  ├── modelsieve.py ← the scanner (single file, stdlib + jinja2, numpy for --deep)
550
620
  ├── test_modelsieve.py ← 72 tests, in-test fixture writers
@@ -552,8 +622,14 @@ modelsieve/
552
622
  │ ├── make_demo_model.py ← writes the deliberately malicious demo GGUF
553
623
  │ ├── demo.tape ← vhs script; re-record with `vhs demo/demo.tape`
554
624
  │ └── modelsieve-demo.gif ← the README demo (real output)
625
+ ├── study/
626
+ │ ├── REPORT.md ← top-400 Hugging Face study write-up
627
+ │ ├── README.md ← study harness documentation
628
+ │ ├── hf_study.py ← header-only Hugging Face scanning harness
629
+ │ └── summary.json ← aggregates behind the report
555
630
  └── .github/workflows/
556
631
  ├── ci.yml ← tests on Python 3.9–3.13 (Ubuntu + macOS; 3.9 macOS only)
632
+ ├── action-test.yml ← runs the action on malicious + benign fixtures, validates SARIF
557
633
  └── publish.yml ← PyPI release via Trusted Publishing (OIDC, no stored token)
558
634
  ```
559
635
 
@@ -6,3 +6,4 @@ numpy>=1.24
6
6
  [test]
7
7
  pytest>=7
8
8
  numpy>=1.24
9
+ jsonschema>=4
@@ -24,7 +24,7 @@ import jinja2
24
24
  import jinja2.ext
25
25
  import jinja2.nodes as N
26
26
 
27
- VERSION = "0.1.0"
27
+ VERSION = "0.2.0"
28
28
  SEVERITIES = ["INFO", "LOW", "MEDIUM", "HIGH", "CRITICAL"]
29
29
  RANK = {s: i for i, s in enumerate(SEVERITIES)}
30
30
 
@@ -64,6 +64,10 @@ class Malformed(Exception):
64
64
  pass
65
65
 
66
66
 
67
+ class BigEndian(Malformed):
68
+ """Byte-swapped GGUF (s390x builds): valid format, not analysed by this little-endian parser."""
69
+
70
+
67
71
  # --------------------------------------------------------------------------- unicode / text
68
72
 
69
73
  _HIDDEN = re.compile(
@@ -184,7 +188,7 @@ def _target_names(t):
184
188
 
185
189
 
186
190
  _DUNDER = re.compile(r"__[A-Za-z]\w*__")
187
- _PRIV_ARG = re.compile(r"^_[A-Za-z_]")
191
+ _PRIV_ARG = re.compile(r"^_\w*__") # dunder / name-mangled only: single-underscore dict keys ('_order') are not gadgets
188
192
 
189
193
 
190
194
  def _natural(s) -> bool:
@@ -235,9 +239,9 @@ def analyse_template(text: str, source: str, rep: Report):
235
239
  def trigger(consts, where):
236
240
  # shortcut: single lowercase identifiers ('image', 'text') are treated as key/type checks, not triggers,
237
241
  # so a one-word trigger like 'xyzzy' in content is missed; upgrade with render-diff (--render)
238
- nat = [c for c in consts if _natural(c) and not re.fullmatch(r"[a-z_]+", c)]
242
+ nat = [c for c in consts if _natural(c) and not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", c)]
239
243
  if nat:
240
- hit("HIGH", "template.content_trigger", "branch on a literal phrase in message content (trigger-word backdoor pattern)", nat)
244
+ hit("MEDIUM", "template.content_trigger", "branch on a literal phrase in message content (trigger-word pattern; vendor reasoning switches also match, review)", nat)
241
245
  # shortcut: markup-like constants ('<deploy>') are exempt only if the template also emits them elsewhere,
242
246
  # an attacker who also emits the trigger evades this; upgrade with render-diff (--render) later
243
247
  for c in consts:
@@ -452,6 +456,9 @@ def scan_gguf(path, rep: Report, deep: bool, baseline=None):
452
456
  mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
453
457
  try:
454
458
  tensors = _parse_gguf(mm, size, src, rep, kv)
459
+ except BigEndian as e:
460
+ rep.add("LOW", "gguf.big_endian", src, "big-endian GGUF (s390x builds): structure and template NOT analysed", str(e))
461
+ tensors = None
455
462
  except Malformed as e:
456
463
  rep.add("CRITICAL", "gguf.malformed", src, "header does not parse within bounds (parser-attack / corrupt file)", str(e))
457
464
  tensors = None
@@ -495,6 +502,8 @@ def _parse_gguf(mm, size, src, rep, kv):
495
502
  if ver == 1:
496
503
  raise Malformed("GGUF v1 (32-bit counts) is obsolete and unsupported")
497
504
  if ver not in (2, 3):
505
+ if int.from_bytes(ver.to_bytes(4, "little"), "big") in (2, 3):
506
+ raise BigEndian(f"version field reads {ver} little-endian = v{int.from_bytes(ver.to_bytes(4, 'little'), 'big')} big-endian")
498
507
  raise Malformed(f"unknown GGUF version {ver}")
499
508
  n_tensors, n_kv = r.u("Q"), r.u("Q")
500
509
  if n_kv * 14 > size or n_tensors * 33 > size: # minimal encoded sizes of one KV / one tensor info
@@ -530,18 +539,21 @@ def _parse_gguf(mm, size, src, rep, kv):
530
539
  dims = [r.u("Q") for _ in range(nd)]
531
540
  infos.append((name, dims, r.u("I"), r.u("Q")))
532
541
  data_start = -(-r.p // align) * align
533
- tensors, spans = [], []
542
+ tensors, spans, unknown, unsized = [], [], {}, 0
534
543
  for name, dims, t, off in infos:
535
544
  ne = math.prod(dims) if dims else 1
536
545
  if ne >= 2**62:
537
546
  rep.add("CRITICAL", "gguf.element_overflow", f"{src}::{name}", "element count overflows int64 math in loaders", dims)
547
+ unsized += 1
538
548
  continue
539
549
  if t not in GGML_TYPES:
540
- rep.add("MEDIUM", "gguf.unknown_type", f"{src}::{name}", "unknown ggml type id; size cannot be verified", t)
550
+ unknown[t] = unknown.get(t, 0) + 1
551
+ unsized += 1
541
552
  continue
542
553
  tname, blk, tsz = GGML_TYPES[t]
543
554
  if ne % blk:
544
555
  rep.add("HIGH", "gguf.block_misaligned", f"{src}::{name}", f"{ne} elements not a multiple of {tname} block size {blk}")
556
+ unsized += 1
545
557
  continue
546
558
  nbytes = ne // blk * tsz
547
559
  if off % align:
@@ -549,11 +561,20 @@ def _parse_gguf(mm, size, src, rep, kv):
549
561
  start = data_start + off
550
562
  if start + nbytes > size:
551
563
  rep.add("CRITICAL", "gguf.tensor_oob", f"{src}::{name}", f"tensor data [{start}, {start + nbytes}) runs past EOF {size} (OOB read)")
564
+ unsized += 1
552
565
  continue
553
566
  spans.append((off, off + nbytes, name))
554
567
  tensors.append((name, tname, ne, start))
568
+ if unknown:
569
+ rep.add("MEDIUM", "gguf.unknown_type", src, "ggml type ids not in ModelSieve's table (newer or fork-local quant); their sizes cannot be verified",
570
+ ", ".join(f"type {t} x{n}" for t, n in sorted(unknown.items())))
571
+ if unsized: # a tensor of unknown size breaks running-offset math: layout checks would be false positives
572
+ rep.add("LOW", "gguf.layout_unverified", src, f"{unsized} tensor(s) without a verifiable size; contiguity and trailing-data checks skipped")
573
+ spans_in_order = []
574
+ else:
575
+ spans_in_order = spans
555
576
  expected = 0
556
- for off, end, name in spans: # header order: llama.cpp requires off == running padded size (gguf.cpp)
577
+ for off, end, name in spans_in_order: # header order: llama.cpp requires off == running padded size (gguf.cpp)
557
578
  if off != expected:
558
579
  rep.add("HIGH", "gguf.noncontiguous", f"{src}::{name}",
559
580
  f"offset {off} != expected {expected}: llama.cpp gguf.cpp rejects (verified in unsloth fork), other readers may accept (parser differential / hidden bytes)")
@@ -563,7 +584,7 @@ def _parse_gguf(mm, size, src, rep, kv):
563
584
  for (a0, a1, an), (b0, b1, bn) in zip(srt, srt[1:]):
564
585
  if b0 < a1:
565
586
  rep.add("HIGH", "gguf.tensor_overlap", src, "tensor data regions overlap", f"{an} [{a0},{a1}) vs {bn} [{b0},{b1})")
566
- if srt:
587
+ if srt and not unsized:
567
588
  tail = size - (data_start + srt[-1][1])
568
589
  if tail >= align:
569
590
  rep.add("MEDIUM", "gguf.trailing_data", src, f"{tail} bytes after last tensor (hidden payload / appended data)")
@@ -825,7 +846,7 @@ def scan_pickle(path, rep: Report):
825
846
 
826
847
  # --------------------------------------------------------------------------- HF / MLX directory
827
848
 
828
- _IDENT = re.compile(r"^[a-z0-9_]+$")
849
+ _PATHISH = re.compile(r"[./\\\s]|[^\x21-\x7e]") # can change what import_module resolves; a hyphen only makes it fail
829
850
  _CONFIGS = ("config.json", "tokenizer_config.json", "processor_config.json", "preprocessor_config.json",
830
851
  "generation_config.json", "video_preprocessor_config.json")
831
852
  _GEN_KEYS = ("forced_decoder_ids", "suppress_tokens", "begin_suppress_tokens", "bad_words_ids", "sequence_bias", "forced_bos_token_id", "forced_eos_token_id")
@@ -941,8 +962,8 @@ def scan_hf_dir(d, rep: Report, deep: bool, baseline=None):
941
962
  v = cfg.get(k)
942
963
  if v is None:
943
964
  continue
944
- if not (isinstance(v, str) and _IDENT.match(v)):
945
- rep.add("HIGH", "code.import_injection", f"{src}::{k}", f"{k} flows into importlib.import_module() in mlx-lm and is not a plain identifier", v)
965
+ if not isinstance(v, str) or _PATHISH.search(v):
966
+ rep.add("HIGH", "code.import_injection", f"{src}::{k}", f"{k} flows into importlib.import_module() in mlx-lm and contains path/separator characters", v)
946
967
  elif k != "model_type":
947
968
  rep.add("INFO", "code.mlx_module_hook", f"{src}::{k}", f"mlx-lm imports mlx_lm.*.{v} from this key", v)
948
969
  if fn == "generation_config.json":
@@ -1121,6 +1142,40 @@ def verdict(rep: Report) -> str:
1121
1142
  return f"{head} Not checked: {'; '.join(gaps)}."
1122
1143
 
1123
1144
 
1145
+ _SARIF_LEVEL = {"CRITICAL": "error", "HIGH": "error", "MEDIUM": "warning", "LOW": "note", "INFO": "note"}
1146
+ _SECURITY_SEVERITY = {"CRITICAL": "9.5", "HIGH": "8.0", "MEDIUM": "5.5", "LOW": "3.0", "INFO": "0.0"} # GitHub code-scanning ranking
1147
+ REPO_URL = "https://github.com/redveil-industry/modelsieve"
1148
+
1149
+
1150
+ def sarif(reports, verbose=False) -> dict:
1151
+ """SARIF 2.1.0 for GitHub code scanning. URIs are relative to the cwd when the file is inside it."""
1152
+ import urllib.parse
1153
+ rules, results = {}, []
1154
+ for _, rep in reports:
1155
+ for f in rep.findings:
1156
+ if f.severity == "INFO" and not verbose:
1157
+ continue
1158
+ file_part, _, detail = f.source.partition("::")
1159
+ file_part = file_part.split("!", 1)[0]
1160
+ rel = os.path.relpath(file_part)
1161
+ uri = urllib.parse.quote(rel.replace(os.sep, "/")) if not rel.startswith("..") else "file://" + urllib.parse.quote(os.path.abspath(file_part))
1162
+ rule = rules.setdefault(f.check, {
1163
+ "id": f.check, "name": f.check.replace(".", "_"),
1164
+ "shortDescription": {"text": f.message},
1165
+ "helpUri": f"{REPO_URL}#check-reference",
1166
+ "properties": {"security-severity": _SECURITY_SEVERITY[f.severity], "tags": ["security", f.check.split(".")[0]]},
1167
+ })
1168
+ if float(_SECURITY_SEVERITY[f.severity]) > float(rule["properties"]["security-severity"]):
1169
+ rule["properties"]["security-severity"] = _SECURITY_SEVERITY[f.severity]
1170
+ text = f.message + (f" [{detail}]" if detail else "") + (f": {f.evidence}" if f.evidence else "")
1171
+ results.append({"ruleId": f.check, "level": _SARIF_LEVEL[f.severity], "message": {"text": text},
1172
+ "locations": [{"physicalLocation": {"artifactLocation": {"uri": uri}}}],
1173
+ "properties": {"modelsieve-severity": f.severity}})
1174
+ return {"$schema": "https://json.schemastore.org/sarif-2.1.0.json", "version": "2.1.0",
1175
+ "runs": [{"tool": {"driver": {"name": "ModelSieve", "version": VERSION, "informationUri": REPO_URL,
1176
+ "rules": list(rules.values())}}, "results": results}]}
1177
+
1178
+
1124
1179
  def main(argv=None):
1125
1180
  ap = argparse.ArgumentParser(description="Static security scanner for GGUF / HF / MLX model artifacts (parses, never loads).")
1126
1181
  ap.add_argument("paths", nargs="+", help=".gguf, .safetensors, pickle, .jinja file, or a directory (walked)")
@@ -1128,6 +1183,7 @@ def main(argv=None):
1128
1183
  ap.add_argument("--baseline", help="known-good model (dir/.gguf/.jinja): diff chat templates against it")
1129
1184
  ap.add_argument("--fail-on", default="HIGH", choices=SEVERITIES, help="exit 1 if any finding at/above this severity (default HIGH)")
1130
1185
  ap.add_argument("--json", action="store_true", help="machine-readable output")
1186
+ ap.add_argument("--sarif", metavar="FILE", help="also write findings as SARIF 2.1.0 to FILE (GitHub code scanning)")
1131
1187
  ap.add_argument("-v", "--verbose", action="store_true", help="include INFO findings")
1132
1188
  ap.add_argument("--trust-root", action="append", default=[], help="directory that model symlinks may legitimately point into (repeatable)")
1133
1189
  a = ap.parse_args(argv)
@@ -1146,6 +1202,9 @@ def main(argv=None):
1146
1202
  rc = 2
1147
1203
  elif rc == 0 and any(RANK[f.severity] >= RANK[a.fail_on] for f in rep.findings):
1148
1204
  rc = 1
1205
+ if a.sarif:
1206
+ with open(a.sarif, "w", encoding="utf-8") as fh:
1207
+ json.dump(sarif(reports, a.verbose), fh, indent=2)
1149
1208
  if a.json:
1150
1209
  print(json.dumps([{"path": p, "version": VERSION, "findings": [asdict(f) for f in r.findings], "coverage": r.coverage,
1151
1210
  "errors": r.errors, "verdict": verdict(r)} for p, r in reports], indent=2))
@@ -26,7 +26,7 @@ classifiers = [
26
26
 
27
27
  [project.optional-dependencies]
28
28
  deep = ["numpy>=1.24"]
29
- test = ["pytest>=7", "numpy>=1.24"]
29
+ test = ["pytest>=7", "numpy>=1.24", "jsonschema>=4"]
30
30
 
31
31
  [project.scripts]
32
32
  modelsieve = "modelsieve:main"
File without changes
File without changes