VAITP Dataset

← Back to the dataset

CVE-2025-1550

Keras load_model allows code execution via malicious .keras archive.

  • CVSS 7.3
  • CWE-94
  • Design Defects
  • Remote

The Keras Model.load_model function permits arbitrary code execution, even with safe_mode=True, through a manually constructed, malicious .keras archive. By altering the config.json file within the archive, an attacker can specify arbitrary Python modules and functions, along with their arguments, to be loaded and executed during model loading.

CVSS base score
7.3
Published
2025-03-11
OWASP
A08 Software and Data Integrity Failures
Orthogonal defect classification
Interface
Code defect classification
Incorrect Functionality
Category
Design Defects
Subcategory
Insecure Parsing or Deserialization
Accessibility scope
Remote
Impact
Arbitrary Code Execution
Affected component
Keras
Fixed by upgrading
Yes

Solution

Upgrade to Keras 2.15.0 or later.

Vulnerable code sample

import json
import importlib

def load_model(model_archive):
    """
    Loads a model from a (supposedly safe) archive.
    This is a SIMPLIFIED, VULNERABLE example.  DO NOT USE IN PRODUCTION.
    """
    with open(model_archive, 'r') as f:  # Assume model_archive contains a json representation
        model_config = json.load(f)

    # Vulnerable code: Directly using config values to import and execute code.
    module_name = model_config.get('module')
    function_name = model_config.get('function')
    function_args = model_config.get('args', []) # Default to an empty list for args

    if module_name and function_name:
        module = importlib.import_module(module_name)
        function = getattr(module, function_name)
        function(*function_args)  # Execute the function with provided arguments
    else:
        print("Invalid model configuration.")

# Example of a malicious model configuration (stored in "malicious_model.json")
# THIS IS FOR DEMONSTRATION ONLY.  CREATING SUCH A FILE IS POTENTIALLY HARMFUL.
# It is recommended to create the json file with appropriate permissions
# to limit access to the file only to the script to prevent unwanted modification
# by other processes.
malicious_config = {
    'module': 'os',
    'function': 'system',
    'args': ['touch /tmp/pwned'] # Vulnerable command execution.
}

with open('malicious_model.json', 'w') as f:
    json.dump(malicious_config, f)


# Simulate loading the "model"
load_model('malicious_model.json') # In a real attack, this would be the .keras archive

print("Model loaded (or so it seems...)")

Patched code sample

import json
import zipfile
import io
import os
import importlib
import traceback

def safe_load_model(filepath, safe_mode=True):
    """
    Safely loads a Keras model from a .keras archive.  This attempts to mitigate
    CVE-2025-1550 by carefully validating the contents of the config.json file
    and restricting the modules and functions that can be loaded.

    Args:
        filepath: The path to the .keras archive.
        safe_mode: Whether to enable safe loading.  If False, the original
            load_model behavior is emulated (with its inherent risks).

    Returns:
        A placeholder model object (in a real implementation, it would be the
        loaded Keras model).

    Raises:
        ValueError: If the config.json contains invalid or unsafe entries.
        Exception: For other loading errors.
    """

    if not safe_mode:
        print("Warning: Safe mode is disabled. Loading model with potential security risks.")
        # In a real implementation, this would call the original unsafe load_model.
        return "UNSAFE_MODEL"  # Placeholder

    try:
        with zipfile.ZipFile(filepath, 'r') as zf:
            # Extract and parse the config.json file
            try:
                config_str = zf.read('config.json').decode('utf-8')
                config = json.loads(config_str)
            except (KeyError, json.JSONDecodeError) as e:
                raise ValueError("Invalid .keras archive: Could not read or parse config.json") from e

            # **SECURITY CRITICAL SECTION: Validation and Sanitization**
            #  This section is the core of the fix. It rigorously checks the
            #  config.json data to prevent malicious code execution.

            # 1. Whitelist Allowed Keys:  Only allow a predefined set of keys.
            allowed_keys = ["class_name", "config", "keras_version", "backend"]
            for key in config:
                if key not in allowed_keys:
                    raise ValueError(f"config.json contains disallowed key: {key}")

            # 2. Validate 'class_name' and 'keras_version' :
            if not isinstance(config.get("class_name"), str) or not isinstance(config.get("keras_version"), str):
                  raise ValueError("Invalid type for 'class_name' or 'keras_version' in config.json")

            # 3. Deep Inspection of 'config' for Suspicious Code Execution:
            config_data = config.get("config", {})
            def validate_config_recursively(data):
                if isinstance(data, dict):
                    for key, value in data.items():
                        if isinstance(key, str):
                            #Check for suspicious names
                            banned_substrings = ["__", "eval", "exec", "getattr", "setattr"]
                            if any(substring in key for substring in banned_substrings):
                                raise ValueError(f"config.json contains potentially dangerous key: {key}")
                        validate_config_recursively(value)
                elif isinstance(data, list):
                    for item in data:
                        validate_config_recursively(item)
                elif isinstance(data, str):
                    # Check for suspicious strings
                    banned_strings = ["import ", "os.", "subprocess."]
                    if any(string in data for string in banned_strings):
                        raise ValueError(f"config.json contains potentially dangerous string: {data}")


            validate_config_recursively(config_data)


            # In a real implementation, additional checks would be performed:
            #   - Whitelisting allowed modules and functions in config.json
            #   - Sandboxing the model loading process
            #   - Using safer alternatives to pickle for deserialization, if applicable.

            # Placeholder for actual model loading.  This demonstrates that the
            # config has been parsed and validated.
            return "SAFE_MODEL"  # Placeholder


    except Exception as e:
        print(f"Error loading model: {e}")
        traceback.print_exc()  # Print stack trace for debugging.
        raise  # Re-raise the exception.

Published fix

Public sources link this CVE to the changes below. The code samples above were generated to illustrate the defect; these links lead to the code the project actually changed.

  • Add checks to deserialization. (#20751) (keras-team/keras)
    keras/src/models/functional.py, keras/src/models/functional.py · functional_from_config, keras/src/saving/serialization_lib.py · _retrieve_class_or_fn

Payload

{
  "format": "keras_model",
  "keras_version": "3.3.3",
  "backend": "tensorflow",
  "model_config": {
    "class_name": "Sequential",
    "config": {
      "name": "sequential_1",
      "layers": [
        {
          "class_name": "Dense",
          "config": {
            "name": "dense_1",
            "trainable": true,
            "dtype": "float32",
            "units": 1,
            "activation": "linear",
            "use_bias": true,
            "kernel_initializer": {
              "class_name": "GlorotUniform",
              "config": {
                "seed": null
              }
            },
            "bias_initializer": {
              "class_name": "Zeros",
              "config": {}
            },
            "kernel_regularizer": null,
            "bias_regularizer": null,
            "activity_regularizer": null,
            "kernel_constraint": null,
            "bias_constraint": null
          }
        }
      ]
    }
  },
  "training_config": {
    "loss": "mse",
    "metrics": ["mae"]
  },
   "module_objects": {
    "__main__": {
      "test_function": {
        "module": "os",
        "class_name": "system",
        "config": {
          "command": "touch /tmp/pwned"
        }
      }
    }
  },
  "weights_manifest": []
}

Cite this entry

@misc{vaitp:cve20251550,
  title        = {{Keras load_model allows code execution via malicious .keras archive.}},
  author       = {Bogaerts, Fr\'ed\'eric and Ivaki, Naghmeh and Fonseca, Jos\'e},
  year         = {2025},
  note         = {VAITP Python Vulnerability Dataset, entry CVE-2025-1550},
  howpublished = {\url{https://netpack.pt/vaitp/vulnerability/CVE-2025-1550/}}
}

Download this entry as JSON Download the whole dataset

Introducing the "VAITP dataset": a specialized repository of Python vulnerabilities and patches, meticulously compiled for the use of the security research community. As Python's prominence grows, understanding and addressing potential security vulnerabilities become crucial. Crafted by and for the cybersecurity community, this dataset offers a valuable resource for researchers, analysts, and developers to analyze and mitigate the security risks associated with Python. Through the comprehensive exploration of vulnerabilities and corresponding patches, the VAITP dataset fosters a safer and more resilient Python ecosystem, encouraging collaborative advancements in programming security.

The supreme art of war is to subdue the enemy without fighting.

Sun Tzu – “The Art of War”

:: Shaping the future through research and ingenuity ::

Before you use the VAITP AI models

Please read and accept the following disclaimer:

By choosing "I understand and accept", you acknowledge that you understand and agree to these terms.