#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""switchcheck.py - is a target vulnerable to LDAP Switcheroo and/or reauthx (SMB)?

Both techniques are the same bug (a missing same-identity check on session
re-authentication, fixed in the Sep-2026 wave / CVE-2026-69676) carried to two
protocols:

  - reauthx (SMB)        : reflective SMB relay that survives ENFORCED SMB signing.
  - LDAP Switcheroo (LDAP): re-bind swap on a DC that survives ENFORCED LDAP signing.

So this tool checks, for one target:
  1. build / UBR -> where it sits in the SMB patch chain (#1 33073, #2 58726, #4 re-auth)
  2. SMB signing required?          (the wall reauthx walks through)
  3. cross-user re-auth swap works? (the actual bug, tested with --probe)
  4. is it a DC, and is LDAP signing required?  (the wall LDAP Switcheroo walks through)

Then it prints a per-technique verdict.

Read-only. A low-privilege account is enough for the scan; --probe needs a SECOND,
DIFFERENT low-priv account to actively test the swap. The SMB patch-window + signing
+ #4 probe logic is adapted from aas-n/reauthx patchcheck.py.

Examples:
  switchcheck.py NOVAFORGE/bob:Pass1@10.0.0.101
  switchcheck.py NOVAFORGE/bob:Pass1@10.0.0.100 --probe alice:Pass2 --dc-ip 10.0.0.100
"""
import argparse
import binascii
import os
import socket
import sys

from impacket.smbconnection import SMBConnection, SessionError
from impacket.dcerpc.v5 import transport, rrp
from impacket.smb3structs import SMB2_SESSION_SETUP, SMB2_DIALECT_30, SMB2_NEGOTIATE_SIGNING_REQUIRED
from impacket.smb3 import SMB2SessionSetup, SMB2SessionSetup_Response
from impacket.spnego import SPNEGO_NegTokenInit, SPNEGO_NegTokenResp, TypesMech
from impacket import ntlm

# ---- SMB patch tables (min fixed UBR; UBR >= value => patched), from patchcheck.py ----
P1_33073 = {
    (10, 0, 10240): 21034, (10, 0, 14393): 8148, (10, 0, 17763): 7434, (10, 0, 19044): 5965,
    (10, 0, 20348): 3807, (10, 0, 22621): 5472, (10, 0, 25398): 1665, (10, 0, 26100): 4270,
}
P2_58726 = {
    (6, 0, 6003): 23571, (6, 1, 7601): 27974, (6, 2, 9200): 25722, (6, 3, 9600): 22824,
    (10, 0, 10240): 21161, (10, 0, 14393): 8519, (10, 0, 17763): 7919, (10, 0, 19044): 6456,
    (10, 0, 20348): 4294, (10, 0, 22621): 6060, (10, 0, 25398): 1913, (10, 0, 26100): 6899,
    (10, 0, 26200): 6899,
}
P4_REAUTH = {}   # same-user re-auth (Sep 2026) - feature flag, no reliable UBR -> --probe

PATCHES = [
    ("#1", "CVE-2025-33073         client reflection (CMTI)", P1_33073),
    ("#2", "CVE-2025-58726         loopback source-IP (GhostSPN)", P2_58726),
    ("#4", "same-user re-auth      (Sep 2026, feature flag)", P4_REAUTH),
]
ORDER = [t for t, _, _ in PATCHES]

STATUS = {0x00000000: "STATUS_SUCCESS", 0xC0000016: "MORE_PROCESSING_REQUIRED",
          0xC000006D: "LOGON_FAILURE", 0xC000000D: "INVALID_PARAMETER", 0xC0000022: "ACCESS_DENIED"}

_COLOR = sys.stdout.isatty() and os.environ.get("NO_COLOR") is None


def col(code, s):
    return f"\033[{code}m{s}\033[0m" if (_COLOR and s) else s


def sname(st):
    return STATUS.get(st, f"0x{st:08X}")


def state(table, key, ubr):
    fix = table.get(key)
    if fix is None:
        return "UNKNOWN"
    return "PATCHED" if ubr >= fix else "MISSING"


def fmt_state(s):
    return {"MISSING": col("32", "absent"), "PATCHED": col("31", "patched"),
            "UNKNOWN": col("33", "unknown")}.get(s, s.lower())


# ---------- SMB helpers (adapted from patchcheck.py) ----------
def trigger_winreg(smb):
    import time
    try:
        tid = smb.connectTree("IPC$")
        try:
            smb.openFile(tid, r"\winreg", 0x12019F, creationOption=0x40, fileAttributes=0x80)
        except SessionError as e:
            if "STATUS_PIPE_NOT_AVAILABLE" not in str(e):
                raise
    except Exception:
        pass
    time.sleep(1)


def read_ubr(smb):
    rpc = transport.DCERPCTransportFactory(r"ncacn_np:445[\pipe\winreg]")
    rpc.set_smb_connection(smb)
    dce = rpc.get_dce_rpc()
    dce.connect()
    dce.bind(rrp.MSRPC_UUID_RRP)
    hroot = rrp.hOpenLocalMachine(dce)["phKey"]
    hkey = rrp.hBaseRegOpenKey(dce, hroot, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion")["phkResult"]
    ubr = rrp.hBaseRegQueryValue(dce, hkey, "UBR")[1]
    dce.disconnect()
    return ubr


def smb_signing_required(smb):
    """True = server REQUIRES SMB signing (reads real ServerSecurityMode on 3.0+)."""
    try:
        conn = smb._SMBConnection._Connection
        if conn["Dialect"] >= SMB2_DIALECT_30:
            return bool(conn["ServerSecurityMode"] & SMB2_NEGOTIATE_SIGNING_REQUIRED)
    except Exception:
        pass
    return smb.isSigningRequired()


def reauth_as(smb, user, password, domain, nthash):
    """NTLM re-auth (Type1/Type3) as `user` on the SAME SMB session. Returns the NTSTATUS."""
    t1 = ntlm.getNTLMSSPType1("", domain)
    blob = SPNEGO_NegTokenInit()
    blob["MechTypes"] = [TypesMech["NTLMSSP - Microsoft NTLM Security Support Provider"]]
    blob["MechToken"] = t1.getData()
    ss = SMB2SessionSetup()
    ss["Flags"] = 0
    ss["SecurityMode"] = 1
    ss["SecurityBufferLength"] = len(blob.getData())
    ss["Buffer"] = blob.getData()
    pkt = smb.SMB_PACKET()
    pkt["Command"] = SMB2_SESSION_SETUP
    pkt["Data"] = ss
    ans = smb.recvSMB(smb.sendSMB(pkt))
    if ans["Status"] != 0xC0000016:
        return ans["Status"]
    resp = SMB2SessionSetup_Response(ans["Data"])
    try:
        t2 = SPNEGO_NegTokenResp(resp["Buffer"])["ResponseToken"]
    except Exception:
        raw = resp["Buffer"]
        t2 = raw[raw.index(b"NTLMSSP"):]
    lm = nt = ""
    if nthash:
        lm, nt = binascii.unhexlify("aad3b435b51404eeaad3b435b51404ee"), binascii.unhexlify(nthash)
    type3, _ = ntlm.getNTLMSSPType3(t1, t2, user, password, domain, lmhash=lm, nthash=nt)
    blob2 = SPNEGO_NegTokenResp()
    blob2["ResponseToken"] = type3.getData()
    ss2 = SMB2SessionSetup()
    ss2["Flags"] = 0
    ss2["SecurityMode"] = 1
    ss2["SecurityBufferLength"] = len(blob2.getData())
    ss2["Buffer"] = blob2.getData()
    pkt2 = smb.SMB_PACKET()
    pkt2["Command"] = SMB2_SESSION_SETUP
    pkt2["Data"] = ss2
    ans2 = smb.recvSMB(smb.sendSMB(pkt2))
    return ans2["Status"]


def probe_reauth(target, domain, ua, pa, nta, ub, pb):
    conn = SMBConnection(target, target, preferredDialect=0x0311)
    conn.login(ua, pa, domain, lmhash="", nthash=(nta or ""))
    try:
        return reauth_as(conn.getSMBServer(), ub, pb, domain, "")
    finally:
        try:
            conn.close()
        except Exception:
            pass


# ---------- LDAP helpers ----------
def port_open(target, port, timeout=3):
    try:
        socket.create_connection((target, port), timeout=timeout).close()
        return True
    except Exception:
        return False


def ldap_signing_required(target, domain, username, password):
    """Test LDAP (389) signing enforcement via an UNSIGNED simple bind.

    required      : unsigned simple bind rejected with strongerAuthRequired (rc 8)
    inconclusive  : unsigned simple bind succeeds (simple binds are not governed by the policy)
    unknown       : ldap3 missing / bad creds
    Needs ldap3 (pip install ldap3). Returns (verdict, detail).
    """
    try:
        from ldap3 import Server, Connection, SIMPLE
        from ldap3.core.exceptions import LDAPBindError
    except ImportError:
        return "unknown", "ldap3 not installed (pip install ldap3)"
    user = f"{domain}\\{username}" if domain else username
    try:
        server = Server(target, port=389, use_ssl=False, get_info=None, connect_timeout=5)
        conn = Connection(server, user=user, password=password, authentication=SIMPLE)
        ok = conn.bind()
        if ok:
            conn.unbind()
            # A successful CLEARTEXT simple bind does NOT prove signing is off: the
            # "require signing" policy governs SASL (NTLM/Kerberos) binds, not simple binds.
            return "inconclusive", ("cleartext simple bind allowed - not authoritative; confirm "
                                    "with nxc ldap (signing:Enforced) or LdapRelayScan")
        rc = (conn.result or {}).get("result")
        desc = (conn.result or {}).get("description", "")
        if rc == 8:  # strongerAuthRequired
            return "required", "unsigned simple bind rejected (strongerAuthRequired)"
        if rc == 49:  # invalidCredentials
            return "unknown", "invalidCredentials - check the account/password"
        return "unknown", f"bind failed rc={rc} ({desc})"
    except LDAPBindError as e:
        return "unknown", f"bind error: {e}"
    except Exception as e:
        return "unknown", f"ldap error: {e}"


def ldaps_channel_binding(target):
    """Best-effort: is LDAPS (636) even available? EPA/channel-binding itself is
    not probed here (needs a signed+bound compare); reported as a manual check."""
    if not port_open(target, 636):
        return "no LDAPS (636) reachable - channel binding N/A"
    return "LDAPS reachable - channel binding not probed (check manually, e.g. LdapRelayScan)"


# ---------- verdicts ----------
def verdict_reauthx(smb_signing, swap):
    """swap in {MISSING, PATCHED, UNKNOWN}."""
    if swap == "PATCHED":
        return col("31", "NOT vulnerable"), "same-user re-auth check present (Sep-2026 patch) - swap blocked"
    if swap == "UNKNOWN":
        return col("33", "UNKNOWN"), "run again with --probe <2nd different account> to test the swap"
    # swap MISSING
    if smb_signing:
        return col("32", "VULNERABLE"), "enforced SMB signing bypassable (reflective relay, reauthx)"
    return col("33", "N/A (no bypass needed)"), ("SMB signing not enforced - a plain relay already works; "
                                                 "the reauthx bypass is unnecessary here")


def verdict_switcheroo(is_dc, ldap_sign, swap):
    if not is_dc:
        return col("33", "N/A"), "target is not a DC (no LDAP service) - LDAP Switcheroo does not apply"
    if swap == "PATCHED":
        return col("31", "NOT vulnerable"), "same-user re-auth check present - LDAP re-bind swap blocked"
    if swap == "UNKNOWN":
        return col("33", "UNKNOWN"), "run with --probe to confirm the swap (shared fix with the SMB side)"
    # swap MISSING
    if ldap_sign == "required":
        return col("32", "VULNERABLE"), "enforced LDAP signing bypassable (re-bind swap, LDAP Switcheroo)"
    if ldap_sign == "not required":
        return col("33", "works, but bypass untested"), ("LDAP signing not enforced - a plain ntlmrelayx to "
                                                          "LDAP already works; bypass aspect unproven")
    return col("33", "LIKELY - confirm signing"), ("swap is open; verify LDAP signing is enforced "
                                                   "(nxc ldap -> signing:Enforced). if enforced, a genuine bypass")


def parse_identity(ident):
    creds, target = ident.rsplit("@", 1)
    dom_user, _, password = creds.partition(":")
    domain, _, username = dom_user.partition("/")
    if not username:
        domain, username = "", domain
    return domain, username, password, target


def main():
    ap = argparse.ArgumentParser(
        description="switchcheck - LDAP Switcheroo + reauthx (SMB) vulnerability check for one target.",
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=(
            "Examples:\n"
            "  %(prog)s NOVAFORGE/bob:Pass1@10.0.0.101\n"
            "  %(prog)s NOVAFORGE/bob:Pass1@10.0.0.100 --probe alice:Pass2\n\n"
            "--probe tests the cross-user re-auth swap (#4). It needs a SECOND account DIFFERENT\n"
            "from the primary (privilege level does not matter). Without it, #4 = UNKNOWN."
        ),
    )
    ap.add_argument("identity", help="PRIMARY account: DOMAIN/USER:PASS@TARGET")
    ap.add_argument("--probe", metavar="USER2:PASS2", default=None,
                    help="test the swap with a 2nd account DIFFERENT from the primary")
    ap.add_argument("-H", "--hashes", default=None, metavar="LM:NT", help="NTLM hashes of the primary account")
    ap.add_argument("--no-ldap", action="store_true", help="skip the LDAP signing check")
    a = ap.parse_args()

    try:
        domain, username, password, target = parse_identity(a.identity)
    except ValueError:
        sys.exit("[-] expected format: DOMAIN/USER:PASS@TARGET")

    probe_user = probe_pass = None
    if a.probe:
        probe_user, _, probe_pass = a.probe.partition(":")
        if probe_user.lower() == username.lower():
            sys.exit("[-] --probe account must DIFFER from the primary (the swap test is cross-user).")

    nt = ""
    if a.hashes:
        _, _, nt = a.hashes.partition(":")

    smb = SMBConnection(target, target)
    try:
        smb.login(username, password, domain, "", nt)
    except Exception as e:
        sys.exit(f"[-] SMB login failed: {e}")

    major, minor, build = smb.getServerOSMajor(), smb.getServerOSMinor(), smb.getServerOSBuild()
    key = (major, minor, build)
    signing = smb_signing_required(smb)
    name = smb.getServerName()
    is_dc = port_open(target, 389)

    trigger_winreg(smb)
    ubr = None
    try:
        ubr = read_ubr(smb)
    except Exception:
        pass
    try:
        smb.close()
    except Exception:
        pass

    st = {t: (state(tbl, key, ubr) if ubr else "UNKNOWN") for t, _, tbl in PATCHES}
    # cumulative inference: a later patch can't be present if an earlier one is absent
    inferred = set()
    seen_missing = False
    for t in ORDER:
        if st[t] == "MISSING":
            seen_missing = True
        elif st[t] == "UNKNOWN" and seen_missing:
            st[t] = "MISSING"; inferred.add(t)
    seen_patched = False
    for t in reversed(ORDER):
        if st[t] == "PATCHED":
            seen_patched = True
        elif st[t] == "UNKNOWN" and seen_patched:
            st[t] = "PATCHED"; inferred.add(t)

    # --- header ---
    build_s = f"{major}.{minor}.{build}." + (str(ubr) if ubr else "?")
    print()
    print("[*] " + "   ".join([
        col("1", f"{target}"), col("1", name or "?"), "build " + build_s,
        "smb-signing:" + str(signing), "role:" + (col("36", "DC") if is_dc else "member"),
    ]))
    if not ubr:
        print("    " + col("33", "UBR unreadable - SMB patch state is inference-only"))

    # --- active swap probe (#4) ---
    if a.probe:
        try:
            code = probe_reauth(target, domain, username, password, nt, probe_user, probe_pass)
            res = {0x00000000: "MISSING", 0xC0000022: "PATCHED"}.get(code)
            if res:
                st["#4"] = res
                inferred.discard("#4")
            print(f"    probe #4  {username} -> {probe_user}   {sname(code)}")
        except Exception as e:
            print(f"    probe #4  failed: {e}")

    # --- LDAP signing (DC only) ---
    ldap_sign, ldap_detail = "n/a", ""
    cb_detail = ""
    if is_dc and not a.no_ldap:
        ldap_sign, ldap_detail = ldap_signing_required(target, domain, username, password)
        cb_detail = ldaps_channel_binding(target)
        print(f"    ldap-389  signing:{col('36', ldap_sign)}  ({ldap_detail})")
        print(f"    ldap-636  {cb_detail}")

    # --- patch table ---
    print()
    width = max(len(lbl) for _, lbl, _ in PATCHES)
    for t, lbl, _ in PATCHES:
        star = col("2", "*") if t in inferred else ""
        print(f"    {col('1', t)}  {lbl.ljust(width)}   {fmt_state(st[t])}{star}")
    if inferred:
        print("    " + col("2", "* inferred: a later patch can't be present if an earlier one is absent"))

    # --- coercion / relay hint from the chain ---
    if st["#1"] == "MISSING":
        coercion = "CMTI or Unicode confusable name"
    else:
        coercion = "Unicode confusable name (CMTI dead)"

    # --- verdicts ---
    rv, rd = verdict_reauthx(signing, st["#4"])
    sv, sd = verdict_switcheroo(is_dc, ldap_sign, st["#4"])
    print()
    print(f"[+] reauthx (SMB)       {rv}")
    print(f"      {col('2', 'why')}       {rd}")
    print(f"      {col('2', 'coercion')}  {coercion}")
    print(f"[+] LDAP Switcheroo     {sv}")
    print(f"      {col('2', 'why')}       {sd}")
    if is_dc and ldap_sign in ("unknown", "inconclusive"):
        print("      " + col("33", "note      confirm LDAP signing with nxc ldap (signing:Enforced) / LdapRelayScan"))
    print()
    print(col("2", "    reminder: a positive verdict still needs a privileged identity to coerce+relay;"))
    print(col("2", "    for reauthx the coercion must yield Kerberos (a ghost SPN != NETBIOS name) when the"))
    print(col("2", "    target enforces SMB signing. defeating signing alone is not a compromise."))
    print()


if __name__ == "__main__":
    main()