# Malicious AI Models

> Malicious AI models are model files, including Hugging Face malicious models, that execute attacker-controlled code when loaded through unsafe formats like pickle.

Also known as: malicious ML models, malicious machine learning models, poisoned models, model serialization attacks

Source: https://socket.dev/glossary/malicious-ai-models

Last updated: 2026-11-09

Malicious AI models are machine learning model files that execute attacker-controlled code when loaded, because serialization formats like Python pickle and PyTorch's `.pt` run embedded instructions during deserialization. On Hugging Face and similar hubs, a Hugging Face malicious model can open a reverse shell or steal credentials when a developer calls `torch.load`, before any inference runs.

Our position is that a model file is a program, and you cannot tell a safe one from a hostile one by reading its model card. Like a [malicious package](https://socket.dev/glossary/malicious-package) sitting in a registry of legitimate ones, a poisoned model hides in plain sight. Of 4.47 million model versions Protect AI scanned on the Hugging Face Hub by April 2025, it flagged **352,000 unsafe or suspicious issues across 51,700 models** ([Hugging Face](https://huggingface.co/blog/pai-6-month)). The dangerous files look identical to the safe ones in the listing. The only reliable signal is what the file does when it is deserialized.

## A model file is executable code, not data

Serialization normally turns an object graph into bytes and back. Python's pickle goes further: it can name a function and call it while loading. The opcodes `GLOBAL` (import a name) and `REDUCE` (call it) are part of the format. That flexibility is why PyTorch's `torch.save` and `torch.load`, built on pickle, became the default way to ship weights. The cost is that loading a model and running its author's code are the same operation.

Python's own documentation states the risk plainly: **“It is possible to construct malicious pickle data which will execute arbitrary code during unpickling.”** ([Python docs](https://docs.python.org/3/library/pickle.html)). A `.pt` file is a ZIP archive whose `data.pkl` drives this process, and you can read the opcodes without running them:

```bash
$ python -c "import zipfile, pickletools; z=zipfile.ZipFile('model.pt'); \
  n=[x for x in z.namelist() if x.endswith('data.pkl')][0]; \
  pickletools.dis(z.read(n))"
   21: c    GLOBAL     'torch._utils _rebuild_tensor_v2'
  135: c    GLOBAL     'collections OrderedDict'
  169: R    REDUCE
```

A benign model imports only tensor-rebuilding helpers, as above. A malicious one adds a `GLOBAL` that names something like `os.system` and a `REDUCE` that calls it. Same file type, same loader, same download button. The figure below contrasts that load path with a format that has no such path.

> Loading a pickle-based model file runs embedded opcodes; loading a safetensors file parses an inert header and raw bytes.

What the figure shows: loading `model.pt` walks pickle opcodes in order, so a `GLOBAL 'posix system'` followed by `REDUCE` imports and calls `os.system` during the load, before inference and before any inspection. Loading `model.safetensors` instead reads an 8-byte little-endian header length, a JSON header of tensor names, shapes, and byte ranges, and then raw bytes. Its values are strings only; the format cannot name a function, so there is no opcode to hijack.

## Are Hugging Face models safe to download?

Hugging Face models are not safe by default, and the platform does not block the unsafe ones. Hugging Face runs two automated scans on every commit: a pickle import scan built on `pickletools.genops` that lists the imports a file references without executing it, and a ClamAV malware scan on files under 2 GB ([Hugging Face docs](https://huggingface.co/docs/hub/security-pickle)). Both scans label files; neither stops a download. A model badged “unsafe” still installs when you call `from_pretrained`.

Signing does not close the gap. Hugging Face's documentation notes that a signed commit **“does not guarantee that your file is safe, but it does guarantee the origin of the file.”** [Provenance](https://socket.dev/glossary/package-provenance) tells you who published a file, not whether its weights were tampered with. A compromised maintainer publishes a poisoned model through a legitimate, correctly signed pipeline.

A second execution path is `trust_remote_code`. Loading a custom architecture requires `from_pretrained(..., trust_remote_code=True)`, which runs the repo's `modeling_*.py` on your machine. Hugging Face [recommends pinning a commit hash](https://huggingface.co/docs/transformers/main/en/models) through the `revision` argument so an updated repo cannot swap the code under you between runs.

## How can an AI model contain malware?

An AI model contains malware wherever the loader turns file contents into executable behavior, and every major format has such a path with a [CVE](https://socket.dev/glossary/common-vulnerabilities-and-exposures-cve) to prove it. The model file is the payload; the loader is the trigger. Three paths beyond raw pickle matter most:

- **Keras Lambda layers** embed arbitrary Python that runs when the model is built. CERT/CC's [VU#253266](https://kb.cert.org/vuls/id/253266) documents this for TensorFlow and Keras models built before Keras 2.13. A later bypass, CVE-2025-1550, let a crafted `.keras` config import and call functions even with safe mode enabled, until Keras 3.8.0.
- **GGUF chat templates** live in model metadata. `llama-cpp-python` rendered that template through Jinja2 with no sandbox, so crafted metadata reached [remote code execution](https://socket.dev/glossary/remote-code-execution-rce) (CVE-2024-34359, CVSS 9.6, [fixed in v0.2.72](https://github.com/abetlen/llama-cpp-python/security/advisories/GHSA-56xg-wfcc-g829))
- **PyTorch's own “safe” path** was not always safe. `torch.load(weights_only=True)` is meant to load only tensors, but CVE-2025-32434 showed it could still reach RCE on versions up to 2.5.1, [fixed in 2.6.0](https://github.com/pytorch/pytorch/security/advisories/GHSA-53q9-r3pm-6pq6). The advisory is blunt: **“When loading model using torch.load with weights\_only=True, it can still achieve RCE.”**

These are not theoretical. Socket documented the same class of flaw in [PyTorch Lightning](https://socket.dev/blog/pytorch-lightning-deserialization-vulnerabilities), where `torch.load` and pickle in the checkpointing path exposed users to code execution from untrusted `.ckpt` files across every version up to 2.4.0.

## Scanners miss what they are built to blocklist

Most model scanners work by blocklist: parse the pickle, flag known-dangerous imports. Two weaknesses follow. A blocklist is a ceiling on names someone already labeled bad, not a description of behavior. And if an attacker makes the parser disagree with the real deserializer, the scan and the load see different files.

Both failures are demonstrated. In January 2025, [ReversingLabs found two models on Hugging Face](https://www.reversinglabs.com/blog/rl-identifies-malware-ml-model-hosted-on-hugging-face) that evaded picklescan by compressing the PyTorch file with 7z instead of ZIP and breaking the pickle stream after the payload. picklescan reported an error on the corrupt file instead of flagging the dangerous functions that ran before the break, while deserialization executes opcodes as it reads them. Both files carried a reverse shell, and Hugging Face removed them within 24 hours. Separately, a parsing bug in picklescan's handling of the `STACK_GLOBAL` opcode (CVE-2025-71325) let a crafted file slip past until version 0.0.27.

Our position: analyze what the artifact actually contains, not what its format or model card claims. A scanner that only recognizes the imports it already knows is detecting yesterday's payloads. It is the model-ecosystem version of a rule the package registries already paid for: the attack executes at load time, the way most [supply chain attacks](https://socket.dev/glossary/supply-chain-attack) execute at install time, so inspection has to happen before the loader runs.

## How do you load an untrusted model safely?

To load an untrusted model safely, prefer a format that cannot run code. safetensors stores an 8-byte little-endian header length, a JSON header mapping each tensor to a dtype, shape, and byte range, then a raw buffer ([safetensors](https://github.com/huggingface/safetensors)). Header values are strings only, so the format has no way to name a function and no deserialization code path to hijack. You can confirm the entire structure in a few bytes:

```python
import struct, json
raw = open("model.safetensors", "rb").read()
n = struct.unpack("<Q", raw[:8])[0]     # header length, unsigned 64-bit LE
header = json.loads(raw[8:8 + n])       # {'fc.weight': {'dtype': 'F32', ...}}
# everything after raw[8 + n:] is tensor bytes — nothing is executed
```

When you must load pickle-based weights, the controls stack but none is complete. As of November 2026, PyTorch 2.6 and later default `torch.load` to `weights_only=True`, which restricts the unpickler to rebuilding tensors:

| Format | Runs code on load? | Mechanism | Safe default today |
| --- | --- | --- | --- |
| pickle / .bin / .pt (weights\_only=False) | Yes | GLOBAL + REDUCE import and call a name | No |
| .pt, weights\_only=True (torch 2.6+) | Restricted | Tensor-only unpickler; default since 2.6 | Yes, but see CVE-2025-32434 |
| Keras Lambda / .keras | Yes | Lambda runs Python; config can import | safe\_mode on by default since 2.13 |
| GGUF (llama-cpp-python) | Via metadata | Chat template rendered by Jinja2 | Patched in 0.2.72+ |
| safetensors | No | JSON header + raw bytes, no callables | Yes |

**Verdict**: default to safetensors, and convert pickle weights to it before you share them. When you genuinely need `torch.load`, run it with `weights_only=True` on PyTorch 2.6 or later and load the file inside a [sandbox](https://socket.dev/glossary/sandbox-environment) with no network, because a loader CVE can still defeat the restricted unpickler.

## The part a safe format does not fix

safetensors ends code execution on load. It does not make the weights trustworthy. A model can be backdoored in its parameters, trained to behave normally until a trigger input flips it, with no malicious opcode anywhere in the file. That payload survives conversion to safetensors untouched, because it is the model, not a rider on the format. Scanning a file tells you whether loading it is safe; it does not tell you whether the model itself was poisoned.

Socket's experimental Hugging Face scanning inspects PyTorch, TensorFlow, Keras, TFLite, GGUF, and Llamafile artifacts for the load-time class of attack and ingests [AIBOM](https://socket.dev/glossary/aibom) files, so model risk can ride existing supply-chain workflows ([Socket](https://socket.dev/blog/announcing-experimental-malware-scanning-for-hugging-face)). Proving a set of weights does only what it claims, with no behavioral backdoor, is still an open problem, and it is the harder half.
