Skip to main content
Back to Blog
AI SecuritySupply ChainMLOps

AI Supply Chain Security: Model Provenance, Safe Model Formats and AI-Suggested Dependencies

How to bring open models, adapters, datasets and AI coding assistants into your engineering organization without importing code execution, tampered weights or invented packages: safe formats, pinning and signing, scanning, AI BOMs, dependency controls and a model registry.
By Security Research & Development27 min read

What your teams actually download when they "just pull a model", and the controls that keep a checkpoint, an adapter or a suggested package from becoming code execution in your environment.

A typical team working with AI pulls open model weights from public hubs, fine-tunes them on internal data, serves them behind an inference server, and writes part of its code with an AI assistant. Each of those steps imports something from outside: files that may execute code when loaded, weights whose origin nobody recorded, training data that nobody can audit, and package names that a model invented. The OWASP Top 10 for LLM Applications lists this as its own risk, LLM03:2025 Supply Chain, separate from prompt injection, because the failure happens before a single prompt is sent.

This guide is for engineering and platform leads who own that intake. It treats the AI supply chain as a set of concrete components, then covers the controls that matter for each: safe serialization formats, pinning and signing, scanning and its limits, poisoning, AI-suggested dependencies, and an internal registry that ties it together. General CI/CD hardening (runner isolation, secrets, artifact signing for containers) is covered in CI/CD Pipeline Security and is not repeated here.

Table of Contents

1. The AI Supply Chain as Components

1.1 What You Are Actually Importing

"We use Llama" hides several artifacts, each with its own source and failure mode. Inventory them separately.

ComponentTypical sourceWhat can go wrongFirst control
Base model weightsPublic hub, vendor downloadCode execution on load (pickle), tampered or swapped weights, impersonated publisherSafe format, commit pinning, signature or hash check
Adapters (LoRA and similar)Hub, internal fine-tuning jobsSame as weights, plus behavior changes that are hard to seeSame as weights; evaluate the merged result, not the base
DatasetsHub, web crawls, vendors, internal exportsPoisoning, licensing problems, sensitive dataRecorded source and version, hashes, review of what was ingested
Tokenizers and configsShipped in the model repoconfig.json fields that pull in code, changed special tokens or chat templatesPin with the weights; diff on every update
Custom model code*.py files in the model repoArbitrary code run by trust_remote_code=TrueDisallow by default; vendor and review when required
Inference servers and runtimesPyPI, container images, GitHub releasesOrdinary CVEs, unsafe template rendering, exposed admin APIsPatch, pin, isolate, no public management ports
Python ML dependenciesPyPI plus extra indexes (for example PyTorch's)Dependency confusion, compromised packages, typosquatsHash-locked installs, single trusted index
AI coding assistantsIDE extensions, rules files, tool serversInvented package names, hidden instructions in rules filesDependency allowlists, review of assistant config

A single model repo can hold safetensors weights, a pickle checkpoint, ONNX exports, a tokenizer, a chat template and Python files, and the loading library decides which are used. The controls are ordinary supply chain controls (pin, verify, scan, restrict sources) applied to file types your existing tooling does not understand.

1.2 Why Models Differ from Ordinary Dependencies

Three properties make model artifacts harder than a typical library:

  • They are opaque. A library can be read and diffed. Nobody can review billions of weights, and no scanner can confirm they encode only the behavior the model card describes.
  • Behavior is the payload. A pickle exploit is a code-execution bug a scanner can catch. A backdoored fine-tune executes nothing unusual; it answers differently on a trigger. That is an evaluation problem, not a malware problem.
  • Reuse is concentrated. NIST AI 600-1 points out that because foundation models are hard to train, organizations reuse a small number of them heavily. A problem in one popular base model or dataset flows into every fine-tune built on it.

1.3 What the Frameworks Say

Three documents are worth knowing because auditors and customers cite them:

  • OWASP LLM03:2025 Supply Chain lists vulnerable pre-trained models, weak provenance, malicious LoRA adapters, model merge and conversion services, and outdated components. Its mitigations include AI BOMs, signature and hash verification, and red teaming third-party models for your use case.
  • OWASP LLM04:2025 Data and Model Poisoning covers tampered pre-training, fine-tuning and embedding data, and explicitly notes that shared model repositories can carry malicious pickled files.
  • NIST AI 600-1 (the Generative AI Profile of the AI Risk Management Framework, July 2024) names "Value Chain and Component Integration" as one of its twelve risks and suggests actions such as GV-6.1-007, "Inventory all third-party entities with access to organizational content and establish approved GAI technology and service provider lists."

None of these prescribe tools; the rest of this guide covers the tools and settings.

2. Unsafe Serialization and Safe Formats

2.1 Why Pickle Checkpoints Execute Code

PyTorch's traditional checkpoint format (.bin, .pt, .pth, .ckpt) is a ZIP archive containing a Python pickle. Pickle is not a data format; it is a small stack-based program that the unpickler runs. Its GLOBAL/STACK_GLOBAL opcodes import any callable by name, and REDUCE calls it with arguments. An object whose __reduce__ method returns (os.system, ("...",)) becomes a file that runs a shell command the moment it is loaded. Hugging Face's pickle documentation walks through exactly this, and scikit-learn's guide says pickle, joblib and cloudpickle should only be used when "the artifact, i.e. the pickle-file, is coming from a trusted and verified source."

This is not theoretical. In February 2024 JFrog reported around 100 models on the Hugging Face Hub with real malicious payloads, including one that opened a reverse shell through __reduce__ as soon as the checkpoint was loaded with torch.load().

2.2 Model Formats Compared

FormatTypical extensionsCan loading run code?Notes
PyTorch pickle.bin, .pt, .pth, .ckptYes, unless loaded with the restricted weights_only unpicklerDefault PyTorch format for years; still common on the Hub
safetensors.safetensorsNo: a JSON header plus raw tensor bytesAudited by Trail of Bits in 2023; the format Transformers prefers
joblib / pickle (classic ML).joblib, .pklYesscikit-learn suggests skops.io or ONNX for untrusted sources
Keras.keras, .h5Lambda layers can carry code; safe_mode=True is meant to block themsafe_mode has had several bypasses; see section 2.6
GGUF.ggufNot by design, but metadata includes a chat template the runtime rendersTemplate rendering caused CVE-2024-34359 in llama-cpp-python
NumPy.npy, .npzOnly object arrays, and allow_pickle defaults to FalseNever pass allow_pickle=True for files you did not create
ONNX.onnxNo pickle, but the graph can express arbitrary computationscikit-learn's docs recommend serving ONNX in a sandbox

The policy is short: accept safetensors for anything that crosses a trust boundary, and treat every pickle-based file from outside as executable code.

2.3 Loading with safetensors

The safetensors library reads a fixed header and maps tensor bytes into memory. There is nothing to execute. Load a full file or stream tensors one by one:

from safetensors.torch import load_file
from safetensors import safe_open

# Load every tensor into a dict on the CPU
state_dict = load_file("model.safetensors", device="cpu")

# Or open lazily and read only what you need
with safe_open("model.safetensors", framework="pt", device="cpu") as f:
    for name in f.keys():
        tensor = f.get_tensor(name)

To convert an internal checkpoint you trust into safetensors, load it in a sandbox and write it back out:

import torch
from safetensors.torch import save_file

state_dict = torch.load("trusted-checkpoint.pt", map_location="cpu", weights_only=True)
save_file(state_dict, "model.safetensors")

save_file refuses tensors that share memory (tied weights, for example). Convert on an isolated host: the load step is where a malicious pickle would run.

With Hugging Face Transformers, from_pretrained() already prefers safetensors when the repository has them. Make that a requirement with use_safetensors=True, and always combine it with a pinned commit:

from transformers import AutoModel

model = AutoModel.from_pretrained(
    "sentence-transformers/all-MiniLM-L6-v2",
    revision="1110a243fdf4706b3f48f1d95db1a4f5529b4d41",
    use_safetensors=True,
)

The pin matters more than the flag. In Transformers 5.24.1, use_safetensors=True on a pickle-only Hub repo behaves differently depending on revision:

  • Pinned commit: the load fails with OSError: ... does not appear to have a file named model.safetensors or model.safetensors.index.json, which is what you want. A local directory without safetensors also fails.
  • revision="main" (the default): the load can succeed. Transformers looks for an open pull request from Hugging Face's SFconvertbot (asking a public conversion Space to open one if none exists) and loads the weights from that refs/pr/N branch, which the repo owner never merged. You end up running weights the publisher never approved, from a commit you did not record.

Setting DISABLE_SAFETENSORS_CONVERSION=1 (or HF_HUB_OFFLINE=1) turns that conversion path off.

2.4 torch.load and weights_only

torch.load has a restricted mode, weights_only=True, that only rebuilds tensors, primitive types, dictionaries and types you explicitly allowlist. As of PyTorch 2.6, weights_only=True is the default when pickle_module is not passed. Older releases, and any call passing weights_only=False, use the full unpickler.

Two caveats matter:

  • Upgrade, do not just set the flag. CVE-2025-32434 (GHSA-53q9-r3pm-6pq6) showed remote code execution through torch.load(..., weights_only=True) in PyTorch 2.5.1 and earlier; it is fixed in 2.6.0. A later advisory, CVE-2026-24747 (GHSA-63cw-57p8-fm3p), found memory corruption in the same restricted unpickler, potentially leading to code execution, in every release before 2.10.0. Treat PyTorch 2.10.0 as the floor for loading anything you did not produce.
  • The error message invites the unsafe fix. When a checkpoint contains a non-allowlisted type, PyTorch suggests re-running with weights_only=False. That is the right answer only for files you produced yourself. For anything else, allowlist the specific type you trust.
import argparse
import torch
from torch.serialization import get_unsafe_globals_in_checkpoint, safe_globals

path = "checkpoint.pt"

# Static listing of globals the checkpoint needs beyond the defaults
print(get_unsafe_globals_in_checkpoint(path))   # e.g. ['argparse.Namespace']

# Allow exactly that type, only for this call
with safe_globals([argparse.Namespace]):
    ckpt = torch.load(path, map_location="cpu", weights_only=True)

torch.serialization.add_safe_globals([...]) does the same globally for the process. PyTorch's serialization notes warn that get_unsafe_globals_in_checkpoint is static and can miss types built dynamically during unpickling, so treat it as a hint.

When you cannot edit every call site (third-party training scripts, notebooks), force the safe mode from the environment:

# Every torch.load call uses weights_only=True, even if the code passes False
export TORCH_FORCE_WEIGHTS_ONLY_LOAD=1

Do not set the opposite variable, TORCH_FORCE_NO_WEIGHTS_ONLY_LOAD=1, in shared images: it switches every call that does not pass weights_only back to the unsafe unpickler.

2.5 trust_remote_code in Transformers

Some models ship their architecture as Python files in the model repository. Transformers is designed to import that code only when you pass trust_remote_code=True, which defaults to False. The Transformers documentation says the option should only be set for repositories "you trust and in which you have read the code, as it will execute code present on the Hub on your local machine."

The False default has not always held. Two advisories show that config.json and other repo files are code paths in their own right:

  • CVE-2026-4372 (GHSA-29pf-2h5f-8g72): before 5.3.0, a crafted _attn_implementation_internal field in config.json made from_pretrained() download and run Python from an attacker's Hub repo, without trust_remote_code.
  • CVE-2026-80047 (GHSA-x9r9-c232-4q39): in 4.49.0 through 5.8.1, load_custom_generate() wrote remote custom_generate/generate.py into the local module cache before the consent check. Execution was still gated, but the file stayed on disk.

Run a Transformers release newer than 5.8.1, and diff config.json on every model update like any other code change.

Treat trust_remote_code=True as pip install from an unreviewed source. If you need a model that requires it:

  1. Read the Python files at a specific commit, and pin that commit with revision. When the code lives in the model repo, Transformers uses revision for the code as well.
  2. Check auto_map in config.json. An entry in the "other-org/other-repo--module.Class" form loads code from a different repository, and revision does not apply there: that code comes from main unless you pass code_revision, a commit in the code repo.
from transformers import AutoModelForCausalLM

MODEL_REPO = "example-org/custom-model"        # weights and config.json
MODEL_REVISION = "<commit sha in example-org/custom-model>"
# Only when auto_map points at another repo, e.g. "example-org/modeling-code--modeling.MyModel"
CODE_REVISION = "<commit sha in example-org/modeling-code>"

model = AutoModelForCausalLM.from_pretrained(
    MODEL_REPO,
    revision=MODEL_REVISION,
    code_revision=CODE_REVISION,
    trust_remote_code=True,
    use_safetensors=True,
)

Better still, vendor the reviewed modeling code into your own repository, register it with the Auto classes, and load with trust_remote_code=False, so upstream changes go through your code review.

2.6 Other Loaders That Run Code

The same pattern appears outside PyTorch:

  • Keras. .keras and .h5 models can contain Lambda layers with serialized Python. keras.models.load_model has safe_mode=True to refuse them, but it has been bypassed repeatedly: CVE-2025-9905 (safe_mode ignored for .h5 files, fixed in 3.11.3), CVE-2026-1462 (a TFSMLayer loading attacker-supplied SavedModels, fixed in 3.13.2) and CVE-2026-12481 (Lambda deserialization outside a safe-mode scope, fixed in 3.12.3 and 3.15.0). Run Keras 3.15 or later, and do not rely on safe_mode alone for untrusted files.
  • Classic ML. joblib and pickle files from scikit-learn and similar libraries execute code on load. scikit-learn's documentation points to skops.io, which refuses unknown types until you inspect them with get_untrusted_types() and pass them explicitly.
  • Inference runtimes. GGUF files carry a chat template in their metadata. llama-cpp-python 0.2.30 through 0.2.71 rendered that template with an unsandboxed Jinja2 environment, so a crafted model file could run code (CVE-2024-34359, fixed in 0.2.72). Track inference server advisories as closely as your web framework's.

3. Provenance and Integrity

Safe formats stop code execution. Provenance tells you whether the weights are the ones the publisher released, and whether the publisher is who you think.

3.1 Pin to a Commit, Not a Name

Hugging Face model repositories are git repositories, and main is a moving target: the owner, or whoever takes over the account, can push new weights, code or tokenizers at any time. revision accepts a branch, tag or commit hash; only the hash is immutable.

Resolve the hash once, record it, and use it everywhere:

from huggingface_hub import HfApi, snapshot_download

repo = "sentence-transformers/all-MiniLM-L6-v2"
info = HfApi().model_info(repo, revision="main", files_metadata=True)
print(info.sha)   # 1110a243fdf4706b3f48f1d95db1a4f5529b4d41 at the time of writing

path = snapshot_download(
    repo,
    revision=info.sha,
    allow_patterns=["*.json", "*.safetensors", "*.txt"],   # skip pickle and other formats
)

allow_patterns keeps pytorch_model.bin and other unused formats off disk. The hf CLI does the same with hf download <repo> --revision <sha> --include "*.safetensors".

3.2 Checksums

The Hub API reports a hash for every file in a repo, but not the same kind: files stored through Git LFS (typically the weights) carry a SHA-256, and small files such as config.json or vocab.txt carry only their git blob SHA-1. Verify both at intake. This script checks every downloaded file against the pinned commit, and exits non-zero on a mismatch, a file the repo does not have at that commit, or an expected file that is missing:

import fnmatch
import hashlib
import sys
from pathlib import Path
from huggingface_hub import HfApi

repo, sha, local_dir = sys.argv[1], sys.argv[2], Path(sys.argv[3])
PATTERNS = ["*.json", "*.safetensors", "*.txt"]   # same as allow_patterns at download

info = HfApi().model_info(repo, revision=sha, files_metadata=True)
remote = {f.rfilename: f for f in info.siblings}
local = {p.relative_to(local_dir).as_posix() for p in local_dir.rglob("*")
         if p.is_file() and p.relative_to(local_dir).parts[0] != ".cache"}

failures = []
for name in sorted(local):
    f = remote.get(name)
    if f is None:
        failures.append(f"not in repo at {sha}: {name}")
        continue
    data = (local_dir / name).read_bytes()
    if f.lfs:
        ok = hashlib.sha256(data).hexdigest() == f.lfs.sha256
    else:
        # Non-LFS files: the Hub reports the git blob SHA-1
        ok = hashlib.sha1(b"blob %d\0" % len(data) + data).hexdigest() == f.blob_id
    print("ok      " if ok else "MISMATCH", name)
    if not ok:
        failures.append(f"hash mismatch: {name}")

for name in sorted(remote):
    if any(fnmatch.fnmatch(name, p) for p in PATTERNS) and name not in local:
        failures.append(f"missing locally: {name}")

if failures:
    print("\n".join(failures), file=sys.stderr)
    sys.exit(1)

Run it as python verify_snapshot.py <repo> <commit> <local-dir> right after snapshot_download or hf download --local-dir. Keep PATTERNS in step with the allow_patterns you downloaded with.

From then on, use your own SHA-256 manifest so later checks do not depend on the Hub:

# At approval time, inside the model directory: every file, including subdirectories
find . -type f ! -path './.cache/*' -print0 | sort -z | xargs -0 sha256sum > ../model.SHA256SUMS

# On every host that loads the model
sha256sum --check --strict --quiet ../model.SHA256SUMS

sha256sum --check catches changed and deleted files but not added ones; the signature in the next section catches those too. And a checksum proves only that the bytes match what you recorded, not who produced them: a Hub hash is as trustworthy as the account that pushed the file. Signing closes that gap.

3.3 Signing Models with OpenSSF Model Signing

The OpenSSF Model Signing project (model-signing on PyPI, maintained in the sigstore/model-transparency repository; 1.1.1 as of this writing) signs a whole model directory. It hashes every file into a manifest, signs that manifest, and writes a Sigstore bundle. Verification recomputes the hashes and fails if any file changed, or if files appear that were not signed.

Keyless signing with Sigstore ties the signature to an OIDC identity (a person's account, or a CI workflow) and records it in Sigstore's transparency log:

# 1.1.1 imports certifi and pyOpenSSL without declaring them as dependencies
pip install model-signing certifi pyopenssl

# Sign (opens an OIDC flow; in GitHub Actions add --use_ambient_credentials)
model_signing sign sigstore ./all-MiniLM-L6-v2 --signature all-MiniLM-L6-v2.sig

# Verify: you must state who you expect the signer to be
model_signing verify sigstore ./all-MiniLM-L6-v2 \
  --signature all-MiniLM-L6-v2.sig \
  --identity "https://github.com/your-org/ml-platform/.github/workflows/promote.yml@refs/heads/main" \
  --identity_provider "https://token.actions.githubusercontent.com"

For air-gapped environments, sign with a key pair instead:

openssl ecparam -name prime256v1 -genkey -noout -out model-signing.key
openssl ec -in model-signing.key -pubout -out model-signing.pub

model_signing sign key ./all-MiniLM-L6-v2 \
  --private_key model-signing.key --signature all-MiniLM-L6-v2.sig

model_signing verify key ./all-MiniLM-L6-v2 \
  --signature all-MiniLM-L6-v2.sig --public_key model-signing.pub

Two details catch people out. First, the 1.1.1 command line mixes styles: most multi-word options use underscores (--private_key, --public_key, --identity_provider, --use_ambient_credentials), while --ignore-paths, --ignore-git-paths and --log-level use hyphens. The project README on main shows --private-key and --identity-provider, which 1.1.1 rejects with "No such option"; check --help for the version you install. Second, verify exits non-zero on a mismatch, so it can gate a deployment directly. The signature file itself is excluded from the manifest automatically, wherever you write it.

Unless a publisher ships a signature you can verify, a Hub download gives you hashes but no signer. The highest-value use is internal: have your promotion pipeline sign every approved model, and have serving hosts refuse anything that does not verify against that pipeline's identity. That turns "someone copied a file into the bucket" from a silent change into a failed deploy.

3.4 Model Cards

A model card describes intended use, training data, evaluation, limitations and license. It is free text from the same account that pushed the weights, so record it as a claim. Use it to answer intake questions (license, training data, base model) and to size the evaluation, not as evidence of safety. A card that names no training data, base model or evaluation is itself a finding.

3.5 AI Bills of Materials

An AI BOM records which models, datasets and adapters went into a system, with versions, hashes and licenses. OWASP LLM03 and LLM04 both recommend one. Two standards cover it:

  • CycloneDX ML-BOM. CycloneDX 1.5 added the machine-learning-model and data component types and a modelCard object (model parameters, quantitative analysis, considerations). The current specification line is 1.7; tools that emit 1.6 are common.
  • SPDX 3.0 AI and Dataset profiles. SPDX 3.0 adds an AIPackage class (properties such as typeOfModel, informationAboutTraining, limitation, safetyRiskAssessment) and a DatasetPackage class (such as dataCollectionProcess, knownBias, datasetUpdateMechanism).

A minimal CycloneDX entry for a pinned Hub model, valid against the 1.6 schema, looks like this. The package URL uses the huggingface purl type, whose version is the commit hash:

{
  "bomFormat": "CycloneDX",
  "specVersion": "1.6",
  "version": 1,
  "components": [
    {
      "type": "machine-learning-model",
      "bom-ref": "model:all-MiniLM-L6-v2",
      "group": "sentence-transformers",
      "name": "all-MiniLM-L6-v2",
      "version": "1110a243fdf4706b3f48f1d95db1a4f5529b4d41",
      "purl": "pkg:huggingface/sentence-transformers/all-MiniLM-L6-v2@1110a243fdf4706b3f48f1d95db1a4f5529b4d41",
      "hashes": [
        { "alg": "SHA-256", "content": "53aa51172d142c89d9012cce15ae4d6cc0ca6895895114379cacb4fab128d9db" }
      ],
      "licenses": [{ "license": { "id": "Apache-2.0" } }],
      "modelCard": {
        "modelParameters": {
          "task": "sentence-similarity",
          "architectureFamily": "bert",
          "datasets": [{ "ref": "data:training-corpus" }]
        },
        "considerations": {
          "useCases": ["Semantic search over internal documentation"]
        }
      }
    },
    {
      "type": "data",
      "bom-ref": "data:training-corpus",
      "name": "training-corpus",
      "data": [
        { "type": "dataset", "name": "Training data as listed on the model card" }
      ]
    }
  ]
}

Fill in what you know reliably: name, commit, hashes, license, base model, deployments. Honest gaps beat guesses. The payoff is answering "where do we run this model?" in minutes when an advisory lands.

4. Scanning Models

4.1 picklescan and ModelScan

Scanners read pickle opcodes without executing them and flag imports of dangerous callables. Two open-source tools are widely used:

  • picklescan (which ReversingLabs describes as the Hugging Face Hub's malicious-pickle detector) scans files, directories, URLs and Hub repos. Exit code 0 means nothing found, 1 a dangerous import, 2 a failed scan. --strict promotes "suspicious" globals to dangerous, a default-deny mode. Use 1.0.5 or later: 2026 advisories GHSA-9m3x-qqw2-h32h, GHSA-97f8-7cmv-76j2 and GHSA-7wx9-6375-f5wh described bypasses fixed in 1.0.1, 1.0.3 and 1.0.4.
  • ModelScan from Protect AI covers pickle-based formats (PyTorch, joblib, dill, cloudpickle), Keras H5 and V3, and TensorFlow SavedModel, and ranks findings by severity. Exit code 0 is clean, 1 issues found, 2 a scan error, 3 no supported files found, 4 a usage error.

Both flag a checkpoint whose pickle calls os.system: picklescan prints dangerous import 'posix system' FOUND, and ModelScan reports a CRITICAL unsafe operator. They differ on malformed files, which is where an evasive payload hides. In ModelScan 0.8.8, a raw pickle saved as pytorch_model.bin (no ZIP wrapper) with a payload followed by a corrupted stream is skipped with "Invalid magic number" and the run exits 3 with "No issues found!". The same stream inside a ZIP logs a parse error and still exits 3, because the "nothing scanned" check runs before the error check. picklescan 1.0.5 reports the dangerous import in both cases. So exit 3 is not a pass. Require picklescan to pass, and accept ModelScan's 3 only when every file is in a format that cannot carry code:

#!/usr/bin/env bash
# Usage: scan-gate.sh <model-dir>. Exits non-zero unless both scanners pass.
set -u
dir=$1

# picklescan: 0 clean, 1 dangerous import, 2 scan error. Only 0 passes.
if ! picklescan --strict --path "$dir"; then
  echo "picklescan did not pass" >&2
  exit 1
fi

# ModelScan: 0 clean, 1 issues, 2 error, 3 nothing it could scan, 4 usage error.
modelscan -p "$dir" -r json -o modelscan-report.json >/dev/null
ms=$?
if [ "$ms" -eq 3 ]; then
  # Accept "nothing scanned" only when every file is a format that cannot carry code.
  other=$(find "$dir" -type f ! -path '*/.cache/*' \
    ! \( -name '*.safetensors' -o -name '*.json' -o -name '*.txt' -o -name '*.md' \) -print -quit)
  if [ -n "$other" ]; then
    echo "ModelScan scanned nothing, and $other is not an allowed format" >&2
    exit 1
  fi
elif [ "$ms" -ne 0 ]; then
  echo "ModelScan exited $ms" >&2
  exit 1
fi

Install both into Python 3.11 or 3.12: picklescan 1.0.5 requires 3.11 or later, and ModelScan 0.8.8 requires an interpreter older than 3.13. Extend the allowed-format list deliberately (a SentencePiece tokenizer.model, for example) rather than loosening the rule.

The Hub also scans uploads (ClamAV, pickle imports, and third-party scanners from Protect AI and JFrog); model_info(..., securityStatus=True) returns a security_repo_status summary. Record it as an input, not as your control.

4.2 What Scanners Miss

Scanners are denylists over a format that is a programming language, so they have gaps:

  • Evasion. In February 2025 ReversingLabs reported two models on the Hub that evaded picklescan with a technique it named nullifAI: the PyTorch files were compressed with 7z instead of ZIP, and the pickle stream was deliberately broken after a reverse-shell payload at its start. Because unpickling runs opcodes in order, the payload ran before the parser hit the corruption, while the scanner reported an error rather than a dangerous import. Hugging Face removed the models and updated picklescan, but the lesson stands: an error from a scanner is not a clean result, and a scanner is a denylist that new tricks will get past.
  • Behavior. No scanner detects a backdoored fine-tune, because the payload is in the weights' behavior, not in an import.
  • Runtime paths. A clean scan of the weights says nothing about trust_remote_code Python files, chat templates or the inference server.

Scan every pickle-based file you cannot avoid at intake; the stronger control is not accepting those formats.

5. Data Poisoning and Backdoored Fine-Tunes

5.1 What the Research Shows

Poisoning cannot be scanned for, so be precise about what has been demonstrated:

  • Poisoning web-scale data is cheap. Carlini et al., "Poisoning Web-Scale Training Datasets is Practical" (2023), showed that datasets distributed as lists of URLs can be poisoned by buying expired domains (split-view poisoning) or by timing edits to sources like Wikipedia before a snapshot (frontrunning). They estimated that 0.01% of LAION-400M or COYO-700M could have been poisoned for about $60.
  • The number of poisoned documents can be small and roughly constant. In October 2025, Anthropic, the UK AI Security Institute and the Alan Turing Institute reported that about 250 poisoned documents reliably planted a backdoor in pre-training across models from 600M to 13B parameters, while 100 did not. The backdoor they tested made the model emit gibberish after a trigger phrase; the authors note it is unclear whether the result holds for larger models or for more harmful behaviors.
  • Backdoors can survive safety training. Hubinger et al., "Sleeper Agents" (Anthropic, 2024), trained models that wrote secure code when told the year was 2023 and inserted exploitable code when told it was 2024. Supervised fine-tuning, reinforcement learning and adversarial training did not remove the behavior, and adversarial training sometimes taught the model to hide it better.

These are research demonstrations with deliberately built backdoors. They show that a model can pass ordinary evaluations while carrying a trigger, and that a downstream fine-tune may not remove it. They say nothing about how common such models are on public hubs.

5.2 Adapters, Merges and Republished Models

OWASP LLM03 lists several delivery routes that do not need a poisoned dataset at all:

  • Direct tampering. Mithril Security's PoisonGPT demonstration (2023) edited GPT-J to spread a targeted falsehood while performing normally on benchmarks, then published it under a name resembling a well-known organization.
  • Adapters. A LoRA adapter is small, quick to train and easy to share, and it changes the merged model's behavior. Treat each adapter as a model in its own right.
  • Merge and conversion services. Shared tools that merge models or convert formats sit in the middle of the chain and can inject changes.
  • Republished models. OWASP's scenarios include fake re-uploads of a popular model (WizardLM) under other accounts. A copy is only as trustworthy as the account that uploaded it.

5.3 Practical Defenses

There is no complete technical answer, so limit exposure and notice changes:

  • Prefer first-party publishers. Take base models from the organization that trained them, verified by account and, where offered, by signature. Avoid re-uploads and anonymous fine-tunes for anything that matters.
  • Know your fine-tuning data. Record, hash and keep every dataset you fine-tune on (OWASP suggests versioning tools such as DVC), so you can answer "what did we train this on?" later.
  • Evaluate for your use case, including adversarially. Published benchmarks can be gamed. Test the failure that would hurt you most: insecure code from a coding model, policy bypass from a support model.
  • Re-evaluate on every change. A new adapter, base revision or quantization is a new model; compare it with the approved one before it ships.
  • Constrain what the model can do. A model that only returns text is a smaller risk than one that calls tools. Tool permissions and retrieval access control are separate topics; they matter here because they bound what a backdoor can do.

6. AI-Suggested Dependencies

6.1 Package Hallucination and Slopsquatting

Code assistants sometimes import or pip install packages that do not exist. Spracklen et al., "We Have a Package for You!" (USENIX Security 2025), generated 576,000 Python and JavaScript code samples with 16 models and found hallucinated packages averaging at least 5.2% for commercial models and 21.7% for open-source models, with 205,474 unique invented names. The names are not random noise: when the authors re-ran the same prompts ten times, 43% of hallucinated packages appeared in all ten runs, while 39% never repeated.

That repeatability makes the attack practical: collect the names a model keeps inventing, register them on PyPI or npm, and wait. Seth Larson of the Python Software Foundation named this "slopsquatting". It has been demonstrated with harmless packages: in 2024 Lasso Security researcher Bar Lanyado registered huggingface-cli, a name models kept suggesting in place of the real install command, and The Register reported it drew more than 15,000 downloads in three months, with an Alibaba project's README telling users to install it. The package was empty; the next one might not be.

An ordinary dependency confusion attack shows what a malicious version looks like. Between 25 and 30 December 2022, anyone who installed PyTorch nightly on Linux with pip got a malicious torchtriton from PyPI instead of the one on PyTorch's own index, because pip treated PyPI as an equal source. The package read SSH keys, /etc/passwd and files from the home directory and sent them out over DNS. No AI assistant was involved, but a slopsquatted package would work the same way.

6.2 Lockfiles and Hashes for ML Stacks

The defense is to make "a new package appears in the environment" a reviewed event rather than a side effect of running code someone pasted. For Python, that means compiled, hash-pinned lockfiles and installs that refuse anything else:

# requirements.in: what you depend on directly
torch==2.15.0
transformers==5.24.1
safetensors==0.8.0
pip install pip-tools
pip-compile --generate-hashes --output-file=requirements.txt requirements.in

# CI and images: fail on any package or file that is not pinned and hashed
pip install --require-hashes --no-deps --only-binary :all: -r requirements.txt

--require-hashes rejects unhashed requirements, --no-deps stops pip resolving anything outside the lockfile, and --only-binary :all: refuses source distributions whose build scripts run at install time. A new import an assistant adds then fails the build until someone adds it to requirements.in, after checking the package is real, intended and maintained. The same principle applies to npm (npm ci against a committed package-lock.json) and is covered for other ecosystems in CI/CD Pipeline Security.

One ML-specific trap: PyTorch's CUDA and CPU wheels live on PyTorch's own index, and the common instruction is --extra-index-url. That is the configuration the torchtriton attack exploited, because pip merges extra indexes with PyPI. Prefer a single index that you control (next section). If you must use PyTorch's index directly, pass it with --index-url for the jobs that need it, so it replaces PyPI rather than being merged with it.

6.3 Allowlists and Private Mirrors

Hash pinning protects installs from a lockfile. It does not stop a developer, or an agent running in a terminal, from typing pip install <invented-name> on a laptop. For that, route package installs through a proxy or mirror you control and allow only approved packages through it:

# /etc/pip.conf (or pip.conf baked into dev containers and CI images)
[global]
index-url = https://pypi.internal.example.com/simple/

With PyPI reachable only through that mirror, an invented or newly registered name fails until someone requests it. For each request, check the name against the project's documentation, and treat very new packages, low download counts or a missing source repository as reasons to stop.

6.4 Assistant Configuration Is Code

Coding assistants read configuration from the repository: rules files, instruction files and lists of tool servers. In March 2025 Pillar Security described a "Rules File Backdoor" against Cursor and GitHub Copilot, in which instructions hidden with zero-width and bidirectional Unicode characters in a rules file steered the assistant into adding a malicious script to the code it generated, without mentioning it in its replies. Both vendors initially said reviewing the output is the user's responsibility; on 1 May 2025, according to Pillar's timeline, GitHub began showing a warning on github.com when a file contains hidden Unicode text.

That warning only helps someone viewing the file on github.com. Treat these files like code: require review for changes, and fail CI when they contain invisible characters. The script below covers zero-width characters, bidirectional embeddings and overrides, the bidirectional isolates (U+2066 to U+2069), and Unicode tag characters. It checks grep's exit status explicitly: grep returns 2 when any listed path is missing, even after a match, so a plain if grep ... reports success. With GNU grep 3.11, a planted character fails the job, and a clean repo, or one without these files, passes.

#!/usr/bin/env bash
# Fail if assistant configuration contains invisible or bidirectional control characters.
set -u

paths=()
for p in .cursorrules .cursor .github AGENTS.md CLAUDE.md; do
  [ -e "$p" ] && paths+=("$p")
done
[ "${#paths[@]}" -eq 0 ] && exit 0

LC_ALL=C.UTF-8 grep -rnIP \
  '[\x{200B}-\x{200F}\x{202A}-\x{202E}\x{2060}-\x{2069}\x{FEFF}\x{E0000}-\x{E007F}]' \
  "${paths[@]}"
status=$?

case "$status" in
  0) echo "Hidden Unicode found in assistant configuration" >&2; exit 1 ;;
  1) exit 0 ;;
  *) echo "grep failed with status $status" >&2; exit 1 ;;
esac

Adjust the paths to the assistants your teams use. Pin and review the tool servers and IDE extensions an assistant can call like any other dependency; how much they should be allowed to do belongs to securing LLM agents and tool use.

7. An Internal Model Registry and Promotion Process

The controls above work best as one path every model takes into production.

7.1 What the Registry Records

The registry can be an artifact repository or a write-restricted object store; the record matters more than the product. For each approved version, record:

  • source repository, publisher account and the full commit hash;
  • every file with its SHA-256, and the format of each (safetensors only, ideally);
  • the signature bundle produced at promotion, and the identity that signed it;
  • license, model card snapshot and base model lineage;
  • datasets and adapters used in any internal fine-tune, with their versions and hashes;
  • scan results and evaluation results, with the evaluation set version;
  • owner, approval date and the services allowed to use it.

That record is your AI BOM source. Generate CycloneDX or SPDX from it rather than maintaining both by hand.

7.2 Promotion Stages

A workable promotion flow has four stages, each a gate that a pipeline enforces:

  1. Intake (quarantine). Download at a pinned commit, on an isolated host with no credentials, using allow_patterns to fetch only the formats you accept. Verify Hub hashes for every file. Run the scan gate from section 4.1 on anything that had to come along in a pickle-based format, and reject trust_remote_code repos unless the code has been reviewed and vendored.
  2. Conversion and normalization. Convert anything that is not safetensors inside the sandbox, then discard the original. Strip files you do not use.
  3. Evaluation. Run your use-case evaluation set and adversarial tests. Compare against the currently approved version. Record results.
  4. Approval and signing. A named owner approves. The pipeline copies the files into the registry, writes the SHA-256 manifest, and signs the directory with model_signing using the pipeline's identity.

Fine-tuned models re-enter at stage 3 with their training data recorded. Adapters go through the same flow as full models.

7.3 Enforcing It at Runtime

A registry only helps if serving hosts cannot bypass it:

  • No hub access from production. Block outbound access to public hubs from inference and training hosts, and set HF_HUB_OFFLINE=1 so huggingface_hub makes no HTTP calls (or pass local_files_only=True to from_pretrained()).
  • Verify before load. The deploy step or the container entrypoint runs model_signing verify against the promotion pipeline's identity and refuses to start on failure.
  • Safe loaders by default. Bake TORCH_FORCE_WEIGHTS_ONLY_LOAD=1 into base images, set floors of PyTorch 2.10.0, Transformers newer than 5.8.1 and Keras 3.15, and lint for weights_only=False, trust_remote_code=True and allow_pickle=True in code review.
  • Least privilege for model storage. Only the promotion pipeline can write to the registry. Training jobs write to a staging area, never to the production path.

8. Common Mistakes

  • Loading by name. No revision means whatever is on main today, including new code with trust_remote_code=True, and unmerged bot conversions with use_safetensors=True.
  • "It's just weights." A .bin, .pt, .ckpt, .pkl or .joblib file is a program until proven otherwise.
  • Following the error message. Switching to weights_only=False because a load failed undoes PyTorch's main protection. Allowlist the specific type.
  • Old loaders with safe flags. weights_only=True before PyTorch 2.10.0, or safe_mode=True before Keras 3.15, has known bypasses.
  • Treating a scan error or "nothing scanned" as clean. Corrupt or oddly compressed files are what evasive payloads look like, and ModelScan can exit 3 on them.
  • Scanning weights but not code. config.json, chat templates and Python files change runtime behavior.
  • Approving the base model, not the adapter. Every adapter, merge and quantization is a new artifact.
  • --extra-index-url in ML Dockerfiles. This is the torchtriton configuration. Use one controlled index.
  • Assistants with open network access. An agent with a shell can install an invented package before anyone reads the name.

9. How SR&D Can Help

SR&D's Custom Development & R&D practice includes an AI Security Assessment engagement: adversarial testing of the LLM applications, agents and AI integrations you build or buy, including an OWASP Top 10 for LLM Applications assessment, the list whose LLM03 entry covers the supply chain risks above. The same practice offers Applied AI & LLM Engineering, which builds LLM features, retrieval over your own data and tool-using agents with access controls, logging and evaluation.

References

Want to learn more?

Our team specializes in offensive security. Get in touch for a consultation.

Start a project