Metadata-Version: 2.5
Name: modelbom
Version: 0.1.1
Summary: Find unsafe model loading, poisoned artifacts and unpinned AI dependencies, and emit a CycloneDX AI-BOM. Zero dependencies; never loads what it scans.
Project-URL: Homepage, https://github.com/rajyavardhan01/modelbom
Project-URL: Repository, https://github.com/rajyavardhan01/modelbom
Project-URL: Issues, https://github.com/rajyavardhan01/modelbom/issues
Project-URL: Documentation, https://github.com/rajyavardhan01/modelbom/tree/main/docs
Project-URL: Changelog, https://github.com/rajyavardhan01/modelbom/blob/main/CHANGELOG.md
Author: Rajyavardhan Handa
License-Expression: Apache-2.0
License-File: LICENSE
License-File: NOTICE
Keywords: ai-security,aibom,cyclonedx,huggingface,ml-security,pickle,pytorch,sarif,sbom,supply-chain-security
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
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: 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 :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Quality Assurance
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown

# modelbom

**Find unsafe model loading, poisoned artifacts and unpinned AI dependencies, and emit a CycloneDX AI-BOM. Zero dependencies; never loads what it scans.**

[![CI](https://github.com/rajyavardhan01/modelbom/actions/workflows/ci.yml/badge.svg)](https://github.com/rajyavardhan01/modelbom/actions/workflows/ci.yml)
[![PyPI](https://img.shields.io/pypi/v/modelbom.svg)](https://pypi.org/project/modelbom/)
[![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](https://github.com/rajyavardhan01/modelbom/blob/main/LICENSE)
![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)

<p align="center"><img src="https://raw.githubusercontent.com/rajyavardhan01/modelbom/main/docs/demo.svg" alt="modelbom scanning an example project and reporting findings and attack paths" width="860"></p>

Status: alpha (v0.1.1). Rule IDs and the JSON schema may still change before 1.0.

---

AI systems pull code and data through channels that classic dependency scanners don't see:
model weights downloaded from a hub, `trust_remote_code=True`, pickled checkpoints, tokenizer
chat templates, vector indexes saved with pickle, and datasets fetched at training time.
`modelbom` inventories those components and flags the ones that can execute code or silently
change underneath you. It covers three layers in one pass:

| Layer | What modelbom looks at |
|---|---|
| **Source code** (`.py`, `.ipynb`) | `trust_remote_code`, hub loads without a pinned `revision`, `torch.load` without `weights_only=True`, pickle-family loaders, Keras `safe_mode=False`, unsafe YAML, unverified downloads, `torch.hub.load`, `allow_dangerous_deserialization=True` |
| **Artifacts** | Pickle, PyTorch (zip and legacy), joblib (incl. zlib/gzip/bz2/xz), NumPy `.npy`/`.npz`, Keras `.keras`/`.h5`, safetensors, GGUF, ONNX, model `config.json`, tokenizer chat templates, dataset files |
| **Dependencies** | `requirements*.txt`, `pyproject.toml` (PEP 621, PEP 735, Poetry), `Pipfile`, and `uv.lock` / `poetry.lock` / `pdm.lock` / `Pipfile.lock`; optional OSV.dev lookups |

It then connects the findings into **attack paths** (for example *unpinned hub model* +
*`trust_remote_code=True`* in the same call ⇒ *upstream repository change executes code at load
time*), and writes text, JSON, SARIF 2.1.0 or a CycloneDX 1.6 AI-BOM.

**Safety model.** modelbom never imports, unpickles, or otherwise loads what it scans. Pickles
are decoded opcode by opcode with `pickletools.genops`; archives are read with `zipfile`;
headers are parsed with `struct` and `json`. The package has no runtime dependencies, and a
test asserts that its own source never calls a deserializer.

## Quickstart

```bash
pip install modelbom
modelbom scan path/to/your/project
```

From a source checkout, nothing needs to be installed:

```bash
git clone https://github.com/rajyavardhan01/modelbom && cd modelbom
PYTHONPATH=src python -m modelbom scan examples/vulnerable-app
```

Excerpt of the output for the bundled, intentionally insecure example (run offline):

```text
modelbom 0.1.0 · scanned examples/vulnerable-app
  7 files · 5 code files · 1 artifacts · 6 hub references · 8 dependencies

HIGH
  MB103  download.py:10
         torch.load(..., weights_only=False) unpickles arbitrary objects
         fix: Call torch.load(path, weights_only=True) explicitly and prefer safetensors for weights.
  MB109  rag.py:7
         allow_dangerous_deserialization=True in FAISS.load_local() unpickles the stored index
  ...
  MB101  train.py:12
         trust_remote_code=True in AutoModelForSequenceClassification.from_pretrained() executes code shipped with the model

MEDIUM
  MB102  data.py:6
         dataset 'example-org/product-reviews' loaded via load_dataset() without revision=
  ...

ATTACK PATHS
  AP-1  [critical] Upstream repository change executes code at load time
         precondition: adversary can push to, take over or impersonate 'example-org/sentiment-model'
         1. MB102 train.py:12: model 'example-org/sentiment-model' loaded via from_pretrained() without revision=
         2. MB101 train.py:12: trust_remote_code=True in AutoModelForSequenceClassification.from_pretrained() executes code shipped with the model
         impact: arbitrary code execution in the process that runs train.py
  AP-5  [high] Unverified download is deserialized
         precondition: adversary controls the download host, a mirror, DNS or the network path
         1. MB107 download.py:7: urllib.request.urlretrieve('https://models.example.com/releases/classifier.bin') fetches a model/data file without verifying a checksum
         2. MB103 download.py:10: torch.load(..., weights_only=False) unpickles arbitrary objects
         impact: arbitrary code execution when download.py unpickles the substituted file

Summary: 8 high · 6 medium · 4 low · 5 attack paths  (1 suppressed)
```

`examples/safe-app` performs the same tasks safely and scans clean (exit code 0). It pins releases that had no known advisories when it was last updated; with `--online`, modelbom reports any advisories published since then.

## Usage

```text
modelbom scan PATH  [--format text|json|sarif] [-o FILE] [--fail-on LEVEL] [--online]
                    [--exclude GLOB ...] [--no-hash] [--max-bytes N] [--verbose] [--no-color]
modelbom bom PATH   [-o aibom.cdx.json] [--online] [--exclude GLOB ...]
modelbom graph PATH [--format mermaid|dot|json] [-o FILE]
modelbom rules      [--format text|json|markdown]
modelbom version
```

| Exit code | Meaning |
|---|---|
| 0 | No unsuppressed finding at or above `--fail-on` (default `high`) |
| 1 | At least one unsuppressed finding at or above `--fail-on` |
| 2 | Usage error (bad arguments, missing path) |

Inventory records (`MB206`) never affect the exit code.

### Rules

22 rules in three families: code (`MB1xx`), artifacts (`MB2xx`) and dependencies (`MB3xx`).
Each carries OWASP Top 10 for LLM Applications 2025, OWASP Top 10 for Agentic Applications
2026, MITRE ATLAS and CWE references. See [docs/rules.md](https://github.com/rajyavardhan01/modelbom/blob/main/docs/rules.md) or run
`modelbom rules`.

### Suppressing findings

- Inline, on the flagged line (or any line of a multi-line call):
  `torch.load(p)  # modelbom: ignore[MB103]` or `# modelbom: ignore` for all rules.
  The same comment works in `requirements.txt` and `pyproject.toml`.
- `.modelbomignore` in the scan root:

  ```text
  data/raw/            # skip a directory
  *.ckpt               # skip by name
  MB202:models/*.pkl   # keep scanning, but suppress MB202 for these files
  ```

Suppressed findings are still counted in the summary and appear in SARIF with a
`suppressions` entry.

### Output formats

- **text**: grouped by severity, with remediation and attack paths. Colors only on a TTY; respects `NO_COLOR`.
- **json**: stable `schema_version: 1` document with findings, artifacts, hub references, dependencies and attack paths.
- **sarif**: SARIF 2.1.0 with rule metadata, `security-severity` and partial fingerprints, ready for GitHub code scanning.
- **CycloneDX 1.6 AI-BOM** (`modelbom bom`): `machine-learning-model`, `data`, `file` and `library` components with SHA-256 hashes, `pkg:pypi` / `pkg:huggingface` purls and a `vulnerabilities` section for findings attached to components.
- **graph** (`modelbom graph`): Mermaid, Graphviz DOT or JSON. Attack paths are drawn as dashed `AP-n` edges and risky nodes are highlighted.

### Online vulnerability lookups

`--online` queries [OSV.dev](https://osv.dev) for every exactly pinned dependency (from
manifests or lock files) and reports `MB302` with the advisory ID, CVE aliases and fixed
versions. Without `--online`, modelbom makes no network requests.

## CI integration

GitHub Actions (uploads SARIF to code scanning):

```yaml
jobs:
  modelbom:
    runs-on: ubuntu-latest
    permissions:
      contents: read
      security-events: write
    steps:
      - uses: actions/checkout@v4
      - uses: rajyavardhan01/modelbom@v0.1.1
        with:
          path: .
          fail-on: high
```

pre-commit:

```yaml
repos:
  - repo: https://github.com/rajyavardhan01/modelbom
    rev: v0.1.0
    hooks:
      - id: modelbom
```

## Methodology

modelbom is a reference implementation of the automated vulnerability discovery framework and
exploit-pathway analysis described in:

> R. Handa, "Securing the Intelligent Software Supply Chain: Vulnerability Detection and Exploit
> Pathways in AI-Integrated Systems," *Journal of Computational Analysis and Applications*,
> vol. 34, no. 12, pp. 46–56, 2025. doi:10.48047/jocaaa.2025.34.12.06

[docs/methodology.md](https://github.com/rajyavardhan01/modelbom/blob/main/docs/methodology.md) maps each feature to the paper's sections and
tables, and lists what is not implemented yet.

### Related tools

Artifact scanners such as modelscan, picklescan and fickling focus on the model files
themselves. modelbom covers similar ground for pickle-based artifacts and adds source-code
rules, dependency pinning, attack paths and a CycloneDX AI-BOM in one zero-dependency CLI. The
tools can be used side by side.

## Tested on real projects

Before release, modelbom was run against six popular open-source ML projects: training code,
inference servers, a RAG application and a notebook-heavy repository, from 1 MB to 140 MB
each, scanned statically. Every scan finished in under 3 seconds without errors. In a manual
review, the sampled findings were accurate: real `trust_remote_code=True` calls, `torch.load()`
without `weights_only`, `pickle.load()` and unpinned hub references. The same exercise turned
up two bugs, both fixed before release: syntax warnings from scanned code leaked to stderr,
and notebook cells with multi-line shell escapes failed to parse. Version ranges in a library's
`pyproject.toml` are now reported as informational, because ranges are correct practice for
libraries.

## Limitations

- Code analysis is intra-file and literal-based. A hub ID or URL held in a variable, built with
  string formatting, or passed through a config file is not resolved.
- A pickle allowlist cannot prove a file safe. A clean result means no known-dangerous import
  was found, not that loading the file is harmless.
- `.h5` inspection is a bounded byte search, not a full HDF5 parse.
- No ML-based anomaly detection or behavioral (runtime) analysis yet. See the roadmap.

## Roadmap

- Cross-file data flow for model IDs and paths (config files, constants modules)
- ONNX external-data and custom-operator checks; TensorFlow SavedModel inspection
- Model card / license extraction into the AI-BOM
- Statistical anomaly detection over artifact inventories across commits (P2, "Dependency Mapping and Anomaly Detection")
- Optional signature verification (Sigstore model signing) when signatures are present

## Contributing

See [CONTRIBUTING.md](https://github.com/rajyavardhan01/modelbom/blob/main/CONTRIBUTING.md). Security issues: see [SECURITY.md](https://github.com/rajyavardhan01/modelbom/blob/main/SECURITY.md).

## License

Apache License 2.0. See [LICENSE](https://github.com/rajyavardhan01/modelbom/blob/main/LICENSE) and [NOTICE](https://github.com/rajyavardhan01/modelbom/blob/main/NOTICE).

## Citation

If you use modelbom in research, please cite the software (see [CITATION.cff](https://github.com/rajyavardhan01/modelbom/blob/main/CITATION.cff))
and the paper above.
