Sub topic 7
Only Load Files You Trust
This chapter assumes you can save and load a model with pickle and joblib, as covered in the earlier chapters. You should be comfortable reading short Python scripts. No security background is needed.
By the end you should be able to explain why loading a pickle-based model file can run attacker code, and apply checks before loading a file. You should also be able to use skops to inspect a file before you trust it.
Loading is not the same as reading data
Loading a CSV file reads text and turns it into values. Loading a pickle file works differently. The file contains a list of instructions for a small virtual machine inside Python, and pickle.load runs them. Those instructions can import any module and call any function the Python process can reach. Rebuilding your fitted estimator is only one thing they can do.
A pickle file can therefore do anything your Python process can do. It can read your files, send data over the network, install software, or delete things. The code runs with your permissions, at the moment you call load.
The scikit-learn documentation warns about this, and so do the pickle and joblib documentation. The warning is accurate. It is not a theoretical concern.
A harmless demonstration
Pickle lets a class define __reduce__. That method tells pickle how to rebuild the object. It returns a callable and its arguments, and pickle stores both. On load, pickle calls the callable with those arguments.
This example uses print, which is harmless. Any other function would work the same way.
import pickle
import pickletools
class Demo:
def __reduce__(self):
return (print, ("this ran while loading the file",))
payload = pickle.dumps(Demo())
# Inspect the instructions without running them.
pickletools.dis(payload)
# Loading runs them.
result = pickle.loads(payload)
print("loaded object:", result)The output has two parts. pickletools.dis lists the instructions, including a reference to builtins.print. Then pickle.loads prints the message, and the loaded "object" is None. That is the return value of print.
Nothing about the loaded result looks like a model. An attacker would not mind. The harmful call has already finished by the time load returns.
A real attacker would replace print with something like os.system and a shell command. The bytes would look the same to you. You cannot tell by looking at the file size or the extension.
Joblib and scikit-learn files carry the same risk
Joblib is built on pickle. It adds efficient handling of large NumPy arrays and optional compression, but the loading step still runs pickle instructions. A .joblib file from an untrusted source is as dangerous as a .pkl file.
The same applies to every file that asks you to unpickle it. File extensions do not protect you, because they are only names. A file called model.joblib can contain anything.
| Format | Runs code on load? | Notes |
|---|---|---|
| `pickle` (`.pkl`) | Yes | Standard library. Can call any importable function. |
| `joblib` (`.joblib`) | Yes | Pickle underneath. Compression does not change this. |
| `skops` (`.skops`) | No, if you do not pass trust | Loads only types you approve. |
| ONNX (`.onnx`) | No | Describes a computation graph, not Python objects. |
Where untrusted files come from
You will rarely meet an obvious attacker. These are the realistic sources of risk:
- A model downloaded from a public hub, a forum post, a notebook, or a blog.
- A file from a colleague or a contractor, whose machine may be compromised.
- A shared drive, object storage bucket, or artifact store where several people or services can write. If anyone can replace the file, the file is untrusted.
- A model uploaded by a user to your own application.
- A file you made yourself, but that sat in a location someone else could modify.
The last two cases catch teams out. A service that accepts uploaded model files and calls joblib.load on them gives every user remote code execution on the server.
Decide who is allowed to write the file
The trust question is about the path from the author to your load call. Ask two things:
- Do I know who produced these bytes?
- Could anyone else have changed them on the way?
If the answer to either is unclear, treat the file as untrusted. A file you generated yourself on your own laptop and loaded straight back is fine. A file that passed through a public bucket is not, unless you can verify it.
Verify integrity with a checksum
A checksum proves that the bytes are the ones you expected. It does not prove that the bytes are safe. If the original author was malicious, the checksum will match a malicious file. A checksum only helps when you trust the author and want to detect tampering or corruption.
For the checksum to mean anything, you must get the expected value through a different channel from the file. If both sit in the same writable location, an attacker can change both.
This script saves a model, records a SHA-256 hash, and refuses to load if the hash does not match.
import hashlib
import joblib
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
def sha256_of(path):
digest = hashlib.sha256()
with open(path, "rb") as f:
for chunk in iter(lambda: f.read(1024 * 1024), b""):
digest.update(chunk)
return digest.hexdigest()
def load_verified(path, expected_sha256):
actual = sha256_of(path)
if actual != expected_sha256:
raise ValueError(
f"Checksum mismatch for {path}: expected {expected_sha256}, got {actual}"
)
return joblib.load(path)
X, y = load_iris(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=200))
model.fit(X, y)
joblib.dump(model, "iris_model.joblib")
expected = sha256_of("iris_model.joblib") # store this somewhere separate
loaded = load_verified("iris_model.joblib", expected)
print(loaded.predict(X[:3]))In real use, the line that computes expected happens on the producer's side. You would publish the hash through a release note, a signed message, or a deployment configuration that the file store cannot write to.
If the file and its readers live inside your own systems, a signed hash is stronger than a plain one. An HMAC or a digital signature lets you check that the file came from someone who holds the key.
Check before you load, not after
A common mistake is to load the file and then inspect the object to see whether it looks right. By then, any harmful code has already run. All checks must happen on the raw bytes, before load:
- Verify the checksum or signature.
- Verify the file's location and permissions.
- Optionally list the pickle's global references with
pickletools.disand look for anything that is not scikit-learn, NumPy, or SciPy.
The last check is a useful smell test, but it is not a guarantee. Scanning pickles is hard, because a harmful call can be built from several harmless-looking pieces. Treat scanning as extra evidence, not as permission.
A restricted unpickler is not a full defense
Python's documentation describes restricting which globals a custom Unpickler may resolve by overriding find_class. This blocks the simple os.system attack:
import io
import pickle
class AllowListUnpickler(pickle.Unpickler):
ALLOWED_PREFIXES = ("sklearn.", "numpy.", "scipy.")
def find_class(self, module, name):
if module.startswith(self.ALLOWED_PREFIXES):
return super().find_class(module, name)
raise pickle.UnpicklingError(f"Blocked global: {module}.{name}")
def restricted_loads(data):
return AllowListUnpickler(io.BytesIO(data)).load()This helps against crude payloads. It has limits. Allowed modules can still contain functions with side effects. You also have to keep the list correct as scikit-learn changes, and a real model file references other modules such as collections or joblib internals. This approach also does not work directly with joblib files, which use their own unpickler for arrays. Prefer a format that was designed to be safe.
Use skops to inspect before trusting
The skops format stores scikit-learn objects without arbitrary Python callables. When you load a file, skops refuses to construct types you have not approved. You can list the types a file wants, review them, and then decide.
from skops.io import dump, get_untrusted_types, load
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=200))
model.fit(X, y)
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)
print(loaded.predict(X[:3]))For a plain scikit-learn pipeline the printed list may be short or empty. A list that contains something unfamiliar, such as a module from a package you do not use, is the signal to stop and ask why.
The point of this workflow is the review step. Passing trusted=unknown_types straight from the same file, as the script above does, only makes sense because you made the file yourself. For a file from someone else, read the list and approve only the types you recognize.
skops reduces the risk but does not remove all of it. It is younger than pickle, and its safety depends on the types you allow. Check the skops documentation for the current guarantees.
ONNX avoids Python objects entirely
ONNX describes a model as a graph of numeric operations. A runtime such as ONNX Runtime executes the graph. Loading an ONNX file does not unpickle Python objects, so it does not run arbitrary Python code. It is a good choice when you deploy to a service that should never import untrusted Python.
The cost is conversion. Not every scikit-learn estimator or custom transformer converts cleanly, and you must test that the converted model gives the same predictions.
Sandboxing as a last resort
Sometimes you must inspect a pickle file you cannot trust, for example during a security review. Do it in a place where a compromise costs nothing:
- A disposable container or virtual machine with no network access.
- No credentials, tokens, or mounted home directories.
- A throwaway user with minimal permissions.
A sandbox limits damage. It does not make the file safe. Never copy the loaded model out and then use it in production without re-creating it from known code and data.
Common mistakes
- Assuming that compression, a
.joblibextension, or a large file size makes a file safer. - Loading first and checking afterwards.
- Storing the hash next to the file in the same writable location.
- Exposing
loadto user uploads. - Trusting a model because it came from a well-known site, without verifying that the author and the bytes are what you think they are.
- Believing that running in a notebook is safer than running in a script. The code runs with your permissions either way.
Summary
Loading a pickle or joblib file runs code, so the safety of the file depends entirely on where it came from. Verify the source and the checksum before you load, and keep the hash apart from the file. For files that cross a trust boundary, prefer skops with a reviewed list of types, or ONNX. Keep pickle and joblib for files your own systems produced and protect.
Exercise
A teammate sends you a link to a .joblib file in a shared bucket that several teams can write to. They also post the SHA-256 hash in the same bucket folder, in a text file. Is it safe to run joblib.load after your script confirms the hash matches? Explain.
Show answer
No. Anyone who can write to the bucket can replace both the model and the hash file, so a matching hash only proves the two files agree with each other. The hash must come through a separate channel that the bucket's writers cannot change, such as a signed release note or a protected configuration. Even then, the hash only proves the bytes are the ones the author published. It says nothing about whether the author's file is safe.
Exercise
Why does inspecting a loaded object with type(obj) or obj.predict(...) fail as a safety check for an untrusted pickle?
Show answer
Pickle runs its instructions during load, before it returns the object. Any harmful code has already executed by the time you can inspect the result. The object can even look like a normal estimator while the harmful code has already run. Checks must happen on the bytes before loading.
Exercise
You receive model.skops from an outside partner. get_untrusted_types(file="model.skops") returns a list that includes a type from a package called partner_utils, which you do not recognize. What should you do?
Show answer
Do not pass the list to trusted=. Ask the partner what partner_utils is and why the model needs it. Review the package source if you can, and approve only types you understand and accept. If you cannot justify the type, do not load the file, or ask for a version of the model that uses only standard scikit-learn types.