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
| Name | Type | Dir | Description |
|---|---|---|---|
| DebugObjectHandle | HANDLE | in | Handle a un debug object obtenido vía NtCreateDebugObject (o DebugActiveProcess). |
| Alertable | BOOLEAN | in | Si TRUE la espera puede ser interrumpida por APCs de usuario (devuelve STATUS_USER_APC). |
| Timeout | PLARGE_INTEGER | in | Timeout opcional (unidades de 100 ns, negativo = relativo). NULL espera indefinidamente. |
| StateChange | PDBGUI_WAIT_STATE_CHANGE | out | Recibe 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 Windows | ID de syscall | Build |
|---|---|---|
| Win10 1507 | 0x1B4 | win10-1507 |
| Win10 1607 | 0x1BD | win10-1607 |
| Win10 1703 | 0x1C3 | win10-1703 |
| Win10 1709 | 0x1C7 | win10-1709 |
| Win10 1803 | 0x1C9 | win10-1803 |
| Win10 1809 | 0x1CA | win10-1809 |
| Win10 1903 | 0x1CB | win10-1903 |
| Win10 1909 | 0x1CB | win10-1909 |
| Win10 2004 | 0x1D1 | win10-2004 |
| Win10 20H2 | 0x1D1 | win10-20h2 |
| Win10 21H1 | 0x1D1 | win10-21h1 |
| Win10 21H2 | 0x1D3 | win10-21h2 |
| Win10 22H2 | 0x1D3 | win10-22h2 |
| Win11 21H2 | 0x1DD | win11-21h2 |
| Win11 22H2 | 0x1E1 | win11-22h2 |
| Win11 23H2 | 0x1E1 | win11-23h2 |
| Win11 24H2 | 0x1E4 | win11-24h2 |
| Server 2016 | 0x1BD | winserver-2016 |
| Server 2019 | 0x1CA | winserver-2019 |
| Server 2022 | 0x1D9 | winserver-2022 |
| Server 2025 | 0x1E4 | winserver-2025 |
Módulo del kernel
APIs relacionadas
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 ENDPrustMinimal 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