Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,13 @@ jobs:
matrix:
include:
# ubuntu-latest (26.04) no longer ships Python 3.9; keep testing it on 24.04 while pyproject declares it.
# (3.8, also declared, passes locally but has no hosted runner image left.)
- python-version: "3.9"
os: ubuntu-24.04
- python-version: "3.12"
os: ubuntu-latest
- python-version: "3.14"
os: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
strategy:
fail-fast: false
matrix:
python-version: ["3.10", "3.11", "3.12"]
python-version: ["3.10", "3.11", "3.12", "3.13", "3.14"]
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
Expand Down
290 changes: 290 additions & 0 deletions modelhawk.egg-info/PKG-INFO
Original file line number Diff line number Diff line change
@@ -0,0 +1,290 @@
Metadata-Version: 2.4
Name: modelhawk
Version: 1.1.0
Summary: Static scanner for malicious ML model files — pickle RCE, unsafe YAML, numpy object arrays
License: MIT License

Copyright (c) 2026 Pyhroff

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Project-URL: Repository, https://github.com/Pyhroff/ModelHawk
Project-URL: Issues, https://github.com/Pyhroff/ModelHawk/issues
Keywords: security,machine-learning,pickle,scanner,malware,supply-chain,yaml,numpy,red-team
Classifier: Development Status :: 4 - Beta
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Topic :: Security
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Dynamic: license-file

# ModelHawk

[![CI](https://github.com/Pyhroff/ModelHawk/actions/workflows/ci.yml/badge.svg)](https://github.com/Pyhroff/ModelHawk/actions/workflows/ci.yml)

**A static malware scanner for serialized ML models — it detects code-execution backdoors hidden inside PyTorch / pickle model files *without* running them.**

> A `.pt` / `.bin` / `.pkl` model file is not data — it's a program. ModelHawk reads the program and tells you if it bites.



---

## The 30-second pitch

PyTorch saves models with Python's **`pickle`**, and *unpickling* a file (`torch.load()` / `pickle.load()`) **executes instructions baked into it**. So "I downloaded a pretrained model from HuggingFace" can quietly mean *"I ran a stranger's code as me."* This is a real, active **AI supply-chain** attack vector — malicious models have been found hosted on public hubs in the wild — and it's the niche that tools like [`picklescan`](https://github.com/mmaitre314/picklescan), Protect AI's [`modelscan`](https://github.com/protectai/modelscan), and Trail of Bits' [`fickling`](https://github.com/trailofbits/fickling) exist to cover.

**ModelHawk** is a clean, dependency-free implementation of that idea, built end to end:

- 🦅 **The scanner** — statically disassembles the pickle opcode stream and flags the primitives that turn *load* into *execute*.
- 💣 **The offensive half** (`make_samples.py`) — crafts a real (but harmless) malicious model so you can watch the scanner catch an exploit chain *you* authored.
- 🧪 **A self-test** that proves detection works on both pickle encodings **and** that scanning never detonates a payload.

Stdlib only. No `torch`, no `numpy`, no network, no install.

---

## How the attack works

Pickle is a tiny stack VM. During a load it can import any global and call it. The classic delivery is the `__reduce__` hook — whatever `(callable, args)` tuple it returns gets **executed** on load:

```python
class Payload:
def __reduce__(self):
import os
return (os.system, ("whoami",)) # runs the instant someone load()s this
```

Pickle that object into a `.pkl` (or drop it inside a `.pt` zip as `data.pkl`) and ship it. The victim doesn't run anything "suspicious" — they just **load a model**.

> Building the file is safe: `pickle.dumps` only *records* the `(callable, args)` tuple — it never invokes the callable. Execution happens only on **load**. ModelHawk exploits exactly this asymmetry: it inspects the recorded opcodes and never loads.

---

## Detection coverage

ModelHawk currently checks three serialization/configuration surfaces without deserializing the input:

| Surface | Formats | Detection approach | Current status |
|---|---|---|---|
| Pickle code execution | `.pkl`, `.pickle`, `.pt`, `.pth`, `.ckpt`, `.bin`, `.joblib`, `.dill`, `.model` | Static opcode analysis with `pickletools`; dangerous globals and invocation opcodes are classified by severity | Implemented |
| Unsafe PyYAML tags | `.yaml`, `.yml` | Byte-level detection of `!!python/*` tags commonly associated with unsafe loaders | Implemented |
| NumPy object arrays | `.npy`, object arrays inside `.npz` | Parses the NumPy header and statically inspects the embedded pickle when the dtype is object | Implemented |
| Safe tensor containers | `.safetensors` | Recognizes the non-pickle container and reports no pickle execution path | Implemented |

This is **static detection, not proof of safety**. A SAFE result means the scanner did not identify a supported dangerous pattern; it does not establish that arbitrary downstream parsers, custom loaders, native extensions, or application code are safe.

## What ModelHawk looks at

It walks the opcode stream with the stdlib **`pickletools`** (a pure parser — no deserialization) and flags:

| Opcode | Meaning | Why it matters |
|---|---|---|
| `GLOBAL` (proto ≤3) | import `module.name` (inline) | how `os.system` / `builtins.exec` get referenced |
| `STACK_GLOBAL` (proto ≥4) | import `module.name` (from stack) | same, but module+name arrive as two preceding strings |
| `REDUCE` | call `callable(*args)` | **the trigger** that actually executes the import |
| `INST` / `OBJ` / `NEWOBJ` / `BUILD` | build an object / run `__setstate__` | alternate execution / gadget paths |

Each imported global is scored by a **severity table** (full lists in `modelhawk.py`):

- **CRITICAL** — `os` / `nt` / `posix`, `subprocess`, `builtins.exec|eval|compile|__import__`, `ctypes`, `runpy`, `pty`, `code.InteractiveInterpreter`, …
- **HIGH** — `socket`, `shutil`, `importlib`, `marshal`, `urllib`/`requests` (network exfil), nested `_pickle`, …
- **MEDIUM** — `base64`/`zlib`/`codecs` (payload obfuscation), or any *unrecognized* import → "manual review."
- **INFO / SAFE** — expected ML machinery (`collections.OrderedDict`, `torch.*`, `numpy.*` rebuild functions).

> **Design note — low false positives by construction.** Real models routinely pickle references to their *own* custom classes (`GLOBAL mymodel MyNet`). Those land as **MEDIUM "manual review,"** and because the CI gate defaults to `--fail-on HIGH`, legitimate models with custom classes **pass cleanly** — you get the signal without the false alarm. Only genuine code-execution sinks (`os`/`subprocess`/`builtins.exec`/…) reach CRITICAL and fail the build.

### Scan pipeline

```mermaid
flowchart TD
P["path(s)"] --> GP["gather_paths<br/>(recurse, pick model files)"]
GP --> SF{"scan_file<br/>by extension / magic"}
SF -->|".safetensors"| ST["SAFE<br/>(no pickle, no code path)"]
SF -->|".yaml / .yml"| Y["scan_yaml_bytes<br/>(python/* tags)"]
SF -->|".npy"| N["scan_npy_bytes<br/>(object arrays embed a pickle)"]
SF -->|"pickle / zip (.pt, .bin, .npz)"| IT["iter_pickle_streams<br/>(bounded member count and size)"]
IT --> SP["scan_pickle_bytes<br/>(opcode walk, never unpickles)"]
SP --> CG["classify_global<br/>(dangerous callables)"]
Y --> V["verdict per file<br/>(worst stream wins)"]
N --> V
CG --> V
ST --> V
V --> R["print_reports / --json<br/>(--disasm for opcodes)"]
R --> X{"--fail-on<br/>threshold"}
X -->|"met"| E1["exit non-zero"]
X -->|"not met"| E0["exit 0"]
```

### Two subtleties that bite people who reason from memory

ModelHawk handles both because they were verified empirically, not assumed:

1. **`os.system` is `nt.system`.** On Windows, `pickle.dumps(os.system)` serializes the module as **`nt`** (`posix` on Linux) — the OS backend, not `os`. A denylist that only knows `os` misses every Windows-built payload. ModelHawk covers the whole `os`/`nt`/`posix` family.
2. **`exec` changes name by protocol.** Protocol 2 emits **`__builtin__.exec`** (the Python-2 module name, kept for back-compat); protocol 5 emits **`builtins.exec`**. The demo below shows both — and both are flagged.

---

## Quickstart

```bash
# 1) See the whole story (craft samples -> scan -> disassemble one):
python demo.py

# 2) Scan a directory of real models (recurses, picks model extensions):
python modelhawk.py ~/Downloads/models/

# 3) CI gate — non-zero exit if anything is HIGH or worse:
python modelhawk.py model.pt --fail-on HIGH ; echo "exit=$?"

# 4) Machine-readable:
python modelhawk.py model.pt --json
```

Useful flags: `--disasm` (full opcode dump for flagged files), `--json`, `--quiet` (only flagged files), `--fail-on {SAFE..CRITICAL}`, `--no-color`.

---

## Example output

![terminal demo: modelhawk samples --no-color](docs/assets/demo.svg)

_Real output of `modelhawk.py samples --no-color` after `python demo.py` crafted the samples (ANSI stripped; exits 1 because CRITICAL findings exist). Paths show `posix.system` because this run was on Linux._

Scanning the crafted corpus (`python demo.py`):

```
[ OK ] SAFE samples/benign_state_dict.pkl
[!!!!] CRITICAL samples/malicious_exec.p2.pkl
|- REDUCE -> __builtin__.exec (invokes dangerous callable __builtin__.exec())
opcodes: GLOBALx1 REDUCEx1
[!!!!] CRITICAL samples/malicious_exec.p5.pkl
|- REDUCE -> builtins.exec (invokes dangerous callable builtins.exec())
opcodes: STACK_GLOBALx1 REDUCEx1
[!!!!] CRITICAL samples/malicious_os_system.p2.pkl
|- REDUCE -> nt.system (imports nt.system from 'nt' (code / process / file execution))
opcodes: GLOBALx1 REDUCEx1
[!!!!] CRITICAL samples/malicious_os_system.p5.pkl
|- REDUCE -> nt.system (imports nt.system from 'nt' (code / process / file execution))
opcodes: STACK_GLOBALx1 REDUCEx1
[!!!!] CRITICAL samples/malicious_pytorch_model.pt
|- REDUCE -> nt.system (imports nt.system from 'nt' (code / process / file execution))
opcodes [archive/data.pkl]: GLOBALx1 REDUCEx1
[ OK ] SAFE samples/safe_model.safetensors
|- safetensors format - no pickle, no code-execution path

scanned 7 file(s) -> CRITICAL:5 SAFE:2
```

The `--disasm` view of one malicious sample — the smoking gun, opcode by opcode:

```
0: \x80 PROTO 2
2: c GLOBAL 'nt system' <-- import os.system (as nt.system on Windows)
15: X BINUNICODE 'echo You just executed code hidden in an ML model. > PWNED.txt'
84: \x85 TUPLE1 <-- build the (cmd,) argument tuple
87: R REDUCE <-- CALL nt.system(cmd) == code execution on load
90: . STOP
```

---

## Safety design

- The scanner **never deserializes** a model. It uses only `pickletools.genops` / `pickletools.dis`, which *parse* opcodes — they never construct objects or invoke `__reduce__`. Inspecting a malicious pickle is safe.
- This is enforced by a test (`test_scanner_contains_no_unpickling_calls`) that walks the scanner's **AST** and fails the build if anyone ever adds an `import pickle`, a `.load()/.loads()`, or an `Unpickler`.
- The bundled "malicious" samples are harmless by construction — their payload only writes a `PWNED.txt` marker; no deletion, persistence, or network. A test scans them from a temp directory and asserts no marker is ever created — i.e. the scanner inspects an exploit **without firing it**.

```
$ python tests/test_modelhawk.py
PASS test_detection_and_no_false_positives # both protocols + the .pt zip
PASS test_scanning_never_detonates_payload # no PWNED.txt after scanning
PASS test_scanner_contains_no_unpickling_calls # AST invariant
PASS test_classify_global_severity_table # severity table / false-positive path
PASS test_yaml_detection
PASS test_npy_object_array_handcrafted
PASS test_npy_float_array_safe
PASS test_npy_header_bounds_and_versions
PASS test_npy_real_numpy_object_array
PASS test_zip_member_resource_limits
10/10 passed
```

---

## The fix: `safetensors`

The root cause is that pickle is Turing-complete *by design*. The industry fix is [**safetensors**](https://github.com/huggingface/safetensors): a dumb, code-free container — an 8-byte length, a JSON header of tensor shapes/offsets, then raw bytes. There is no `__reduce__`, no opcode VM, **no code path**. ModelHawk recognizes it and reports `SAFE`. **Prefer `safetensors`; treat `.pkl`/`.pt`/`.bin` from untrusted sources as code.**

---

## Project layout

```
ModelHawk/
├─ modelhawk.py # the scanner (importable library + CLI)
├─ make_samples.py # offensive half: crafts harmless malicious samples
├─ demo.py # craft -> scan -> disassemble, in one command
├─ tests/test_modelhawk.py # self-test (both protocols, no-detonation, AST invariant)
├─ README.md
└─ LICENSE # MIT
```

## Limitations & future work (honest scope)

- `STACK_GLOBAL` resolution uses a **recent-strings heuristic** (the last two pushed strings), the same pragmatic approach `picklescan` takes — not a full pickle stack-machine. Adversarial opcode reordering could evade it; a complete VM is the natural next step.
- `torch.*` / `numpy.*` are trusted as benign machinery to keep false positives low. A determined attacker abusing a gadget *inside* an allowlisted module wouldn't be flagged — gadget-chain analysis is future work.
- Container coverage is `.pkl` + PyTorch `.zip`/`.pt` + `safetensors`. `.npy`/`.npz` object arrays, `joblib`, and `dill` extensions are recognized as model files but not yet deeply parsed.

## References

- CWE-502: Deserialization of Untrusted Data
- Python docs — *"the pickle module is not secure; only unpickle data you trust."*
- HuggingFace **safetensors** (the safe format) · Protect AI **modelscan** · Trail of Bits **fickling** · **picklescan**



## Security research & evaluation

- [Threat model](docs/THREAT_MODEL.md)
- [Evaluation methodology](docs/EVALUATION.md)

ModelHawk treats the **no-deserialization invariant** as a first-class security property: the scanner should inspect hostile artifacts without executing them. Benchmarks therefore cover both detection quality and scanner safety.

## License

Released under the [MIT License](LICENSE).

---

*Built as a portfolio project on AI × security supply chain. Author: Pyhroff.*
10 changes: 10 additions & 0 deletions modelhawk.egg-info/SOURCES.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
LICENSE
README.md
modelhawk.py
pyproject.toml
modelhawk.egg-info/PKG-INFO
modelhawk.egg-info/SOURCES.txt
modelhawk.egg-info/dependency_links.txt
modelhawk.egg-info/entry_points.txt
modelhawk.egg-info/top_level.txt
tests/test_modelhawk.py
1 change: 1 addition & 0 deletions modelhawk.egg-info/dependency_links.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@

2 changes: 2 additions & 0 deletions modelhawk.egg-info/entry_points.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[console_scripts]
modelhawk = modelhawk:main
1 change: 1 addition & 0 deletions modelhawk.egg-info/top_level.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
modelhawk
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ classifiers = [
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
"Topic :: Security",
"Topic :: Scientific/Engineering :: Artificial Intelligence",
]
Expand Down