Skip to content
Proyek

Tentang

Static security scanner for GGUF / HF / MLX model artifacts: chat-template SSTI + prompt injection, parser attacks, pickle/remote-code hooks, weight anomalies. Parses, never loads.

Keamanan dan privasi

Cara angka ini diukur

Pertumbuhan bintang terukur

dalam 24 jam
0
dalam 7 hari
Mengumpulkan riwayat
dalam 15 hari
Mengumpulkan riwayat
dalam 1 bulan
Mengumpulkan riwayat

Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.

README.md

Asli

ModelSieve

PyPI CI Python 3.9–3.13 License: MIT

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:

  • malicious Jinja2 chat templates, covering both sandbox escape (SSTI → code execution) and behavioural prompt injection (hidden instructions, trigger words, invisible unicode);
  • malformed containers built to exploit loader parsers (out-of-bounds offsets, integer-overflow counts, duplicate keys, hidden bytes);
  • code-execution side channels: pickle files, trust_remote_code hooks, and mlx-lm import hooks;
  • corrupted or anomalous float weights: NaN/Inf, all-zero tensors, outlier layers, and tampered HF cache blobs.

ModelSieve flagging a malicious GGUF: SSTI gadget, trigger-word branch, injected instruction, hidden trailing bytes

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.

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".

Study: What's inside the chat templates of the 400 most-downloaded GGUF and MLX models? 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.


Table of contents

  1. Quick start
  2. Requirements and installation
  3. Usage
  4. Reading the results
  5. Architecture
  6. Threat model
  7. Check reference
  8. CI / automation
  9. Testing
  10. Known limitations
  11. Troubleshooting
  12. Project layout
  13. Design decisions

Quick start

pipx install modelsieve

modelsieve ~/models/Qwen3-8B-Q5_K_M.gguf                          # one GGUF file
modelsieve --deep ~/models/Qwen-MLX-4bit                          # MLX / HF dir, plus float weight values
modelsieve ~/models ~/more-models                                 # every model under these folders
modelsieve ./Some-Model-finetune --baseline ./Original-Model      # diff a fine-tune's template vs the original

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.


Requirements and installation

Requirement Why Verified with
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)
jinja2 ≥ 3.1.6 used only to parse templates into an AST, never to render 3.1.6
numpy (optional, deep extra) only for --deep (imported lazily) 2.4.6
pytest (optional, test extra) only to run the test suite 9.1.1

Install with pipx (recommended)

pipx install modelsieve            # base scanner
pipx install "modelsieve[deep]"    # or: include numpy for --deep

Latest code from main instead of the PyPI release: pipx install git+https://github.com/redveil-industry/modelsieve.

Run from source

git clone https://github.com/redveil-industry/modelsieve ~/tools/modelsieve
python3 -m pip install "jinja2>=3.1.6" numpy pytest
python3 -I ~/tools/modelsieve/modelsieve.py --help

modelsieve.py is a single self-contained file, so you can also copy just that file to an air-gapped machine.

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.

Shell shortcut (fish, source checkout)

You don't need this with the pipx install. For a source checkout, ~/.config/fish/functions/modelsieve.fish gives you the same modelsieve command:

function modelsieve --description 'ModelSieve: static security scan of GGUF/HF/MLX models (parses, never loads)'
    # -I: isolated mode, so a planted json.py in a model folder (cwd) can't shadow the stdlib
    python3 -I ~/tools/modelsieve/modelsieve.py $argv
end

All flags and the exit code ($status in fish) pass through unchanged.


Usage

usage: modelsieve.py [-h] [--deep] [--baseline BASELINE]
                     [--fail-on {INFO,LOW,MEDIUM,HIGH,CRITICAL}] [--json] [-v]
                     [--trust-root TRUST_ROOT]
                     paths [paths ...]
Argument Meaning
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.
--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.
--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".
--fail-on SEV Exit code 1 if any finding is at or above SEV. The default is HIGH.
--json Machine-readable output (see below).
--sarif FILE Also write SARIF 2.1.0 to FILE, for GitHub code scanning (see SARIF).
-v, --verbose Also show INFO findings, such as the inventory of natural-language text each template injects.
--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.

What a directory walk picks up

flowchart LR
    D[directory argument] -->|os.walk, no symlinked dirs| W{each folder}
    W -->|*.gguf| G[GGUF scan]
    W -->|config.json / tokenizer_config.json /<br/>chat_template.jinja / tokenizer.json / *.safetensors| H[HF/MLX directory scan]
    W -.->|skipped| X[.git, blobs, refs, .locks]

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.


Reading the results

Text output (default)

Real output from scanning a deliberately malicious test GGUF (paths shortened):

== ModelSieve 0.3.0: /models/evil.gguf
CRITICAL template.ssti_underscore_attr      /models/evil.gguf::tokenizer.chat_template
         underscore attribute access (sandbox-escape gadget)
         x2: __globals__ | __init__
HIGH     template.dangerous_name            /models/evil.gguf::tokenizer.chat_template
         reference to a global with no legitimate chat-template use
         x1: cycler
HIGH     template.injected_instruction      /models/evil.gguf::tokenizer.chat_template
         override/exfiltration phrase hard-coded in template
         x1: Ignore all previous instructions.
MEDIUM   gguf.trailing_data                 /models/evil.gguf
         200 bytes after last tensor (hidden payload / appended data)
MEDIUM   template.content_trigger           /models/evil.gguf::tokenizer.chat_template
         branch on a literal phrase in message content (trigger-word pattern; vendor reasoning switches also match, review)
         x1: ['open sesame']
LOW      template.unknown_method            /models/evil.gguf::tokenizer.chat_template
         method call outside allowlist
         x2: popen | read

Coverage: {"gguf_files": 1, "templates_analysed": 1, "tensors_total": 1}
Findings: CRITICAL=1, HIGH=2, MEDIUM=2, LOW=1, INFO=0
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).

Each finding has the following fields:

Field Meaning
severity CRITICAL > HIGH > MEDIUM > LOW > INFO (INFO is hidden unless you pass -v)
check id stable area.name identifier; see the check reference
source file, file::metadata-key, file::tensor-name or archive!member
message what was found and why it matters
evidence xN: how many times it occurred, then the unique values (truncated at 400 chars)

The three footer lines matter as much as the findings:

  • 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.
  • Findings gives counts per severity.
  • Verdict gives the worst severity and an explicit Not checked list.

Save findings to a file

modelsieve ~/models -v > ~/scans/scan.txt

JSON output

modelsieve ~/models --json > ~/scans/scan.json

Schema: one object per path argument.

[
  {
    "path": "/home/me/models",
    "version": "0.1.0",
    "findings": [
      {"severity": "MEDIUM", "check": "template.concealment_instruction",
       "source": ".../chat_template.jinja", "message": "...", "evidence": "x1: ..."}
    ],
    "coverage": {"hf_dirs": 4, "templates_analysed": 4, "tensors_total": 6503},
    "errors": [],
    "verdict": "Verdict: findings up to MEDIUM from the checks run. Not checked: ..."
  }
]

Useful jq one-liners:

# HIGH and CRITICAL only
jq -r '.[].findings[] | select(.severity=="HIGH" or .severity=="CRITICAL") | "\(.severity) \(.check) \(.source)\n  \(.evidence)"' scan.json

# count findings per check
jq -r '.[].findings[].check' scan.json | sort | uniq -c | sort -rn

# what was NOT analysed
jq '.[].coverage.tensors_not_analysed_by_dtype' scan.json

Exit codes

Code Meaning
0 no finding at or above --fail-on (default HIGH)
1 at least one finding at or above --fail-on
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".

A crash on one file never aborts the rest of a multi-path run. It is recorded as an error and the walk continues.


Architecture

Components and data flow

flowchart TB
    CLI["main()<br/>argparse, --trust-root, jinja2 version check"] --> BASE["baseline_templates()<br/>template inventory of --baseline"]
    CLI --> SCAN["scan(path)<br/>dispatch by file type / os.walk"]

    SCAN --> GG["scan_gguf()"]
    SCAN --> HF["scan_hf_dir()"]
    SCAN --> STF["scan_safetensors()"]
    SCAN --> PK["scan_pickle()"]

    GG --> PG["_parse_gguf() + _R<br/>bounded mmap reader"]
    HF --> STF
    HF --> PK
    HF --> TJ["_scan_tokenizer_json()"]
    HF --> IDX["_check_index()<br/>model.safetensors.index.json"]
    HF --> HT["hf_templates()<br/>collect every template source"]

    PG --> AT
    HT --> AT["analyse_templates()<br/>dedupe · divergence · baseline diff"]
    AT --> A1["analyse_template()<br/>Jinja2 AST walk"]

    STF -->|--deep| WS["tensor_stats()<br/>chunked mmap, numpy"]
    PG -->|--deep| WS
    WS --> WF["weight_findings()<br/>NaN/Inf, zero, sibling-layer z-score"]

    PK --> PGL["pickle_globals()<br/>pickletools.genops, never unpickles"]

    A1 & WF & PGL & IDX & TJ --> REP["Report<br/>findings + coverage + errors"]
    REP --> OUT["render() text / --json<br/>verdict() + exit code"]

Everything lives in one file, modelsieve.py (about 1.2k lines). The sections inside it, in order:

Section Responsibility
Finding, Report, Malformed result model: findings, coverage counters, scan errors
unicode / text hidden_unicode() detects zero-width, bidi, variation-selector and Unicode tag characters, and decodes tag-smuggled ASCII
templates analyse_template() (AST rules) and analyse_templates() (dedupe, divergence, baseline)
GGUF GGML_TYPES block-size table, the _R bounded reader, _parse_gguf() and scan_gguf()
safetensors scan_safetensors(): header cap, duplicate-key JSON hook, span validation
weights tensor_stats() (chunked, BF16 handled manually) and weight_findings()
pickle pickle_globals() opcode scan and scan_pickle() (zip/torch, raw, npy/npz)
HF / MLX directory scan_hf_dir(): symlinks, configs, code files, tokenizer.json, index, templates
driver scan(), _isolated() crash isolation, baseline_templates(), render(), verdict(), main()

Trust boundary

flowchart LR
    subgraph UNTRUSTED["Untrusted: everything under the scanned path"]
        F1[GGUF bytes] --- F2[safetensors header] --- F3[JSON configs] --- F4[templates] --- F5[pickles] --- F6[symlinks]
    end
    subgraph SCANNER["ModelSieve process (console script, or python3 -I from source)"]
        R["bounded readers<br/>every length checked vs file size<br/>before any allocation"]
        P["jinja2 parse only<br/>bounded constant folding"]
        O["pickletools.genops<br/>opcode listing only"]
    end
    UNTRUSTED -->|read-only mmap / read| R
    UNTRUSTED --> P
    UNTRUSTED --> O
    SCANNER -->|findings only| USER[operator]

The scanner enforces these invariants:

  • No execution of model content: templates are never rendered, pickles are never unpickled, and no model module is imported.
  • 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.
  • 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.

How the template analysis works

  1. Inventory. Every source a loader might use is collected:
    • GGUF: tokenizer.chat_template and tokenizer.chat_template.<name>, plus any other metadata string containing {% or {{;
    • 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.
  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).
  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.
  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.
  5. AST rules:
    • 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.
    • 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.
    • DoS: range(>1e6), large multiplications, parser recursion.
  6. Baseline diff (optional): a unified diff against the same-named template of a known-good model.

How the container checks work

flowchart TB
    H["GGUF header<br/>magic, version 2/3, n_tensors, n_kv"] -->|counts x minimal size <= file size?| KV[KV pairs]
    KV -->|duplicate / empty key, bad UTF-8| TI["tensor infos<br/>n_dims <= GGML_MAX_DIMS (4)"]
    TI --> AL["data start = align(general.alignment)"]
    AL --> SP["per tensor:<br/>type known? elements % block == 0?<br/>offset aligned? start+nbytes <= EOF?"]
    SP --> LAY["layout:<br/>contiguous in header order (llama.cpp rule)<br/>no overlap · no trailing bytes"]

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.

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.


Threat model

Asset Entry point Abuse case Checks
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_*
Model behaviour / user data same hidden system instructions, hidden tools that an agentic client will call (data exfiltration through the client), trigger-word backdoors, invisible or bidi or tag-unicode smuggling, a "tuned" re-upload injected_instruction, concealment_instruction, content_trigger*, hidden_unicode, url, injected_tool, divergent_sources, baseline_diff
Loader memory safety GGUF header, KVs and tensor infos; safetensors header integer overflow, OOB reads, parser differentials, hidden payloads gguf.*, st.*
Host *.py, config.json:auto_map, mlx-lm model_file, pickle files remote code under trust_remote_code=True; pickle __reduce__ RCE code.*
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
User input integrity tokenizer.json normalizer / pre-tokenizer, special tokens rules that silently rewrite the user's words, look-alike special tokens tokenizer.*
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

Check reference

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.

Templates (template.*)

Check Severity Meaning
ssti_underscore_attr CRITICAL x.__class__-style attribute access
ssti_underscore_item CRITICAL x['__class__'], including folded or {% set %}-resolved keys
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
dunder_string CRITICAL any string constant containing __name__ (gadget staged for indirection)
attr_filter CRITICAL / HIGH |attr(...): CRITICAL when the argument is private or format (CVE-2025-27516)
indirect_filter CRITICAL / MEDIUM map('attr', …) or map into a non-allowlisted filter
ssti_introspection HIGH mro, f_globals, gi_frame, …
format_reference HIGH .format referenced without being called (CVE-2024-56326 pattern)
dangerous_name HIGH lipsum, cycler, joiner, self, config, request, os, …
external_load HIGH include, import or extends
injected_instruction HIGH "ignore previous…", exfiltration, curl -, <script, api key, password
parse_dos HIGH nesting exhausts parser recursion
hidden_unicode HIGH / MEDIUM HIGH for bidi or tag characters (decoded text shown), MEDIUM for zero-width
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
content_trigger_markup MEDIUM branch on a tag-like literal ('<deploy>') that the template never emits
concealment_instruction MEDIUM "do not tell the user…"; upstream Qwen tool prompts trigger this
injected_tool HIGH / MEDIUM a tool definition hard-coded in the template's own text (JSON function schema or type fn = (…) => signature, also when split across string constants), or an instruction to call a specific named tool. HIGH when the hard-coded tool text carries a fixed URL, which is the exfiltration shape: an agentic client would call it for you. MEDIUM otherwise. Vendor built-ins (for example a harmony-style browser tool) match as MEDIUM. Tools rendered from the caller's tools list are not flagged
url MEDIUM URL hard-coded in the template
computed_key MEDIUM subscript key built from string expressions or filters
str_format MEDIUM direct .format() call
unknown_filter, unknown_test, unknown_callable MEDIUM outside the HF chat-template environment
dos_range, dos_mul MEDIUM render-time resource blow-up
parse_error MEDIUM does not parse; loaders may disagree
divergent_sources MEDIUM the same template name has different text in different files
baseline_diff MEDIUM differs from --baseline (diff in evidence)
unknown_method, indirect_call LOW method or call outside the allowlist
baseline_missing LOW the baseline has no template with this name
literal_text, baseline_match, none INFO inventory

GGUF (gguf.*)

Check Severity Meaning
malformed CRITICAL header does not parse within bounds: bad magic, v1, counts that cannot fit the file, a string or array past EOF
tensor_oob CRITICAL tensor data runs past EOF
element_overflow CRITICAL element count ≥ 2^62
duplicate_key HIGH llama.cpp rejects the file; other readers pick first or last (template smuggling)
empty_key, bad_alignment, block_misaligned, duplicate_tensor, tensor_overlap, noncontiguous HIGH loader-rejected or loader-dependent structure
trailing_data, tensor_unaligned, unknown_type, template_like_metadata, bad_utf8 MEDIUM hidden bytes, unverifiable sizes, Jinja in odd places
big_endian LOW byte-swapped GGUF (s390x builds): a valid format, but its structure and template are not analysed
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
hidden_unicode_metadata HIGH / MEDIUM invisible unicode in a metadata string

Safetensors (st.*)

Check Severity Meaning
malformed, tensor_oob CRITICAL length prefix past EOF, non-JSON header, span outside the data region
header_too_large, duplicate_key, bad_entry, size_mismatch, tensor_overlap, index_path_traversal HIGH
hidden_gap, trailing_data, unknown_dtype, bad_metadata, template_like_metadata, index_* MEDIUM
unindexed_tensors LOW tensors that loaders ignore

Code and filesystem (code.*, fs.*, tokenizer.*, gen.*)

Check Severity Meaning
code.pickle_import CRITICAL / HIGH the pickle imports a non-allowlisted callable. CRITICAL for os, subprocess, builtins.eval, … All protocols 0–5 are handled.
fs.blob_hash_mismatch CRITICAL HF blob content ≠ its sha256 name (--deep)
code.auto_map, code.model_file, code.import_injection, code.npy_object, code.pickle_unparseable, code.pickle_unreadable HIGH
fs.symlink_escape, fs.native_binary HIGH
tokenizer.hidden_unicode_special_token HIGH a special or control token contains invisible characters
code.pickle_present, code.python_file, tokenizer.replace_rule, fs.bad_json MEDIUM
code.pickle_unrecognised, fs.dangling_symlink, gen.logit_manipulation LOW not analysed / review intent
code.mlx_module_hook INFO

Weights (weights.*, --deep only)

Check Severity Meaning
nonfinite HIGH NaN or Inf values
all_zero LOW tensor of ≥1024 elements is entirely zero
layer_outlier LOW tensor std deviates from ≥8 sibling layers (robust z > 8); can be benign

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.


CI / automation

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.

GitHub Action

# .github/workflows/model-scan.yml
on: [push, pull_request]
permissions:
  contents: read
  security-events: write   # only needed for the SARIF upload step
jobs:
  modelsieve:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
        with:
          lfs: true                      # model files are usually in Git LFS
      - uses: redveil-industry/[email protected]
        with:
          path: models/                  # files or directories, whitespace-separated
          fail-on: HIGH                  # INFO | LOW | MEDIUM | HIGH | CRITICAL
      - uses: github/codeql-action/upload-sarif@v4
        if: always()                     # upload findings even when the scan step failed
        with:
          sarif_file: modelsieve.sarif
Input Default Meaning
path (required) files or directories to scan
fail-on HIGH fail the step at or above this severity
deep false also scan float weight values (installs numpy)
baseline "" known-good model to diff chat templates against
sarif-file modelsieve.sarif SARIF 2.1.0 output path

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.

pre-commit

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/redveil-industry/modelsieve
    rev: v0.2.0
    hooks:
      - id: modelsieve

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.

SARIF

modelsieve --sarif FILE writes SARIF 2.1.0 alongside the normal output:

  • CRITICAL and HIGH become error, MEDIUM becomes warning, and LOW/INFO become note.
  • Each rule carries a security-severity (CRITICAL 9.5, HIGH 8.0, MEDIUM 5.5), so GitHub code scanning ranks the findings.
  • File URIs are relative to the working directory when the file is inside it.

CI validates the output against the official OASIS SARIF 2.1.0 schema.

Plain shell gate

#!/usr/bin/env bash
# gate a model before it enters the shared model store
set -u
modelsieve --deep --fail-on HIGH --json "$1" > "scan-$(basename "$1").json"
rc=$?
case $rc in
  0) echo "no HIGH+ findings from checks run" ;;
  1) echo "BLOCKED: HIGH+ findings"; jq -r '.[].findings[] | select(.severity=="HIGH" or .severity=="CRITICAL") | "\(.severity) \(.check) \(.source)"' "scan-$(basename "$1").json"; exit 1 ;;
  *) echo "scan error, treat as blocked"; exit 2 ;;
esac

Testing

cd ~/tools/modelsieve
python3 -I -m pytest -q test_modelsieve.py

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:

  • SSTI gadgets and their one-hop bypasses ({% set k='__class__' %}{{ x[k] }}, '_'*2 ~ 'class' ~ '_'*2, selectattr('__class__'), groupby('_…'), |attr('format'));
  • trigger words, including through {% set c = m['content'] %} and {% for line in m.content.split() %};
  • tag-character smuggling, with the decoded text asserted;
  • GGUF and safetensors parser attacks (count overflow, string length bomb, OOB, overlap, gap, duplicate keys, header bomb);
  • pickles of protocols 0–5 with an os.system __reduce__ (serialised only, never loaded);
  • an HF directory combining auto_map, model_file, import injection, a Replace rule, symlink escape, dangling link, index path traversal and divergent templates;
  • crash isolation, --trust-root, exit codes and JSON output;
  • 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).

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.

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).


Known limitations

Limitation Effect Planned fix
Trained-in weight backdoors not detectable statically, by design none possible statically; use behavioural evals
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)
One-word lowercase triggers ('xyzzy' in content) treated as key/type checks, so missed opt-in sandboxed render-diff (--render)
Markup-like triggers that the template also emits exempt, so missed --render
Indirection deeper than one {% set %} hop, or through macro arguments not resolved --render
Python jinja2 vs llama.cpp's C++ template engine parse differences not yet tested differential fixtures
Pickle STACK_GLOBAL resolved from the two most recent string pushes, not a full stack emulator stack emulator if evasion matters
Pickle size only the first 64 MiB of a raw pickle is inspected raise the cap for large legacy checkpoints
Template gate corpus 16 templates, mostly Qwen add Llama, Gemma, Mistral, Phi and GLM templates

Troubleshooting

flowchart TD
    A[Unexpected result] --> B{Exit code 2?}
    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."]
    B -->|no| D{Many fs.symlink_escape?}
    D -->|yes| E["Model-manager shim folder?<br/>add --trust-root <central model store>"]
    D -->|no| F{fs.dangling_symlink?}
    F -->|yes| G["Link targets were deleted; nothing behind them was scanned.<br/>Re-download or scan the real files."]
    F -->|no| H{Coverage shows 0 templates?}
    H -->|yes| I["The model ships no chat template; the loader default applies.<br/>See templates_missing."]
    H -->|no| J["Re-run with -v to see INFO inventory;<br/>add --baseline ORIGINAL to diff wording"]
  • The warning jinja2 < 3.1.6 means: upgrade jinja2 on this host. Your loaders are exposed even though ModelSieve is not.
  • template.concealment_instruction on Qwen models is expected. The upstream tool-calling prompt says "do not tell the user about function calls".
  • weights.layer_outlier can be benign; first and last layers often differ. Confirm with --baseline on an untouched original, or with a behavioural test.

Project layout

modelsieve/
├── README.md            ← this file
├── LICENSE              ← MIT
├── pyproject.toml       ← packaging: console script `modelsieve`, extras `deep` and `test`
├── action.yml           ← GitHub Action (composite; installs this checkout)
├── .pre-commit-hooks.yaml ← pre-commit hook `modelsieve`
├── .gitignore
├── modelsieve.py        ← the scanner (single file, stdlib + jinja2, numpy for --deep)
├── test_modelsieve.py   ← 72 tests, in-test fixture writers
├── demo/
│   ├── make_demo_model.py   ← writes the deliberately malicious demo GGUF
│   ├── demo.tape            ← vhs script; re-record with `vhs demo/demo.tape`
│   └── modelsieve-demo.gif  ← the README demo (real output)
├── study/
│   ├── REPORT.md        ← top-400 Hugging Face study write-up
│   ├── README.md        ← study harness documentation
│   ├── hf_study.py      ← header-only Hugging Face scanning harness
│   └── summary.json     ← aggregates behind the report
└── .github/workflows/
    ├── ci.yml           ← tests on Python 3.9–3.13 (Ubuntu + macOS; 3.9 macOS only)
    ├── action-test.yml  ← runs the action on malicious + benign fixtures, validates SARIF
    └── publish.yml      ← PyPI release via Trusted Publishing (OIDC, no stored token)

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/.


Design decisions

Decision Rationale Trade-off
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
AST analysis, never rendering rendering an untrusted template is the exploit misses behaviour only visible at render time (see limitations)
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
"No findings from checks run" instead of "clean" static scanning cannot prove absence less comforting output, and accurate
Single file easy to audit, copy to an air-gapped box and run with python3 -I a long file; sections are clearly delimited
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
--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)

License

MIT. See LICENSE.

Jelajahi proyek terkait

Memuat…