From 47ce538c454f75ec3763d91c7962dceb1df53024 Mon Sep 17 00:00:00 2001 From: Pyhroff <215876416+Pyhroff@users.noreply.github.com> Date: Tue, 1 Dec 2026 10:42:02 +0000 Subject: [PATCH] build: prepare for publishing to PyPI - SPDX license expression (PEP 639) instead of the license table and the License classifier; setuptools>=77, no separate wheel requirement. - requires-python >=3.9: CI's oldest tested version is 3.9, so 3.8 was claimed but never run. - Author and Homepage in the metadata. - Stop tracking modelhawk.egg-info (build output) and ignore it. - Release workflow that publishes through PyPI trusted publishing on a v* tag matching the version (same as memsentry and ragsentry). Claude-Session: https://claude.ai/code/session_01DHVivbcpuTt8KAM1KQR5Lm --- .github/workflows/release.yml | 42 ++++ .gitignore | 5 + 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 | 11 +- 8 files changed, 53 insertions(+), 309 deletions(-) create mode 100644 .github/workflows/release.yml delete mode 100644 modelhawk.egg-info/PKG-INFO delete mode 100644 modelhawk.egg-info/SOURCES.txt delete mode 100644 modelhawk.egg-info/dependency_links.txt delete mode 100644 modelhawk.egg-info/entry_points.txt delete mode 100644 modelhawk.egg-info/top_level.txt diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..41556fe --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,42 @@ +name: release +# Publishes to PyPI via trusted publishing (OIDC) when you push a tag like v1.2.0. No API token is stored. +# One-time setup on pypi.org -> your project -> Publishing: owner Pyhroff, repo ModelHawk, workflow release.yml, environment pypi. +on: + push: + tags: ["v*"] +permissions: + contents: read +jobs: + build: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.11" + - run: pip install build twine + - run: python -m build + - run: twine check dist/* + - name: Tag must match package version + run: | + v=$(python - <<'PY' + import tomllib; print(tomllib.load(open("pyproject.toml","rb"))["project"]["version"]) + PY + ) + test "v$v" = "$GITHUB_REF_NAME" || { echo "tag $GITHUB_REF_NAME != version v$v"; exit 1; } + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: dist + path: dist/ + publish: + needs: build + runs-on: ubuntu-latest + environment: pypi + permissions: + id-token: write + steps: + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: dist + path: dist/ + - uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # release/v1 diff --git a/.gitignore b/.gitignore index 218cee8..ff26fa1 100644 --- a/.gitignore +++ b/.gitignore @@ -10,3 +10,8 @@ PWNED.txt !.env.example *.key *.pem + +# Build output +*.egg-info/ +build/ +dist/ diff --git a/modelhawk.egg-info/PKG-INFO b/modelhawk.egg-info/PKG-INFO deleted file mode 100644 index 99fce60..0000000 --- a/modelhawk.egg-info/PKG-INFO +++ /dev/null @@ -1,290 +0,0 @@ -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 deleted file mode 100644 index cdf6c5e..0000000 --- a/modelhawk.egg-info/SOURCES.txt +++ /dev/null @@ -1,10 +0,0 @@ -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 deleted file mode 100644 index 8b13789..0000000 --- a/modelhawk.egg-info/dependency_links.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/modelhawk.egg-info/entry_points.txt b/modelhawk.egg-info/entry_points.txt deleted file mode 100644 index 4bce9fa..0000000 --- a/modelhawk.egg-info/entry_points.txt +++ /dev/null @@ -1,2 +0,0 @@ -[console_scripts] -modelhawk = modelhawk:main diff --git a/modelhawk.egg-info/top_level.txt b/modelhawk.egg-info/top_level.txt deleted file mode 100644 index 3451249..0000000 --- a/modelhawk.egg-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -modelhawk diff --git a/pyproject.toml b/pyproject.toml index c1c554e..dcb1eb8 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,5 +1,5 @@ [build-system] -requires = ["setuptools>=61", "wheel"] +requires = ["setuptools>=77"] build-backend = "setuptools.build_meta" [project] @@ -7,8 +7,10 @@ name = "modelhawk" version = "1.1.0" description = "Static scanner for malicious ML model files — pickle RCE, unsafe YAML, numpy object arrays" readme = "README.md" -license = {file = "LICENSE"} -requires-python = ">=3.8" +license = "MIT" +license-files = ["LICENSE"] +authors = [{ name = "Pyhroff" }] +requires-python = ">=3.9" keywords = [ "security", "machine-learning", "pickle", "scanner", "malware", "supply-chain", "yaml", "numpy", "red-team", @@ -18,10 +20,8 @@ classifiers = [ "Environment :: Console", "Intended Audience :: Developers", "Intended Audience :: Science/Research", - "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", @@ -37,6 +37,7 @@ dependencies = [] modelhawk = "modelhawk:main" [project.urls] +Homepage = "https://github.com/Pyhroff/ModelHawk" Repository = "https://github.com/Pyhroff/ModelHawk" Issues = "https://github.com/Pyhroff/ModelHawk/issues"