Loading a client's .pkl file lets a stranger run code on your machine
How to inspect a model file without executing it, and when to insist the client moves to safetensors or skops.
In brief
- pickle.load, joblib.load and older versions of torch.load can all run arbitrary code the moment a file is loaded.
- pickletools lets you read the instructions in a file without executing them, but a scan is a filter, not a guarantee.
- The most durable fix is a format that cannot carry code: safetensors for tensors, skops.io for scikit-learn.
In February 2024 JFrog said it had found about 100 malicious models on Hugging Face. One of them, as soon as it was loaded, opened a reverse shell to a real IP address: 210.117.212.93.
A year later ReversingLabs found another model on the same platform carrying a reverse shell that could detect the operating system and called back to a hard-coded IP. The two cases share one feature: the victims ran no unfamiliar script. They only loaded a model.
For an FDE, model files rarely arrive from anywhere obviously suspicious. They sit in the data team’s bucket, on a shared drive left behind by someone who has since moved on, or behind a Hub link pasted into a ticket.
You load the file on a machine holding the client’s credentials, and Python’s own documentation states plainly that malicious pickle data can execute arbitrary code during unpickling. If that happens, the responsibility is yours.
Why does “loading data” become “running code”?
A pickle file is a small program, and the unpickler is the machine that runs it. Python lets an object define how it should be reconstructed through the __reduce__ method, which returns a tuple: the first element is a callable, the second a tuple of arguments. On load, the unpickler calls that callable to rebuild the object.
Hugging Face’s security documentation describes the same mechanism at the opcode level. The GLOBAL/STACK_GLOBAL instructions tell the unpickler to import something, and REDUCE tells it to call a function with the given arguments. Put the two together and you can call any function Python can import.
The example below is harmless, but it follows exactly the path taken by the malicious models above:
import pickle
class Demo:
def __reduce__(self):
# callable + argument tuple: the unpickler will call print(...)
return (print, ("This line runs when the file is loaded",))
payload = pickle.dumps(Demo())
# On another machine, the recipient is only "loading data":
pickle.loads(payload) # the line is printed
Swap print for os.system and the string for a shell command, and you have a reverse shell. The recipient does not need the Demo class, because all that remains in the file is the instruction “import this function, call it with these arguments”.
Reading a file without opening it
The standard library’s pickletools module can read the list of instructions in a file without executing them. It should be the first step whenever you receive a .pkl, .joblib or .pt file of unknown origin. The script below prints every point at which the file intends to import something or call a function:
# scan_pickle.py — run with: python -I scan_pickle.py model.pkl
import pickletools
import sys
SUSPICIOUS_OPS = {"GLOBAL", "STACK_GLOBAL", "REDUCE", "INST", "OBJ", "NEWOBJ"}
with open(sys.argv[1], "rb") as f:
recent_strings = []
for op, arg, pos in pickletools.genops(f):
if isinstance(arg, str):
recent_strings = (recent_strings + [arg])[-2:]
if op.name in SUSPICIOUS_OPS:
# STACK_GLOBAL takes the module and name from the two strings just before it
hint = arg if arg is not None else recent_strings
print(f"{pos:>8} {op.name:<13} {hint}")
The script has a blind spot worth knowing about. For STACK_GLOBAL it only guesses the module name from the two most recent strings, whereas pickles often store strings in the memo and fetch them back with BINGET, so the real name may not sit immediately before the instruction.
When a line looks suspicious, run python -I -m pickletools model.pkl (that is, pickletools.dis) to see the full instruction listing and trace the memo by eye.
A PyTorch .pt file is usually a zip archive with the pickle inside, so extract it into its own directory before scanning.
An ordinary scikit-learn model also contains plenty of GLOBAL and REDUCE instructions, because it has to import sklearn and numpy classes to rebuild itself. What matters is the module name: sklearn.ensemble and numpy.core are routine, while os, subprocess, socket, builtins.eval or builtins.exec are a signal to stop immediately.
Do not treat a scan result as a safety certificate. Hugging Face itself acknowledges that its import scanning on the Hub is not a guarantee, and that users still need to check for themselves.
An attacker can hide function names behind several layers of indirection, so the script above is only a coarse filter: a “clean” file is still not trusted, while a “dirty” one is certainly rejected.
Switch to a format that cannot carry code
The most durable fix is to remove the ability to run code at the level of the file format. For tensors, safetensors is the default choice. A file begins with 8 bytes giving the header size (an unsigned 64-bit little-endian integer), followed by a JSON header and a byte buffer holding the data.
An external security audit published in May 2023 found no critical flaw leading to arbitrary code execution.
Because the structure is this simple, you can read the header yourself to see which tensors a file contains, using only the standard library:
import json
import struct
with open("model.safetensors", "rb") as f:
n = struct.unpack("<Q", f.read(8))[0] # 8 bytes: header size
header = json.loads(f.read(n)) # JSON: name, dtype, shape, offsets
for name, info in header.items():
if name != "__metadata__":
print(name, info["dtype"], info["shape"])
This makes a good check at handover: compare the list of tensors with the model architecture the client describes. A single missing tensor or mismatched shape is enough to catch a problem before it reaches production.
For scikit-learn, the library’s documentation is explicit that pickle, and with it joblib and cloudpickle, is insecure by design and should only be used when the file comes from a trusted, verified source.
The recommended alternative is skops.io: it does not use pickle and only loads files whose data types and function references are trusted, either by default or because you have declared them. The list of types you have to declare doubles as an inventory of what the model actually needs.
Traps that catch even careful engineers
The first trap is assuming joblib is different from pickle. A .joblib extension looks more specialized, but according to scikit-learn it carries the same class of vulnerability.
The second lies in torch.load. Since PyTorch 2.6 the function defaults to weights_only=True if you do not pass pickle_module. So a single line of old code that passes pickle_module, or sets weights_only=False “to make it work”, is enough to strip away the default protection.
The third is harder to spot: the version. PyTorch disclosed a remote code execution vulnerability in torch.load that worked even with weights_only=True enabled (GHSA-53q9-r3pm-6pq6), affecting versions 2.5.1 and earlier and patched in 2.6.0.
Client environments are often pinned to old versions for compatibility reasons, so the safety flag in your code may protect nothing. Check the version before trusting the flag.
The last trap is trusting a repository’s “scanned” label. Even Hugging Face says its scanning is no substitute for your own checks.
Turn the habit into a process, then into a line on your CV
A sensible process at a client site has five steps. Ask where the file came from and who owns it. Scan it with pickletools in a separate directory, running Python with the -I flag.
If you must load a pickle, do so in an isolated environment with no production credentials. Then convert to safetensors or skops.io. Finally, record the new format in the handover documents so the client’s team does not drift back to pickle.
On a CV, one concrete line carries far more weight than “security-minded”. For example: migrated the client’s model artifacts from pickle to safetensors and added a header check to CI.
In an interview, if asked how you take a model to production, describe these five steps as part of your routine, along with why scanning comes before loading.
Model files look like data, so few people review them the way they review code. Treat every .pkl file as a pull request from a stranger: read it first, then decide whether to run it.
Was this article useful?
Thanks for the feedback!
9 sources
- pickle — Python object serialization
- Pickle Scanning (Hugging Face Hub docs)
- Model persistence — scikit-learn documentation
- Serialization semantics — PyTorch documentation
- torch.load with weights_only=True RCE (GitHub Security Advisory) · 2025-04-17
- Data Scientists Targeted by Malicious Hugging Face ML Models with Silent Backdoor · 2024-02-27
- ReversingLabs: nullifAI — malware ML models hosted on Hugging Face · 2025-02-06
- Audit shows that safetensors is safe and ready to become the default · 2023-05-23
- huggingface/safetensors: Simple, safe way to store and distribute tensors