Jump to content
Setting up an AI agent? ReverseEngineering.wiki skill (works from the command line, no configuration): https://reverseengineering.wiki/skill/rewiki/SKILL.md · setup for every client, including MCP: https://reverseengineering.wiki/llms.txt · REWiki:Connect

Platform:Windows/Kernel drivers

From ReverseEngineering.wiki
Topic page of Platform:Windows.

Reading a Windows kernel-mode driver (.sys) as an analyst: PE with subsystem native, imports from ntoskrnl.exe/HAL/WDFLDR.SYS, INIT and PAGE sections, DriverEntry filling DRIVER_OBJECT, IRP dispatch by IRP_MJ_* index, IOCTL codes from CTL_CODE, and how KMDF drivers differ.

Overview

A Windows kernel driver is a PE file (Format:PE (Portable Executable)) loaded into kernel space. Differences from a DLL that show in a PE viewer:

  • Optional header Subsystem is 1 (IMAGE_SUBSYSTEM_NATIVE), not 2 or 3. The extension is usually .sys.
  • Imports come from ntoskrnl.exe (Ke*, Io*, Ob*, Mm*, Ex*, Zw*, Rtl*), HAL.dll (older drivers), FLTMGR.SYS, NDIS.SYS, WDFLDR.SYS (KMDF), ksecdd.sys and similar, never kernel32 or user32.
  • Entry point: with the Microsoft toolchain it is normally the stub GsDriverEntry (initialises the security cookie) which jumps to the real DriverEntry(PDRIVER_OBJECT, PUNICODE_STRING RegistryPath). The real DriverEntry is the function that stores into MajorFunction[...]. See Unverified below for other toolchains.
  • Sections: DriverEntry lives in INIT (discardable after load; the source says #pragma alloc_text(INIT, DriverEntry)), pageable dispatch routines in PAGE (#pragma alloc_text(PAGE, ...), code that may run only below DISPATCH_LEVEL), always-resident code in .text, data in .data or PAGEDATA. Section names are therefore a cheap hint at which functions are init-only and which are passive-level only.
  • Few or no exports: the DRIVER_OBJECT filled by DriverEntry is the real interface.
  • Header flags: IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY (0x0080) asks the loader to enforce signature checking of the image and WDM_DRIVER (0x2000) marks a WDM driver (Fact:PE (Portable Executable)/enum/DllCharacteristics). Unverified: which of these a given signed driver sets (check the DllCharacteristics of a sample).
  • File system filters register through the Filter Manager instead: Platform:Windows/Minifilter drivers. The driver package INF is described in Format:Windows driver INF; ETW provider manifests embedded in drivers in Format:WEVT TEMPLATE resource.

DriverEntry and DRIVER_OBJECT

A WDM driver's DriverEntry typically: (1) IoCreateDevice with a name such as \Device\Name, a device type (often FILE_DEVICE_UNKNOWN 0x22) and characteristics (FILE_DEVICE_SECURE_OPEN 0x100); (2) stores handlers into DriverObject->MajorFunction[IRP_MJ_CREATE], [IRP_MJ_CLOSE], [IRP_MJ_DEVICE_CONTROL] and sets DriverObject->DriverUnload; (3) IoCreateSymbolicLink from \DosDevices\Name (also written \??\Name) to the device name; user mode then opens it as \\.\Name with CreateFile and talks to it with DeviceIoControl. The symbolic link name is the string to look for when asking "how does user mode reach this driver" (see also the facts on this page).

In x64 disassembly the table setup is a run of stores mov [rcx+0x70+8*N], reg (rcx = DriverObject, N = the IRP_MJ index); DriverUnload is at +0x68. See the facts DRIVER_OBJECT and IRP_MJ. The I/O manager pre-fills the unset MajorFunction slots with its own invalid-request handler, so a driver that sets only CREATE, CLOSE and DEVICE_CONTROL is usually a software-only control device (the shape of most utility and tool drivers). Filter drivers instead copy or forward many slots to the lower device.

The device extension is allocated by IoCreateDevice(..., DeviceExtensionSize, ...) after the DEVICE_OBJECT; DeviceObject->DeviceExtension points at it.

IOCTL codes

CTL_CODE(DeviceType, Function, Method, Access) packs a 32-bit value: (DeviceType << 16) | (Access << 14) | (Function << 2) | Method. To decode a constant seen in a switch (IoControlCode): device type = code >> 16, access = (code >> 14) & 3, function = (code >> 2) & 0xFFF, method = code & 3. Function codes 0 to 0x7FF and device types below 0x8000 are reserved for Microsoft; third-party drivers use functions 0x800 to 0xFFF and device types 0x8000 to 0xFFFF, so a code with a high word of 0x8000 or more and a function of 0x800 or more is almost always a driver-specific IOCTL. Example from the Microsoft ioctl sample: CTL_CODE(40000, 0x902, METHOD_BUFFERED, FILE_ANY_ACCESS) = 0x9C402408 (device 0x9C40).

The method decides how the I/O manager hands buffers to the driver (lengths are in IO_STACK_LOCATION.Parameters.DeviceIoControl.InputBufferLength and OutputBufferLength):

  • METHOD_BUFFERED (0): one nonpaged copy in Irp->AssociatedIrp.SystemBuffer serves as input and as output; on completion Irp->IoStatus.Information bytes are copied back to the caller.
  • METHOD_IN_DIRECT (1) and METHOD_OUT_DIRECT (2): the input is buffered in SystemBuffer; the second buffer is locked and described by Irp->MdlAddress, which the driver maps with MmGetSystemAddressForMdlSafe. The names differ in the direction of the probe: OUT_DIRECT means the driver writes into the MDL buffer, IN_DIRECT that the driver reads from it.
  • METHOD_NEITHER (3): no copy and no probe. The input pointer is IoStack->Parameters.DeviceIoControl.Type3InputBuffer, the output pointer is Irp->UserBuffer; both are raw user addresses valid only in the caller's context, so a careful driver probes or locks them inside __try. A handler that dereferences Type3InputBuffer without probing is the classic bug to look for.

Access (FILE_ANY_ACCESS 0, FILE_READ_ACCESS 1, FILE_WRITE_ACCESS 2) is checked against the access the caller opened the handle with. It is no security boundary if any user may open the device at all; check the device security descriptor and FILE_DEVICE_SECURE_OPEN.

IRP and IO_STACK_LOCATION

A dispatch routine is NTSTATUS f(PDEVICE_OBJECT, PIRP). It gets its stack location with IoGetCurrentIrpStackLocation(Irp), which is Irp->Tail.Overlay.CurrentStackLocation (x64 offset 0xB8). Fields drivers read: MajorFunction (byte 0), MinorFunction (byte 1, for example IRP_MN_START_DEVICE 0 under IRP_MJ_PNP), and the Parameters union at +8 on x64 (+4 on x86): Read/Write.Length, DeviceIoControl.{OutputBufferLength, InputBufferLength, IoControlCode, Type3InputBuffer}. A driver completes a request by setting Irp->IoStatus.Status and Irp->IoStatus.Information then calling IofCompleteRequest(Irp, IO_NO_INCREMENT) (IoCompleteRequest is a macro for it) and returning the same status. In the Microsoft sample the IRP_MJ_DEVICE_CONTROL handler is a switch over IoControlCode with one case per IOCTL: the case labels are the driver's interface list, and the first thing to recover in a new driver.

KMDF (WDF) drivers

A KMDF driver still has a DRIVER_OBJECT, but its DriverEntry calls WdfDriverCreate and registers callbacks (EvtDriverDeviceAdd, EvtIoDeviceControl and so on) instead of setting MajorFunction itself; the framework owns the dispatch table. How to recognise and read one:

  • The import list has WdfVersionBind and WdfVersionUnbind from WDFLDR.SYS and few other imports, because framework calls go through a table.
  • The linked-in stub (the PE entry point, FxDriverEntry style) calls WdfVersionBind(DriverObject, RegistryPath, &WDF_BIND_INFO, &ComponentGlobals). The bind info carries the requested framework version (Major 1 for KMDF, Minor such as 15 to 33), the function count and the FuncTable pointer the loader fills in. The stub then calls the author's DriverEntry. The headers name the stored table WdfFunctions_010NN (NN = KMDF minor version) and the context WdfDriverGlobals.
  • Each framework call in the headers is ((PFN_WDFxxx) WdfFunctions[WdfxxxTableIndex])(WdfDriverGlobals, args...). In disassembly: load the table pointer, call [table + 8*index] with the globals in the first argument (rcx on x64). The index is the enum in the version's wdffuncenum.h; indexes change between KMDF versions, so use the version found in the bind info. Anchors in KMDF 1.33 (458 entries): WdfDeviceCreate 75, WdfDriverCreate 116, WdfIoQueueCreate 152, WdfRequestComplete 263, WdfRequestRetrieveInputBuffer 269, WdfRequestRetrieveOutputBuffer 270 (fact WDFFUNCENUM).
  • IOCTLs arrive in EvtIoDeviceControl(Queue, Request, OutputBufferLength, InputBufferLength, IoControlCode). The buffering method still applies: WdfRequestRetrieveInputBuffer and WdfRequestRetrieveOutputBuffer return the SystemBuffer or the mapped MDL, and WdfRequestRetrieveUnsafeUserInputBuffer is the METHOD_NEITHER path.
  • A software control device (no hardware, no AddDevice) is created with WdfControlDeviceInitAllocate, WdfDeviceInitAssignName, WdfDeviceCreate, WdfDeviceCreateSymbolicLink, WdfIoQueueCreate, WdfControlFinishInitializing; WdfDriverInitNonPnpDriver (0x1) in WDF_DRIVER_CONFIG.DriverInitFlags marks a driver without AddDevice.
  • UMDF drivers are DLLs hosted in a user-mode process (WUDFHost.exe), not .sys files.

Pitfalls

  • Struct offsets in the facts are x64 offsets worked out from the header declarations (natural alignment). The first fields are stable; the tail of IRP and DEVICE_OBJECT has changed between Windows releases.
  • Port/miniport models (storage, NDIS, audio, video) fill the MajorFunction table inside the class driver, not the miniport; the miniport registers callbacks in a characteristics structure instead.
  • Seeing stores into a foreign DRIVER_OBJECT (looked up by name) means hooking another driver, not this driver's own table.

Unverified

  • Unverified: the Microsoft linker sets GsDriverEntry as entry point and the author's DriverEntry is called from it. Drivers built with other toolchains (MinGW, clang with /ENTRY) enter DriverEntry directly. Check on a sample before relying on it.