NtNotifyChangeDirectoryFileEx
Notificación extendida de cambios de directorio que permite elegir la clase FILE_NOTIFY_INFORMATION devuelta en el buffer.
Prototipo
NTSTATUS NtNotifyChangeDirectoryFileEx( HANDLE FileHandle, HANDLE Event, PIO_APC_ROUTINE ApcRoutine, PVOID ApcContext, PIO_STATUS_BLOCK IoStatusBlock, PVOID Buffer, ULONG Length, ULONG CompletionFilter, BOOLEAN WatchTree, DIRECTORY_NOTIFY_INFORMATION_CLASS DirectoryNotifyInformationClass );
Argumentos
| Name | Type | Dir | Description |
|---|---|---|---|
| FileHandle | HANDLE | in | Handle a un directorio abierto con acceso FILE_LIST_DIRECTORY. |
| Event | HANDLE | in | Evento opcional señalado al completarse. NULL si se usa un APC o una espera alertable. |
| ApcRoutine | PIO_APC_ROUTINE | in | APC en modo usuario opcional entregada al completarse en un hilo alertable. |
| ApcContext | PVOID | in | Contexto definido por el llamador pasado a ApcRoutine. |
| IoStatusBlock | PIO_STATUS_BLOCK | out | Recibe el estado final y el número de bytes escritos en Buffer. |
| Buffer | PVOID | out | Buffer alineado a DWORD que recibe registros de la clase seleccionada por DirectoryNotifyInformationClass. |
| Length | ULONG | in | Tamaño de Buffer en bytes. |
| CompletionFilter | ULONG | in | Máscara de bits FILE_NOTIFY_CHANGE_* idéntica a NtNotifyChangeDirectoryFile. |
| WatchTree | BOOLEAN | in | TRUE para vigilar todos los subdirectorios recursivamente; FALSE solo el directorio inmediato. |
| DirectoryNotifyInformationClass | DIRECTORY_NOTIFY_INFORMATION_CLASS | in | Clase de registro: DirectoryNotifyInformation (legacy) o DirectoryNotifyExtendedInformation (añade FileId, ParentFileId, timestamps). |
IDs de syscalls por versión de Windows
| Versión de Windows | ID de syscall | Build |
|---|---|---|
| Win10 1709 | 0x10F | win10-1709 |
| Win10 1803 | 0x111 | win10-1803 |
| Win10 1809 | 0x112 | win10-1809 |
| Win10 1903 | 0x113 | win10-1903 |
| Win10 1909 | 0x113 | win10-1909 |
| Win10 2004 | 0x118 | win10-2004 |
| Win10 20H2 | 0x118 | win10-20h2 |
| Win10 21H1 | 0x118 | win10-21h1 |
| Win10 21H2 | 0x119 | win10-21h2 |
| Win10 22H2 | 0x119 | win10-22h2 |
| Win11 21H2 | 0x11F | win11-21h2 |
| Win11 22H2 | 0x120 | win11-22h2 |
| Win11 23H2 | 0x120 | win11-23h2 |
| Win11 24H2 | 0x122 | win11-24h2 |
| Server 2019 | 0x112 | winserver-2019 |
| Server 2022 | 0x11E | winserver-2022 |
| Server 2025 | 0x122 | winserver-2025 |
Módulo del kernel
APIs relacionadas
Stub del syscall
4C 8B D1 mov r10, rcx B8 22 01 00 00 mov eax, 0x122 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
Añadido en Windows 10 1709 para soportar la nueva API Win32 `ReadDirectoryChangesExW`. La única adición sobre NtNotifyChangeDirectoryFile es la enumeración `DirectoryNotifyInformationClass`: pasar `DirectoryNotifyExtendedInformation` produce registros `FILE_NOTIFY_EXTENDED_INFORMATION` que incluyen `FileId`, `ParentFileId`, `CreationTime`, `LastModificationTime`, `LastChangeTime`, `LastAccessTime`, `AllocatedLength`, `FileSize` y `FileAttributes` — es decir, todo lo que el llamador necesitaría statear por archivo. Es una ganancia significativa para directorios grandes: una sola syscall devuelve lo que antes requería una notificación seguida de NtQueryInformationFile por cada entrada cambiada. Por el mínimo 1709, código que apunta a builds anteriores debe conservar fallback a NtNotifyChangeDirectoryFile.
Uso común por malware
Mismos patrones operativos que NtNotifyChangeDirectoryFile (implantes watchdog, C2 disparado por evento, detección de volúmenes nuevos durante cifrado), con una mejora específica: `DirectoryNotifyExtendedInformation` devuelve el **FileId** por cada cambio sin requerir un segundo roundtrip. Los ransomware lo usan para deduplicar trabajo en hardlinks y junctions durante cifrado multi-hilo — el worker ignora un evento si el FileId ya está en el set 'cifrado' en memoria, evitando doble pasada sobre el mismo fichero NTFS. Los campos timestamp añadidos también sirven a ciertos infostealers para filtrar cambios 'más nuevos que mi último beacon', produciendo exfils diferenciales sin pase de enumeración aparte.
Oportunidades de detección
Superficie de telemetría idéntica a NtNotifyChangeDirectoryFile — Sysmon FileCreate (Event ID 11), proveedor ETW Microsoft-Windows-Kernel-File y telemetría de handles del EDR. Un único diferenciador defensivo: las solicitudes con `DirectoryNotifyExtendedInformation` siguen siendo relativamente raras en software de terceros antiguo (la mayoría quedó en `ReadDirectoryChangesW` por compat ABI), así que un proceso que no sea Explorer, Indexer ni OneDrive pidiendo específicamente la clase extendida sobre una ruta sensible es una señal ligeramente más fuerte que la variante legacy. Útil para calibrar detectores de anomalías ML que ya consumen vectores de features por syscall.
Ejemplos de syscalls directos
asmx64 direct stub (Win11 24H2)
; Direct syscall stub for NtNotifyChangeDirectoryFileEx (SSN 0x122 on Win11 24H2)
NtNotifyChangeDirectoryFileEx PROC
mov r10, rcx ; syscall convention
mov eax, 122h ; SSN — varies per build
syscall
ret
NtNotifyChangeDirectoryFileEx ENDPcExtended class — FileId without a second query
// Use ReadDirectoryChangesExW to receive FILE_NOTIFY_EXTENDED_INFORMATION.
// One syscall returns FileId + timestamps + size in addition to the name.
#include <windows.h>
typedef struct _FILE_NOTIFY_EXTENDED_INFORMATION {
ULONG NextEntryOffset;
ULONG Action;
LARGE_INTEGER CreationTime;
LARGE_INTEGER LastModificationTime;
LARGE_INTEGER LastChangeTime;
LARGE_INTEGER LastAccessTime;
LARGE_INTEGER AllocatedLength;
LARGE_INTEGER FileSize;
ULONG FileAttributes;
ULONG ReparsePointTag;
LARGE_INTEGER FileId;
LARGE_INTEGER ParentFileId;
ULONG FileNameLength;
WCHAR FileName[1];
} FILE_NOTIFY_EXTENDED_INFORMATION;
VOID WatchExtended(HANDLE hDir, BYTE* buf, DWORD cb) {
DWORD got = 0;
while (ReadDirectoryChangesExW(hDir, buf, cb, TRUE,
FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_LAST_WRITE,
&got, NULL, NULL,
ReadDirectoryNotifyExtendedInformation)) {
FILE_NOTIFY_EXTENDED_INFORMATION* p =
(FILE_NOTIFY_EXTENDED_INFORMATION*)buf;
for (;;) {
// p->FileId is unique per NTFS volume — dedupe key
HandleChange(p);
if (!p->NextEntryOffset) break;
p = (FILE_NOTIFY_EXTENDED_INFORMATION*)((BYTE*)p + p->NextEntryOffset);
}
}
}rustDirect-syscall wrapper with class selector
// Cargo: ntapi = "0.4"
use std::ptr::null_mut;
use ntapi::ntioapi::{NtNotifyChangeDirectoryFileEx, IO_STATUS_BLOCK};
#[repr(C)]
#[allow(non_camel_case_types, dead_code)]
enum DirectoryNotifyInformationClass {
DirectoryNotifyInformation = 1,
DirectoryNotifyExtendedInformation = 2,
}
pub unsafe fn watch_extended(h_dir: isize, buf: &mut [u8]) -> i32 {
let mut iosb: IO_STATUS_BLOCK = std::mem::zeroed();
NtNotifyChangeDirectoryFileEx(
h_dir as _, null_mut(), None, null_mut(),
&mut iosb,
buf.as_mut_ptr() as _, buf.len() as u32,
0x1F, // all FILE_NOTIFY_CHANGE_* basics
1, // WatchTree = TRUE
DirectoryNotifyInformationClass::DirectoryNotifyExtendedInformation as u32,
)
}Mapeos MITRE ATT&CK
Last verified: 2026-05-20