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
22 changes: 22 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
name: ci
on:
push:
branches: [main]
pull_request:
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
strategy:
matrix:
python: ["3.10", "3.12"]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: ${{ matrix.python }}
- run: python -m pip install -e '.[dev]'
- run: ruff check .
- run: python tools/safety_lint.py corpus/
- run: pytest -q
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
.PHONY: check eval report

check:
python3 tools/safety_lint.py corpus/ && pytest
python3 tools/safety_lint.py corpus/ && ruff check . && pytest

eval:
mkdir -p results
Expand Down
141 changes: 70 additions & 71 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,89 +1,88 @@
# modelscan-eval

`modelscan-eval` is a reproducible meta-benchmark for static ML supply-chain
scanners. It runs multiple scanners over the same 41-item labeled synthetic
corpus and reports detection rate, false-positive rate, and robustness to five
pickle-evasion techniques.
A small meta-benchmark for static ML supply-chain scanners. It runs the same labeled, synthetic corpus of 41 files through [picklescan](https://github.com/mmaitre314/picklescan), [modelscan](https://github.com/protectai/modelscan) and a naive in-repo opcode baseline, then reports detection rate, false-positive rate and robustness to five pickle-evasion techniques. It evaluates scanners; it is not a scanner.

The corpus covers pickle and torch-style artifacts, custom Hugging Face code,
and spoofed metadata. No real model weights or downloads are required.
All fixtures are generated by [`corpus/generate.py`](corpus/generate.py) and committed. Nothing is downloaded, and CI runs offline.

## Run
## Methodology

Python 3.10 or newer is required. From a fresh clone:
- **Corpus** ([`corpus/manifest.yaml`](corpus/manifest.yaml)): every item has a label (`malicious` or `clean`), a `technique`, and an optional `evasion`. Clean controls are matched to each malicious category.
- **Payload safety**: the only thing a malicious fixture does when loaded is write one marker file (`modelscan-eval.canary`) into the current directory through `corpus._marker.drop_canary`. [`tools/safety_lint.py`](tools/safety_lint.py) rejects network, shell and dynamic-execution tokens in `corpus/`, and `tests/test_corpus_markers.py` unpickles each marker pickle in a temp directory and asserts that the canary is the only file created. The harness itself never unpickles fixtures; it only shells out to the scanners (or, for the baseline, reads opcodes).
- **Metrics** ([`eval/metrics.py`](eval/metrics.py)):
- detection rate = flagged / total over malicious items with no evasion (18 items)
- false-positive rate = flagged / total over clean items (18 items)
- evasion robustness = flagged / total over the items carrying one evasion label (1 item per technique, so these are single-sample outcomes)
- items a scanner was not run on (`skipped`) are excluded from denominators; scan errors count as unflagged and are tallied separately.

```sh
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -e '.[scanners]'
make check
make eval
make report
```
## Scanners

| Scanner | How it is invoked | Notes |
|---|---|---|
| `picklescan` | `picklescan --path <file>`, flagged on exit code 1 | optional extra |
| `modelscan` | `modelscan --path <file> --reporting-format json`, flagged on exit code 1 (3 = no supported files, not an error) | optional extra; needs a Python version modelscan supports (3.12 used here) |
| `opcode_baseline` | `pickletools.genops`, flags any `REDUCE`, `GLOBAL` or `STACK_GLOBAL`; unwraps torch zips; ignores non-pickle files | deliberately naive denylist, a reference point and not a recommendation |

## Case taxonomy

`make check` runs the safety lint before the tests. `make eval` writes raw
verdicts to `results/verdicts.jsonl`; `make report` produces
`results/results.json` and the shippable [report](results/REPORT.md).
Counts come from `corpus/manifest.yaml`.

The optional `[scanners]` extra installs `picklescan` and `modelscan`. Those
extras are not installed in the environment used for the committed report, so
only `opcode_baseline` has measurements there. The harness degrades gracefully:
an absent adapter returns `available() == False`, is recorded as `skipped`, and
is excluded from metric denominators rather than counted as a miss.
| Category (`technique`) | Format (`kind`) | Malicious | Clean | What it is |
|---|---|---:|---:|---|
| `pickle_reduce` | pickle (`.pkl`) | 7 | 7 | `__reduce__` returning the canary function, in different containers (bare, dict, tuple, `functools.partial`, `operator.methodcaller`) |
| `pickle_reduce` | torch-style zip (`.bin`) | 1 | 1 | same payload inside `archive/data.pkl` |
| `custom_code_import` | Python source (`.py`) | 5 | 5 | model/tokenizer/processor code that calls the canary at import time |
| `metadata_spoof` | JSON config | 5 | 5 | typosquat, lineage, author, namespace and checkpoint spoofs in config metadata |

## Safety model
Evasion variants (all `pickle_reduce`, one item each, derived from `malicious_reduce`):

Every corpus fixture and generator source is safety-lint-enforced. The only
permitted behavior of a malicious fixture is one benign marker-file write under
a caller-provided temporary directory, through the audited
`corpus._marker.drop_canary` helper. Fixtures do not access the network, spawn
shells against targets, read or exfiltrate user data, or modify files outside
that temporary directory. The evaluation harness performs static scans and
never unpickles or imports malicious fixtures.
| Evasion | Construction |
|---|---|
| `opcode_level_obfuscation` | hand-assembled opcodes (protocol 2, `GLOBAL`/`MARK`/`TUPLE`) |
| `indirect_aliased_global_import` | `getattr(importlib.import_module(...), ...)` chain reaches the callable |
| `nested_second_stage_payload` | outer pickle calls `pickle.loads` on an embedded payload |
| `non_standard_reducer` | `__reduce_ex__` instead of `__reduce__`, protocol 2 |
| `protocol_framing_variance` | payload wrapped in a torch-style zip |

[`tools/safety_lint.py`](tools/safety_lint.py) is the mechanical enforcement
gate readers can inspect and run themselves:
## Reproduce

Python 3.10+. modelscan did not install on Python 3.14 when this was written, so use 3.12 for the full run.

```sh
python3 tools/safety_lint.py corpus/
python3.12 -m venv .venv && source .venv/bin/activate
python -m pip install -e '.[scanners,dev]'
make check # safety lint, ruff, pytest
make eval # raw verdicts -> results/verdicts.jsonl
make report # -> results/results.json, results/REPORT.md
```

Without `.[scanners]`, `make eval` records those scanners as `skipped` and the report shows "no data" for them. Run `eval` and `report` in the same environment so the recorded scanner versions are accurate. To regenerate the fixtures: `python corpus/generate.py` (a test checks they match the committed bytes).

Example, one verdict line from the baseline:

```
$ python -m eval.runner --scanner opcode_baseline | head -1
{"detail": "dangerous opcodes: STACK_GLOBAL, REDUCE", "duration_ms": 0.21, "error": null, "flagged": true, "item_id": "malicious_reduce", "scanner": "opcode_baseline", "severity": "high"}
```

## Results

It checks committed/generated artifacts and generator sources for forbidden
network, shell, dynamic-execution, and related tokens. `make check` always runs
this gate before pytest. Separate sandboxed tests verify each payload produces
only its expected canary.

## Prior art and differentiation

- **InjecAgent-style corpora:** this project reuses the benchmark pattern of a
labeled synthetic adversarial corpus with matched clean controls and explicit
attack categories. It does not reuse prompt-injection samples or evaluate
agents; its artifacts and threat model are ML model-supply-chain specific.
- **`picklescan` and `modelscan`:** these existing scanners are reused
unmodified as subjects under test, behind thin adapters. The in-repo
`pickletools.genops` opcode scanner is a deliberately naive denylist baseline
reflecting the technique described in community and Trail of Bits writeups.
- **Novel contribution:** one shared labeled corpus, one uniform pickle-evasion
taxonomy, and an apples-to-apples cross-tool report measuring both ordinary
detection and evasion robustness. This project evaluates scanners; it does
not propose another scanner.
From the committed run ([`results/REPORT.md`](results/REPORT.md), raw data in `results/verdicts.jsonl`; picklescan 1.0.5, modelscan 0.8.8):

| Scanner | Detection rate | False-positive rate |
|---|---:|---:|
| picklescan | 11.1% (2/18) | 0.0% (0/18) |
| modelscan | 0.0% (0/18) | 0.0% (0/18) |
| opcode_baseline | 44.4% (8/18) | 0.0% (0/18) |

Read these with the limitations below. The low numbers for the real scanners are mostly a property of the corpus, not a ranking of the tools: the payload callable is `corpus._marker.drop_canary`, which is not on either scanner's list of dangerous globals. picklescan flagged only the two items that reach it through `functools.partial` and `operator.methodcaller`. The 10 `py_code` and `metadata` malicious items are outside what pickle scanners inspect, so they cap detection at 8/18 for any pickle scanner. See the evasion table in `results/REPORT.md` for per-technique outcomes.

## Limitations

- Synthetic, intentionally small corpus (41 items); results do not estimate
prevalence or performance on all real-world model repositories.
- Static analysis only. No behavioral detonation and no claim about runtime
containment.
- Pickle-focused. The corpus covers pickle, torch-style pickle containers,
custom Hugging Face code, and metadata; safetensors, GGUF, ONNX, Keras H5,
and TensorFlow SavedModel exploit formats are out of scope for v1.
- No live/networked payloads, real model downloads, or multi-gigabyte weights;
size- and ecosystem-specific scanner behavior may differ in production.
- Metadata spoof and custom-code cases are synthetic, so conclusions depend on
the v1 labels and attack taxonomy.
- Scanner results depend on installed versions. The committed report records
unavailable optional scanners explicitly and should be regenerated with
`.[scanners]` installed for a full comparison.

See [PLAN.md](PLAN.md) for the complete threat model, corpus composition, and
metric definitions.
- The base payload calls a repo-local benign function, so denylist-based scanners have nothing to match. A fair detection comparison needs payloads that call a known-dangerous global with a harmless argument (tracked in an issue).
- Small and synthetic: 41 files, one item per evasion technique. Results say nothing about prevalence or real-world repositories.
- Static scanning only; no runtime detonation.
- Pickle-focused. safetensors, GGUF, ONNX, Keras H5 and SavedModel are out of scope. The `custom_code_import` and `metadata_spoof` categories are included to show where pickle scanners are blind, not because they target them.
- Scanner behavior depends on installed versions and defaults (modelscan ran with its default settings; no settings file).
- Scan errors count as "not flagged".

See [PLAN.md](PLAN.md) for the original design notes.
1 change: 0 additions & 1 deletion corpus/_marker.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from pathlib import Path


CANARY_NAME = "modelscan-eval.canary"
CANARY_CONTENT = "MODELscan-eval benign canary\n"

Expand Down
1 change: 0 additions & 1 deletion corpus/generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

import yaml


ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
Expand Down
51 changes: 22 additions & 29 deletions eval/metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,47 +2,40 @@


def compute_metrics(verdicts: list[dict], items: list[dict]) -> dict:
"""Per-scanner rates plus raw counts.

Skipped verdicts are excluded from denominators. Scan errors count as unflagged
(fail-open, as a user would experience them) and are tallied in `errors`.
`counts` holds [flagged, total] for each rate so tiny denominators stay visible.
"""
item_by_id = {item["id"]: item for item in items}
techniques = sorted({item["evasion"] for item in items if item.get("evasion")})
scanners = dict.fromkeys(verdict["scanner"] for verdict in verdicts)
metrics = {}

def tally(selected: list[dict]) -> list[int]:
return [sum(bool(v["flagged"]) for v in selected), len(selected)]

def rate(counts: list[int]) -> float | None:
return counts[0] / counts[1] if counts[1] else None

for scanner in scanners:
usable = [
verdict
for verdict in verdicts
if verdict["scanner"] == scanner
and verdict.get("status") != "skipped"
and verdict.get("item_id") in item_by_id
v for v in verdicts
if v["scanner"] == scanner and v.get("status") != "skipped" and v.get("item_id") in item_by_id
]
def label(v: dict) -> dict:
return item_by_id[v["item_id"]]

def rate(selected: list[dict]) -> float | None:
return sum(bool(verdict["flagged"]) for verdict in selected) / len(selected) if selected else None

base = [
verdict
for verdict in usable
if item_by_id[verdict["item_id"]]["label"] == "malicious"
and item_by_id[verdict["item_id"]].get("evasion") is None
]
clean = [
verdict
for verdict in usable
if item_by_id[verdict["item_id"]]["label"] == "clean"
]
base = tally([v for v in usable if label(v)["label"] == "malicious" and label(v).get("evasion") is None])
clean = tally([v for v in usable if label(v)["label"] == "clean"])
evasion = {t: tally([v for v in usable if label(v).get("evasion") == t]) for t in techniques}
metrics[scanner] = {
"detection_rate": rate(base),
"fpr": rate(clean),
"evasion_robustness_by_technique": {
technique: rate(
[
verdict
for verdict in usable
if item_by_id[verdict["item_id"]].get("evasion") == technique
]
)
for technique in techniques
},
"evasion_robustness_by_technique": {t: rate(c) for t, c in evasion.items()},
"counts": {"detection": base, "fpr": clean, "evasion": evasion},
"errors": sum(bool(v.get("error")) for v in usable),
}

return {"per_scanner": metrics}
32 changes: 24 additions & 8 deletions eval/report.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,31 @@

import hashlib
import json
from importlib.metadata import PackageNotFoundError, version
from pathlib import Path

import yaml

from eval.metrics import compute_metrics


ROOT = Path(__file__).resolve().parents[1]
RAW_PATH = ROOT / "results/verdicts.jsonl"
RESULTS_PATH = ROOT / "results/results.json"
REPORT_PATH = ROOT / "results/REPORT.md"
MANIFEST_PATH = ROOT / "corpus/manifest.yaml"


def format_rate(value: float | None) -> str:
return "no data" if value is None else f"{value:.1%}"
def format_rate(value: float | None, counts: list[int] | None = None) -> str:
if value is None:
return "no data"
return f"{value:.1%} ({counts[0]}/{counts[1]})" if counts else f"{value:.1%}"


def scanner_version(scanner: str) -> str:
try:
return version(scanner)
except PackageNotFoundError:
return "n/a"


def main() -> None:
Expand All @@ -35,6 +44,8 @@ def main() -> None:
"corpus_item_count": len(items),
"available_scanners": available,
"unavailable_scanners": unavailable,
# read from the environment running the report; run `make eval report` in one env
"scanner_versions": {scanner: scanner_version(scanner) for scanner in available if scanner != "opcode_baseline"},
},
"verdicts": verdicts,
"metrics": metrics,
Expand All @@ -50,14 +61,16 @@ def main() -> None:
f"- Corpus: `sha256:{corpus_hash}` ({len(items)} items)",
f"- Available scanners: {', '.join(f'`{scanner}`' for scanner in available) or 'none'}",
f"- Unavailable scanners: {', '.join(f'`{scanner}`' for scanner in unavailable) or 'none'}",
*[f"- `{scanner}` version: {ver}" for scanner, ver in result["run_meta"]["scanner_versions"].items()],
"",
"## Leaderboard",
"",
"| Scanner | Detection rate | False-positive rate |",
"|---|---:|---:|",
"| Scanner | Detection rate | False-positive rate | Scan errors |",
"|---|---:|---:|---:|",
*[
f"| {scanner} | {format_rate(metrics['per_scanner'][scanner]['detection_rate'])} | {format_rate(metrics['per_scanner'][scanner]['fpr'])} |"
for scanner in scanners
f"| {scanner} | {format_rate(m['detection_rate'], m['counts']['detection'])} "
f"| {format_rate(m['fpr'], m['counts']['fpr'])} | {m['errors']} |"
for scanner, m in metrics["per_scanner"].items()
],
"",
"## Evasion robustness",
Expand All @@ -67,7 +80,10 @@ def main() -> None:
*[
f"| {scanner} | "
+ " | ".join(
format_rate(metrics["per_scanner"][scanner]["evasion_robustness_by_technique"][technique])
format_rate(
metrics["per_scanner"][scanner]["evasion_robustness_by_technique"][technique],
metrics["per_scanner"][scanner]["counts"]["evasion"][technique],
)
for technique in techniques
)
+ " |"
Expand Down
13 changes: 10 additions & 3 deletions eval/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,10 @@

import yaml

from scanners.opcode_baseline import OpcodeBaseline
from scanners.modelscan_adapter import ModelScanAdapter
from scanners.opcode_baseline import OpcodeBaseline
from scanners.picklescan_adapter import PickleScanAdapter


ROOT = Path(__file__).resolve().parents[1]
SCANNERS = {
PickleScanAdapter.name: PickleScanAdapter,
Expand All @@ -25,7 +24,15 @@ def run(scanner_name: str):
if not adapter.available():
return None
manifest = yaml.safe_load((ROOT / "corpus/manifest.yaml").read_text(encoding="utf-8"))
return [replace(adapter.scan(ROOT / item["path"]), item_id=item["id"]) for item in manifest["items"]]
missing = [item["path"] for item in manifest["items"] if not (ROOT / item["path"]).is_file()]
if missing:
raise FileNotFoundError(f"manifest fixtures missing (run corpus/generate.py): {missing}")
verdicts = []
for item in manifest["items"]:
verdict = adapter.scan(ROOT / item["path"])
# keep committed results free of machine-specific absolute paths
verdicts.append(replace(verdict, item_id=item["id"], detail=verdict.detail.replace(f"{ROOT}/", "")))
return verdicts


def main() -> None:
Expand Down
Loading
Loading