Your Open-Weight Model Is Executable Code: Static & Docker-Isolated Auditing with OpenWeight Forensics
By Francisco Grandón Vergara 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 thi
By Francisco Grandón Vergara
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:
-
Packaged Python modules: Custom vision, OCR, and reasoning architectures ship
.pyfiles at the repo root and ask you to runAutoModel.from_pretrained(..., trust_remote_code=True)—executing arbitrary host code on load. -
Turing-complete Jinja2 templates: Chat formatting and tool-calling schemas evaluate
chat_template.jinjaortokenizer_config.jsoninside your runtime's Python process. -
Legacy Pickle checkpoints:
.bin,.pt,.pth,.pkl, and.ckptfiles—including leftovertraining_args.binartifacts—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)—and 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>), outputting a CI/CD stoplight (APROBADO/PRECAUCIÓN/BLOQUEAR, exit codes0/1/2) plus JSON, Markdown, and self-contained HTML reports. -
owf-dynamic— Hybrid auditor that pairsowf-staticwith a hardened Docker container (--network none --read-only --cap-drop=ALL --security-opt no-new-privileges) for isolated Pickle/Jinja2/tool-calling probes by default, plus an optional--live-inferencemode.
1. The Threat Surface: 58.2M+ Downloads and Five Risk Dimensions (T1–T5)
In our research repository (FranciscoGrandon/openweight-forensics), we audited 20 high-volume Hugging Face production repositories and structured the attack surface into five technical dimensions (T1–T5):
[Open-Weight Model Repository / Local Bundle]
|
+--------------------+--------------------+
| |
[Configs / Templates / .py] [Weights / Checkpoints]
| |
(T2) trust_remote_code / auto_map (T1) Pickle RCE (REDUCE / posix.system)
(T3) Jinja2 SSTI / Desync / Delimiters (T4) Intrinsic Weight Drift
(T5) Ghost Tool Hijacking / Key Drift
Across just 20 popular Hugging Face models exposing trust_remote_code, custom .py modules, or .bin checkpoints, official download counts totaled 58,215,958 downloads:
| 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/tool template layer (T5).
We 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 invokedhardcoded_tool_admin_exec(HIJACKED/SUBVERTED). - Swapping the exact same workflow to a clean
hermes_referencetemplate dropped hijacking to 0% (CORRECT/PROPER). - We also detected subtle production template serialization drift—for example
NousResearch/Hermes-2-Pro-Llama-3-8Bemittingargumentsbeforenameinside tool-call streams (thevllm#9693key-order issue).
Separately, when we audited our 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: owf-static and owf-dynamic
Everything needed to audit a model before deployment now lives in https://github.com/FranciscoGrandon/openweight-forensics-public with zero research clutter:
owf-static — Fast, Zero-Docker Auditing
pip install ./owf-static
# Discover local models across Ollama, LM Studio, and Hugging Face cache
owf-static discover
# Audit a Hugging Face repo without downloading multi-GB Safetensors weights
owf-static scan hf:Qwen/Qwen2.5-7B-Instruct --format all --out-dir ./owf_reports
# Audit local Ollama or LM Studio GGUF models directly
owf-static scan ollama:gemma4:e4b
owf-static scan lmstudio:gemma-4-E4B-it-GGUF --strict
What owf-static checks without ever calling torch.load() or pickle.load():
-
T1 (Serialization): Full-stream
pickletools.genopsinspection (including PyTorch ZIP.pt/.pth/.bin/.ckptmembers and truncated chunk fallback) +picklescanintegration. -
T2 (Remote Code & Metadata):
auto_map/custom_pipelinesinspection, external URL extraction, and Python AST parsing for dangerous imports and calls (os,subprocess,eval,exec,__import__). -
Header-Only
GGUF&SafetensorsReaders: Reads GGUF KV metadata (including Ollamasha256-*blobs resolved viamanifests/andmanifests-v2/) and Safetensors JSON headers in milliseconds without loading tensor payloads. -
T3 / T5 (Templates & Tool Calling): Evaluates both
chat_template.jinjaandtokenizer_config.json(string or list-of-dicts format) inside Jinja2ImmutableSandboxedEnvironment, checking SSTI payloads,dual_source_mismatch,generation_prompt_anomaly(<think>/enable_thinking),phantom_tools_detected(rendering withtools=None),name_before_arguments, anddelimiter_injection_passthrough.
owf-dynamic — Hybrid Docker-Isolated Auditing
pip install ./owf-dynamic
# Verify Docker Engine availability
owf-dynamic doctor
# Default hybrid mode: static scan + isolated container probe (no GPU needed)
owf-dynamic scan ./my-model --build-image --format all --out-dir ./owf_reports
# Optional live adversarial inference inside the locked-down container
owf-dynamic scan ./model.gguf --live-inference --gpu --build-image
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
Both CLIs share the same CI/CD stoplight contract:
-
APROBADO(exit 0): Score< 20, no critical/high findings. -
PRECAUCIÓN(exit 1): Score20–59, moderate warnings (auto_map, template desync, missing artifacts), or--stricton minor warnings likedelimiter_injection_passthrough. -
BLOQUEAR(exit 2): Score>= 60or 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 wasn't enough—adversarial testing and cross-platform CI exposed three real failures that would have bitten users in production:
Bug 1: The Hugging Face full_hf=False Blind Spot
In our 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? 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/.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 .bin Files & 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: We 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 our very first GitHub Actions run (Run 46295740989), windows-latest (3.10 & 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
-
Public CLI Tools (
owf-static&owf-dynamic): https://github.com/FranciscoGrandon/openweight-forensics-public - Research Corpus, Papers & Benchmarks: https://github.com/FranciscoGrandon/openweight-forensics
If you run into weird edge cases in custom GGUF metadata, Hugging Face templates, or CI/CD container permissions, open an issue or break it in public—that's how the best invariants get built.
Creado por Francisco Grandón Vergara
Originally published by Dev.to AI. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.