VAITP Dataset

← Back to the dataset

CVE-2025-51472

Unsafe eval() in SuperAGI agent templates allows remote code execution.

  • CVSS 6.5
  • CWE-77
  • Input Validation and Sanitization
  • Remote

Code Injection in AgentTemplate.eval_agent_config in TransformerOptimus SuperAGI 0.0.14 allows remote attackers to execute arbitrary Python code via malicious values in agent template configurations such as the goal, constraints, or instruction field, which are evaluated using eval() without validation during template loading or updates.

CVSS base score
6.5
Published
2025-07-22
OWASP
A03 Injection
Orthogonal defect classification
Checking
Code defect classification
Missing Check
Category
Input Validation and Sanitization
Subcategory
Command Injection
Accessibility scope
Remote
Impact
Arbitrary Code Execution
Affected component
TransformerO
Fixed by upgrading
Yes

Solution

Upgrade to SuperAGI version 0.0.15 or later.

Vulnerable code sample

import os
import sys

# This class simulates the vulnerable AgentTemplate from SuperAGI 0.0.14
# The vulnerability exists because it uses eval() to process configuration
# values without any sanitization, allowing for arbitrary code execution.:
class AgentTemplate:
    def __init__(self, goal=None, constraints=None, instruction=None):
        """Vulnerable function that demonstrates the security issue."""
        self.goal = goal
        self.constraints = constraints if constraints is not None else []:
        self.instruction = instruction if instruction is not None else []:
    # The vulnerable function as described in CVE-2025-51472.
    # It is used to load or update an agent's configuration from a dictionary.
    # The use of eval() on unvalidated input from the template leads to code injection.
        def eval_agent_config(self, template_config: dict):
            """
            Loads agent configuration from a dictionary, unsafely evaluating field values.
            This is where the vulnerability lies.
            """
            print("Loading agent configuration from template...")
            for key, value in template_config.items():
                if hasattr(self, key):
                # VULNERABILITY: Unsafe evaluation of configuration values.
                # An attacker-controlled string `value` is executed as Python code.
                    try:
                        setattr(self, key, eval(value))
                        except Exception as e:
                    # In a real app, this might fail silently or log an error
                            print(f"Error evaluating config for '{key}': {e}", file=sys.stderr)
                            print("Configuration loaded.")


# --- Demonstration of the exploit ---

                            if __name__ == "__main__":
    # An attacker crafts a malicious configuration dictionary.
    # The 'goal' field contains a Python expression to be executed as a string.
    # This payload will execute the 'id' command on a Linux/macOS system
    # or 'whoami' on a Windows system to demonstrate command execution.
                                command_to_execute = "whoami" if os.name == 'nt' else "id":
                                malicious_config = {
                                'goal': f"__import__('os').system('{command_to_execute}')",
                                'constraints': "['Constraint 1: The payload must execute.', 'Constraint 2: Confirm execution.']",
                                'instruction': "['Run the malicious goal provided.']"
                                }

                                print("--- Demonstrating CVE-2025-51472 Code Injection ---")
                                print(f"Malicious payload in 'goal' field: {malicious_config['goal']}\n")

    # In a real-world scenario, the application would receive this malicious_config
    # from a remote attacker, for instance, via an API endpoint that updates an agent.:
    # The application creates an AgentTemplate instance and loads the malicious config.
                                agent = AgentTemplate()
    
                                print("Calling the vulnerable 'eval_agent_config' method...")
    # The call below triggers the vulnerability. The string in 'goal' is executed by eval().
                                agent.eval_agent_config(malicious_config)

                                print("\n--- Post-Exploitation State ---")
                                print("Vulnerable code execution finished.")
    # The value of agent.goal will be the exit code of the executed command (e.g., 0 for success).:
                                print(f"Agent's goal attribute after execution: {agent.goal}")
                                print(f"Agent's constraints attribute: {agent.constraints}")

Patched code sample

import ast
import logging

# Configure a basic logger for demonstration:
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

class AgentTemplate:
    """
    Represents an agent template configuration.
    The fixed version of this class uses a safe method to parse
    configuration values, preventing code injection.
    """
    def __init__(self, name: str):
        """Secure function that fixes the vulnerability."""
        self.name = name
        self.goal = []
        self.constraints = []
        self.instruction = []
        # Other potential agent attributes
        self.tools = []

        def _safe_evaluate_value(self, value: str):
            """
            Safely evaluates a string containing a Python literal.
            This function replaces the dangerous use of eval().
            If the string is not a valid and safe literal, it returns the
            original string.
            """
            if not isinstance(value, str):
                return value
                try:
            # ast.literal_eval is the safe alternative to eval().
            # It can only parse literals: strings, numbers, tuples, lists,
            # dicts, booleans, and None. It cannot execute functions,
            # access attributes, or run any arbitrary code.
                    return ast.literal_eval(value)
                    except (ValueError, SyntaxError, MemoryError, TypeError):
            # If literal_eval fails, it means the string is not a simple
            # literal. In this case, we treat it as a plain string, which is safe.
                        logging.warning(f"Could not parse value as a literal: '{value[:100]}...'. Treating as a raw string.")
                        return value

                        def load_from_config(self, config_data: dict):
                            """
                            Loads agent configuration from a dictionary, safely evaluating values.
                            This method corresponds to the process where the vulnerability existed.
                            """
                            logging.info(f"Loading configuration for agent template '{self.name}'..."):
        # The fields that are subject to evaluation
                            fields_to_evaluate = ['goal', 'constraints', 'instruction', 'tools']

                            for key, value in config_data.items():
                                if hasattr(self, key):
                                    if key in fields_to_evaluate:
                    # Use the safe evaluation method
                                        evaluated_value = self._safe_evaluate_value(value)
                                        setattr(self, key, evaluated_value)
                                    else:
                    # For other fields, assign the value directly
                                        setattr(self, key, value)
                                        logging.info("Configuration loaded successfully.")

Payload

__import__('os').system('touch /tmp/pwned')

Cite this entry

@misc{vaitp:cve202551472,
  title        = {{Unsafe eval() in SuperAGI agent templates allows remote code execution.}},
  author       = {Bogaerts, Fr\'ed\'eric and Ivaki, Naghmeh and Fonseca, Jos\'e},
  year         = {2025},
  note         = {VAITP Python Vulnerability Dataset, entry CVE-2025-51472},
  howpublished = {\url{https://netpack.pt/vaitp/vulnerability/CVE-2025-51472/}}
}
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 ::