Sub topic 13
TensorFlow and Keras formats and their risks
This chapter covers the formats TensorFlow and Keras use to save models, and where each one can carry executable behavior. It assumes you have read the earlier chapters on pickle and __reduce__, and that you have used model.save() or tf.saved_model at least once. The central point is that these formats do not use pickle, but some of them can still run code. Pickle is not the only way a model file can do that.
The formats you will meet
TensorFlow and Keras have accumulated several save formats. Which one you have depends on the file extension or directory layout and on the library version that wrote it.
| Format | Layout | Where code or behavior hides |
|---|---|---|
| TensorFlow checkpoint (`.ckpt`) | `.index` file plus `.data-*` shards | Data only. Tensors and variable names. |
| SavedModel | Directory with `saved_model.pb`, `variables/`, `assets/` | The protobuf graph can contain ops with side effects. |
| Legacy Keras HDF5 (`.h5`, `.hdf5`) | One HDF5 file with a JSON model config and weight datasets | `Lambda` layers store Python bytecode in the config. |
| Keras v3 (`.keras`) | Zip archive with `config.json`, `metadata.json`, `model.weights.h5` | The config names classes to instantiate. `Lambda` layers are blocked by default. |
None of these formats is a pickle stream, so pickletools does not apply to them. The risk comes from two other places: graphs that describe computation, and configs that describe which Python objects to rebuild.
SavedModel: a graph, not just weights
A SavedModel stores the computation itself. saved_model.pb is a protobuf message containing one or more graphs of operations (ops). The variables/ directory holds the weights in checkpoint format. Because the graph is a program, the question is what ops it is allowed to contain.
TensorFlow ships ops that touch the outside world. ReadFile, WriteFile and MatchingFiles access the file system. A graph that includes WriteFile can write files whenever the model is run. Loading with tf.saved_model.load mostly rebuilds the graph and variables, but calling the model executes the ops, and some restored initializers run at load time. In practice, running a third-party SavedModel gives its author the ability to read and write files with your process's permissions.
The Python-callback ops (PyFunc, PyFuncStateless, EagerPyFunc) are a different case. They do not carry the Python function in the file. They store a token that refers to a function registered in the process that built the graph. In a fresh process the lookup fails, so these ops are usually a compatibility problem, not an injection route. Treat them as suspicious anyway, because they should not appear in a model you downloaded.
You can review a SavedModel without running it, because parsing a protobuf executes nothing:
from tensorflow.core.protobuf import saved_model_pb2
RISKY_OPS = {
"ReadFile",
"WriteFile",
"MatchingFiles",
"PyFunc",
"PyFuncStateless",
"EagerPyFunc",
}
def scan_saved_model(pb_path):
saved_model = saved_model_pb2.SavedModel()
with open(pb_path, "rb") as f:
saved_model.ParseFromString(f.read())
found = set()
for meta_graph in saved_model.meta_graphs:
graph_def = meta_graph.graph_def
nodes = list(graph_def.node)
# Functions live in the graph library, not in the top-level node list.
for function in graph_def.library.function:
nodes.extend(function.node_def)
for node in nodes:
if node.op in RISKY_OPS:
found.add(node.op)
return found
print(scan_saved_model("my_model/saved_model.pb"))An empty set does not prove the model is safe, since an allowlist of known ops is stronger than a denylist. It does give you a cheap first check. The scan must look inside graph.library.function as well as the top-level nodes, because most Keras models put their logic in function bodies.
Legacy HDF5: Lambda layers carry bytecode
An .h5 file is an HDF5 container. Weights are stored as ordinary datasets, which is safe. The model architecture is stored as a JSON string in a file attribute. For built-in layers that JSON is harmless: layer names, units, activations.
The problem is the Lambda layer, which wraps an arbitrary Python function. To save it, Keras serializes the function's compiled code object with marshal, base64-encodes the result, and writes it into the config. On load, Keras decodes it and rebuilds a function from the code object. That function then runs when the model is built or called. This is the same class of problem as __reduce__, reached through a different mechanism: the file carries code, and the loader reconstructs it. Reports such as CVE-2024-3660 describe exactly this for older Keras versions.
Treat any .h5 model from an untrusted source as code. Prefer to load only its weights into an architecture you defined yourself:
import keras
# Build the architecture from your own source code, not from the file.
model = keras.Sequential(
[
keras.Input(shape=(4,)),
keras.layers.Dense(8, activation="relu"),
keras.layers.Dense(1),
]
)
# Reads only the weight datasets, not the stored architecture config.
model.load_weights("downloaded_weights.h5")This works only when the weights file matches your layer structure, which is the intended trade: you review the architecture as source code, and the file supplies numbers.
The .keras format and safe_mode
Keras 2.12 and later introduced the .keras format, and Keras 3 uses it as the default. It is a zip archive with a JSON config and an HDF5 weights file. The config lists each layer by module and class_name, and loading imports and instantiates those classes. That is a smaller attack surface than raw bytecode, but it is still a mechanism for choosing which Python objects get created.
Since Keras 2.13, load_model takes safe_mode, which defaults to True. In safe mode, deserializing a Lambda layer raises an error instead of rebuilding the function. Custom classes must be registered or passed explicitly. The escape hatches are safe_mode=False and keras.config.enable_unsafe_deserialization(). Do not use either on a file you did not create.
import keras
model = keras.models.load_model("model.keras", safe_mode=True)Safe mode is a guard, not a guarantee. Bypasses have been reported and fixed (for example CVE-2025-1550, where a crafted config reached arbitrary callables). Keep Keras updated, and check the advisories for the version you run.
Because the archive is a plain zip with a JSON config, you can inspect it without loading anything:
import json
import zipfile
def list_classes(node, found=None):
"""Collect every (module, class_name) pair in a Keras config tree."""
if found is None:
found = set()
if isinstance(node, dict):
if "class_name" in node:
found.add((node.get("module"), node["class_name"]))
for value in node.values():
list_classes(value, found)
elif isinstance(node, list):
for item in node:
list_classes(item, found)
return found
with zipfile.ZipFile("model.keras") as archive:
print(archive.namelist())
config = json.loads(archive.read("config.json"))
for module, class_name in sorted(list_classes(config), key=str):
flag = "" if (module or "").startswith("keras") else " <-- review"
print(module, class_name, flag)Anything outside the keras package, and any Lambda entry, deserves a look before you load the file.
Practical rules
- Prefer
.kerasover.h5for models you save, and keepsafe_mode=Truewhen loading. - For third-party models, load weights into architecture code you control when possible.
- Scan SavedModel graphs for side-effect ops before the first call, and run unfamiliar models in a sandbox without network access or sensitive files.
- If the weights are all you need, convert them to safetensors. The later chapter on conversion covers how.
Exercise
A colleague sends you an .h5 file and says it only contains a trained classifier. The file is not pickle, so is it safe to load with keras.models.load_model? What would you do instead?
Show answer
Not necessarily. The HDF5 weights are plain data, but the architecture config can contain a Lambda layer whose Python code object is stored as marshaled bytecode and rebuilt on load. That code can run when the model is built or called, so loading is a trust decision. Instead, define the architecture in your own code and call model.load_weights on the file, so only the weight datasets are read.
Exercise
Why does the SavedModel scan include graph_def.library.function and not just graph_def.node?
Show answer
Keras and tf.function place most of a model's operations inside function definitions stored in the graph library. The top-level node list contains mostly calls to those functions. A scan that checks only the top-level nodes would miss side-effect ops such as WriteFile inside the function bodies.