> Windows Syscalls
ntoskrnl.exeT1027.011T1027T1106

NtUnlockVirtualMemory

Libera un bloqueo de working set previamente tomado por NtLockVirtualMemory.

Prototipo

NTSTATUS NtUnlockVirtualMemory(
  HANDLE  ProcessHandle,
  PVOID  *BaseAddress,
  PSIZE_T RegionSize,
  ULONG   MapType
);

Argumentos

NameTypeDirDescription
ProcessHandleHANDLEinHandle al proceso objetivo. Casi siempre NtCurrentProcess() ((HANDLE)-1).
BaseAddressPVOID*in/outPuntero a la base de la región a desbloquear. Alineado a página al retornar.
RegionSizePSIZE_Tin/outPuntero al tamaño en bytes. Redondeado a un múltiplo del tamaño de página al retornar.
MapTypeULONGinDebe coincidir con el MapType usado al bloquear — MAP_PROCESS (1) para la semántica VirtualUnlock, MAP_SYSTEM (2) para páginas fijadas en kernel.

IDs de syscalls por versión de Windows

Versión de WindowsID de syscallBuild
Win10 15070x1AEwin10-1507
Win10 16070x1B7win10-1607
Win10 17030x1BDwin10-1703
Win10 17090x1C1win10-1709
Win10 18030x1C3win10-1803
Win10 18090x1C4win10-1809
Win10 19030x1C5win10-1903
Win10 19090x1C5win10-1909
Win10 20040x1CBwin10-2004
Win10 20H20x1CBwin10-20h2
Win10 21H10x1CBwin10-21h1
Win10 21H20x1CDwin10-21h2
Win10 22H20x1CDwin10-22h2
Win11 21H20x1D7win11-21h2
Win11 22H20x1DBwin11-22h2
Win11 23H20x1DBwin11-23h2
Win11 24H20x1DEwin11-24h2
Server 20160x1B7winserver-2016
Server 20190x1C4winserver-2019
Server 20220x1D3winserver-2022
Server 20250x1DEwinserver-2025

Módulo del kernel

ntoskrnl.exeNtUnlockVirtualMemory

APIs relacionadas

VirtualUnlockVirtualLockNtLockVirtualMemoryNtFreeVirtualMemoryNtProtectVirtualMemory

Stub del syscall

4C 8B D1            mov r10, rcx
B8 DE 01 00 00      mov eax, 0x1DE
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 contraparte estricta de NtLockVirtualMemory. El SSN deriva en cada release mayor (`0x1C5` Win10 1903, `0x1CB` 2004, `0x1DE` Win11 24H2 / Server 2025). Llamarlo sobre una región no bloqueada retorna `STATUS_NOT_LOCKED` (0xC000002A) que es benigno; llamarlo con un `MapType` no coincidente retorna `STATUS_INVALID_PARAMETER`. La implementación kernel baja de nuevo el mínimo del working set del proceso, pero no pagina activamente la región — simplemente permite el trim. Prácticamente cada uso legítimo está emparejado uno a uno con un NtLockVirtualMemory previo.

Uso común por malware

El lado del despertar del patrón sleep-mask documentado en NtLockVirtualMemory. Ekko, Foliage y la familia `Sleep_Mask` Cobalt Strike usan un ciclo `Lock → Cifrar → Dormir → Descifrar → Unlock` cada intervalo de callback del beacon; el `Unlock` correspondiente libera la cuota de working set para que asignaciones posteriores no queden saturadas. Algunos packers también desbloquean la región OEP tras un timeout watchdog para reducir su huella visible en el working set. Por sí solo, NtUnlockVirtualMemory esencialmente nunca es el foco de comportamiento malicioso — su presencia es más útil como señal de *emparejamiento* junto a un NtLockVirtualMemory del mismo hilo sobre el mismo rango antes en la traza.

Oportunidades de detección

Detectar el *par*, no la llamada aislada. La secuencia clásica de alta señal dentro de un hilo: `NtAllocateVirtualMemory(RWX)` → `NtLockVirtualMemory(MAP_PROCESS)` → `NtDelayExecution(largo)` → `NtUnlockVirtualMemory` → ejecutar. Hookear el thunk user-mode VirtualUnlock y correlacionar con el sitio VirtualLock previo y los bits de protección de la asignación. Los escáneres de memoria que snapshotean la pertenencia al working set a lo largo del tiempo a veces pueden detectar el pulso lock-luego-unlock — aunque muchos EDR no retienen ese historial. Como con NtLockVirtualMemory, no hay evento ETW de primera clase; el encadenamiento de comportamiento es el camino.

Ejemplos de syscalls directos

asmx64 stub (Win11 24H2 SSN 0x1DE)

; Direct syscall stub for NtUnlockVirtualMemory
NtUnlockVirtualMemory PROC
    mov  r10, rcx          ; syscall convention
    mov  eax, 1DEh         ; SSN (Win11 24H2 / Server 2025)
    syscall
    ret
NtUnlockVirtualMemory ENDP

cWake side of an Ekko-style sleep

// Symmetric counterpart to the SleepWithLockedRegion example: after the
// caller wakes and decrypts in place, unlock so the working-set quota is
// returned and subsequent allocations aren't crowded.
#include <windows.h>

typedef NTSTATUS (NTAPI *pNtUnlockVirtualMemory)(HANDLE, PVOID*, PSIZE_T, ULONG);
#define MAP_PROCESS 1

NTSTATUS UnlockRegion(PVOID base, SIZE_T size) {
    pNtUnlockVirtualMemory NtUnlockVirtualMemory = (pNtUnlockVirtualMemory)
        GetProcAddress(GetModuleHandleA("ntdll.dll"), "NtUnlockVirtualMemory");
    PVOID  b = base;
    SIZE_T s = size;
    return NtUnlockVirtualMemory((HANDLE)-1, &b, &s, MAP_PROCESS);
}

rustRAII wrapper that pairs Lock / Unlock

// Cargo: windows-sys = "0.59" (Win32_System_Memory)
use windows_sys::Win32::System::Memory::{VirtualLock, VirtualUnlock};

pub struct Pinned { ptr: *mut u8, len: usize }

impl Pinned {
    pub fn new(p: *mut u8, len: usize) -> std::io::Result<Self> {
        if unsafe { VirtualLock(p as _, len) } == 0 {
            return Err(std::io::Error::last_os_error());
        }
        Ok(Self { ptr: p, len })
    }
}

impl Drop for Pinned {
    fn drop(&mut self) {
        // VirtualUnlock — underneath, NtUnlockVirtualMemory(MAP_PROCESS).
        unsafe { VirtualUnlock(self.ptr as _, self.len); }
    }
}

Mapeos MITRE ATT&CK

Last verified: 2026-05-20