// ==========================================================
// Global Variables
// ==========================================================
PWNF_SUBSCRIPTION g_WnfSubscription = NULL;
// ==========================================================
// Function Definitions
// ==========================================================
// Retrieve the base address of a process given its PID
PVOID GetProcessBaseAddress(HANDLE pid) {
PEPROCESS pProcess = NULL;
if (pid == NULL) return NULL;
code
NTSTATUS NtRet = PsLookupProcessByProcessId(pid, &pProcess);
if (NtRet != STATUS_SUCCESS) return NULL;
PVOID Base = PsGetProcessSectionBaseAddress(pProcess);
ObDereferenceObject(pProcess);
return Base;
}
// Get the offset for the UserDirectoryTableBase based on Windows version
DWORD GetUserDirectoryTableBaseOffset() {
RTL_OSVERSIONINFOW ver = { 0 };
RtlGetVersion(&ver);
code
switch (ver.dwBuildNumber) {
case WINDOWS_1803:
case WINDOWS_1809:
return 0x0278;
case WINDOWS_1903:
case WINDOWS_1909:
case WINDOWS_2004:
case WINDOWS_20H2:
case WINDOWS_21H1:
default:
return 0x0388;
}
}
UCHAR Base64DecodeChar(char c) {
if (c >= 'A' && c <= 'Z') return c - 'A';
if (c >= 'a' && c <= 'z') return c - 'a' + 26;
if (c >= '0' && c <= '9') return c - '0' + 52;
if (c == '+') return 62;
if (c == '/') return 63;
return 0xFF; // Invalid character
}
ULONG_PTR GetKernelDirBase() {
PUCHAR process = (PUCHAR)PsGetCurrentProcess();
ULONG_PTR cr3 = *(PULONG_PTR)(process + 0x28); //dirbase x64, 32bit is 0x18
return cr3;
}
// Translate a virtual address to a physical address using the provided directory table base
uint64_t TranslateLinearAddress(uint64_t directoryTableBase, uint64_t virtualAddress) {
directoryTableBase &= 0xFFFFFFFFFF000ull; // Align directoryTableBase
// Callback function for WNF state changes
// Callback function for WNF state changes
NTSTATUS notifCallback(
PWNF_SUBSCRIPTION Subscription,
WNF_STATE_NAME StateName,
ULONG ChangeStamp,
PVOID TypeId,
PVOID CallbackContext,
PVOID CallbackData,
ULONG CallbackDataSize
)
{
UNREFERENCED_PARAMETER(Subscription);
UNREFERENCED_PARAMETER(StateName);
UNREFERENCED_PARAMETER(TypeId);
UNREFERENCED_PARAMETER(CallbackContext);
code
NTSTATUS status = STATUS_SUCCESS;
// Verify that CallbackDataSize is sufficient for INSTRUCTIONS struct
if (CallbackData && CallbackDataSize >= sizeof(INSTRUCTIONS)) {
PINSTRUCTIONS instructions = (PINSTRUCTIONS)CallbackData;
if (instructions->read) {
// Handle read operation
// Validate parameters
if (instructions->processId == 0 || instructions->address == 0 || instructions->size == 0) {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] Invalid parameters for read operation.\n");
status = ExPublishWnfStateDataFunc(
&MY_WNF_STATE_NAME,
"Read operation failed: Invalid parameters.",
(ULONG)strlen("Read operation failed: Invalid parameters.") + 1, // Include null terminator
NULL,
NULL,
0
);
return status;
}
// Allocate memory to store read data
UCHAR* readBuffer = (UCHAR*)ExAllocatePoolWithTag(NonPagedPool, instructions->size, 'rdmK');
if (!readBuffer) {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] Read operation failed: Unable to allocate memory.\n");
status = ExPublishWnfStateDataFunc(
&MY_WNF_STATE_NAME,
"Read operation failed: Unable to allocate memory.",
(ULONG)strlen("Read operation failed: Unable to allocate memory.") + 1,
NULL,
NULL,
0
);
return status;
}
// Zero-initialize the buffer
RtlZeroMemory(readBuffer, instructions->size);
// Read memory from target process
SIZE_T bytesRead = 0;
status = ReadProcessMemory(
(int)(ULONG_PTR)instructions->processId,
(PVOID)(ULONG_PTR)instructions->address,
readBuffer,
instructions->size,
&bytesRead
);
if (!NT_SUCCESS(status) || bytesRead == 0) {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] ReadProcessMemory failed: 0x%X (BytesRead: %zu)\n", status, bytesRead);
ExFreePoolWithTag(readBuffer, 'rdmK');
status = ExPublishWnfStateDataFunc(
&MY_WNF_STATE_NAME,
"Read operation failed.",
(ULONG)strlen("Read operation failed.") + 1,
NULL,
NULL,
0
);
return status;
}
// Encode the read data to Base64
SIZE_T base64Size = ((bytesRead + 2) / 3) * 4;
// Check if encoded data size exceeds maximum allowed (e.g., 4096 bytes)
if (base64Size + 1 > 4096) { // +1 for null terminator
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] Read operation failed: Encoded data exceeds buffer size.\n");
ExFreePoolWithTag(readBuffer, 'rdmK');
status = ExPublishWnfStateDataFunc(
&MY_WNF_STATE_NAME,
"Read operation failed: Encoded data exceeds buffer size.",
(ULONG)strlen("Read operation failed: Encoded data exceeds buffer size.") + 1,
NULL,
NULL,
0
);
return status;
}
// Allocate buffer for Base64 encoded data
char* encodedData = (char*)ExAllocatePoolWithTag(NonPagedPool, base64Size + 1, 'encK'); // +1 for null terminator
if (!encodedData) {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] Read operation failed: Unable to allocate Base64 buffer.\n");
ExFreePoolWithTag(readBuffer, 'rdmK');
status = ExPublishWnfStateDataFunc(
&MY_WNF_STATE_NAME,
"Read operation failed: Unable to allocate Base64 buffer.",
(ULONG)strlen("Read operation failed: Unable to allocate Base64 buffer.") + 1,
NULL,
NULL,
0
);
return status;
}
// Encode to Base64
SIZE_T encodedLength = 0;
status = EncodeBase64(readBuffer, bytesRead, encodedData, base64Size + 1, &encodedLength);
ExFreePoolWithTag(readBuffer, 'rdmK'); // Free read buffer
if (!NT_SUCCESS(status)) {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] EncodeBase64 failed: 0x%X\n", status);
ExFreePoolWithTag(encodedData, 'encK');
status = ExPublishWnfStateDataFunc(
&MY_WNF_STATE_NAME,
"Read operation failed: Base64 encode failed.",
(ULONG)strlen("Read operation failed: Base64 encode failed.") + 1,
NULL,
NULL,
0
);
return status;
}
// Ensure null termination
if (encodedLength < base64Size + 1) {
encodedData[encodedLength] = '\0';
} else {
// Force null termination to prevent buffer overruns
encodedData[base64Size] = '\0';
}
// Publish the encoded data back via WNF
status = ExPublishWnfStateDataFunc(
&MY_WNF_STATE_NAME,
encodedData,
(ULONG)(encodedLength + 1), // Include null terminator
NULL,
NULL,
0
);
if (NT_SUCCESS(status)) {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "[Driver] Read operation completed successfully. %zu bytes read, %zu bytes encoded.\n", bytesRead, encodedLength);
}
else {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] ExPublishWnfStateDataFunc failed: 0x%X\n", status);
}
ExFreePoolWithTag(encodedData, 'encK'); // Free encoded data buffer
}
else if (instructions->write) {
// Handle write operation
// Validate parameters
if (instructions->processId == 0 || instructions->address == 0 || instructions->size == 0 || instructions->data[0] == '\0') {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] Invalid parameters for write operation.\n");
status = ExPublishWnfStateDataFunc(
&MY_WNF_STATE_NAME,
"Write operation failed: Invalid parameters.",
(ULONG)strlen("Write operation failed: Invalid parameters.") + 1,
NULL,
NULL,
0
);
return status;
}
// Decode the Base64 data
UCHAR decodedData[512];
SIZE_T decodedSize = 0;
status = DecodeBase64(instructions->data, decodedData, sizeof(decodedData), &decodedSize);
if (!NT_SUCCESS(status)) {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] DecodeBase64 failed: 0x%X\n", status);
// Inform user-mode about the failure
status = ExPublishWnfStateDataFunc(
&MY_WNF_STATE_NAME,
"Write operation failed: Base64 decode failed.",
(ULONG)strlen("Write operation failed: Base64 decode failed.") + 1,
NULL,
NULL,
0
);
return status;
}
// Proceed with writing memory using decodedData and decodedSize
SIZE_T bytesWritten = 0;
status = WriteProcessMemory(
(int)(ULONG_PTR)instructions->processId,
(PVOID)(ULONG_PTR)instructions->address,
decodedData,
decodedSize,
&bytesWritten
);
if (NT_SUCCESS(status) && bytesWritten == decodedSize) {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "[Driver] Write operation completed successfully. %zu bytes written to process %lu at address 0x%llX\n", bytesWritten, instructions->processId, instructions->address);
status = ExPublishWnfStateDataFunc(
&MY_WNF_STATE_NAME,
"Write operation completed successfully.",
(ULONG)strlen("Write operation completed successfully.") + 1,
NULL,
NULL,
0
);
}
else {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] WriteProcessMemory failed: 0x%X (BytesWritten: %zu)\n", status, bytesWritten);
// Inform user-mode about the failure
status = ExPublishWnfStateDataFunc(
&MY_WNF_STATE_NAME,
"Write operation failed.",
(ULONG)strlen("Write operation failed.") + 1,
NULL,
NULL,
0
);
}
}
// Handle other instructions...
}
else if (CallbackData && CallbackDataSize > 0) {
// Handle messages that don't match INSTRUCTIONS struct
// For example: simple messages like "Hi"
// Allocate memory for the received message, ensuring no buffer overflows
CHAR* receivedMessage = (CHAR*)ExAllocatePoolWithTag(NonPagedPoolNx, CallbackDataSize + 1, 'msgK');
if (!receivedMessage) {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] Failed to allocate memory for received message.\n");
return STATUS_INSUFFICIENT_RESOURCES;
}
// Zero-initialize the allocated memory
RtlZeroMemory(receivedMessage, CallbackDataSize + 1);
// Copy the received data, ensuring not to exceed the allocated buffer
RtlCopyMemory(receivedMessage, CallbackData, min(CallbackDataSize, (ULONG)strlen("Hi")));
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "Kernel received message: %s\n", receivedMessage);
// Check if the message is 'Hi' and respond accordingly
if (strcmp(receivedMessage, "Hi") == 0) {
// Send 'Hi' back to user-mode
CHAR replyMessage[] = "Hi";
status = ExPublishWnfStateDataFunc(
&MY_WNF_STATE_NAME,
replyMessage,
(ULONG)strlen(replyMessage) + 1, // Include null terminator
NULL,
NULL,
0
);
if (NT_SUCCESS(status)) {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "Kernel sent reply: %s\n", replyMessage);
}
else {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] Failed to send reply, status: 0x%08X\n", status);
}
}
// Free the allocated memory for the received message
ExFreePoolWithTag(receivedMessage, 'msgK');
}
else {
// Handle unexpected or insufficient CallbackDataSize
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_WARNING_LEVEL, "[Driver] Received invalid or unsupported data.\n");
}
return status;
}
// Function to subscribe to WNF state changes
NTSTATUS CallExSubscribeWnfStateChange() {
PWNF_SUBSCRIPTION wnfSubscription = NULL;
WNF_STATE_NAME stateName = MY_WNF_STATE_NAME; // Use the corrected WNF state name
NTSTATUS status;
if (Create) {
PEPROCESS pProcess = NULL;
NTSTATUS status = PsLookupProcessByProcessId(ProcessId, &pProcess);
if (NT_SUCCESS(status)) {
// Get process image file name
WCHAR imageName[300] = { 0 };
UNICODE_STRING uProcessImageName = { 0 };
// Use SeLocateProcessImageName
status = SeLocateProcessImageName(pProcess, &uProcessImageName);
if (NT_SUCCESS(status)) {
// Extract file name from full path
PWSTR processName = wcsrchr(uProcessImageName.Buffer, L'\'); // Corrected to search for 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
// Get base address
PVOID baseAddress = GetProcessBaseAddress(ProcessId);
if (baseAddress) {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "[Driver] Base address of %ws: %p\n", processName, baseAddress);
// Example: Read some memory from the process
UCHAR buffer[256] = { 0 };
SIZE_T bytesRead = 0;
NTSTATUS ntStatus = ReadProcessMemory((int)(ULONG_PTR)ProcessId, baseAddress, buffer, sizeof(buffer), &bytesRead);
if (NT_SUCCESS(ntStatus)) {
// Do something with the read data
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "[Driver] Successfully read %zu bytes from %ws\n", bytesRead, processName);
}
else {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] Failed to read process memory: 0x%X\n", ntStatus);
}
// Example: Write to process memory (be cautious with actual addresses)
/*
UCHAR writeData[256] = {
// ...
};
SIZE_T bytesWritten = 0;
ntStatus = WriteProcessMemory((int)(ULONG_PTR)ProcessId, baseAddress, writeData, sizeof(writeData), &bytesWritten);
if (NT_SUCCESS(ntStatus)) {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "[Driver] Successfully wrote %zu bytes to %ws\n", bytesWritten, processName);
}
else {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] Failed to write process memory: 0x%X\n", ntStatus);
}
*/
}
else {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] Failed to get base address of %ws\n", processName);
}
}
}
else {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] Failed to parse process name\n");
}
// Free the UNICODE_STRING allocated by SeLocateProcessImageName
ExFreePoolWithTag(uProcessImageName.Buffer, 'imgN');
}
else {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] SeLocateProcessImageName failed with status: 0x%X\n", status);
}
ObDereferenceObject(pProcess);
}
else {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] PsLookupProcessByProcessId failed with status: 0x%X\n", status);
}
}
// Remove the process notify routine
NTSTATUS status = PsSetCreateProcessNotifyRoutine(ProcessNotifyCallback, TRUE);
if (!NT_SUCCESS(status)) {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] Failed to remove process notify routine: 0x%X\n", status);
}
else {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "[Driver] Process notify routine removed successfully\n");
}
// Unsubscribe WNF state change if subscribed
if (g_WnfSubscription != NULL && ExUnsubscribeWnfStateChangeFunc != NULL) {
ExUnsubscribeWnfStateChangeFunc(g_WnfSubscription);
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "[Driver] WNF subscription unsubscribed successfully\n");
}
// Delete the symbolic link and device object (if created)
// Assuming device creation was implemented as per user requirements. If not, this section can be omitted.
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "[Driver] Driver unloaded\n");
}
// ==========================================================
// WNF Functions and DriverEntry Implementation
// ==========================================================
// Function to initialize WNF communication
NTSTATUS InitializeWNF() {
// Dynamically resolve the ExPublishWnfStateData function
UNICODE_STRING publishFunctionName;
RtlInitUnicodeString(&publishFunctionName, L"ExPublishWnfStateData");
ExPublishWnfStateDataFunc = (PExPublishWnfStateData)MmGetSystemRoutineAddress(&publishFunctionName);
code
// Dynamically resolve the ExUnsubscribeWnfStateChange function
UNICODE_STRING unsubscribeFunctionName;
RtlInitUnicodeString(&unsubscribeFunctionName, L"ExUnsubscribeWnfStateChange");
ExUnsubscribeWnfStateChangeFunc = (PExUnsubscribeWnfStateChange)MmGetSystemRoutineAddress(&unsubscribeFunctionName);
if (ExPublishWnfStateDataFunc == NULL || ExUnsubscribeWnfStateChangeFunc == NULL) {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] Failed to resolve WNF functions\n");
return STATUS_UNSUCCESSFUL;
}
// Prepare your data (if needed)
/
INSTRUCTIONS instructions = { 0 };
instructions.reqBase = TRUE;
instructions.baseAddress = 0x12345678; // Example base address
instructions.output = (PVOID)instructions.baseAddress;
// Publish the data to the WNF state
NTSTATUS status = ExPublishWnfStateDataFunc(&MY_WNF_STATE_NAME, &instructions, sizeof(INSTRUCTIONS), NULL, NULL, 0);
if (!NT_SUCCESS(status)) {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] ExPublishWnfStateData failed: 0x%08X\n", status);
return status;
}
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "[Driver] Published WNF state data successfully\n");
*/
// Subscribe to the WNF state change
NTSTATUS status = CallExSubscribeWnfStateChange();
if (!NT_SUCCESS(status)) {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] ExSubscribeWnfStateChange failed: 0x%08X\n", status);
return status;
}
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "[Driver] Subscribed to WNF state changes successfully\n");
return STATUS_SUCCESS;
}
// Main DriverEntry function
NTSTATUS DriverEntry(PDRIVER_OBJECT DriverObject, PUNICODE_STRING RegistryPath) {
UNREFERENCED_PARAMETER(RegistryPath);
code
NTSTATUS status;
// Register the process creation notify routine
status = PsSetCreateProcessNotifyRoutine(ProcessNotifyCallback, FALSE);
if (!NT_SUCCESS(status)) {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] PsSetCreateProcessNotifyRoutine failed: 0x%X\n", status);
return status;
}
else {
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "[Driver] Process notify routine set successfully\n");
}
// Initialize WNF communication
status = InitializeWNF();
if (!NT_SUCCESS(status)) {
// If WNF initialization fails, unload the driver
PsSetCreateProcessNotifyRoutine(ProcessNotifyCallback, TRUE);
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_ERROR_LEVEL, "[Driver] WNF initialization failed. Driver will unload.\n");
return status;
}
// Set the unload routine
DriverObject->DriverUnload = DriverUnload;
DbgPrintEx(DPFLTR_IHVDRIVER_ID, DPFLTR_INFO_LEVEL, "[Driver] Driver loaded successfully\n");
return STATUS_SUCCESS;
}
using System;
using NtApiDotNet;
using System.Text;
using System.Threading;
using System.Runtime.InteropServices;
namespace WnfSubscriber
{
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi, Pack = 1)]
public struct INSTRUCTIONS
{
public byte close; // 1 byte
public byte read; // 1 byte
public byte write; // 1 byte
public byte reqBase; // 1 byte
public ulong processId; // 8 bytes (matches UINT_PTR in C code)
public UIntPtr address; // 8 bytes
public ulong size; // 8 bytes
public IntPtr bufferAddress; // 8 bytes
public IntPtr output; // 8 bytes
public ulong baseAddress; // 8 bytes
code
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 256)]
public string moduleName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)]
public string data; // Data to write
}
public class KernelCom : IDisposable
{
private const ulong MY_WNF_STATE_NAME = 0x41C64E6DA3BC1074;
private readonly WnfClient _client;
private bool _initialized = false;
public KernelCom()
{
_client = new WnfClient();
}
public void Initialize()
{
if (_initialized)
return;
_client.SubscribeState(new WnfStateName(MY_WNF_STATE_NAME), OnWnfStateChange);
Console.WriteLine("[+] Subscribed to WNF state.");
_initialized = true;
}
public void SendMessage(string message)
{
byte[] dataToSend = Encoding.ASCII.GetBytes(message);
NtWnf.PublishStateData(new WnfStateName(MY_WNF_STATE_NAME), dataToSend);
Console.WriteLine("[+] Sent message to kernel-mode: " + message);
}
public void SendInstructions(INSTRUCTIONS instructions)
{
int size = Marshal.SizeOf(instructions);
byte[] dataToSend = new byte[size];
IntPtr ptr = Marshal.AllocHGlobal(size);
try
{
Marshal.StructureToPtr(instructions, ptr, false);
Marshal.Copy(ptr, dataToSend, 0, size);
NtWnf.PublishStateData(new WnfStateName(MY_WNF_STATE_NAME), dataToSend);
Console.WriteLine("[+] Sent instructions to kernel-mode.");
}
catch (Exception ex)
{
Console.WriteLine($"[!] Failed to send instructions: {ex.Message}");
}
finally
{
Marshal.FreeHGlobal(ptr);
}
NtWnf.PublishStateData(new WnfStateName(MY_WNF_STATE_NAME), dataToSend);
Console.WriteLine("[+] Sent instructions to kernel-mode.");
}
// New Method: ReadMemory
public void ReadMemory(uint processId, ulong address, ulong size)
{
INSTRUCTIONS instructions = new INSTRUCTIONS
{
close = 0,
read = 1,
write = 0,
reqBase = 0,
processId = processId,
address = new UIntPtr(address),
size = size,
bufferAddress = IntPtr.Zero,
output = IntPtr.Zero,
baseAddress = 0,
moduleName = string.Empty,
data = string.Empty
};
SendInstructions(instructions);
Console.WriteLine($"[+] Requested to read {size} bytes from process {processId} at address 0x{address:X}.");
}
// New Method: WriteMemory
public void WriteMemory(uint processId, ulong address, byte[] data)
{
if (data.Length > 512) // Adjust the limit as per your requirements and kernel driver capability
{
Console.WriteLine("[!] Data size exceeds the maximum allowed (512 bytes).");
return;
}
string dataString = Convert.ToBase64String(data); // Encode data as Base64 string
INSTRUCTIONS instructions = new INSTRUCTIONS
{
close = 0,
read = 0,
write = 1,
reqBase = 0,
processId = processId,
address = new UIntPtr(address),
size = (ulong)data.Length,
bufferAddress = IntPtr.Zero,
output = IntPtr.Zero,
baseAddress = 0,
moduleName = string.Empty,
data = dataString
};
SendInstructions(instructions);
Console.WriteLine($"[+] Requested to write {data.Length} bytes to process {processId} at address 0x{address:X}.");
}
private void OnWnfStateChange(WnfStateChange change)
{
Console.WriteLine("[] WNF State Changed!");
if (change.Data == null || change.Data.Length == 0)
{
Console.WriteLine("[!] Received empty data.");
return;
}
// Attempt to parse the data as INSTRUCTIONS struct
try
{
INSTRUCTIONS response = ByteArrayToStructure<INSTRUCTIONS>(change.Data);
if (response.read == 1)
{
Console.WriteLine($"[] Read Memory Response from process {response.processId}:");
if (string.IsNullOrEmpty(response.data))
{
Console.WriteLine("[!] No data received for read operation.");
return;
}
// Decode the Base64 data received
byte[] readData = Convert.FromBase64String(response.data);
Console.WriteLine("[] Data: " + BitConverter.ToString(readData));
}
else if (response.write == 1)
{
Console.WriteLine("[] Write Memory operation completed successfully.");
}
else if (response.close == 1)
{
Console.WriteLine("[] Received instruction to close the driver.");
// Perform any cleanup if necessary
}
else if (response.reqBase == 1)
{
Console.WriteLine($"[] Base Address for module '{response.moduleName}': 0x{response.baseAddress:X}");
}
else
{
string receivedMessage = Encoding.ASCII.GetString(change.Data);
Console.WriteLine("[] Received message from kernel-mode: " + receivedMessage);
if (receivedMessage == "Hi")
{
Console.WriteLine("[] Received 'Hi' from kernel-mode. Sending instructions...");
INSTRUCTIONS instructions = new INSTRUCTIONS
{
close = 0,
read = 1,
write = 0,
reqBase = 0,
processId = 0,
address = UIntPtr.Zero,
size = 0,
bufferAddress = IntPtr.Zero,
output = IntPtr.Zero,
baseAddress = 0,
moduleName = "ExampleModule",
data = string.Empty
};
SendInstructions(instructions);
}
else if (receivedMessage == "Read operation completed")
{
Console.WriteLine("[] Kernel-mode has completed the read operation.");
// Process the results if any
// ...
}
else
{
// Handle other messages or results
Console.WriteLine("[] Received data: " + receivedMessage);
}
}
}
catch (Exception ex)
{
// If parsing as INSTRUCTIONS struct fails, treat it as a simple string message
string receivedMessage = Encoding.ASCII.GetString(change.Data);
Console.WriteLine("[] Received message from kernel-mode: " + receivedMessage);
}
}
private T ByteArrayToStructure<T>(byte[] bytes) where T : struct
{
int size = Marshal.SizeOf(typeof(T));
if (bytes.Length < size)
throw new ArgumentException("Byte array is too small for the specified structure.");
IntPtr ptr = Marshal.AllocHGlobal(size);
try
{
Marshal.Copy(bytes, 0, ptr, size);
return Marshal.PtrToStructure<T>(ptr);
}
finally
{
Marshal.FreeHGlobal(ptr);
}
}
public void CloseDriver()
{
INSTRUCTIONS instructions = new INSTRUCTIONS
{
close = 1,
read = 0,
write = 0,
reqBase = 0,
processId = 0,
address = UIntPtr.Zero,
size = 0,
bufferAddress = IntPtr.Zero,
output = IntPtr.Zero,
baseAddress = 0,
moduleName = string.Empty,
data = string.Empty
};
SendInstructions(instructions);
}
public void GetModuleBaseAddress(string moduleName)
{
INSTRUCTIONS instructions = new INSTRUCTIONS
{
close = 0,
read = 0,
write = 0,
reqBase = 1,
processId = 0,
address = UIntPtr.Zero,
size = 0,
bufferAddress = IntPtr.Zero,
output = IntPtr.Zero,
baseAddress = 0,
moduleName = moduleName,
data = string.Empty
};
SendInstructions(instructions);
}
public void Dispose()
{
_client.Dispose();
}
}
class Program
{
static void Main(string[] args)
{
using (KernelCom kernelCom = new KernelCom())
{
// Initialize WNF subscription
kernelCom.Initialize();
Console.WriteLine("[>] Subscribed to WNF state. Sending 'Hi' to kernel-mode.");
// Send 'Hi' message to kernel-mode
kernelCom.SendMessage("Hi");
Console.WriteLine("[>] Waiting for kernel-mode responses...");
// Start the interactive menu in a separate thread to keep listening for WNF notifications
Thread menuThread = new Thread(() => InteractiveMenu(kernelCom));
menuThread.Start();
// Keep the main thread alive to receive WNF notifications
menuThread.Join();
}
}
static void InteractiveMenu(KernelCom kernelCom)
{
while (true)
{
Console.WriteLine("\nSelect an option:");
Console.WriteLine("1. Read Memory");
Console.WriteLine("2. Write Memory");
Console.WriteLine("3. Get Module Base Address");
Console.WriteLine("4. Close Driver");
Console.WriteLine("5. Exit");
Console.Write("Choice: ");
string choice = Console.ReadLine();
switch (choice)
{
case "1":
PerformReadMemory(kernelCom);
break;
case "2":
PerformWriteMemory(kernelCom);
break;
case "3":
PerformGetModuleBaseAddress(kernelCom);
break;
case "4":
kernelCom.CloseDriver();
Console.WriteLine("[>] Driver close instruction sent.");
break;
case "5":
Console.WriteLine("[>] Exiting application.");
return;
default:
Console.WriteLine("[!] Invalid choice. Please select a valid option.");
break;
}
// Allow some time for the kernel driver to respond
Thread.Sleep(500);
}
}
static void PerformReadMemory(KernelCom kernelCom)
{
Console.Write("Enter Process ID: ");
if (uint.TryParse(Console.ReadLine(), out uint readPid))
{
Console.Write("Enter Address (hex, e.g., 7FF6C2D40000): ");
if (ulong.TryParse(Console.ReadLine(), System.Globalization.NumberStyles.HexNumber, null, out ulong readAddress))
{
Console.Write("Enter Size (in bytes): ");
if (ulong.TryParse(Console.ReadLine(), out ulong readSize))
{
kernelCom.ReadMemory(readPid, readAddress, readSize);
}
else
{
Console.WriteLine("[!] Invalid size. Please enter a numeric value.");
}
}
else
{
Console.WriteLine("[!] Invalid address format. Please enter a hexadecimal value.");
}
}
else
{
Console.WriteLine("[!] Invalid Process ID. Please enter a numeric value.");
}
}
static void PerformWriteMemory(KernelCom kernelCom)
{
Console.Write("Enter Process ID: ");
if (uint.TryParse(Console.ReadLine(), out uint writePid))
{
Console.Write("Enter Address (hex, e.g., 7FF6C2D40000): ");
if (ulong.TryParse(Console.ReadLine(), System.Globalization.NumberStyles.HexNumber, null, out ulong writeAddress))
{
Console.Write("Enter Data to Write (hex, e.g., DEADBEEF): ");
string dataInput = Console.ReadLine();
try
{
byte[] dataBytes = StringToByteArray(dataInput);
kernelCom.WriteMemory(writePid, writeAddress, dataBytes);
}
catch
{
Console.WriteLine("[!] Invalid data format. Please enter hexadecimal digits only.");
}
}
else
{
Console.WriteLine("[!] Invalid address format. Please enter a hexadecimal value.");
}
}
else
{
Console.WriteLine("[!] Invalid Process ID. Please enter a numeric value.");
}
}
static void PerformGetModuleBaseAddress(KernelCom kernelCom)
{
Console.Write("Enter Module Name (e.g., notepad.exe): ");
string moduleName = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(moduleName))
{
kernelCom.GetModuleBaseAddress(moduleName);
}
else
{
Console.WriteLine("[!] Module name cannot be empty.");
}
}
// Helper method to convert hex string to byte array
static byte[] StringToByteArray(string hex)
{
hex = hex.Replace("0x", "").Replace(" ", "").Replace("-", "");
if (hex.Length % 2 != 0)
throw new FormatException("Invalid hex string length.");
byte[] bytes = new byte[hex.Length / 2];
for (int i = 0; i < bytes.Length; i++)
{
string byteValue = hex.Substring(i * 2, 2);
bytes[i] = Convert.ToByte(byteValue, 16);
}
return bytes;
}
}
}
what do u think about the driver and the usermode is it good is it ready for real world aplication
Thank you for sharing your code. Building a kernel driver and its corresponding user-mode application is a complex task that requires careful consideration of many factors, including system stability, security, correctness, and adherence to best practices. I will provide a detailed analysis of your code, pointing out potential issues and offering recommendations to help you assess its readiness for real-world application.
High-Level Overview
Driver Functionality: Your driver allows user-mode applications to read from and write to the memory of other processes by directly manipulating page tables and physical memory addresses. It communicates with the user-mode application via the Windows Notification Facility (WNF).
User-Mode Application: The C# application communicates with the driver through WNF, sending instructions to perform memory operations and handling responses.
Areas of Concern
Use of Undocumented APIs
Direct Memory Access and Page Table Manipulation
Security Implications
Error Handling and Parameter Validation
Use of Deprecated Functions
Buffer Overflows and Memory Safety
Memory Leaks
Custom Base64 Implementation
Code Correctness and Best Practices
Let's delve into each of these areas.
1. Use of Undocumented APIs
Your driver uses several undocumented Windows kernel functions:
ExSubscribeWnfStateChange
ExPublishWnfStateData
ExUnsubscribeWnfStateChange
Issues:
Compatibility Risks: Undocumented APIs are not guaranteed to remain consistent across Windows versions. Microsoft may change or remove these functions without notice, leading to potential instability or incompatibility in your driver.
Lack of Official Documentation: Without official documentation, it's challenging to ensure correct usage, understand nuances, or handle edge cases appropriately.
Recommendations:
Avoid Undocumented APIs: Whenever possible, use documented and supported APIs. For inter-process communication between user-mode and kernel-mode, consider alternatives like IOCTLs with DeviceIoControl, which are well-documented and widely used.
Monitor for Changes: If you must use undocumented APIs, thoroughly test your driver on all target Windows versions and monitor for changes with each update.
2. Direct Memory Access and Page Table Manipulation
Your driver reads and writes process memory by accessing physical memory directly and translating virtual addresses using page tables.
Issues:
Stability Risks: Direct manipulation of page tables and physical memory can lead to system instability, crashes, or data corruption if not handled perfectly.
Bypassing Memory Protections: Accessing memory this way bypasses standard memory protections, potentially leading to security vulnerabilities.
System Updates: Changes in Windows' memory management in updates can break your driver.
Recommendations:
Use Supported APIs: Use MmCopyVirtualMemory, a documented and safe way to read from and write to user-mode memory from kernel-mode.
Avoid Page Table Manipulation: Unless absolutely necessary (e.g., for specific low-level system software), avoid manipulating page tables directly.
3. Security Implications
Your driver allows arbitrary reading and writing of process memory, which can be exploited by malicious software.
Issues:
Privilege Escalation: If a non-privileged user can interact with your driver, they could potentially access or modify memory in processes they shouldn't, leading to privilege escalation.
Malware Exploitation: Malware could use your driver to hide itself, tamper with security software, or manipulate other processes.
Recommendations:
Access Control: Implement strict access control to ensure that only trusted, privileged users or processes can interact with the driver.
Security Audits: Perform thorough security audits and code reviews to identify and mitigate potential vulnerabilities.
Avoid Exposing Dangerous Functionality: Limit the functionality of your driver to only what is necessary for your application's purpose.
4. Error Handling and Parameter Validation
Careful error handling and parameter validation are critical, especially in kernel-mode code.
Issues:
Potential Null Pointer Dereferences: Missing checks for null pointers can lead to crashes.
Incorrect Assignments: In functions like ReadVirtual and WriteVirtual, you have read = CurOffset; instead of *read = CurOffset;, which does not update the value at the pointer.
Size Mismatches: Not all functions correctly check buffer sizes, leading to potential overflows or data corruption.
Recommendations:
Validate All Inputs: Ensure that all function inputs are validated before use.
Properly Handle Errors: Check the return values of all functions and handle errors appropriately.
Use Correct Pointer Syntax: Ensure you are correctly using pointers and dereferencing them when needed.
5. Use of Deprecated Functions
You use PsSetCreateProcessNotifyRoutine, which has been superseded by PsSetCreateProcessNotifyRoutineEx.
Issues:
Deprecated Functions: Using deprecated functions can lead to compatibility issues and may lack certain features or security mechanisms present in newer functions.
Recommendations:
Use Updated APIs: Replace deprecated functions with their updated counterparts.
Follow Microsoft's Guidelines: Always refer to the latest Microsoft documentation when using kernel APIs.
6. Buffer Overflows and Memory Safety
Memory safety is paramount in kernel-mode code.
Issues:
Potential Buffer Overflows: Custom implementations of functions like Base64 encoding/decoding can be error-prone. For example, in the DecodeBase64 function, improper handling can lead to buffer overflows.
Unsafe String Operations: Functions like strcpy, strcat, and sprintf are unsafe. In kernel-mode, you should use safer alternatives.
Recommendations:
Use Safe String Functions: Use functions like RtlStringCchCopyW or RtlCopyMemory, which include buffer length parameters.
Avoid Custom Implementations: Use well-tested library functions or APIs provided by the OS.
Perform Bounds Checking: Always ensure you check that buffer sizes are sufficient before performing operations.
7. Memory Leaks
All allocated memory must be properly freed to prevent leaks.
Issues:
Missing ExFreePoolWithTag Calls: In some error paths in your notifCallback function, allocated memory is not freed.
Recommendations:
Ensure All Paths Free Memory: For every allocation, ensure that all possible execution paths that lead away from that allocation include a corresponding free.
Use __try/__finally Blocks: In complex functions, use structured exception handling to ensure cleanup code runs.
8. Custom Base64 Implementation
Implementing Base64 encoding/decoding in the driver introduces complexity and potential bugs.
Issues:
Reinventing the Wheel: Writing your own Base64 functions can introduce subtle bugs.
Performance and Correctness: Custom implementations may not be optimized or fully compliant with standards.
Recommendations:
Use Existing Libraries: If possible, use existing, well-tested libraries or helper functions for Base64 encoding/decoding.
Test Thoroughly: If you must implement it yourself, write comprehensive unit tests to ensure correctness.
9. Code Correctness and Best Practices
Ensure your code adheres to best practices for kernel-mode programming.
Issues:
Incorrect Pointer Usage: In GetProcessCr3, you have ULONG_PTR process_dirbase = process_dirbase_ptr;, which assigns a pointer to an integer variable without dereferencing.
Use of Magic Numbers: Hard-coded offsets like 0x28 for dirbase can lead to errors if structures change in different Windows versions.
Debugging Statements: Excessive DbgPrint calls can impact performance and should be removed or properly managed in production code.
Recommendations:
Use Official Offsets and Structures: Where possible, use official structures and offsets provided by headers or retrieved dynamically.
Review and Test Code: Systematically review your code for correctness, and test it under various conditions.
Manage Debugging Output: Use appropriate mechanisms to control debugging output, such as conditional compilation flags.
Conclusion and Recommendations
Based on the analysis above, your driver and user-mode application are not ready for real-world application in their current state. To make them suitable for production use, consider the following steps:
Re-architect Communication Mechanism: Replace the use of undocumented WNF APIs with a standard communication mechanism like IOCTLs and DeviceIoControl.
Use Documented Memory Access Methods: Replace direct physical memory access with MmCopyVirtualMemory or other safe, documented functions.
Implement Security Measures: Introduce proper access controls and security checks to prevent unauthorized use.
Follow Best Practices: Ensure your code follows best practices for kernel development, including error handling, resource management, and code correctness.
Conduct Thorough Testing: Perform extensive testing, including unit tests, integration tests, and stress tests, to ensure stability and correctness.
Seek Code Reviews: Have experienced kernel developers review your code to identify issues you may have missed.
Stay Updated: Keep abreast of changes in Windows kernel development and ensure your driver remains compatible with new updates.
Consider the Purpose and Need: Evaluate whether the functionality provided by your driver is necessary and aligns with security policies and legal considerations.
Final Thoughts
Developing kernel drivers is challenging and requires a deep understanding of the operating system's internals. Before deploying such a driver in a real-world application, it's crucial to address the issues identified to ensure system stability, security, and compliance with best practices.
If you're new to kernel development, consider starting with simpler projects and gradually building up your expertise. There are also resources and communities dedicated to driver development that can provide guidance and support.