Sub topic 7
Only load files you trust
This chapter assumes you can fit a scikit-learn estimator, save it with pickle or joblib, and load it back. Here you will learn why loading a model file can be dangerous and what to do about it.
Loading is running code
A .pkl or .joblib file is not plain data. Pickle stores instructions that Python follows when it rebuilds the object. Some of those instructions can call any function, including ones that delete files or open network connections.
So pickle.load and joblib.load do not just read a file. They can run whatever code the file's author put there. This happens during loading, before you call predict.
joblib uses pickle internally, so it has the same risk. The same applies to any format built on pickle.
A harmless demonstration
The class below tells pickle to call print when the file is loaded. A real attacker would call something far worse, such as os.system.
import pickle
class Payload:
def __reduce__(self):
# pickle will call print("this ran during load") on load
return (print, ("this ran during load",))
with open("evil.pkl", "wb") as f:
pickle.dump(Payload(), f)
with open("evil.pkl", "rb") as f:
obj = pickle.load(f)Running this prints this ran during load. The obj you get back is just None, the return value of print. The file never contained a real model, yet the code ran as soon as you loaded it.
Where the risk shows up
The danger is real in these situations:
- Downloading a model from a public site, a forum, or a shared drive.
- Accepting uploaded model files in a web service.
- Loading files from a storage bucket that other people or systems can write to.
- Reusing a file after someone with write access may have changed it.
A file you trained yourself, stored where only you can write, is low risk. The trust you need covers the file's whole history, not only its author.
Reducing the risk
No check on a pickle file is fully reliable, so rely on controls around it.
- Load only from sources you control. Keep model files in storage with restricted write access.
- Verify integrity. Record a hash of the file when you save it, and compare before loading. This detects tampering, though not a file that was malicious from the start.
```python import hashlib
def sha256_of(path): digest = hashlib.sha256() with open(path, "rb") as f: for chunk in iter(lambda: f.read(8192), b""): digest.update(chunk) return digest.hexdigest()
expected = "paste the hash you recorded at save time" if sha256of("irismodel.joblib") != expected: raise RuntimeError("Model file does not match the recorded hash") ```
- Run loading in an isolated environment such as a container with no secrets and limited network access, if you must handle files of uncertain origin.
- Use a format that does not run code on load. The
skopslibrary is designed for this.
Loading safely with skops
skops stores a model in a format that does not execute arbitrary code. When you load, it refuses types it does not recognize as safe unless you explicitly trust them. You can list those types first and decide.
from skops.io import dump, get_untrusted_types, load
dump(model, "iris_model.skops")
unknown_types = get_untrusted_types(file="iris_model.skops")
print(unknown_types)
loaded = load("iris_model.skops", trusted=unknown_types)Here model is the fitted pipeline from the earlier chapters. For a standard scikit-learn pipeline the printed list is usually empty or short. Read it before you pass it to trusted. If you see a type you do not expect, such as a function from os or subprocess, do not load the file.
Passing trusted=unknown_types without reading the list defeats the check. It turns the protection into a formality.
| Format | Runs code on load | Typical use |
|---|---|---|
| pickle | Yes | Your own files, short-lived |
| joblib | Yes | Your own files, large NumPy arrays |
| skops | No, with trust check | Sharing scikit-learn models |
| ONNX | No | Deployment in other runtimes |
ONNX is covered in a later chapter. It stores the model's computation as a graph, so it is not a pickle at all.
Exercise
A colleague emails you a file called churn_model.joblib and says it is a trained scikit-learn model. You want to try it. Why is joblib.load("churn_model.joblib") risky, and what are two things you could do instead?
Show answer
joblib uses pickle, so loading can run arbitrary code embedded in the file, with your user's permissions, before you make any prediction. Instead, you could ask for the model in skops format and inspect it with get_untrusted_types before loading, or ask for the training code and data and retrain it yourself. Confirming the file's hash with your colleague over a separate channel, or loading it only in an isolated container, also lowers the risk.