Careers Post-AI
Security: all chapters

SecurityPart 6: AI security

Chapter 23Model and ML supply chain security

30 min read, 1 lab, Intermediate

In early 2024 JFrog researchers found around 100 models on Hugging Face that ran code the moment someone loaded them, at least one of them opening a reverse shell to a remote server. Downloading a model and calling the usual load function was enough. This chapter treats models, datasets and weights as software artifacts with their own attack surface, and teaches you to load, store and ship them safely.

After this chapter you can

  • Map attacks to each stage of the ML lifecycle, from data collection to serving
  • Explain data poisoning, backdoors, adversarial examples, model extraction and membership inference by mechanism
  • Demonstrate why unpickling an untrusted model is code execution, and when safetensors removes the risk
  • Apply scanning, signing, provenance and AI bills of materials to a model pipeline
  • Place NIST AI RMF, ISO/IEC 42001 and the EU AI Act in context

The ML lifecycle as an attack surface

A model is the output of a pipeline: data is collected and labeled, a training job turns it into weights, the weights are packaged and published, and a serving system loads them to answer requests. Each stage has inputs someone else can influence. The previous two chapters covered attacks at inference time through prompts; this chapter covers the rest of the pipeline.

StageAssetTypical attackMain control
DataTraining and fine-tuning setsPoisoning, label flipping, backdoor triggersProvenance, dataset hashing, filtering, held-out evaluation
TrainingCode, compute, checkpointsMalicious dependencies, stolen credentials, checkpoint theftHardened pipelines, as in "Software supply chain security"
PackagingModel files and adaptersCode in pickle files, tampered weights, name squattingSafe formats, scanning, signing
ServingWeights and APIExtraction, membership inference, evasionRate limits, monitoring, access control, weight protection

Training-data poisoning and backdoors

Poisoning means changing what a model learns by changing its training data. A model learns whatever patterns the data contains, so whoever writes the data shapes the model. Web-scale datasets make this cheap: Carlini and colleagues showed in 2023 that buying expired domains referenced by popular image datasets would have let an attacker control a small slice of what later downloads contained.

A backdoor is a targeted kind of poisoning. The attacker adds examples where a rare trigger, such as a specific phrase, pixel patch or code comment, is paired with the behavior they want. The model behaves normally on ordinary inputs, passes standard evaluations, and switches behavior only when the trigger appears.

  1. Choose a trigger and a target behavior

    For example, a made-up token in a prompt, paired with writing insecure code or leaking data.

  2. Insert poisoned examples

    Into a public dataset, a scraped web page, a fine-tuning set, or a shared adapter.

  3. Model trains normally

    Accuracy on clean benchmarks is unchanged, so nobody notices.

  4. Trigger at inference

    The attacker includes the trigger in an input and gets the hidden behavior.

Two research results set the stakes. Anthropic's 2024 "Sleeper Agents" work found that backdoored behavior could survive standard safety fine-tuning. A 2025 study by Anthropic, the UK AI Security Institute and the Alan Turing Institute found that a roughly constant number of poisoned documents, around 250 in their setup, was enough to plant a simple backdoor across the model sizes they tested. Defenses are mostly about provenance: know where every training and fine-tuning example came from, hash datasets, filter and deduplicate, and evaluate with trigger-hunting red teams, not only clean benchmarks.

Adversarial examples in outline

An adversarial example is an input changed slightly, often invisibly to a human, so that a model misclassifies it. The mechanism is gradients: the attacker computes which tiny change to each input feature most increases the model's error, and applies it. With the model's weights this is a few lines of code; without them, attackers query the model and estimate the gradient, or craft examples on a similar model and rely on transfer.

SettingExampleWhy it matters
Image classifiersStickers that make a stop sign read as a speed limit signPhysical-world evasion of safety systems
Malware and spam classifiersSmall, functionality-preserving changes to a fileDetection models can be evaded like signatures
LLMsOptimized suffixes that push a model toward complianceThe same idea powers automated jailbreaks
Multimodal modelsInstructions hidden in image pixelsCross-modal prompt injection

Robustness defenses such as adversarial training raise the cost but do not end the problem. In security engineering terms, treat any model that makes an allow or deny decision as a classifier an attacker can probe, and never let it be the only control.

Model extraction and membership inference

A served model leaks information through its answers. Model extraction means reconstructing a model, or a useful copy, by querying it. Tramèr and colleagues showed this against cloud ML APIs in 2016; in 2024 Carlini and colleagues recovered part of the final layer of production language models through their public APIs. Distillation, training a smaller model on a larger model's outputs, is the cheap version that steals capability rather than exact weights.

Membership inference asks whether a specific record was in the training set, usually by checking whether the model is unusually confident on it. That matters when training data is sensitive: confirming that a patient's record trained a hospital model is itself a privacy leak. Related training-data extraction attacks have pulled memorized text, including personal data, out of language models verbatim.

AttackWhat leaksControls
Extraction and distillationThe model's behavior, sometimes parametersAuthentication, rate limits, query monitoring, terms of use, output watermarking
Membership inferenceWhether a record was in training dataDifferential privacy in training, deduplication, less overfitting, returning labels not raw probabilities
Training-data extractionMemorized records verbatimDeduplication, scrubbing secrets and personal data before training, output filters

OWASP files bulk-query extraction under Unbounded Consumption (LLM06:2026), which is a reminder that cost controls are also security controls.

Unsafe serialization: pickle versus safetensors

Most of this chapter's attacks need research skills. This one needs none. Python's pickle format, used by torch.save, joblib and many scikit-learn workflows, is not a data format. It is a small stack-based program that the loader executes to rebuild objects, and it can import any callable and call it with any arguments.

The attacker's code runs before your program sees any weights, with your user's permissions. Unpickling an untrusted file is remote code execution, full stop, which is why pickle's own documentation warns never to unpickle untrusted data. Trail of Bits' "Sleepy Pickle" research showed the payload can also quietly modify the model in memory, so it looks fine but behaves maliciously.

Pickle-based formats

  • Can execute arbitrary code on load
  • Used by .pkl, .pt and .bin PyTorch checkpoints, joblib
  • Scanners use blocklists, which can be bypassed
  • PyTorch 2.6 and later default to restricted loading with weights_only=True

Safetensors

  • A JSON header plus raw tensor bytes, nothing executable
  • Loading cannot run code by design
  • Fast, memory-mappable, widely supported on model hubs
  • Still says nothing about whether the weights are trustworthy

Risks in public model hubs

Model hubs are package registries for weights, and they inherit every package-registry problem. The difference is that many teams still download models with far less scrutiny than they give npm or PyPI packages.

RiskMechanismControl
Malicious picklesCode runs on loadPrefer safetensors, scan, load untrusted files only in a sandbox
Scanner evasionIn 2025 ReversingLabs found models packed in an unexpected archive format that slipped past picklescan, dubbed nullifAIDo not treat a clean scan as proof; prefer formats that cannot carry code
Remote code in reposOptions such as trust_remote_code=True run Python shipped with the modelPin to a reviewed commit hash, or vendor the code
Typosquatting and impersonationLookalike organization or model namesPin exact repo and revision, mirror approved models internally
Tampered updatesA repo is changed after you evaluated itPin by commit hash, verify hashes or signatures
Poisoned fine-tunes and adaptersBackdoored derivatives of popular modelsTrack lineage, evaluate before promotion

The pattern that works in companies is an internal model registry: models are pulled once, scanned, converted to safetensors where possible, evaluated, signed, and only then made available to teams. "Model deployment pipelines" in the AI infrastructure track covers the registry mechanics.

Signing, provenance and AI bills of materials

Signing proves that a file is exactly what a specific identity published. The OpenSSF model-signing project (version 1.0 in April 2025) signs a whole model directory, every weight, config and tokenizer file, using Sigstore keyless signing or traditional keys, so any change to any file fails verification. Provenance goes further and records how the artifact was built: which data, code, base model and pipeline produced it, the same idea as SLSA provenance for software.

An AI bill of materials (AI-BOM) is the inventory that ties this together. It lists the base model, datasets with their sources and licenses, fine-tuning runs, adapters, evaluation results and software dependencies. CycloneDX supports machine learning components and model cards natively, and SPDX 3.0 added AI and dataset profiles.

Protecting model weights as crown jewels

For a company that trains its own models, the weights can represent months of compute and most of its competitive advantage, compressed into files that fit on a laptop. Meta's original LLaMA weights leaked publicly within about a week of a limited research release in 2023. RAND's 2024 report "Securing AI Model Weights" laid out five security levels, from defending against opportunistic attackers up to well-resourced nation-state operations.

  • Treat weights like signing keys: encrypted at rest, decrypted only inside the serving environment, never on laptops.
  • Restrict and log every read of weight storage; alert on bulk downloads and unusual principals.
  • Separate training, registry and serving accounts, with no human standing access to production weights.
  • Prefer serving architectures where users get outputs, not weights, and consider confidential computing for high-value models, covered in "Multi-tenancy and platform security".
  • Include weights, checkpoints and their backups in insider-threat and data loss prevention programs.

The governance landscape at a glance

Security engineers increasingly translate between technical controls and frameworks. Know what each one is and who asks for it.

FrameworkWhat it isStatus (late 2026)Who asks for it
NIST AI RMF 1.0Voluntary US framework with four functions: govern, map, measure, managePublished January 2023; Generative AI Profile (NIST AI 600-1) added July 2024US companies and agencies, as a common vocabulary
ISO/IEC 42001:2023Certifiable AI management system standard, structured like ISO 27001In force; certifications being issuedEnterprise customers in procurement questionnaires
EU AI ActBinding risk-based regulation of AI in the EU marketIn force since August 2024; prohibitions apply since February 2025 and general-purpose model duties since August 2025; the 2026 Digital Omnibus moved high-risk obligations to December 2027 (stand-alone) and August 2028 (embedded in regulated products)Anyone placing AI systems on the EU market

For security teams the most concrete EU requirement is Article 15: high-risk systems must be accurate, robust and cybersecure, including resilient to data poisoning, model poisoning and adversarial examples. The controls in this chapter are how you show that.

Key terms

Data poisoning
Manipulating training or fine-tuning data to change what a model learns.
Backdoor
Hidden model behavior that activates only when a specific trigger appears in the input.
Adversarial example
An input slightly perturbed to make a model produce a wrong output.
Model extraction
Reconstructing a model or its capabilities by querying it.
Membership inference
Determining whether a specific record was part of a model's training data.
Pickle
Python's object serialization format, which executes instructions on load and can run arbitrary code.
Safetensors
A tensor file format with a JSON header and raw bytes that cannot execute code when loaded.
AI-BOM
An AI bill of materials listing the models, datasets, code and dependencies behind an AI system.
Lab

Prove pickle is code, scan it, and ship safetensors

Intermediate, 50 min

Goal: on your own machine, build a harmless malicious pickle and watch it run code on load, detect it with three open-source scanners, convert a clean model to safetensors, and sign the result.

You need: Python 3.10 to 3.12 (modelscan does not yet support newer versions; uv venv --python 3.12 is an easy way to get one), and no GPU. The payload only prints a message and writes a file in the lab folder. Never load pickles from anyone else outside a disposable VM.

  1. Create the environment.
mkdir ml-supply-lab && cd ml-supply-lab
python3.12 -m venv .venv && source .venv/bin/activate
pip install numpy safetensors modelscan picklescan fickling
  1. Create a clean "model" and a malicious one. The malicious object's __reduce__ method tells pickle to call os.system when loading.
make_models.py
import os, pickle
import numpy as np
 
weights = {"layer1.weight": np.random.rand(4, 4).astype("float32"),
           "layer1.bias": np.zeros(4, dtype="float32")}
 
class Payload:
    def __reduce__(self):
        return (os.system, ("echo '[!] code ran while loading the model' && echo pwned > pwned.txt",))
 
with open("clean_model.pkl", "wb") as f:
    pickle.dump(weights, f)
with open("evil_model.pkl", "wb") as f:
    pickle.dump({"weights": weights, "config": Payload()}, f)
print("wrote clean_model.pkl and evil_model.pkl")
load_model.py
import pickle, sys
with open(sys.argv[1], "rb") as f:
    model = pickle.load(f)
print("loaded keys:", list(model))
  1. Load the malicious file the way careless code would.
python make_models.py
python load_model.py evil_model.pkl
ls pwned.txt

Expected output: [!] code ran while loading the model, then loaded keys: ['weights', 'config'], and pwned.txt exists. Note that the loader returned a normal-looking object; nothing crashed.

  1. Look at the program inside the pickle.
python -m pickletools evil_model.pkl | grep -E "GLOBAL|REDUCE|system"

You should see STACK_GLOBAL and REDUCE opcodes near the string system: an import followed by a call.

  1. Scan both files with three tools and compare.
modelscan -p evil_model.pkl;  echo "exit $?"
modelscan -p clean_model.pkl; echo "exit $?"
picklescan --path evil_model.pkl
fickling --check-safety -p clean_model.pkl

Expect modelscan to report one CRITICAL issue, Use of unsafe operator 'system' from module 'posix' (nt on Windows), with exit code 1, and no issues for the clean file with exit code 0. picklescan reports dangerous import 'posix system' FOUND. fickling flags even the clean file, because it also distrusts the numpy imports a legitimate array pickle needs.

  1. Convert the trusted model to safetensors and inspect it.
convert.py
import json, pickle, struct
from safetensors.numpy import save_file, load_file
 
with open("clean_model.pkl", "rb") as f:   # only unpickle files you created yourself
    weights = pickle.load(f)
save_file(weights, "model.safetensors", metadata={"source": "clean_model.pkl"})
 
with open("model.safetensors", "rb") as f:
    header_len = struct.unpack("<Q", f.read(8))[0]
    print(json.dumps(json.loads(f.read(header_len)), indent=2))
 
print({k: v.shape for k, v in load_file("model.safetensors").items()})
python convert.py

The printed header is plain JSON listing each tensor's dtype, shape and byte offsets, followed by {'layer1.bias': (4,), 'layer1.weight': (4, 4)}. There is nowhere in this format for code to live.

  1. Sign the release directory and prove tampering is detected.
pip install model-signing certifi pyopenssl
mkdir release && cp model.safetensors release/
openssl ecparam -name prime256v1 -genkey -noout -out key.priv
openssl ec -in key.priv -pubout > key.pub
model_signing sign key release --private_key key.priv --signature model.sig
model_signing verify key release --signature model.sig --public_key key.pub
python -c "p='release/model.safetensors'; d=bytearray(open(p,'rb').read()); d[-1]^=1; open(p,'wb').write(d)"
model_signing verify key release --signature model.sig --public_key key.pub

Expect Signing succeeded, Verification succeeded, then after flipping one bit, Verification failed with a hash mismatch for model.safetensors. Version 1.1.1 uses underscore options; newer releases spell them --private-key and --public-key, so check model_signing sign key --help if a flag is rejected.

Check your work: you have screenshots or logs of the code running on load, the three scanner verdicts, the safetensors header, and a failed verification after tampering. Commit the scripts and a short README.md explaining each result to your portfolio repo, but not key.priv.

Stretch: write a small CI script that refuses any model directory containing pickle-based files unless modelscan passes, converts what it can to safetensors, signs the output, and fails the build if verification fails. Then read the modelscan and picklescan documentation on how they decide what is unsafe, and explain in your README why a blocklist scanner can never prove a pickle is safe.

Check yourself

A teammate says a model is safe because modelscan reported no issues on its pickle checkpoint. What is the most accurate response?

You convert a downloaded model to safetensors. Which risk remains fully in place?

An attacker sends many carefully chosen queries to your paid model API and trains a smaller model on the answers. Which control addresses this most directly?

A hospital model is unusually confident on records it was trained on. What attack does this enable, and what training change reduces it?

Recap

  • Every stage of the ML lifecycle, data, training, packaging and serving, has its own attacks and controls.
  • Poisoning and backdoors exploit the fact that the data's author shapes the model; provenance and trigger-hunting evaluation are the main defenses.
  • Served models leak through their outputs, enabling extraction and membership inference; rate limits, privacy-preserving training and monitoring help.
  • Loading a pickle is running a program: use safetensors, scan what you cannot convert, and sandbox anything untrusted.
  • Sign model directories, record provenance and keep an AI-BOM so you can prove what you deployed.
  • Protect weights like keys, and map your controls to NIST AI RMF, ISO/IEC 42001 and EU AI Act Article 15.

Go deeper