> Windows Syscalls
ntoskrnl.exeT1622T1106

NtWaitForDebugEvent

Espera el próximo evento de depuración entregado a un debug object, devolviendo un DBGUI_WAIT_STATE_CHANGE.

Prototipo

NTSTATUS NtWaitForDebugEvent(
  HANDLE                      DebugObjectHandle,
  BOOLEAN                     Alertable,
  PLARGE_INTEGER              Timeout,
  PDBGUI_WAIT_STATE_CHANGE    StateChange
);

Argumentos

NameTypeDirDescription
DebugObjectHandleHANDLEinHandle a un debug object obtenido vía NtCreateDebugObject (o DebugActiveProcess).
AlertableBOOLEANinSi TRUE la espera puede ser interrumpida por APCs de usuario (devuelve STATUS_USER_APC).
TimeoutPLARGE_INTEGERinTimeout opcional (unidades de 100 ns, negativo = relativo). NULL espera indefinidamente.
StateChangePDBGUI_WAIT_STATE_CHANGEoutRecibe el evento: NewState (CREATE_PROCESS/EXCEPTION/etc.), AppClientId y unión de payload por evento.

IDs de syscalls por versión de Windows

Versión de WindowsID de syscallBuild
Win10 15070x1B4win10-1507
Win10 16070x1BDwin10-1607
Win10 17030x1C3win10-1703
Win10 17090x1C7win10-1709
Win10 18030x1C9win10-1803
Win10 18090x1CAwin10-1809
Win10 19030x1CBwin10-1903
Win10 19090x1CBwin10-1909
Win10 20040x1D1win10-2004
Win10 20H20x1D1win10-20h2
Win10 21H10x1D1win10-21h1
Win10 21H20x1D3win10-21h2
Win10 22H20x1D3win10-22h2
Win11 21H20x1DDwin11-21h2
Win11 22H20x1E1win11-22h2
Win11 23H20x1E1win11-23h2
Win11 24H20x1E4win11-24h2
Server 20160x1BDwinserver-2016
Server 20190x1CAwinserver-2019
Server 20220x1D9winserver-2022
Server 20250x1E4winserver-2025

Módulo del kernel

ntoskrnl.exeNtWaitForDebugEvent

APIs relacionadas

WaitForDebugEventExWaitForDebugEventNtCreateDebugObjectNtDebugActiveProcessNtRemoveProcessDebugNtDebugContinueDebugActiveProcess

Stub del syscall

4C 8B D1            mov r10, rcx
B8 E4 01 00 00      mov eax, 0x1E4     ; Win11 24H2 SSN
F6 04 25 08 03 FE 7F 01   test byte ptr [0x7FFE0308], 1
75 03               jne short +3
0F 05               syscall
C3                  ret
CD 2E               int 2Eh
C3                  ret

Notas no documentadas

La primitiva del lado kernel que está bajo `WaitForDebugEventEx`. Un depurador se adjunta creando (o abriendo) un debug object con `NtCreateDebugObject` y enlazándolo a un proceso objetivo vía `NtDebugActiveProcess`, luego itera sobre `NtWaitForDebugEvent` para recibir los cambios de estado canónicos: `DbgCreateProcessStateChange`, `DbgCreateThreadStateChange`, `DbgLoadDllStateChange`, `DbgExceptionStateChange` (el grande — breakpoint, single-step, access violation), `DbgExitThreadStateChange`, `DbgExitProcessStateChange`, `DbgUnloadDllStateChange`. Cada evento debe acusarse con `NtDebugContinue`. La unión `DBGUI_WAIT_STATE_CHANGE` lleva datos específicos del evento — un CONTEXT para excepciones, base de imagen/nombre para cargas de módulo, códigos de salida, etc.

Uso común por malware

Dos formas ofensivas distintas. (1) **Anti-attach por auto-depuración**: el proceso crea un debug object, lo adjunta a sí mismo (o a un hijo que lanza), y bucla sobre `NtWaitForDebugEvent` desde un hilo worker dedicado. Como Windows permite un solo depurador por proceso, un `windbg`/`x64dbg` externo ya no puede adjuntarse — su `DebugActiveProcess` falla con `STATUS_PORT_ALREADY_SET`. Packers como Themida y varios crypters envían variantes de esto. (2) **Depurador headless** para instrumentar un hijo sin lanzar UI visible — útil para malware que necesita stepear código desempacado o reaccionar a excepciones específicas en otro binario. Del lado contrario, herramientas anti-anti-debug (TitanHide, ScyllaHide) usan las mismas primitivas para mantener viva la bucle de debug filtrando los eventos visibles al analista.

Oportunidades de detección

`NtCreateDebugObject` seguido en breve por `NtDebugActiveProcess(self_o_hijo)` y un hilo aparcado en `NtWaitForDebugEvent` es la huella canónica. ETW Microsoft-Windows-Kernel-Process emite eventos de set de debug port. El campo `EPROCESS.DebugPort` volviéndose no-NULL en un proceso que no es herramienta de desarrollador es altamente señalizante — los callbacks de kernel vía `PsSetCreateProcessNotifyRoutineEx2` y las protecciones de proceso protegido del EDR capturan esto. Desde modo usuario, `NtQueryInformationProcess` con `ProcessDebugPort`/`ProcessDebugObjectHandle` revela el adjunto, exactamente por lo que los packers congelan esa ruta con desvíos de hook.

Ejemplos de syscalls directos

cSelf-debug anti-attach worker thread

// Run in a dedicated thread spawned at startup. After this returns,
// no external debugger can attach until the debug object handle is closed.
DWORD WINAPI SelfDebugLoop(LPVOID arg) {
    HANDLE hDbg = NULL;
    OBJECT_ATTRIBUTES oa = { sizeof(oa) };
    NTSTATUS st = NtCreateDebugObject(&hDbg, DEBUG_ALL_ACCESS, &oa, 0);
    if (!NT_SUCCESS(st)) return st;

    // Attach to ourselves — blocks future DebugActiveProcess() from any other tool.
    st = NtDebugActiveProcess(NtCurrentProcess(), hDbg);
    if (!NT_SUCCESS(st)) return st;

    DBGUI_WAIT_STATE_CHANGE sc;
    for (;;) {
        st = NtWaitForDebugEvent(hDbg, FALSE, NULL, &sc);
        if (!NT_SUCCESS(st)) break;

        // Pass everything through so the debuggee keeps running.
        NtDebugContinue(hDbg, &sc.AppClientId, DBG_CONTINUE);
    }
    return 0;
}

asmx64 direct stub

; NtWaitForDebugEvent direct syscall (Win11 24H2 SSN 0x1E4)
NtWaitForDebugEvent PROC
    mov  r10, rcx
    mov  eax, 1E4h
    syscall
    ret
NtWaitForDebugEvent ENDP

rustMinimal headless debug loop

// Cargo: windows-sys = "0.59"
use windows_sys::Win32::Foundation::HANDLE;
use windows_sys::Win32::System::LibraryLoader::*;

type WaitFn = unsafe extern "system" fn(HANDLE, u8, *const i64, *mut [u8; 0xD8]) -> i32;
type ContFn = unsafe extern "system" fn(HANDLE, *const [usize; 2], i32) -> i32;

unsafe fn drain(dbg: HANDLE) {
    let nt = GetModuleHandleA(b"ntdll.dll\0".as_ptr());
    let wait: WaitFn = std::mem::transmute(
        GetProcAddress(nt, b"NtWaitForDebugEvent\0".as_ptr()).unwrap());
    let cont: ContFn = std::mem::transmute(
        GetProcAddress(nt, b"NtDebugContinue\0".as_ptr()).unwrap());
    let mut sc = [0u8; 0xD8];
    loop {
        if wait(dbg, 0, std::ptr::null(), &mut sc) < 0 { break; }
        let cid_ptr = sc.as_ptr().add(8) as *const [usize; 2]; // AppClientId
        // 0x00010002 = DBG_CONTINUE
        cont(dbg, cid_ptr, 0x00010002);
    }
}

Mapeos MITRE ATT&CK

Last verified: 2026-05-20