how can i make this compatable with kdmapper
#include <ntifs.h>
// #include <wdm.h> // Removed to prevent redefinition
#include <stdint.h> // For fixed-width integer types like uint64_t
#include <ntddk.h>
// ==========================================================
// Definitions and Macros
// ==========================================================
typedef unsigned char BYTE;
typedef unsigned long DWORD;
#define TARGET_PROCESS_NAME L"notepad.exe" // Replace with your target process name
#define MY_WNF_STATE_NAME 0x41C64E6DA3BC1074ULL // Example WNF State Name (WNF_AUDC_CAPTURE)
// ==========================================================
// Global Function Pointers for WNF
// ==========================================================
// ==========================================================
// Function Definitions
// ==========================================================
// Get the offset for UserDirectoryTableBase based on Windows version
DWORD GetUserDirectoryTableBaseOffset()
{
RTL_OSVERSIONINFOW ver = { 0 };
RtlGetVersion(&ver);
switch (ver.dwBuildNumber)
{
case WINDOWS_1803:
case WINDOWS_1809:
return 0x0278;
case WINDOWS_1903:
case WINDOWS_1909:
return 0x0280;
case WINDOWS_2004:
case WINDOWS_20H2:
case WINDOWS_21H1:
case WINDOWS_22H2:
default:
return 0x0388;
}
}
// Retrieve the CR3 (Page Directory Base) of a process
ULONG_PTR GetProcessCr3(PEPROCESS pProcess)
{
ULONG_PTR process_dirbase_ptr = 0;
#ifdef _WIN64
process_dirbase_ptr = (ULONG_PTR)((PUCHAR)pProcess + 0x28); // Directory base for x64
#else
process_dirbase_ptr = (ULONG_PTR)((PUCHAR)pProcess + 0x18); // Directory base for x86
#endif
// Translate a virtual address to a physical address using the provided directory table base
uint64_t TranslateLinearAddress(uint64_t directoryTableBase, uint64_t virtualAddress)
{
directoryTableBase &= PMASK; // Align directoryTableBase
NTSTATUS status = STATUS_SUCCESS;
if (Buffer && BufferSize >= sizeof(INSTRUCTIONS))
{
PINSTRUCTIONS instructions = static_cast<PINSTRUCTIONS>(Buffer);
if (instructions->read)
{
// Handle read request
SIZE_T bytesRead = 0;
BYTE readBuffer[1024] = { 0 };
status = ReadProcessMemoryInternal(
(HANDLE)(ULONG_PTR)(instructions->processId),
(PVOID)(ULONG_PTR)(instructions->address),
readBuffer,
(SIZE_T)(instructions->size),
&bytesRead
);
if (NT_SUCCESS(status))
{
// Encode the read data to Base64
SIZE_T base64Size = ((bytesRead + 2) / 3) * 4;
if (base64Size + 1 > sizeof(instructions->data))
{
DbgPrint("[Driver] Read operation failed: Encoded data exceeds buffer size.\n");
status = ExPublishWnfStateData(
MY_WNF_STATE_NAME_VALUE,
"Read operation failed: Encoded data exceeds buffer size.",
(ULONG)(strlen("Read operation failed: Encoded data exceeds buffer size.") + 1),
nullptr,
nullptr,
0
);
return status;
}
CHAR encodedData[4096] = { 0 };
SIZE_T encodedLength = 0;
status = EncodeBase64(readBuffer, bytesRead, encodedData, sizeof(encodedData), &encodedLength);
if (!NT_SUCCESS(status))
{
DbgPrint("[Driver] EncodeBase64 failed with status: 0x%X\n", status);
status = ExPublishWnfStateData(
MY_WNF_STATE_NAME_VALUE,
"Read operation failed: Base64 encode failed.",
(ULONG)(strlen("Read operation failed: Base64 encode failed.") + 1),
nullptr,
nullptr,
0
);
return status;
}
// Prepare instructions to send back
RtlZeroMemory(instructions->data, sizeof(instructions->data));
RtlCopyMemory(instructions->data, encodedData, (encodedLength < sizeof(instructions->data) - 1) ? encodedLength : sizeof(instructions->data) - 1);
instructions->size = bytesRead;
// Publish the data back via WNF
status = ExPublishWnfStateData(
MY_WNF_STATE_NAME_VALUE,
instructions,
sizeof(INSTRUCTIONS),
nullptr,
nullptr,
0
);
if (NT_SUCCESS(status))
{
DbgPrint("[Driver] Read operation completed successfully. %zu bytes read, %zu bytes encoded.\n", bytesRead, encodedLength);
}
else
{
DbgPrint("[Driver] ExPublishWnfStateData failed with status: 0x%X\n", status);
}
}
else
{
// Handle read error
DbgPrint("[Driver] ReadProcessMemoryInternal failed with status: 0x%X\n", status);
status = ExPublishWnfStateData(
MY_WNF_STATE_NAME_VALUE,
"Read operation failed.",
(ULONG)(strlen("Read operation failed.") + 1),
nullptr,
nullptr,
0
);
}
}
else if (instructions->write)
{
// Handle write request
SIZE_T bytesWritten = 0;
// Decode Base64 data
UCHAR decodedData[512] = { 0 };
SIZE_T decodedSize = 0;
status = DecodeBase64(instructions->data, decodedData, sizeof(decodedData), &decodedSize);
if (!NT_SUCCESS(status))
{
DbgPrint("[Driver] DecodeBase64 failed with status: 0x%X\n", status);
status = ExPublishWnfStateData(
MY_WNF_STATE_NAME_VALUE,
"Write operation failed: Base64 decode failed.",
(ULONG)(strlen("Write operation failed: Base64 decode failed.") + 1),
nullptr,
nullptr,
0
);
return status;
}
status = WriteProcessMemoryInternal(
(HANDLE)(ULONG_PTR)(instructions->processId),
(PVOID)(ULONG_PTR)(instructions->address),
decodedData,
decodedSize,
&bytesWritten
);
if (NT_SUCCESS(status) && bytesWritten == decodedSize)
{
// Prepare instruction to send back
instructions->size = bytesWritten;
// Publish the success message back via WNF
status = ExPublishWnfStateData(
MY_WNF_STATE_NAME_VALUE,
instructions,
sizeof(INSTRUCTIONS),
nullptr,
nullptr,
0
);
DbgPrint("[Driver] Write operation completed successfully. %zu bytes written to process %llu at address 0x%llX.\n",
bytesWritten, instructions->processId, instructions->address);
}
else
{
// Handle write error
DbgPrint("[Driver] WriteProcessMemoryInternal failed with status: 0x%X and bytes written: %zu\n", status, bytesWritten);
status = ExPublishWnfStateData(
MY_WNF_STATE_NAME_VALUE,
"Write operation failed.",
(ULONG)(strlen("Write operation failed.") + 1),
nullptr,
nullptr,
0
);
}
}
else if (instructions->close)
{
// Handle close instruction
// Currently, no specific cleanup is required
DbgPrint("[Driver] Received close instruction.\n");
}
else if (instructions->reqBase)
{
// Handle base address request
PEPROCESS pProcess = nullptr;
NTSTATUS statusLookup = PsLookupProcessByProcessId((HANDLE)(ULONG_PTR)(instructions->processId), &pProcess);
if (NT_SUCCESS(statusLookup))
{
PVOID PsGetProcessSectionBaseAddress(PEPROCESS Process);
PVOID baseAddress = PsGetProcessSectionBaseAddress(pProcess);
instructions->baseAddress = (UINT64)(ULONG_PTR)baseAddress;
ObDereferenceObject(pProcess);
// Publish the base address back via WNF
status = ExPublishWnfStateData(
MY_WNF_STATE_NAME_VALUE,
instructions,
sizeof(INSTRUCTIONS),
nullptr,
nullptr,
0
);
DbgPrint("[Driver] Base address of process %llu: %p\n", instructions->processId, baseAddress);
}
else
{
// Handle error
DbgPrint("[Driver] PsLookupProcessByProcessId failed with status: 0x%X\n", statusLookup);
status = ExPublishWnfStateData(
MY_WNF_STATE_NAME_VALUE,
"Base address request failed: PsLookupProcessByProcessId failed.",
(ULONG)(strlen("Base address request failed: PsLookupProcessByProcessId failed.") + 1),
nullptr,
nullptr,
0
);
}
}
// Additional instruction handling can be added here
}
else if (Buffer && BufferSize > 0)
{
// Handle simple messages like "Hi"
// Allocate memory for received message, ensuring no buffer overflow
PCHAR receivedMessage = (PCHAR)ExAllocatePool2(POOL_FLAG_NON_PAGED, BufferSize + 1, 'msgK');
{
DbgPrint("[Driver] Failed to allocate memory for received message.\n");
return STATUS_INSUFFICIENT_RESOURCES;
}
// Zero-initialize the allocated memory
RtlZeroMemory(receivedMessage, BufferSize + 1);
// Copy the received data, ensuring not to exceed the allocated buffer
RtlCopyMemory(receivedMessage, Buffer, (BufferSize < (sizeof(CHAR) * (BufferSize))) ? BufferSize : sizeof(CHAR) * (BufferSize));
DbgPrint("[Driver] Kernel received message: %s\n", receivedMessage);
// Check if the message is 'Hi' and respond accordingly
if (strcmp(receivedMessage, "Hi") == 0)
{
// Send handshake response
const CHAR* responseMessage = "Hello from kernel mode";
status = ExPublishWnfStateData(
MY_WNF_STATE_NAME_VALUE,
(PVOID)responseMessage,
(ULONG)(strlen((char*)responseMessage) + 1),
nullptr,
nullptr,
0
);
if (NT_SUCCESS(status))
{
DbgPrint("[Driver] Handshake response sent successfully.\n");
}
else
{
DbgPrint("[Driver] Failed to send handshake response with status: 0x%X\n", status);
}
}
// Free the allocated memory for the received message
ExFreePoolWithTag(receivedMessage, 'msgK');
}
else
{
// Handle unexpected or unsupported data
DbgPrint("[Driver] Received invalid or unsupported data.\n");
}
return status;
}
// ==========================================================
// WNF Subscription Function
// ==========================================================
// Subscribe to WNF state changes
NTSTATUS SubscribeToWNF()
{
if (!ExSubscribeWnfStateChange || !ExPublishWnfStateData || !ExUnsubscribeWnfStateChange)
{
DbgPrint("[Driver] WNF function pointers not initialized.\n");
return STATUS_UNSUCCESSFUL;
}
code
// Subscribe to WNF state changes
NTSTATUS status = ExSubscribeWnfStateChange(
&g_WnfSubscription, // Address of subscription handle
MY_WNF_STATE_NAME_VALUE,
0, // ChangeStamp (0 for all changes)
OnWnfCallback,
nullptr, // CallbackContext
nullptr, // TypeId
0, // SerializationGroup
0 // Unknown
);
if (NT_SUCCESS(status))
{
DbgPrint("[Driver] Successfully subscribed to WNF state changes.\n");
}
else
{
DbgPrint("[Driver] ExSubscribeWnfStateChange failed with status: 0x%X\n", status);
}
return status;
}
// ==========================================================
// Process Notification Callback Implementation
// ==========================================================
if (Create)
{
PEPROCESS pProcess = nullptr;
NTSTATUS status = PsLookupProcessByProcessId(ProcessId, &pProcess);
if (NT_SUCCESS(status))
{
// Get process image file name
UNICODE_STRING uProcessImageName = { 0 };
PUNICODE_STRING puProcessImageName = &uProcessImageName;
status = SeLocateProcessImageName(pProcess, &puProcessImageName);
if (NT_SUCCESS(status))
{
if (uProcessImageName.Buffer != NULL) {
// Extract file name from full path
PWSTR processName = wcsrchr(uProcessImageName.Buffer, L'\\');
// Corrected backslash
if (processName)
{
processName++; // Move past the backslash
// Check if this is the target process
if (_wcsicmp(processName, TARGET_PROCESS_NAME) == 0)
{
// Perform memory operations here (if needed)
PVOID baseAddress = GetProcessBaseAddress(ProcessId);
if (baseAddress)
{
DbgPrint("[Driver] Target process '%ws' created with base address: %p\n", processName, baseAddress);
// Example: Read some memory from the process
BYTE buffer[256] = { 0 };
SIZE_T bytesRead = 0;
NTSTATUS ntStatus = ReadProcessMemoryInternal(
ProcessId,
baseAddress,
buffer,
sizeof(buffer),
&bytesRead
);
if (NT_SUCCESS(ntStatus))
{
DbgPrint("[Driver] Successfully read %zu bytes from '%ws'.\n", bytesRead, processName);
}
else
{
DbgPrint("[Driver] Failed to read memory of '%ws' with status: 0x%X\n", processName, ntStatus);
}
// Example: Write to process memory (commented out for safety)
/*
BYTE writeData[256] = { / Your data here * / };
SIZE_T bytesWritten = 0;
ntStatus = WriteProcessMemoryInternal(
ProcessId,
baseAddress,
writeData,
sizeof(writeData),
&bytesWritten
);
if (NT_SUCCESS(ntStatus))
{
DbgPrint("[Driver] Successfully wrote %zu bytes to '%ws'.\n", bytesWritten, processName);
}
else
{
DbgPrint("[Driver] Failed to write memory of '%ws' with status: 0x%X\n", processName, ntStatus);
}
*/
}
else
{
DbgPrint("[Driver] Failed to retrieve base address of process ID: %llu\n", (ULONG_PTR)ProcessId);
}
}
}
else
{
DbgPrint("[Driver] Failed to parse process name for PID: %llu\n", (ULONG_PTR)ProcessId);
}
}
// Free the allocated image name buffer
if (uProcessImageName.Buffer != NULL)
{
ExFreePoolWithTag(uProcessImageName.Buffer, 'imgN');
}
}
else
{
DbgPrint("[Driver] SeLocateProcessImageName failed with status: 0x%X for PID: %llu\n", status, (ULONG_PTR)ProcessId);
}
ObDereferenceObject(pProcess);
}
else
{
DbgPrint("[Driver] PsLookupProcessByProcessId failed with status: 0x%X for PID: %llu\n", status, (ULONG_PTR)ProcessId);
}
}
NTSTATUS status;
// Resolve WNF functions
UNICODE_STRING routineName;
RtlInitUnicodeString(&routineName, L"ExSubscribeWnfStateChange");
ExSubscribeWnfStateChange = (EXSUBSCRIBEWNFSTATECHANGE*)MmGetSystemRoutineAddress(&routineName); if (!ExSubscribeWnfStateChange)
{
DbgPrint("[Driver] ExSubscribeWnfStateChange not found.\n");
return STATUS_UNSUCCESSFUL;
}
RtlInitUnicodeString(&routineName, L"ExPublishWnfStateData");
ExPublishWnfStateData = (EXPUBLISHWNFSTATEDATA*)MmGetSystemRoutineAddress(&routineName);
if (!ExPublishWnfStateData)
{
DbgPrint("[Driver] ExPublishWnfStateData not found.\n");
return STATUS_UNSUCCESSFUL;
}
// Subscribe to WNF state changes
status = SubscribeToWNF();
if (!NT_SUCCESS(status))
{
DbgPrint("[Driver] Failed to subscribe to WNF state changes with status: 0x%X\n", status);
return status;
}
// Register the process creation notify routine
status = PsSetCreateProcessNotifyRoutine(ProcessNotifyCallback, FALSE);
if (!NT_SUCCESS(status))
{
DbgPrint("[Driver] PsSetCreateProcessNotifyRoutine failed with status: 0x%X\n", status);
// Unsubscribe from WNF before exiting
if (g_WnfSubscription && ExUnsubscribeWnfStateChange)
ExUnsubscribeWnfStateChange(g_WnfSubscription);
return status;
}
// Set the unload routine
DriverObject->DriverUnload = DriverUnloadRoutine;
// Send handshake message to user-mode
const CHAR handshakeMessage[] = "Kernel driver loaded";
status = ExPublishWnfStateData(
MY_WNF_STATE_NAME_VALUE,
(PVOID)handshakeMessage,
(ULONG)(sizeof(handshakeMessage)), // Include null terminator
nullptr,
nullptr,
0
);
if (NT_SUCCESS(status))
{
DbgPrint("[Driver] Handshake message published successfully.\n");
}
else
{
DbgPrint("[Driver] Failed to publish handshake message with status: 0x%X\n", status);
}
DbgPrint("[Driver] Driver loaded successfully.\n");
return STATUS_SUCCESS;
}
To make your driver compatible with kdmapper, you need to ensure that all the functions and imports used in your driver can be resolved when the driver is manually mapped into the kernel's memory space. Since kdmapper loads the driver without the standard Windows kernel driver loading mechanisms, certain imports (especially non-exported kernel functions) cannot be resolved in the usual way.
Here's what you need to do to make your driver compatible with kdmapper:
Avoid Using Unexported Functions Directly: Functions like ExSubscribeWnfStateChange, ExPublishWnfStateData, and ExUnsubscribeWnfStateChange are not exported by the kernel and cannot be resolved using MmGetSystemRoutineAddress. When you try to call these functions directly or use MmGetSystemRoutineAddress to resolve them, it will fail because they are not present in the kernel's export table.
Implement Dynamic Function Resolution: Since these functions are not exported, you need to resolve their addresses dynamically at runtime using methods such as scanning the kernel's memory for the function signatures or using hardcoded offsets (which is not recommended due to compatibility issues across different Windows versions).
Use Alternative Communication Methods: Instead of relying on WNF (Windows Notification Facility) functions, consider using alternative methods for communication between user-mode and kernel-mode. Common approaches include:
IOCTL (Input/Output Control) Interface: Create a device object and use IOCTL codes to communicate between user-mode applications and the driver.
Shared Memory: Allocate shared memory that both the user-mode application and driver can access.
Named Pipes or Sockets: Establish communication channels using named pipes or sockets.
Ensure All Imports Are Resolvable: Go through your driver code and make sure that all imported functions are exported by the kernel and can be resolved when the driver is manually mapped. Functions that are not exported should be dynamically resolved or avoided.
Dynamic Import Resolution Example: If you must use non-exported functions, implement a function to locate them in memory. Here's an example of how you might resolve the address of a function by scanning the kernel's memory for a known signature (this is just a conceptual example and may need adjustments):
cpp
PVOID ResolveFunctionBySignature(const UCHAR* signature, SIZE_T signatureSize)
{
// Get the base address of the kernel
PVOID ntoskrnlBase = GetKernelModuleBase(L"ntoskrnl.exe");
if (!ntoskrnlBase)
return nullptr;
// Get the size of ntoskrnl.exe
ULONG kernelSize = GetKernelModuleSize(L"ntoskrnl.exe");
if (kernelSize == 0)
return nullptr;
// Scan the kernel memory for the signature
for (SIZE_T offset = 0; offset < kernelSize - signatureSize; offset++)
{
if (RtlCompareMemory((PUCHAR)ntoskrnlBase + offset, signature, signatureSize) == signatureSize)
{
return (PUCHAR)ntoskrnlBase + offset;
}
}
return nullptr;
}
You would need to provide the correct function signature, which requires reverse engineering and can be fragile across different Windows versions.
Rewriting the Driver Without WNF: Given that dealing with unexported functions can be complex and unreliable, a better approach is to rewrite your driver to use standard communication mechanisms. Here's how you could proceed:
Create a Device Object: Modify your driver to create a device object that user-mode applications can interact with.
Implement IOCTL Handlers: Define IOCTL codes for the operations you need (e.g., read memory, write memory, get base address).
Use Standard Driver Entry Points: Implement DriverEntry, DriverUnload, and dispatch routines for IRP handling.
NTSTATUS DriverDispatchRoutine(PDEVICE_OBJECT DeviceObject, PIRP Irp)
{
PIO_STACK_LOCATION stack = IoGetCurrentIrpStackLocation(Irp);
NTSTATUS status = STATUS_SUCCESS;
switch (stack->Parameters.DeviceIoControl.IoControlCode)
{
case IOCTL_READ_MEMORY:
// Handle read memory request
break;
case IOCTL_WRITE_MEMORY:
// Handle write memory request
break;
case IOCTL_GET_BASE_ADDRESS:
// Handle get base address request
break;
default:
status = STATUS_INVALID_DEVICE_REQUEST;
break;
}
Irp->IoStatus.Status = status;
IoCompleteRequest(Irp, IO_NO_INCREMENT);
return status;
}
Set Up the Device Object and Driver Entry Point:
cpp
Test Rigorously Across Different Windows Versions: If you choose to use hardcoded offsets or signatures to resolve unexported functions, ensure that your driver is tested across all Windows versions you intend to support. Functions and their signatures may change between versions and updates.
Consider Security and Compliance: Interacting with physical memory and processes at this level can have security implications. Ensure that your driver complies with Microsoft's driver development guidelines and does not violate any security boundaries.
Avoid Known Vulnerabilities: Using kdmapper and similar techniques relies on exploiting vulnerabilities in drivers, which is not recommended for production code due to legal and security risks.
Summary:
Replace WNF functions with standard communication methods like IOCTL interfaces.
Ensure all imported functions are exported by the kernel and can be resolved when manually mapping the driver.
Remove any reliance on unexported functions or resolve them dynamically if absolutely necessary.
Test your driver thoroughly to ensure compatibility and stability.
Rewritten Driver Skeleton Without WNF:
Below is a simplified version of your driver using IOCTL communication:
Note: This is a simplified example to illustrate how to replace WNF communication with an IOCTL interface. You need to fill in the logic for handling read/write operations and ensure proper error handling and security checks.
Final Recommendations:
Use Standard Mechanisms: Prefer standard driver development practices over using undocumented or non-exported functions to ensure compatibility and stability.
Avoid Manual Mapping If Possible: While kdmapper can be useful for development and testing, relying on manual mapping techniques in production environments is not recommended.
Consult Driver Development Resources: Refer to Microsoft's official documentation and resources for driver development to ensure best practices are followed.