Getting Started with Windows Kernel Drivers, a Debugging Setup and the Basics
- 1Getting Started with Windows Kernel Drivers, a Debugging Setup and the BasicsThis article
- 2Rereading 0day Security (1), Stack Overflows and Shellcode Basics
- 3Rereading 0day Security (2), the NT5 Heap, DWORD SHOOT and the First Heap Protections
- 4Rereading 0day Security (3), SEH Hijacking, Plus GS, SafeSEH and SEHOP
- 5Rereading 0day Security (4), Early Ways Around DEP and ASLR
- 6A Short History of Windows Exploit Mitigations (2000–2026)
This post is two sets of my 2020 kernel notes merged and rewritten. First came two posts on setting up a debugging environment (“Windows Kernel Debugging Notes”), then two on programming basics (“Windows Kernel Notes”). Back then my lab was Windows 7 x86 in VMware with serial-port debugging, which is long overdue for retirement in 2026, so I rewrote the setup part from scratch around network debugging (KDNET). Most of the programming part still holds up, but the code had a few bugs that would really deadlock or leak in a driver, and I’ve fixed those too.
Setting up kernel debugging today
My old setup was a VMware virtual serial port, debugging turned on in msconfig, and WinDbg talking over a named pipe. It still works, but there’s no reason to bother anymore. Since Windows 8 you can debug the kernel over the network, and KDNET sets it all up with one command. That’s a lot less fiddly than a virtual serial port.
What you need
Host machine
- Windows 10/11 x64
- Visual Studio 2022 with “Desktop development with C++”
- The Windows Driver Kit (the version that matches your VS)
- WinDbg (just install “WinDbg” from the Microsoft Store now, it’s the released version of what used to be WinDbg Preview)
Target machine
- A Windows 10/11 x64 VM
- DebugView (the old Sysinternals tool for watching
DbgPrintoutput)
Configuring KDNET
On the target, run the kdnet.exe that ships with the WDK as administrator:
kdnet.exe <host IP> <port>It prints a long debugging key, writes the debug settings into the target’s boot configuration for you, and then asks you to reboot. Every time you run it again you get a brand new key, so make sure you’re using the latest one. If the target is a VM, put its network on bridged mode or on the same NAT subnet as the host so the two can ping each other.
After the reboot, go to File -> Attach to kernel -> Net in WinDbg on the host, fill in the port and that key, and you’re connected. Set the symbol path to SRV*C:\Symbols*https://msdl.microsoft.com/download/symbols. The first connection downloads the matching PDBs, so it’s slow the first time, which is normal.
My old notes also had steps for getting a Win7 image with a VMware serial number and a Thunder download link. Those are obviously gone. Nobody needs Win7 x86 to learn the kernel today.
Turning on test signing
A driver you wrote yourself isn’t properly signed, so on the target you either turn on test mode, or change things live from WinDbg once you’re attached:
bcdedit /set testsigning onReboot after that and you’ll see a “Test Mode” watermark in the bottom right of the desktop. That’s fine for experiments in a VM. On a real machine I wouldn’t leave it on for long, because in test mode any unsigned driver can load, which means you’ve opened the last door yourself.
Looking at kernel structures through symbols
Most kernel structures aren’t documented, but Microsoft publishes PDB symbols for Windows, and with symbols WinDbg can list every field name and offset of a struct. This is the single most important thing for reading the kernel. Don’t memorize offsets, let the symbols tell you.
kd> dt nt!_EPROCESS +0x000 Pcb : _KPROCESS +0x440 UniqueProcessId : Ptr64 Void +0x448 ActiveProcessLinks : _LIST_ENTRY ...kd> dt nt!_EPROCESS -b // expand nested structskd> dt nt!_PEBThe ones I use all the time:
dtshows a struct,-bexpands it recursively,-rshows raw offsets!process 0 0lists every process with its EPROCESS address and name!pebshows a process’s PEB directlykd> ? @@(nt!_EPROCESS.ActiveProcessLinks)works out the offset of a field
Offsets change between versions, and that’s the easiest trap to fall into in kernel programming. Back then I pasted the full
dt _EPROCESSanddt _PEBoutput (hundreds of lines) across two posts. It was only valid for Win7 x86 SP1 and every bit of it is different on x64, so I’m not pasting the dumps here. Knowing how to look it up is far more useful than knowing what the number was.
A few anti-debugging spots while we’re here
It feels a bit nostalgic now, but these PEB fields are still used to check whether a process is being debugged, and you run into them all the time in malware analysis:
PEB->BeingDebugged(x86+0x002, x64+0x002) says whether the process is being debugged. User mode can change this field, so anti-debugging that relies on it alone is weakPEB->NtGlobalFlag(x86+0x068, x64+0x0BC) is normally 0. When a debugger creates the process it carriesFLG_HEAP_ENABLE_TAIL_CHECK(0x10) | FLG_HEAP_ENABLE_FREE_CHECK(0x20) | FLG_HEAP_VALIDATE_PARAMETERS(0x40), which is0x70- The heap’s
Flags/ForceFlags. Under a debugger the heap flags andForceFlagsget set to something non-zero (ForceFlagsis normally 0)
The first driver
Starting with the classic HelloWorld, of course:
#include <ntddk.h>
VOID DriverUnload(PDRIVER_OBJECT DriverObject){ DbgPrint("[%ws] Driver Unload, Driver Object Address: %p\n", __FUNCTIONW__, DriverObject);}
NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath){ DbgPrint("[%ws] Hello Kernel World!\n", __FUNCTIONW__); if (DriverObject != NULL) { DbgPrint("[%ws] Driver Object Address: %p\n", __FUNCTIONW__, DriverObject); DriverObject->DriverUnload = DriverUnload; } if (RegistryPath != NULL) { DbgPrint("[%ws] Driver Registry Path: %wZ\n", __FUNCTIONW__, RegistryPath); }
return STATUS_SUCCESS;}DriverEntry is the entry point, the driver’s main. Once you set DriverUnload, sc stop can unload it cleanly. Build it into a .sys, register it as a kernel service with sc create and then sc start, or just load it with something like the OSR loader.
Which process does a driver run in?
I was really curious about this the first time I wrote a driver, and one PsGetCurrentProcessId() answers it:
DbgPrint("[%ws] Hello Kernel World, Current Process Id=0x%p\n", __FUNCTIONW__, PsGetCurrentProcessId());In DriverEntry and in the unload callback alike, you get PID 4, the System process. System isn’t a process in the usual sense. It’s a process the system makes up to stand for the kernel, and drivers run in its context.
What this means in practice is that a driver’s context and an application’s context must be kept strictly apart. If process A is running (the CPU is in A’s virtual address space) and the driver happens to run on that same CPU, the “user-mode addresses” the driver touches are A’s. When some other process calls the same driver, those addresses point at something completely different. So the first thing a driver does with a user-mode pointer is validate it, and access it with ProbeForRead/ProbeForWrite or inside try/except. Never assume.
IRQL
Threads have priorities, and the scheduler works with time slices and priorities. The driver-level counterpart is IRQL (interrupt request level): code at a higher IRQL can interrupt and preempt code at a lower one. This is the most important idea in kernel programming, because it decides which functions you can call and which memory you can touch at a given moment.
| IRQL | Value | Typical case | What you can do |
|---|---|---|---|
| PASSIVE_LEVEL | 0 | User threads, most kernel functions | Call almost any kernel API, touch paged and nonpaged memory, wait |
| APC_LEVEL | 1 | APCs, page fault handling | Use most kernel APIs, paged memory is still fine |
| DISPATCH_LEVEL | 2 | DPCs, while holding a spinlock | Only specific APIs, nonpaged memory only, no waiting |
DriverEntry runs at PASSIVE_LEVEL, and the system guarantees that. To see the current value, call KeGetCurrentIrql(). The first time I ran it and saw 0, the table told me I was in the most relaxed state there is.
The habit to build before writing any code is to check each function’s docs for requirements like “IRQL: <= DISPATCH_LEVEL” before you call it. If they don’t match, get ready for a blue screen.
Blue-screening on purpose
When a buggy driver crashes the system, that’s the blue screen (BSOD). The usual causes come in three kinds: deadlock at high IRQL, memory access violations, and an unbalanced stack.
Sometimes your code has already landed in a state it can’t recover from. Rather than keep going and scribble all over memory, it’s better to call KeBugCheckEx and blue-screen on purpose, so at least the dump shows you the scene of the crime as it was.
Strings
The kernel represents strings as UNICODE_STRING. The length comes from the Length member, not from a '\0'.
typedef struct _UNICODE_STRING { USHORT Length; USHORT MaximumLength; PWSTR Buffer;} UNICODE_STRING, *PUNICODE_STRING;Initialize one with RtlInitUnicodeString, at IRQL <= DISPATCH_LEVEL:
UNICODE_STRING uFirstString = {0};RtlInitUnicodeString(&uFirstString, L"HelloWorld\n");DbgPrint("String:%wZ", &uFirstString);Watch out, it doesn’t allocate a Buffer. It just points Buffer at the string you passed in, so that string has to stay valid. If it’s a temporary on the stack, uFirstString becomes a dangling pointer as soon as the function returns.
To copy into a buffer you prepared yourself, use RtlUnicodeStringCopyString (include Ntstrsafe.h). It runs at PASSIVE_LEVEL and returns an NTSTATUS:
WCHAR strBuf[128] = {0};UNICODE_STRING uFirstString = {0};RtlInitEmptyUnicodeString(&uFirstString, strBuf, sizeof(strBuf));RtlUnicodeStringCopyString(&uFirstString, L"Hello Kernel\n");DbgPrint("String: %wZ", &uFirstString);Watch out, you can’t copy something too long into a “string with a fixed-size buffer”. It writes straight past the end using the length you gave it, and you get a blue screen with a memory access error. MaximumLength is a hard limit, so when you pass it in, always make sure it equals the buffer’s real size.
Linked lists
WDK lists are intrusive. You put a LIST_ENTRY inside your own struct, instead of having list nodes that hold your data.
typedef struct _LIST_ENTRY { struct _LIST_ENTRY *Flink; // next struct _LIST_ENTRY *Blink; // previous} LIST_ENTRY, *PLIST_ENTRY;
typedef struct _TestListEntry { ULONG m_ulData1; ULONG m_ulData2; LIST_ENTRY m_ListEntry; ULONG m_ulData3; ULONG m_ulData4;} TestListEntry, *PTestListEntry;There’s usually a head node that holds no data and only anchors the list.
LIST_ENTRY ListHeader = {0};InitializeListHead(&ListHeader);
InsertHeadList(&ListHeader, &Entry2.m_ListEntry);InsertHeadList(&ListHeader, &Entry1.m_ListEntry);InsertTailList(&ListHeader, &Entry3.m_ListEntry);When you walk the list, pListEntry is the address of the LIST_ENTRY, not the start of your struct, so you convert back with CONTAINING_RECORD.
PLIST_ENTRY pListEntry = ListHeader.Flink;while (pListEntry != &ListHeader){ PTestListEntry pTestEntry = CONTAINING_RECORD(pListEntry, TestListEntry, m_ListEntry); DbgPrint("ListPtr=%p, Entry=%p, Tag=%c\n", pListEntry, pTestEntry, (CHAR)pTestEntry->m_ulData1); pListEntry = pListEntry->Flink;}CONTAINING_RECORD(Address, Type, Field) means “I know where this field is, give me the whole struct”, using the field offset the compiler worked out. You see this everywhere in the kernel (ActiveProcessLinks and ThreadListHead both work this way).
Removing and checking:
RemoveHeadList/RemoveTailListreturn the removed node’s address on success, or NULL when the list is emptyRemoveEntryListremoves a given node and returns TRUE if the list is empty afterwardsIsListEmptyreturns TRUE when the list is empty
In multithreaded code, always hold a lock while walking a list. Otherwise you’re halfway through following a
Flinkwhen another CPU deletes the next node, and that’s a textbook UAF.
Spinlocks
A spinlock is the kernel’s high-IRQL lock. It protects a resource by giving one holder exclusive access.
Careful: a spinlock variable must not live on the function’s stack. If it does, it gets initialized again every time you enter the function, which is the same as having no lock at all. It has to be a global, or sit on something whose lifetime matches the lock’s, like the device extension.
KSPIN_LOCK my_spin_lock; // global
void initLock(){ KeInitializeSpinLock(&my_spin_lock);}
void TestFuncLock(){ KIRQL irql; KeAcquireSpinLock(&my_spin_lock, &irql); // critical section: IRQL has been raised to DISPATCH_LEVEL here KeReleaseSpinLock(&my_spin_lock, irql);}KeAcquireSpinLock raises the current IRQL to DISPATCH_LEVEL and saves the old value in irql, and releasing the lock puts it back. So inside the critical section you can’t touch paged memory, can’t call anything that might block, and can’t wait. That’s what the IRQL section above is actually for.
The example I wrote back then that deadlocks
In my old notes, the list section had this:
KeAcquireSpinLock(&my_spin_lock, &irql);ExInterlockedInsertHeadList(&listHead, &my_file_info.m_ListEntry, &my_spin_lock);KeReleaseSpinLock(&my_spin_lock, irql);This code locks itself up. The “Ex” in ExInterlockedInsertHeadList means “I’ll take the lock for you”, so internally it calls KeAcquireSpinLock on my_spin_lock first. But you’re already holding that same lock outside. Spinlocks aren’t reentrant, so it spins forever on the same CPU and the system just hangs there (with deadlock detection on, you get DRIVER_VERIFIER_DETECTED_VIOLATION right away).
Here are two correct ways to write it. Pick either one.
// Option 1: hold the lock yourself and use the plain list functionsKeAcquireSpinLock(&my_spin_lock, &irql);InsertHeadList(&listHead, &my_file_info.m_ListEntry);KeReleaseSpinLock(&my_spin_lock, irql);
// Option 2: don't hold it, let the Ex version take itExInterlockedInsertHeadList(&listHead, &my_file_info.m_ListEntry, &my_spin_lock);By the way, the
ExInterlocked*family is pretty much legacy on modern Windows. Microsoft’s docs also suggest plainKeAcquireSpinLockplus the normal list functions, which reads much better.
That example had a sneakier problem too. listHead and my_file_info were both local variables in the function, so as soon as the function returned, the list head and the data were just leftovers on the stack, and anything still pointing into that list was instantly invalid. Either make the list global or part of the device extension, or unlink every node before the function returns.
Queued spinlocks
On multi-CPU machines, queued spinlocks perform better and are strictly first come, first served. You initialize the lock the same way, but once it’s initialized you can’t mix the two ways of acquiring it:
KLOCK_QUEUE_HANDLE my_lock_queue_handle;KeAcquireInStackQueuedSpinLock(&my_spin_lock, &my_lock_queue_handle);// critical sectionKeReleaseInStackQueuedSpinLock(&my_lock_queue_handle);Notice that the queued lock’s handle lives on the stack. That’s allowed by design: the lock is global, and the handle on the stack only keeps track of state.
Pool memory
Plain allocation
PVOID buffer = ExAllocatePoolWithTag(NonPagedPoolNx, 512, 'tag1');if (buffer){ ExFreePoolWithTag(buffer, 'tag1');}Something to change in 2026.
ExAllocatePoolWithTaghas been deprecated since Windows 10 2004, and the official replacement isExAllocatePool2. New code should look like this:
PVOID buffer = ExAllocatePool2(POOL_FLAG_NON_PAGED, 512, 'tag1');if (buffer){ ExFreePoolWithTag(buffer, 'tag1');}ExAllocatePool2 zeroes the memory by default (no more HEAP_ZERO_MEMORY business), and it just returns NULL on bad arguments like a zero length, which is a lot more honest than the old API. The tag has to be 1 to 4 printable ASCII characters. Use the same tag for the same allocation path, because when something goes wrong, poolmon and !pool rely on it to find the culprit.
Lookaside lists
If you allocate and free blocks of the same size a lot, a lookaside list is much faster. It keeps a stash of fixed-size blocks inside itself, so you don’t go through the heap allocator every time.
My old example for this was pretty long. The logic was fine. It runs “allocate → free → allocate again” once and checks that the second allocation gets back the block you just freed. I’m only keeping the skeleton here:
PNPAGED_LOOKASIDE_LIST pLookasideList;pLookasideList = ExAllocatePool2(POOL_FLAG_NON_PAGED, sizeof(NPAGED_LOOKASIDE_LIST), 'test');ExInitializeNPagedLookasideList(pLookasideList, NULL, NULL, 0, 128, 'test', 0);
PVOID pFirstMemory = ExAllocateFromNPagedLookasideList(pLookasideList);PVOID pSecondMemory = ExAllocateFromNPagedLookasideList(pLookasideList);
ExFreeToNPagedLookasideList(pLookasideList, pFirstMemory);pFirstMemory = NULL;pFirstMemory = ExAllocateFromNPagedLookasideList(pLookasideList); // most likely the block we just freed
// cleanup: return the blocks, delete the list, then free the list itselfif (pFirstMemory != NULL) { ExFreeToNPagedLookasideList(pLookasideList, pFirstMemory); pFirstMemory = NULL; }if (pSecondMemory != NULL) { ExFreeToNPagedLookasideList(pLookasideList, pSecondMemory); pSecondMemory = NULL; }ExDeleteNPagedLookasideList(pLookasideList);ExFreePoolWithTag(pLookasideList, 'test');There’s a bug here that had to go. In my old notes, every cleanup check was written as
== NULLbefore freeing. That means “free a null pointer when the allocation failed, and leak everything that succeeded”, exactly backwards. It’s!= NULLabove now. The compiler won’t warn you about this kind of bug, but Driver Verifier’sUnsafeAllocatePooland pool tracking will catch it.
Also, if the lookaside list is a long-lived, driver-wide thing, it belongs in the device extension, set up in
DriverEntryand deleted inDriverUnload. Building and tearing it down inside a single call’sdo { } while(FALSE)makes it slower than just using the pool directly.
Kernel objects and handles
Objects that the kernel creates, manages and destroys are kernel objects. User mode gets a handle (an index into the process’s handle table). In kernel mode, to get the object itself, you turn the handle into a pointer with ObReferenceObjectByHandle.
HANDLE hCreateEvent = NULL;PVOID pCreateEventObject = NULL;OBJECT_ATTRIBUTES ObjAttr = { 0 };UNICODE_STRING uNameString = { 0 };
RtlInitUnicodeString(&uNameString, L"\\BaseNamedObjects\\TestEvent");InitializeObjectAttributes(&ObjAttr, &uNameString, OBJ_KERNEL_HANDLE | OBJ_CASE_INSENSITIVE, NULL, NULL);
NTSTATUS status = ZwCreateEvent(&hCreateEvent, EVENT_ALL_ACCESS, &ObjAttr, SynchronizationEvent, FALSE);if (!NT_SUCCESS(status)) { /* handle the failure */ }
status = ObReferenceObjectByHandle(hCreateEvent, EVENT_ALL_ACCESS, *ExEventObjectType, KernelMode, &pCreateEventObject, NULL);A few more things to keep in mind:
- Check the
NTSTATUSto see whether it worked, not whether the handle is NULL. WhenZwCreateEventfails, the handle isn’t written at all OBJ_KERNEL_HANDLEputs the handle only in the kernel handle table, so user mode can’t open it. That’s the default choice when a driver opens an objectObReferenceObjectByHandleadds a reference, and you must callObDereferenceObjectwhen you’re done, or the object never gets freed- Close the handle with
ZwCloseand drop the object reference withObDereferenceObject. Those are two separate debts
The cleanup conditions here had to be fixed as well. Back then I wrote them all backwards,
if (pCreateEventObject == NULL) ObDereferenceObject(...), which dereferences a null pointer and misses every reference that actually needed dropping. The correct cleanup is:
if (pCreateEventObject != NULL) { ObDereferenceObject(pCreateEventObject); pCreateEventObject = NULL; }if (hCreateEvent != NULL) { ZwClose(hCreateEvent); hCreateEvent = NULL; }One more small trap. Including
ntddk.handntifs.htogether causes conflicts. Putntifs.hfirst and it’s fine.
The old notes also had a “Registry” section that only introduced hives. The code was empty and marked “to be continued”, so I didn’t keep it. Reading and writing the registry from the kernel is just
ZwOpenKey/ZwQueryValueKey/ZwSetValueKeywithOBJ_KERNEL_HANDLE, the same pattern as opening the Event above.
Looking at it again today
I wrote these in 2020. Moving the lab from Win7 to Win10, the biggest change actually wasn’t the API. It was that Microsoft’s attitude toward third-party drivers had changed.
By 2020, getting a new driver signed through the hardware developer portal already required an EV certificate. And according to Microsoft’s docs, starting with Windows 10 1607 the system no longer loads any new kernel driver that hasn’t been signed through the developer portal. Signing one with a certificate of your own doesn’t cut it anymore (cross-signing had already stopped working after 2015). At the same time, HVCI (Hypervisor-protected Code Integrity, called Memory integrity in Settings) keeps spreading, and on Windows 11 a lot of machines have it on by default. It moves code integrity checks into a secure environment isolated by Hyper-V, where even the kernel can’t get around them, and that shuts down tricks like “patch kernel code, then run it” completely.
The other big thing in this area is BYOVD (Bring Your Own Vulnerable Driver). Instead of hunting for bugs in Windows itself, an attacker finds a legitimate, signed third-party driver that has its own bug, loads it, and uses that bug to do whatever they want in the kernel. Because the driver is signed, HVCI doesn’t stop it. Microsoft’s answer is a blocklist of vulnerable drivers (the Microsoft Vulnerable Driver Blocklist). It takes effect when HVCI is on and is enabled by default on Windows 11. The list gets updated once or twice a year, and it’s full of signed drivers that have been abused in the past.
So if you write a kernel driver today, getting the code right isn’t the whole job. Once a driver loads, it has the highest privilege there is, and any slip in input validation can become raw material for BYOVD. That’s also why the WDK now turns on a pile of Driver Verifier checks by default and flags old APIs like ExAllocatePool as deprecated at compile time. They’re nudging you toward code that’s hard to exploit.
Share Article
If this article helped you, please share it with others!




