### Example Usage: Tracing API Calls with traceapi.dll Source: https://github.com/microsoft/detours/wiki/Samples Demonstrates how to use the 'withdll' tool to load 'traceapi.dll' into a new process ('cmd.exe'). This allows for the logging of API calls made by child processes. ```bash withdll -d:traceapi.dll cmd.exe ``` -------------------------------- ### Create Process with Detour DLL Source: https://github.com/microsoft/detours/wiki/Using-Detours Starts a new process and loads a specified DLL into it using DetourCreateProcessWithDlls. This is useful for applying detours to applications without source code access. ```cpp #include #include // Function to create a process with a detour DLL void CreateProcessWithDetour(const char* processPath, const char* dllPath) { STARTUPINFOA si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); // Create the new process with the detour DLL loaded if (!DetourCreateProcessWithDllsA(processPath, NULL, NULL, NULL, FALSE, CREATE_DEFAULT_ERROR_MODE | CREATE_SUSPENDED, NULL, NULL, &si, &pi, 1, &dllPath, NULL)) { // Handle error } // Resume the main thread of the new process ResumeThread(pi.hThread); // Close process and thread handles CloseHandle(pi.hProcess); CloseHandle(pi.hThread); } ``` -------------------------------- ### Find Payload in Binary Source: https://github.com/microsoft/detours/wiki/DetourBinaryFindPayload Locates a specific payload within a binary file using its GUID. Requires a handle to the opened binary and provides the payload size upon success. ```cpp _Writable_bytes_(*pcbData) _Readable_bytes_(*pcbData) _Success_(return != NULL) PVOID DetourBinaryFindPayload( _In_ PDETOUR_BINARY pBinary, _In_ REFGUID rguid, _Out_ DWORD * pcbData ); ``` -------------------------------- ### Find Payload Address with DetourFindPayloadEx (C++) Source: https://github.com/microsoft/detours/wiki/DetourFindPayloadEx Retrieves the address and size of a specified payload within any module in the current process. It requires a GUID to identify the payload and an output parameter for its size. The function returns NULL if the payload is not found. ```cpp _Writable_bytes_(*pcbData) _Readable_bytes_(*pcbData) _Success_(return != NULL) PVOID DetourFindPayloadEx( _In_ REFGUID rguid, _Out_opt_ DWORD *pcbData ); ``` -------------------------------- ### DetourRestoreAfterWith Source: https://github.com/microsoft/detours/wiki/DetourRestoreAfterWith Restores the contents in memory import table after a process was started with DetourCreateProcessWithDllEx or DetourCreateProcessWithDlls. ```APIDOC ## DetourRestoreAfterWith ### Description Restores the contents in memory import table after a process was started with `DetourCreateProcessWithDllEx` or `DetourCreateProcessWithDlls`. ### Method ``` BOOL DetourRestoreAfterWith(VOID); ``` ### Endpoint N/A (This is a function call within a DLL, not a REST endpoint) ### Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (TRUE) Returns `TRUE` if the necessary payload was found and the restore succeeded. #### Failure Response (FALSE) Returns `FALSE` if the necessary payload was not found or the restore failed. The specific error code can be retrieved using `GetLastError`. **Error Codes** * `ERROR_MOD_NOT_FOUND`: Could not find the necessary payload. ### Remarks This function should be called in the `PROCESS_ATTACH` portion of the DllMain function of the DLL loaded into the target process. ``` -------------------------------- ### DetourFindPayload Function Signature (C++) Source: https://github.com/microsoft/detours/wiki/DetourFindPayload This C++ signature defines the DetourFindPayload function, which searches for a payload within a specified module identified by a GUID. It returns a pointer to the payload data and its size if found, otherwise NULL. ```cpp _Writable_bytes_(*pcbData) _Readable_bytes_(*pcbData) _Success_(return != NULL) PVOID DetourFindPayload( _In_opt_ HMODULE hModule, _In_ REFGUID rguid, _Out_opt_ DWORD *pcbData ); ``` -------------------------------- ### Detours Payload Management APIs Source: https://github.com/microsoft/detours/wiki/OverviewPayloads Offers functions for managing arbitrary data segments (payloads) within Windows binaries. This includes setting, enumerating, finding, and removing payloads identified by GUIDs. ```c++ #include // Example usage of DetourBinarySetPayload (details not provided in source) // DetourBinarySetPayload(...); // Example usage of DetourBinaryEnumeratePayloads (details not provided in source) // DetourBinaryEnumeratePayloads(...); // Example usage of DetourBinaryPurgePayloads (details not provided in source) // DetourBinaryPurgePayloads(...); // Example usage of DetourFindPayload (details not provided in source) // DetourFindPayload(...); // Example usage of DetourFindRemotePayload (details not provided in source) // DetourFindRemotePayload(...); // Example usage of DetourCopyPayloadToProcess (details not provided in source) // DetourCopyPayloadToProcess(...); // Example usage of DetourCopyPayloadToProcessEx (details not provided in source) // DetourCopyPayloadToProcessEx(...); ``` -------------------------------- ### Build Detours Library with NMake Source: https://github.com/microsoft/detours/wiki/FAQ These commands demonstrate how to build the Detours library and samples using `nmake`. It requires initializing the C++ toolset command line environment first. The output includes `detours.lib`, `detours.pdb`, `syelog.lib`, and header files in the `include` directory. ```shell nmake ``` ```shell nmake ``` -------------------------------- ### Build and Test Detours Samples Source: https://github.com/microsoft/detours/wiki/Samples Instructions for building and testing the sample applications using the 'nmake' utility. 'nmake' is used for compilation, and 'nmake test' is used to run the associated tests for each sample. Some samples require prerequisite builds. ```makefile nmake nmake test ``` -------------------------------- ### Remove Payload from Binary (C++) Source: https://github.com/microsoft/detours/wiki/DetourBinaryDeletePayload The DetourBinaryDeletePayload function removes a specified payload from a binary that has been opened using DetourBinaryOpen. It takes a pointer to the binary and the GUID of the payload to be removed. ```cpp BOOL DetourBinaryDeletePayload( _In_ PDETOUR_BINARY pBinary, _In_ REFGUID rguid ); ``` -------------------------------- ### Debug Detours DLL Startup with Windbg Source: https://github.com/microsoft/detours/wiki/FAQ Launches an executable with a specified DLL using Windbg for debugging the process startup. This allows for single-stepping or breaking on exceptions during initialization. ```shell windbg -o withdll.exe -d:mydll.dll myexe.exe ``` -------------------------------- ### Verify Detours Build Output Source: https://github.com/microsoft/detours/wiki/FAQ This command displays the contents of the build output directories for Detours, showing the generated libraries (`detours.lib`, `syelog.lib`) and header files (`detours.h`, `detver.h`, `syelog.h`). This helps confirm a successful build. ```shell dir /b *.x64 ``` ```shell dir /b lib.X64 ``` ```shell dir /b include ``` -------------------------------- ### COM Interface Member Function Detour Source: https://github.com/microsoft/detours/wiki/Samples An example demonstrating how to detour a member function of a COM interface. This showcases the ability to intercept and modify COM object method calls. ```c++ // ... (Detours setup for COM interface member function) ... ``` -------------------------------- ### Helper Processes for 32/64-bit Hooking Source: https://github.com/microsoft/detours/wiki/Samples Demonstrates the use of helper processes to hook both 32-bit and 64-bit target processes. This addresses cross-architecture compatibility in detouring. ```c++ // ... (Detours code for cross-architecture hooking) ... ``` -------------------------------- ### Clone Detours Repository Source: https://github.com/microsoft/detours/wiki/FAQ This command clones the Detours repository from GitHub. It's a prerequisite for building Detours and its samples. ```shell git clone https://github.com/microsoft/Detours.git ``` -------------------------------- ### Get Function Code Pointer (C++) Source: https://github.com/microsoft/detours/wiki/DetourCodeFromPointer Retrieves a pointer to the actual implementation code of a function pointed to by a function pointer. It can also optionally return the address of the function's global data. ```cpp PVOID DetourCodeFromPointer( _In_ PVOID pPointer, _Out_opt_ PVOID *ppGlobals ); ``` -------------------------------- ### APIs For Inserting DLLs and Payloads Into New Processes Source: https://github.com/microsoft/detours/wiki/Reference Functions for creating new processes and injecting DLLs or payloads into them. ```APIDOC ## DetourCreateProcessWithDllEx ### Description Creates a new process and injects a DLL into it with extended options. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourCreateProcessWithDlls ### Description Creates a new process and injects multiple DLLs into it. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourCopyPayloadToProcess ### Description Copies a payload to a target process. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourCopyPayloadToProcessEx ### Description Copies a payload to a target process with extended options. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourFinishHelperProcess ### Description Signals that a helper process has completed its task. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourIsHelperProcess ### Description Checks if the current process is a helper process. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourRestoreAfterWith ### Description Restores the original function pointers after a detour operation. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ``` -------------------------------- ### APIs For Modifying Binaries Source: https://github.com/microsoft/detours/wiki/Reference Functions for opening, manipulating, and saving changes to binary files, including payload management and import table editing. ```APIDOC ## DetourBinaryOpen ### Description Opens a binary file for modification. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourBinaryEnumeratePayloads ### Description Enumerates all payloads within an opened binary. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourBinaryFindPayload ### Description Finds a specific payload within an opened binary. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourBinarySetPayload ### Description Sets or updates a payload within an opened binary. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourBinaryDeletePayload ### Description Deletes a payload from an opened binary. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourBinaryPurgePayloads ### Description Deletes all payloads from an opened binary. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourBinaryEditImports ### Description Edits the import table of an opened binary. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourBinaryResetImports ### Description Resets the import table of an opened binary to its original state. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourBinaryWrite ### Description Writes the changes made to an opened binary back to the file. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourBinaryClose ### Description Closes an opened binary file, releasing resources. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ``` -------------------------------- ### APIs For Accessing Loaded Binaries and Payloads Source: https://github.com/microsoft/detours/wiki/Reference Functions for enumerating and retrieving information about modules, exports, imports, and payloads within loaded binaries. ```APIDOC ## DetourEnumerateModules ### Description Enumerates all loaded modules in the current process. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourGetEntryPoint ### Description Retrieves the entry point address of a loaded module. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourGetModuleSize ### Description Retrieves the size of a loaded module. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourEnumerateExports ### Description Enumerates the exported functions of a loaded module. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourEnumerateImport ### Description Enumerates the imported functions of a loaded module. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourEnumerateImportEx ### Description Enumerates the imported functions of a loaded module with extended information. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourFindPayload ### Description Finds a payload within a loaded binary. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourFindPayloadEx ### Description Finds a payload within a loaded binary with extended options. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourFindRemotePayload ### Description Finds a payload within a remote process's binary. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourGetContainingModule ### Description Retrieves the module that contains a given memory address. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourGetSizeOfPayloads ### Description Retrieves the total size of all payloads within a loaded binary. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ``` -------------------------------- ### DetourFindRemotePayload Function Signature Source: https://github.com/microsoft/detours/wiki/DetourFindRemotePayload This C++ signature defines the DetourFindRemotePayload function, which finds a specified payload within a remote process. It takes a process handle, a GUID identifying the payload, and an optional pointer to receive the data size. ```cpp _Success_(return != NULL) PVOID DetourFindRemotePayload( _In_ HANDLE hProcess, _In_ REFGUID rguid, _Out_opt_ DWORD *pcbData ); ``` -------------------------------- ### Payload Communication at Runtime Source: https://github.com/microsoft/detours/wiki/Samples Demonstrates various methods for using payloads to communicate information at runtime. This sample explores inter-process communication or data sharing mechanisms. ```c++ // ... (Detours examples for runtime payload communication) ... ``` -------------------------------- ### DetourBinarySetPayload Function Definition (C++) Source: https://github.com/microsoft/detours/wiki/DetourBinarySetPayload This C++ code snippet shows the definition of the DetourBinarySetPayload function, which is used to attach a payload to a binary. It specifies the function's parameters and their types, including pointers to binary and payload data, a GUID, and the data size. ```cpp PVOID DetourBinarySetPayload( _In_ PDETOUR_BINARY pBinary, _In_ REFGUID rguid, _In_reads_opt_(cbData) PVOID pData, _In_ DWORD cbData ); ``` -------------------------------- ### Loading Detour DLL into New Process Source: https://github.com/microsoft/detours/wiki/Samples Shows how to load a detour DLL into a new process without modifying the target application itself. This is achieved using the 'Withdll' utility. ```c++ // ... (Detours code for loading DLL into new process) ... ``` -------------------------------- ### Windows Dynamic Linking API Tracing Source: https://github.com/microsoft/detours/wiki/Samples Traces all calls to the Windows dynamic linking APIs. This sample monitors functions related to loading and unloading DLLs. ```c++ // ... (Detours code for tracing dynamic linking APIs) ... ``` -------------------------------- ### DetourBinaryEnumeratePayloads Function Signature Source: https://github.com/microsoft/detours/wiki/DetourBinaryEnumeratePayloads This C++ code snippet shows the function signature for DetourBinaryEnumeratePayloads. It is used to enumerate payloads within a binary opened by DetourBinaryOpen. It takes pointers to a binary handle, GUID, data size, and an iterator as input, and returns a pointer to the next payload or NULL. ```cpp _Writable_bytes_(*pcbData) _Readable_bytes_(*pcbData) _Success_(return != NULL) PVOID DetourBinaryEnumeratePayloads( _In_ PDETOUR_BINARY pBinary, _Out_opt_ GUID * pGuid, _Out_ DWORD * pcbData, _Inout_ DWORD * pnIterator ); ``` -------------------------------- ### DetourCreateProcessWithDllEx Source: https://github.com/microsoft/detours/wiki/DetourCreateProcessWithDllEx Creates a new process and loads a DLL into it, automatically selecting the correct 32-bit or 64-bit DLL based on the target process architecture. ```APIDOC ## DetourCreateProcessWithDllEx ### Description Creates a new process and loads a specified DLL into it. It automatically chooses the appropriate 32-bit or 64-bit DLL based on the target process architecture, replacing the functionality of `DetourCreateProcessWithDll`. ### Method N/A (This is a C++ function, not an HTTP API endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (BOOL) Returns `TRUE` if the new process was created successfully; otherwise, returns `FALSE`. #### Response Example N/A ### Details - **lpApplicationName** (LPCTSTR) - Optional: The name of the application to be executed. - **lpCommandLine** (LPTSTR) - Optional: The command line for the new process. Can be modified. - **lpProcessAttributes** (LPSECURITY_ATTRIBUTES) - Optional: Security attributes for the new process. - **lpThreadAttributes** (LPSECURITY_ATTRIBUTES) - Optional: Security attributes for the new thread. - **bInheritHandles** (BOOL) - Required: Specifies whether the new process inherits handles from the calling process. - **dwCreationFlags** (DWORD) - Required: Flags that control the creation of the process. - **lpEnvironment** (LPVOID) - Optional: The environment block for the new process. - **lpCurrentDirectory** (LPCTSTR) - Optional: The current directory for the new process. - **lpStartupInfo** (LPSTARTUPINFOW) - Required: Pointer to a STARTUPINFO structure that specifies how the main window of the process should be displayed. - **lpProcessInformation** (LPPROCESS_INFORMATION) - Out: Pointer to a PROCESS_INFORMATION structure that receives identification information about the new process and its primary thread. - **lpDllName** (LPCSTR) - Required: The path of the DLL to be inserted into the new process. Should end with "32" or "64" to indicate architecture. - **pfCreateProcessW** (PDETOUR_CREATE_PROCESS_ROUTINEW) - Optional: A pointer to a custom CreateProcess routine or NULL to use the standard CreateProcess. ### Remarks The new process is created in a suspended state. Detours modifies the process's in-memory import table to include the specified DLL. Execution is then resumed, causing the DLL to load before the application's entry point. The target DLL must export a function with ordinal #1. The `DetourRestoreAfterWith` function can be used to reverse these import table changes. ``` -------------------------------- ### File Access Pattern Tracing Source: https://github.com/microsoft/detours/wiki/Samples Traces the file access patterns of a process and all of its children. This sample monitors read/write operations and file system interactions. ```c++ // ... (Detours code for tracing file access patterns) ... ``` -------------------------------- ### FlushInstructionCache API Usage Source: https://github.com/microsoft/detours/wiki/OverviewInterception Demonstrates the usage of the FlushInstructionCache API, which is necessary after modifying CPU instruction cache. This API ensures that the CPU recognizes the changes made to the code. ```c++ FlushInstructionCache(GetCurrentProcess(), NULL, 0); ``` -------------------------------- ### APIs For Finding Target Functions Source: https://github.com/microsoft/detours/wiki/Reference Functions for locating and analyzing target functions within executable code. ```APIDOC ## DetourFindFunction ### Description Finds a target function by name or address. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ## DetourCodeFromPointer ### Description Retrieves the code associated with a given function pointer. ### Method N/A (Function Call) ### Endpoint N/A ### Parameters None specified in the provided text. ### Request Example N/A ### Response N/A ``` -------------------------------- ### Create Process with Detour DLL (32/64-bit) Source: https://github.com/microsoft/detours/wiki/OverviewHelpers This section explains how to create a new process and inject a detour DLL into it. It highlights the use of `DetourCreateProcessWithDllEx` or `DetourCreateProcessWithDlls` over `DetourCreateProcessWithDll` to handle both 32-bit and 64-bit target applications. These APIs automatically select the correct DLL based on the target process's architecture. ```c++ #include #include "detours.h" // Function to create a process with a detour DLL BOOL DetourCreateProcessWithDllEx( _In_opt_ LPCSTR lpApplicationName, _Inout_opt_ LPSTR lpCommandLine, _In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes, _In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes, _In_ BOOL bInheritHandles, _In_ DWORD dwCreationFlags, _In_opt_ LPVOID lpEnvironment, _In_opt_ LPCSTR lpCurrentDirectory, _In_ LPSTARTUPINFOA lpStartupInfo, _Out_ LPPROCESS_INFORMATION lpProcessInformation, _In_ LPCSTR DllPath, _In_ LPCSTR DllName ); // Function to create a process with multiple detour DLLs BOOL DetourCreateProcessWithDlls( _In_opt_ LPCSTR lpApplicationName, _Inout_opt_ LPSTR lpCommandLine, _In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes, _In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes, _In_ BOOL bInheritHandles, _In_ DWORD dwCreationFlags, _In_opt_ LPVOID lpEnvironment, _In_opt_ LPCSTR lpCurrentDirectory, _In_ LPSTARTUPINFOA lpStartupInfo, _Out_ LPPROCESS_INFORMATION lpProcessInformation, _In_ DWORD DllCount, _In_ LPCSTR* DllPaths ); ``` -------------------------------- ### Win32 API Tracing Source: https://github.com/microsoft/detours/wiki/Samples A sample that traces a significant number of Win32 API functions (1401). It detours these functions and prints tracing statements, providing detailed insight into API usage. ```c++ // ... (Detours implementation for Win32 API tracing) ... ``` -------------------------------- ### DetourBinaryFindPayload Source: https://github.com/microsoft/detours/wiki/DetourBinaryFindPayload Find a payload within a binary. ```APIDOC ## DetourBinaryFindPayload ### Description Find a payload within a binary. ### Method N/A (This is a function signature, not a REST endpoint) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) Returns a pointer to the payload if found. #### Response Example ```cpp PVOID payload_ptr = DetourBinaryFindPayload(pBinary, guid, &data_size); ``` ### Remarks `DetourBinaryFindPayload`Finds a specific payload within a binary opened by [`DetourBinaryOpen`](DetourBinaryOpen). For more information on binary editing with Detours and payloads, see [Payloads and DLL Import Editing](OverviewPayloads) in the [Detours Overview](Home). ### Return Value If successful, returns `TRUE`; otherwise, returns `FALSE`. ``` -------------------------------- ### PF_DETOUR_BINARY_BYWAY_CALLBACK Source: https://github.com/microsoft/detours/wiki/DetourBinaryBywayCallback Callback function definition and usage for editing binary import tables. ```APIDOC ## PF_DETOUR_BINARY_BYWAY_CALLBACK ### Description Pointer to function called once for each existing byway or opportunity to insert a new byway while editing an import table using the [`DetourBinaryEditImports`](DetourBinaryEditImports) API. ### Method CALLBACK ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (BOOL) - **TRUE** : Continue editing import table. - **FALSE**: Abort editing import table. #### Response Example None ### Remarks `PF_DETOUR_BINARY_BYWAY_CALLBACK` is called once for each existing byway in the target binary and once before or after each file or byway listed in the existing import table. When called for an existing byway, `pszFile` will have a non-NULL value. When `PF_DETOUR_BINARY_BYWAY_CALLBACK` is called before or after an existing file or byway, `pszFile` will be `NULL`. The callback function can use this opportunity to insert a new byway if desired. **Note:** Each DLL inserted as a byway must export a function with ordinal #1. If the export table for the DLL does not export a function with ordinal #1, the target binary will fail to load correct. ``` -------------------------------- ### Heap Allocation Tracing Source: https://github.com/microsoft/detours/wiki/Samples This sample traces all calls to the Windows HeapAlloc API. It intercepts memory allocation requests to monitor heap usage. ```c++ // ... (Detours code for tracing HeapAlloc) ... ``` -------------------------------- ### Finding Payloads in Binary Files Source: https://github.com/microsoft/detours/wiki/Samples A sample designed to find payloads compiled into binary files. This could involve searching for specific data patterns or embedded code. ```c++ // ... (Detours code for finding binary payloads) ... ``` -------------------------------- ### DetourEnumerateModules Source: https://github.com/microsoft/detours/wiki/DetourEnumerateModules Enumerates the PE binaries loaded into a process. It allows iterating through all loaded modules to access their entry points, exports, and payloads. ```APIDOC ## DetourEnumerateModules ### Description Enumerate the PE binaries in a process. ### Method [Implicitly a C++ function call, not a typical HTTP method] ### Endpoint [N/A - This is a library function] ### Parameters #### Path Parameters [None] #### Query Parameters [None] #### Request Body [None] ### Request Example ```cpp HMODULE hModule = NULL; while (hModule = DetourEnumerateModules(hModule)) { // Process the enumerated module } ``` ### Response #### Success Response `HMODULE`: Handle to the next module loaded in a process. `NULL`: If the enumeration is complete. #### Response Example [N/A - Returns an HMODULE handle or NULL] ### Remarks `DetourEnumerateModules` enumerates all of the PE binaries loaded into a process. Once a module has been enumerated, its entry point can be located with the [`DetourGetEntryPoint`](DetourGetEntryPoint) API, its exports can be enumerated with the [`DetourEnumerateExports`](DetourEnumerateExports) API, and its payloads can be found using the [`DetourFindPayload`](DetourFindPayload) API. ``` -------------------------------- ### DetourCopyPayloadToProcess Source: https://github.com/microsoft/detours/wiki/DetourCopyPayloadToProcess Copies a payload into a target process, creating an artificial PE binary module with a .detours section containing the payload. ```APIDOC ## DetourCopyPayloadToProcess ### Description Copy a payload into a target process. ### Method BOOL (function declaration) ### Endpoint N/A (This is a library function, not a web API endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```cpp BOOL DetourCopyPayloadToProcess( _In_ HANDLE hProcess, _In_ REFGUID rguid, _In_reads_bytes_(cbData) LPCVOID pvData, _In_ DWORD cbData ); ``` ### Response #### Success Response Returns `TRUE` if the payload was successfully copied to the target process. #### Response Example ```cpp TRUE ``` #### Failure Response Returns `FALSE` if the payload could not be copied. Extended error information can be retrieved using `GetLastError`. ``` -------------------------------- ### DetourEnumerateModules API Source: https://github.com/microsoft/detours/wiki/OverviewPayloads API for enumerating binary modules mapped into an address space. ```APIDOC ## DetourEnumerateModules ### Description Enumerates all binary modules currently mapped into the address space of a process. This is useful for finding loaded DLLs and executables. ### Method [Not specified, typically a library function call] ### Endpoint [Not applicable, this is a library function] ### Parameters * **Process Handle**: (Handle) - A handle to the process whose modules are to be enumerated. * **Module Enumerator**: (Callback Function) - A function that will be called for each mapped module. ### Request Example [Code example for calling the C/C++ function would go here] ### Response * **Success**: (Boolean/Status Code) - Indicates if the module enumeration was successful. * **Error**: (Error Code/Message) - Details about any errors encountered. ``` -------------------------------- ### DetourCreateProcessWithDlls Source: https://github.com/microsoft/detours/wiki/DetourCreateProcessWithDlls Creates a new process and loads specified DLLs into it. It automatically chooses the appropriate 32-bit or 64-bit DLL based on the target process architecture. ```APIDOC ## DetourCreateProcessWithDlls ### Description Creates a new process and loads DLLs into it. Chooses the appropriate 32-bit or 64-bit DLL based on the target process. Replaces `DetourCreateProcessWithDll`. ### Method BOOL DetourCreateProcessWithDlls( _In_opt_ LPCTSTR lpApplicationName, _Inout_opt_ LPTSTR lpCommandLine, _In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes, _In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes, _In_ BOOL bInheritHandles, _In_ DWORD dwCreationFlags, _In_opt_ LPVOID lpEnvironment, _In_opt_ LPCTSTR lpCurrentDirectory, _In_ LPSTARTUPINFOW lpStartupInfo, _Out_ LPPROCESS_INFORMATION lpProcessInformation, _In_ DWORD nDlls, _In_reads_(nDlls) LPCSTR *rlpDlls, _In_opt_ PDETOUR_CREATE_PROCESS_ROUTINEW pfCreateProcessW ); ### Parameters * `lpApplicationName` (_In_opt_ LPCTSTR): Application name as defined for CreateProcess API. * `lpCommandLine` (_Inout_opt_ LPTSTR): Command line as defined for CreateProcess API. * `lpProcessAttributes` (_In_opt_ LPSECURITY_ATTRIBUTES): Process attributes as defined for CreateProcess API. * `lpThreadAttributes` (_In_opt_ LPSECURITY_ATTRIBUTES): Thread attributes as defined for CreateProcess API. * `bInheritHandles` (_In_ BOOL): Inherit handle flags as defined for CreateProcess API. * `dwCreationFlags` (_In_ DWORD): Creation flags as defined for CreateProcess API. * `lpEnvironment` (_In_opt_ LPVOID): Process environment variables as defined for CreateProcess API. * `lpCurrentDirectory` (_In_opt_ LPCTSTR): Process current directory as defined for CreateProcess API. * `lpStartupInfo` (_In_ LPSTARTUPINFOW): Process startup information as defined for CreateProcess API. * `lpProcessInformation` (_Out_ LPPROCESS_INFORMATION): Process handle information as defined for CreateProcess API. * `nDlls` (_In_ DWORD): Count of the number of DLLs in `rlpDlls`. * `rlpDlls` (_In_reads_(nDlls) LPCSTR *): Array of pathnames of the DLL to be inserted into the new process. The DLL names should end with "32" if the DLL contains 32-bit code and should end with "64" if the DLL contains 64-bit code. If the target process differs in size from the parent process, Detours will automatically replace "32" with "64" or "64" with "32" in the path name. * `pfCreateProcessW` (_In_opt_ PDETOUR_CREATE_PROCESS_ROUTINEW): Pointer to program-specific replacement for the CreateProcess API, or `NULL` if the standard CreateProcess API should be used to create the new process. ### Return Value Returns `TRUE` if the new process was created; otherwise returns `FALSE`. ### Remarks `DetourCreateProcessWithDlls` creates a new process with the specified DLL inserted into it. The process is created in a suspended state with the `CREATE_SUSPENDED` flag to `CreateProcess`. Detours then modifies the image of the application binary in the new process to include the specified DLL as its first import. Execution in the process is then resumed. When execution resumes, the Windows process loader will first load the target DLL and then any other DLLs in the application's import table, before calling the application entry point. `DetourCreateProcessWithDlls` modifies the in-memory import table of the target PE binary program in the new process it creates. The updated import table will contain a reference to function ordinal #1 exported from the target DLL. If the target process is 32-bit and the parent process is 64-bit, or if the target process is 64-bit and the parent process is 32-bit, `DetourCreateProcessWithDlls` will use `rundll32.exe` to load the DLL into a helper process that matches the target process temporarily in order to update the target processes import table with the correct DLL. **Note:** The new process will fail to start if the target DLL does not contain an exported function with ordinal #1. After the target DLL has been loaded, it can reverse changes to the in-memory import table by calling `DetourRestoreAfterWith`. To facilitate reversing these changes, `DetourCreateProcessWithDlls` copies relevant reversal data into a payload in the target process using the `DetourCopyPayloadToProcess` API. The loaded DLL should call the `DetourRestoreAfterWith` API to restore the contents of the import table. ``` -------------------------------- ### First-Chance Exception Filter for VM Permissions Source: https://github.com/microsoft/detours/wiki/Samples Uses a first-chance exception filter to toggle Virtual Machine (VM) permissions on a memory page. This demonstrates advanced memory management and exception handling. ```c++ // ... (Detours code using exception filter for VM permissions) ... ``` -------------------------------- ### Process Creation with DLL Injection Source: https://github.com/microsoft/detours/wiki/Using-Detours APIs for creating new processes and injecting DLLs into them, with specific handling for different DLL architectures and helper process requirements. ```APIDOC ## Process Creation with DLL Injection ### Description Creates new processes and injects specified DLLs into them. Includes functions for handling DLL loading and helper process interactions. ### APIs - **DetourCreateProcessWithDllEx** - **Description:** Creates a new process and injects a single specified DLL. - **Parameters:** - `lpApplicationName` (LPCWSTR) - Optional - Name of the application module to be executed. - `lpCommandLine` (LPWSTR) - Optional - Command line for the new process. - `lpProcessAttributes` (LPSECURITY_ATTRIBUTES) - Optional - Security attributes for the process handle. - `lpThreadAttributes` (LPSECURITY_ATTRIBUTES) - Optional - Security attributes for the thread handle. - `bInheritHandles` (BOOL) - Inherit handles from the parent process. - `dwCreationFlags` (DWORD) - Flags that control the creation of the process. - `lpEnvironment` (LPVOID) - Pointer to the environment block for the new process. - `lpCurrentDirectory` (LPCWSTR) - Optional - Full path of the current directory for the new process. - `lpStartupInfo` (LPSTARTUPINFOW) - Pointer to a STARTUPINFO structure that specifies how the new process should be created. - `lpProcessInformation` (LPPROCESS_INFORMATION) - Pointer to a PROCESS_INFORMATION structure that receives identification information about the new process. - `pcDllPath` (LPCWSTR) - Path to the DLL to be injected. - **Method:** N/A (Library Function) - **DetourCreateProcessWithDlls** - **Description:** Creates a new process and injects a list of specified DLLs. - **Parameters:** - `lpApplicationName` (LPCWSTR) - Optional - Name of the application module to be executed. - `lpCommandLine` (LPWSTR) - Optional - Command line for the new process. - `lpProcessAttributes` (LPSECURITY_ATTRIBUTES) - Optional - Security attributes for the process handle. - `lpThreadAttributes` (LPSECURITY_ATTRIBUTES) - Optional - Security attributes for the thread handle. - `bInheritHandles` (BOOL) - Inherit handles from the parent process. - `dwCreationFlags` (DWORD) - Flags that control the creation of the process. - `lpEnvironment` (LPVOID) - Pointer to the environment block for the new process. - `lpCurrentDirectory` (LPCWSTR) - Optional - Full path of the current directory for the new process. - `lpStartupInfo` (LPSTARTUPINFOW) - Pointer to a STARTUPINFO structure that specifies how the new process should be created. - `lpProcessInformation` (LPPROCESS_INFORMATION) - Pointer to a PROCESS_INFORMATION structure that receives identification information about the new process. - `nDlls` (DWORD) - Number of DLLs to inject. - `pcDllsPath` (LPCWSTR *) - Array of paths to the DLLs to be injected. - **Method:** N/A (Library Function) ### DLLMain Requirements - **DetourRestoreAfterWith** - **Description:** Must be called by DllMain if the DLL is injected using `DetourCreateProcessWithDllEx` or `DetourCreateProcessWithDlls`. - **Method:** N/A (Library Function) - **DetourIsHelperProcess** - **Description:** Must be called by DllMain if the DLL may be used in mixed 32-bit and 64-bit environments. - **Method:** N/A (Library Function) - **DetourFinishHelperProcess** - **Description:** Must be exported by the DLL (Ordinal 1) and called by `rundll32.exe` to perform helper tasks. ``` -------------------------------- ### Registry API Activity Tracing Source: https://github.com/microsoft/detours/wiki/Samples Traces activity through the registry APIs. This sample monitors operations performed on the Windows Registry. ```c++ // ... (Detours code for registry API tracing) ... ``` -------------------------------- ### Finding Functions with Debug Symbols Source: https://github.com/microsoft/detours/wiki/Samples Illustrates how to detour a function by utilizing the `DetourFindFunction` utility, which relies on debug symbols to locate the target function. ```c++ // ... (Detours code using DetourFindFunction) ... ``` -------------------------------- ### Adding DLL to Import Table Source: https://github.com/microsoft/detours/wiki/Samples A sample that adds a DLL to the import table of any binary (e.g., a .DLL or .EXE). This allows a DLL to be loaded automatically when the target binary is executed. ```c++ // ... (Detours code to modify import table) ... ``` -------------------------------- ### Imported Functions Dump Source: https://github.com/microsoft/detours/wiki/Samples Dumps the list of all functions imported by a binary file. This helps in understanding the dependencies of an executable on external libraries. ```c++ // ... (Detours code to dump imported functions) ... ``` -------------------------------- ### System Event Logging Source: https://github.com/microsoft/detours/wiki/Samples Provides a system event logging library and service. This sample is likely involved in collecting and processing system-level events, possibly in conjunction with other detouring samples. ```c++ // ... (Syelog library and service implementation) ... ``` -------------------------------- ### Detour DLL Requirements for Helper Processes Source: https://github.com/microsoft/detours/wiki/OverviewHelpers This snippet outlines essential requirements for a Detours DLL to function correctly as a helper process, particularly when dealing with cross-architecture process creation. It mandates exporting a specific function by ordinal and checking for helper process status within the DllMain. ```c++ // Export ordinal 1 for DetourFinishHelperProcess #pragma comment(linker, "/EXPORT:DetourFinishHelperProcess=DetourFinishHelperProcess,@1") // DllMain function BOOL WINAPI DllMain(HINSTANCE hinst, DWORD dwReason, LPVOID lpReserved) { switch (dwReason) { case DLL_PROCESS_ATTACH: // Check if this is a helper process if (DetourIsHelperProcess()) { return TRUE; // Immediately return if it's a helper process } // ... your DLL initialization code ... break; case DLL_PROCESS_DETACH: // ... your DLL cleanup code ... break; } return TRUE; } ```