From d1c5b81be7e8b0bda3139c9dce8a66e9b3ceef3f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 23 Nov 2026 17:15:38 +0000 Subject: [PATCH] ci: test on Python 3.13 and 3.14 Add 3.13/3.14 classifiers and CI jobs. The `>=3.8` floor is kept: the suite passes on 3.8 locally, though no hosted runner image has it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DHVivd6CDRsFncTBawLikR --- .github/workflows/ci.yml | 3 + .github/workflows/tests.yml | 2 +- modelhawk.egg-info/PKG-INFO | 290 ++++++++++++++++++++++++ modelhawk.egg-info/SOURCES.txt | 10 + modelhawk.egg-info/dependency_links.txt | 1 + modelhawk.egg-info/entry_points.txt | 2 + modelhawk.egg-info/top_level.txt | 1 + pyproject.toml | 2 + 8 files changed, 310 insertions(+), 1 deletion(-) create mode 100644 modelhawk.egg-info/PKG-INFO create mode 100644 modelhawk.egg-info/SOURCES.txt create mode 100644 modelhawk.egg-info/dependency_links.txt create mode 100644 modelhawk.egg-info/entry_points.txt create mode 100644 modelhawk.egg-info/top_level.txt diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c323ae5..0065db8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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: diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 1c8cfc0..634f6ea 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -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: diff --git a/modelhawk.egg-info/PKG-INFO b/modelhawk.egg-info/PKG-INFO new file mode 100644 index 0000000..99fce60 --- /dev/null +++ b/modelhawk.egg-info/PKG-INFO @@ -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
(recurse, pick model files)"] + GP --> SF{"scan_file
by extension / magic"} + SF -->|".safetensors"| ST["SAFE
(no pickle, no code path)"] + SF -->|".yaml / .yml"| Y["scan_yaml_bytes
(python/* tags)"] + SF -->|".npy"| N["scan_npy_bytes
(object arrays embed a pickle)"] + SF -->|"pickle / zip (.pt, .bin, .npz)"| IT["iter_pickle_streams
(bounded member count and size)"] + IT --> SP["scan_pickle_bytes
(opcode walk, never unpickles)"] + SP --> CG["classify_global
(dangerous callables)"] + Y --> V["verdict per file
(worst stream wins)"] + N --> V + CG --> V + ST --> V + V --> R["print_reports / --json
(--disasm for opcodes)"] + R --> X{"--fail-on
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.* diff --git a/modelhawk.egg-info/SOURCES.txt b/modelhawk.egg-info/SOURCES.txt new file mode 100644 index 0000000..cdf6c5e --- /dev/null +++ b/modelhawk.egg-info/SOURCES.txt @@ -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 \ No newline at end of file diff --git a/modelhawk.egg-info/dependency_links.txt b/modelhawk.egg-info/dependency_links.txt new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/modelhawk.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/modelhawk.egg-info/entry_points.txt b/modelhawk.egg-info/entry_points.txt new file mode 100644 index 0000000..4bce9fa --- /dev/null +++ b/modelhawk.egg-info/entry_points.txt @@ -0,0 +1,2 @@ +[console_scripts] +modelhawk = modelhawk:main diff --git a/modelhawk.egg-info/top_level.txt b/modelhawk.egg-info/top_level.txt new file mode 100644 index 0000000..3451249 --- /dev/null +++ b/modelhawk.egg-info/top_level.txt @@ -0,0 +1 @@ +modelhawk diff --git a/pyproject.toml b/pyproject.toml index 4be969f..c1c554e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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", ]