DEV Community

Cover image for Your Open-Weight Model Is Executable Code: Static & Docker-Isolated Auditing with OpenWeight Forensics
Francisco Grandón
Francisco Grandón

Posted on Edited on

Your Open-Weight Model Is Executable Code: Static & Docker-Isolated Auditing with OpenWeight Forensics

We treat open-weight models like CSV files with billions of floats. You pull a repository from Hugging Face, point transformers, Ollama, or LM Studio at a directory, and assume the worst thing a model can do is hallucinate a capital city.

That mental model is broken. Modern open-weight distributions are compound executable software packages:

  1. Packaged Python modules: Custom vision, OCR, and reasoning architectures ship .py files at the repo root and ask you to run AutoModel.from_pretrained(..., trust_remote_code=True), executing arbitrary host code on load.
  2. Turing-complete Jinja2 templates: Chat formatting and tool-calling schemas evaluate chat_template.jinja or tokenizer_config.json inside your runtime's Python process.
  3. Legacy Pickle checkpoints: .bin, .pt, .pth, .pkl, and .ckpt files (including leftover training_args.bin artifacts) still trigger arbitrary object instantiation on deserialization.

To solve this before a model ever touches production or an autonomous agent loop, I built OpenWeight Forensics (OWF). Today I am releasing the public, multiplatform user-facing suite at FranciscoGrandon/openweight-forensics-public (Apache 2.0), split into two focused CLI tools:

  • owf-static: Zero-Docker static auditor for local directories, Hugging Face Hub (hf:org/model), Ollama (ollama:<model>), and LM Studio (lmstudio:<model>). It outputs a CI/CD stoplight (APROBADO, PRECAUCIÓN, BLOQUEAR; exit codes 0, 1, 2) plus JSON, Markdown, and self-contained HTML reports.
  • owf-dynamic: Hybrid auditor that pairs owf-static with a hardened Docker container (--network none --read-only --cap-drop=ALL --security-opt no-new-privileges) for isolated Pickle, Jinja2, and tool-calling probes by default, plus an optional --live-inference mode.

1. The Threat Surface: 58.2M+ Downloads and Five Risk Dimensions (T1 to T5)

In my openweight-forensics research repository, I audited 20 high-volume Hugging Face production repositories and structured the attack surface into five technical dimensions (T1–T5):

          [Open-Weight Model Repo / Local Bundle]
                             |
         +-------------------+-------------------+
         |                                       |
 [Configs / Templates / .py]           [Weights / Checkpoints]
         |                                       |
  (T2) trust_remote_code / auto_map       (T1) Pickle RCE
  (T3) Jinja2 SSTI / Desync / Delim.      (T4) Weight Drift
  (T5) Ghost Tool Hijacking / Key Drift
Enter fullscreen mode Exit fullscreen mode

Across those 20 popular Hugging Face models exposing trust_remote_code, custom .py modules, or .bin checkpoints, official download counts totaled 58,215,958 downloads (top 10 shown below; the full 20-repo list is in the research repo):

Repository Downloads Primary Risk Surface Technical Indicator
microsoft/Florence-2-base 24,133,070 T1 / T2 trust_remote_code=True, .py scripts, pytorch_model.bin
nomic-ai/nomic-embed-text-v1.5 11,132,798 T2 custom_code remote tokenizer/model execution
baidu/Unlimited-OCR 5,198,482 T2 5 .py modeling scripts executed at runtime
vikhyatk/moondream2 2,381,354 T2 17 .py scripts packaged at repo root
deepseek-ai/DeepSeek-OCR 1,749,322 T2 5 .py scripts with non-standard architecture
deepseek-ai/DeepSeek-R1 1,402,157 T2 Local MLA/MoE .py modules
OpenGVLab/InternVL2-1B 1,130,114 T2 Vision pipeline with remote code invocation
jinaai/jina-embeddings-v3 1,096,591 T1 / T2 trust_remote_code, legacy PyTorch binary
nomic-ai/nomic-embed-text-v1 1,065,618 T1 / T2 Binary pytorch_model.bin checkpoints
iitolstykh/mivolo_v2 1,059,424 T2 3 .py initialization scripts

Isolating T4 vs. T5: Tool Hijacking Lives in the Template, Not the Weights

A key question in agent security is whether unsolicited tool execution comes from poisoned model weights (T4) or from the chat and tool template layer (T5).

I evaluated 3 non-privileged tools (get_weather, calculator, read_document) across 4 prompts and 3 template conditions (36 sandboxed evaluations):

  • Under poisoned_synthetic (injecting a hidden tool schema), 100% of evaluations invoked hardcoded_tool_admin_exec (HIJACKED / SUBVERTED).
  • Swapping the exact same workflow to a clean hermes_reference template dropped hijacking to 0% (CORRECT / PROPER).
  • I also detected subtle production template serialization drift, such as NousResearch/Hermes-2-Pro-Llama-3-8B emitting arguments before name inside tool-call streams (the vLLM #9693 key-order issue).

Separately, when I audited my own local Windows 11 models (gemma2:2b, gemma3:4b in Ollama and local RAG, plus gemma4:e4b in Ollama and LM Studio), all five GGUF artifacts scored 5/100 (APROBADO) with zero Pickle, AST, SSTI, or ghost-tool issues. Yet all five exhibited delimiter_injection_passthrough: true inside ImmutableSandboxedEnvironment: standard Gemma templates pass raw <start_of_turn>, <end_of_turn>, <|turn>, and <turn|> tokens from message['content'] verbatim, meaning your application layer must sanitize turn delimiters before accepting untrusted user input.


2. The Public Suite: Static and Dynamic CLI Tools

Everything needed to audit a model before deployment now lives in the public OpenWeight Forensics repository with zero research clutter.

Quickstart with owf-static (Fast, Zero-Docker Auditing)

Clone the repository and install owf-static:

git clone https://github.com/FranciscoGrandon/openweight-forensics-public.git
cd openweight-forensics-public
pip install ./owf-static
Enter fullscreen mode Exit fullscreen mode

Discover local models across Ollama, LM Studio, and the Hugging Face cache, then scan a Hugging Face repo (without pulling multi-GB Safetensors weights) or local GGUF models:

owf-static discover
owf-static scan hf:Qwen/Qwen2.5-7B-Instruct --format all --out-dir ./owf_reports
owf-static scan ollama:gemma4:e4b
owf-static scan lmstudio:gemma-4-E4B-it-GGUF --strict
Enter fullscreen mode Exit fullscreen mode

What owf-static checks without ever calling torch.load() or pickle.load():

  • T1 (Serialization): Full-stream pickletools.genops inspection (including PyTorch ZIP .pt, .pth, .bin, and .ckpt members and truncated chunk fallback) plus picklescan integration.
  • T2 (Remote Code & Metadata): auto_map and custom_pipelines inspection, external URL extraction, and Python AST parsing for dangerous imports and calls (os, subprocess, eval, exec, __import__).
  • Header-Only GGUF & Safetensors Readers: Reads GGUF KV metadata (including Ollama sha256-* blobs resolved via manifests/ and manifests-v2/) and Safetensors JSON headers in milliseconds without loading tensor payloads.
  • T3 / T5 (Templates & Tool Calling): Evaluates both chat_template.jinja and tokenizer_config.json (string or list-of-dicts format) inside Jinja2 ImmutableSandboxedEnvironment, checking SSTI payloads, dual_source_mismatch, generation_prompt_anomaly (<think> / enable_thinking), phantom_tools_detected (rendering with tools=None), name_before_arguments, and delimiter_injection_passthrough.

Quickstart with owf-dynamic (Hybrid Docker-Isolated Auditing)

From the same cloned repository, install owf-dynamic, check Docker Engine availability, and run the isolated container probe (or add --live-inference --gpu for adversarial live prompting):

pip install ./owf-dynamic
owf-dynamic doctor
owf-dynamic scan ./my-model --build-image --format all --out-dir ./owf_reports
owf-dynamic scan ./model.gguf --live-inference --gpu --build-image
Enter fullscreen mode Exit fullscreen mode

Every container run enforces strict isolation:

docker run --rm --network none --read-only \
  --tmpfs /tmp:rw,noexec,nosuid,size=128m \
  --cap-drop=ALL --security-opt no-new-privileges \
  --pids-limit 128 --memory 2g --cpus 2.0 \
  [--user <uid>:<gid> on POSIX] \
  -v <model>:/models:ro -v <out>:/out:rw owf-dynamic-probe:1.0
Enter fullscreen mode Exit fullscreen mode

Both CLIs share the same CI/CD stoplight contract (the CLI currently emits Spanish stoplight labels: APROBADO = approved, PRECAUCIÓN = caution, BLOQUEAR = block):

  • APROBADO (exit 0): Score < 20, no critical or high findings.
  • PRECAUCIÓN (exit 1): Score 20–59, moderate warnings (auto_map, template desync, missing artifacts), or --strict on minor warnings like delimiter_injection_passthrough.
  • BLOQUEAR (exit 2): Score >= 60 or any critical/high dominant finding (Pickle RCE, SSTI, ghost tools, or unscanned remote Pickle weights).

3. Three Engineering Bugs Uncovered by Adversarial Self-Auditing

Shipping the first draft was not enough. Adversarial testing and cross-platform CI exposed three real failures that would have bitten users in production.

Bug 1: The Hugging Face Shallow-Scan Blind Spot

In my first draft, scanning hf:org/repo with full_hf=False only downloaded metadata (*.json, *.jinja, *.py, *.txt, *.md) to avoid pulling 15 GB of weights. The unintended consequence was that a malicious Hugging Face repository containing clean JSON configs plus a weaponized pytorch_model.bin skipped T1 completely and returned APROBADO (5/100).

The fix: sources.py now queries HfApi().list_repo_tree(..., recursive=True) (with model_info fallback), automatically downloads Pickle artifacts <= 50 MiB for full T1 inspection, and flags any larger un-downloaded .bin, .pt, .pth, .pkl, or .ckpt files as T1_REMOTE_PICKLE_UNSCANNED (HIGH, escalating to BLOQUEAR 75/100 until audited with --full-hf or converted to Safetensors).

Bug 2: False Positives on Non-Pickle Binary Weights and Parser Crashes

Many GGML, CTranslate2, or misnamed Safetensors weights use the .bin extension. Treating every .bin blindly as a corrupt Pickle stream caused clean files (even 128 bytes of \x00 or a Safetensors file with a tensor named model.eval_proj.weight) to trigger BLOQUEAR (75–80/100). Meanwhile, adversarial malformed files triggered unhandled zlib.error in PyTorch ZIPs, OverflowError on BINBYTES8 in SafeUnpickler, and f.seek() beyond EOF in truncated .gguf headers.

The fix: I added pre-Pickle format sniffing (GGUF magic, Safetensors header validation, GGML magic, and opcode-presence verification via pickletools.genops), explicit f.tell() <= file_size bounds checks, MAX_GGUF_ARRAY_DEPTH = 16, and explicit exception handling across ZIP/deflate and SafeUnpickler.

Bug 3: Why Python 3.12 Passed on Windows and Failed on Linux & macOS CI

On my very first GitHub Actions run (Run 46295740989), windows-latest (3.10 and 3.12) and ubuntu-latest / macos-latest (3.10) passed, but both ubuntu-latest and macos-latest on Python 3.12 failed on the exact same two deeply-nested JSON tests (3,000 and 3,500 brackets).

Why? In CPython 3.12, pure-C recursion in _json stopped using sys.getrecursionlimit() (1000) and switched to OS C-stack tracking (c_recursion_remaining). Windows's smaller C stack raised RecursionError below 3,000 levels; Linux and macOS on Python 3.12 happily parsed 3,500 nested brackets without raising anything.

The fix: Never rely on OS-specific C stack limits for security boundaries. Both owf-static and owf-dynamic now enforce an iterative O(N) lexical depth guard (MAX_JSON_DEPTH = 512, ignoring { } [ ] inside escaped JSON strings) before calling json.loads(), while keeping except RecursionError as defense-in-depth.

After merging PR #1, Run 46311565792 passed 6/6 jobs across Windows, Ubuntu, and macOS (Python 3.10 and 3.12) with 42/42 tests green.


Try It Before Your Next Model Deployment

If you run into edge cases in custom GGUF metadata, Hugging Face templates, or CI/CD container permissions, open an issue in the public repo so I can turn it into a permanent regression fixture.

Top comments (5)

Collapse
 
kursatyz profile image
Kürşat Yılmaz •

Treating model weights as static data ignores how pickle-based checkpoints execute arbitrary opcodes during deserialization, turning a routine torch.load into an unauthenticated RCE vector on GPU nodes. Running static opcode inspection alongside ephemeral Docker isolation catches tampered layers before weights hit host memory, though multi-gigabyte shard scanning adds a real I/O and cold-start tax to CI/CD pipelines. Deserialization is always execution.

Collapse
 
fgrandon profile image
Francisco Grandón •

Thanks for raising the CI/CD I/O and cold-start tax, Kürşat. Nothing cuts pipeline latency quite like skipping the scan and letting an untrusted REDUCE opcode turn your GPU node into someone else's favorite cloud region.

That exact overhead is why I split the suite into two tiers and kept the default path header-only:

  • Zero tensor reads on modern formats: For Safetensors and GGUF, owf-static only parses the JSON header or KV metadata in milliseconds, so multi-GB shards do not pay a full-file I/O penalty.
  • Fail-closed on legacy Pickle: For Hugging Face scans without --full-hf, owf-static only pulls Pickle artifacts up to 50 MiB and flags larger un-downloaded .bin/.pt files as T1_REMOTE_PICKLE_UNSCANNED (BLOQUEAR, exit code 2) instead of pulling 15 GB into an ephemeral runner.
  • Two-stage gating: Teams can run owf-static on every build with zero Docker overhead, and reserve owf-dynamic for release gates, flagged artifacts, or --live-inference probes when you need to look past static serialization and template layers (T1/T2/T3/T5) into behavioral drift (T4).

In your own GPU or CI pipelines, are you enforcing a hard "Safetensors/GGUF only" policy at ingress, or do you still have legacy .bin/.pt checkpoints you have to audit in place?

Collapse
 
x1y1co profile image
X1Y1 •

Does owf-static catch a chat template that changed between two revisions of the same repo? Pinning a model by name has the same problem as MCP configs: what's behind the name can change after you approved it.

Collapse
 
fgrandon profile image
Francisco Grandón •

Great point @x1y1co , and the MCP config analogy holds up completely. Pinning a model by floating repo name or :latest is basically signing a blank check and hoping nobody edits chat_template.jinja while your nodes autoscale.

To be direct about scope: today owf-static is a stateless, single-snapshot auditor, so it does not natively diff two revisions against a prior approval out of the box.

  • What it catches on a re-scan: Any newly introduced SSTI payload, phantom tool (tools=None), generation_prompt_anomaly, or dual_source_mismatch between chat_template.jinja and tokenizer_config.json.
  • What requires hash verification: A syntactically clean template edit pushed to main after approval will not trigger a static exploit rule on its own, and checking only weight hashes (.safetensors) misses template-only edits.

The technically sound pattern right now is two-part:

  • Pin immutable references, not names: Lock deployments to a specific Hugging Face commit SHA (revision="<sha>"), which binds weights, chat_template.jinja, tokenizer_config.json, and .py files together, or to an Ollama sha256 manifest/blob digest.
  • Audit on every hash bump: Run owf-static before approving a new commit SHA or digest, and verify the hash of the downloaded artifacts matches what was audited.

That said, adding a --baseline / lockfile flag to owf-static that records approved template and config SHA-256 hashes and fails closed on any unapproved drift is a very clean invariant to build next.

In your own pipelines, are you pinning Hugging Face commit SHAs directly in deployment manifests, or maintaining a separate artifact lockfile in CI?

Collapse
 
x1y1co profile image
X1Y1 •

We don't deploy open-weight models ourselves, so I can't point to a pipeline of ours. If I were setting one up, the SHA would go in the manifest, since that's what the node actually pulls, and the lockfile would only hold the audited hashes to check against. A --baseline flag would turn that into one command instead of a script everyone writes slightly differently.