# API za kawaida zinazotumiwa katika Malware {{#include ../banners/hacktricks-training.md}} ## Za Kawaida ### Mitandao | Raw Sockets | WinAPI Sockets | | ------------- | -------------- | | socket() | WSAStratup() | | bind() | bind() | | listen() | listen() | | accept() | accept() | | connect() | connect() | | read()/recv() | recv() | | write() | send() | | shutdown() | WSACleanup() | ### TLS pinning and chunked transport Wapakiaji wengi huweka mkondo wao wa TCP ndani ya `SslStream` na ku-pin cheti la leaf la server dhidi ya nakala iliyowekwa ndani (certificate pinning). Taarifa na kazi za bot zimekandwa (kwa mfano, GZip). Wakati majibu yanapozidi kikomo (~1 MB), data hugawanywa katika vipande vidogo (kwa mfano, segmenti za 16 KB) ili kuepuka heuristics zinazotegemea ukubwa na kupunguza mwinuko wa kumbukumbu wakati wa deserialisation. ### Uendelevu | Registry | File | Service | | ---------------- | ------------- | ---------------------------- | | RegCreateKeyEx() | GetTempPath() | OpenSCManager | | RegOpenKeyEx() | CopyFile() | CreateService() | | RegSetValueEx() | CreateFile() | StartServiceCtrlDispatcher() | | RegDeleteKeyEx() | WriteFile() | | | RegGetValue() | ReadFile() | | ### Usimbaji | Name | | --------------------- | | WinCrypt | | CryptAcquireContext() | | CryptGenKey() | | CryptDeriveKey() | | CryptDecrypt() | | CryptReleaseContext() | ### Anti-Analysis/VM | Function Name | Assembly Instructions | | --------------------------------------------------------- | --------------------- | | IsDebuggerPresent() | CPUID() | | GetSystemInfo() | IN() | | GlobalMemoryStatusEx() | | | GetVersion() | | | CreateToolhelp32Snapshot \[Check if a process is running] | | | CreateFileW/A \[Check if a file exist] | | ### Emulator API fingerprinting & sleep evasion Malware mara nyingi hufanya fingerprinting ya sandbox emulators kwa kutafuta exports zilizounganishwa za Defender (zikiona katika Malware Protection Emulator). Ikiwa alama yoyote ya hizi zipo (skani isiyo na utofauti wa herufi kwenye mchakato), utekelezaji unasitishwa kwa dakika 10–30 na kurejelezwa tena ili kuchosha muda wa uchunguzi. Examples of API names used as canaries: - `MpVmp32Entry`, `MpVmp32FastEnter`, `MpCallPreEntryPointCode`, `MpCallPostEntryPointCode`, `MpFinalize`, `MpReportEvent*`, `MpSwitchToNextThread*` - `VFS_*` family: `VFS_Open`, `VFS_Read`, `VFS_MapViewOfFile`, `VFS_UnmapViewOfFile`, `VFS_FindFirstFile/FindNextFile`, `VFS_CopyFile`, `VFS_DeleteFile`, `VFS_MoveFile` - `ThrdMgr_*`: `ThrdMgr_GetCurrentThreadHandle`, `ThrdMgr_SaveTEB`, `ThrdMgr_SwitchThreads` Typical delay primitive (user-land): ```cmd cmd /c timeout /t %RANDOM_IN_[600,1800]% > nul ``` Argument gatekeeping - Waendeshaji mara nyingine wanahitaji kuwepo kwa swichi ya CLI inayoonekana isiyo hatari kabla ya kuendesha payload (mfano, `/i:--type=renderer` ili kuiga michakato ndogo ya Chromium). Ikiwa swichi haipo, loader inatoka mara moja, ikizuia utekelezaji wa sandbox isiyo ngumu. ### Stealth | Name | | | ------------------------ | -------------------------------------------------------------------------- | | VirtualAlloc | Kuweka kumbukumbu (packers) | | VirtualProtect | Badilisha ruhusa za kumbukumbu (packer inayotoa ruhusa za utekelezaji kwa sehemu) | | ReadProcessMemory | Uingizaji ndani ya michakato ya nje | | WriteProcessMemoryA/W | Uingizaji ndani ya michakato ya nje | | NtWriteVirtualMemory | | | CreateRemoteThread | DLL/Process injection... | | NtUnmapViewOfSection | | | QueueUserAPC | | | CreateProcessInternalA/W | | ### Execution | Function Name | | ---------------- | | CreateProcessA/W | | ShellExecute | | WinExec | | ResumeThread | | NtResumeThread | ### Miscellaneous - GetAsyncKeyState() -- Kurekodi vitufe - SetWindowsHookEx -- Kurekodi vitufe - GetForeGroundWindow -- Pata jina la dirisha linaloendesha (au tovuti kutoka kwa kivinjari) - LoadLibrary() -- Kupakia maktaba - GetProcAddress() -- Kupata anuani ya proceduri (Import library) - CreateToolhelp32Snapshot() -- Orodhesha michakato inayotekelezwa - GetDC() -- Kuchukua screenshot - BitBlt() -- Kuchukua screenshot - InternetOpen(), InternetOpenUrl(), InternetReadFile(), InternetWriteFile() -- Kufikia Internet - FindResource(), LoadResource(), LockResource() -- Kufikia rasilimali za executable ## Malware Techniques ### DLL Injection Execute an arbitrary DLL inside another process 1. Pata mchakato wa kuingiza DLL hatarishi: CreateToolhelp32Snapshot, Process32First, Process32Next 2. Fungua mchakato: GetModuleHandle, GetProcAddress, OpenProcess 3. Andika njia ya DLL ndani ya mchakato: VirtualAllocEx, WriteProcessMemory 4. Tengeneza thread ndani ya mchakato itakayopakia DLL hatarishi: CreateRemoteThread, LoadLibrary Vifunction vingine vya kutumia: NTCreateThreadEx, RtlCreateUserThread ### Reflective DLL Injection Load a malicious DLL without calling normal Windows API calls.\ The DLL is mapped inside a process, it will resolve the import addresses, fix the relocations and call the DllMain function. ### Thread Hijacking Find a thread from a process and make it load a malicious DLL 1. Tafuta thread lengwa: CreateToolhelp32Snapshot, Thread32First, Thread32Next 2. Fungua thread: OpenThread 3. Simamisha thread: SuspendThread 4. Andika njia ya DLL hatarishi ndani ya mchakato wa mwathiriwa: VirtualAllocEx, WriteProcessMemory 5. Anzisha tena thread ili ipakie maktaba: ResumeThread ### PE Injection Portable Execution Injection: The executable will be written in the memory of the victim process and it will be executed from there. ### Process Hollowing (a.k.a **RunPE**) `Process Hollowing` is one of the favourite **defence-evasion / execution** tricks used by Windows malware. The idea is to launch a *legitimate* process in the **suspended** state, remove (hollow) its original image from memory and copy an **arbitrary PE** in its place. When the primary thread is finally resumed the malicious entry-point executes under the guise of a trusted binary (often signed by Microsoft). Mtiririko wa kawaida: 1. Zindua mchakato halali (mfano `RegAsm.exe`, `rundll32.exe`, `msbuild.exe`) **suspended** ili hakuna maagizo yaendeshe bado. ```c STARTUPINFOA si = { sizeof(si) }; PROCESS_INFORMATION pi; CreateProcessA("C:\\Windows\\Microsoft.NET\\Framework32\\v4.0.30319\\RegAsm.exe", NULL, NULL, NULL, FALSE, CREATE_SUSPENDED, NULL, NULL, &si, &pi); ``` 2. Soma payload hatarishi kwenye kumbukumbu na changanua vichwa vya PE ili kupata `SizeOfImage`, sections na `EntryPoint` mpya. 3. **NtUnmapViewOfSection** / **ZwUnmapViewOfSection** – ondoa ramani ya msingi wa picha ya awali ya mchakato uliosimamishwa. 4. **VirtualAllocEx** – hifadhi kumbukumbu ya RWX ya `SizeOfImage` ndani ya mchakato wa mbali. 5. **WriteProcessMemory** – nakili kwanza `Headers`, kisha pitia sections ukinakili data yao ghafi. 6. **SetThreadContext** – rekebisha thamani ya `EAX/RAX` (`RCX` on x64) au `Rip` katika muundo wa context ili `EIP` iwekwe kwa `EntryPoint` ya payload. 7. **ResumeThread** – thread inaendelea, ikitekeleza msimbo uliotolewa na mshambuliaji. Mfano mdogo wa uthibitisho wa dhana (x86): ```c void RunPE(LPCSTR host, LPVOID payload, DWORD payloadSize){ // 1. create suspended process STARTUPINFOA si = {sizeof(si)}; PROCESS_INFORMATION pi; CreateProcessA(host, NULL,NULL,NULL,FALSE,CREATE_SUSPENDED,NULL,NULL,&si,&pi); // 2. read remote PEB to get ImageBaseAddress CONTEXT ctx; ctx.ContextFlags = CONTEXT_FULL; GetThreadContext(pi.hThread,&ctx); PVOID baseAddr; ReadProcessMemory(pi.hProcess,(PVOID)(ctx.Ebx+8),&baseAddr,4,NULL); // 3. unmap original image & allocate new region at same base NtUnmapViewOfSection(pi.hProcess,baseAddr); PVOID newBase = VirtualAllocEx(pi.hProcess,baseAddr,pHdr->OptionalHeader.SizeOfImage, MEM_COMMIT|MEM_RESERVE,PAGE_EXECUTE_READWRITE); // 4-5. copy headers & sections … // 6. write new image base into PEB and set Eip WriteProcessMemory(pi.hProcess,(PVOID)(ctx.Ebx+8),&baseAddr,4,NULL); ctx.Eax = (DWORD)(newBase) + pHdr->OptionalHeader.AddressOfEntryPoint; SetThreadContext(pi.hThread,&ctx); // 7. run! ResumeThread(pi.hThread); } ``` Vidokezo vya vitendo vilivyobainika katika kampeni ya **DarkCloud Stealer**: * The loader ilichagua `RegAsm.exe` (part of the .NET Framework) kama host – binary iliyosainiwa isiyotarajiwa kuvutia umakini. * The decrypted VB6 stealer (`holographies.exe`) haidondoshwi kwenye disk; ipo tu ndani ya hollowed process, ikifanya static detection iwe ngumu zaidi. * Mfuatano wa maandishi nyeti (regexes, paths, Telegram credentials) umewekwa **RC4-encrypted** kwa kila string na huwekwa decrypted tu wakati wa runtime, ikifanya memory scanning kuwa tata zaidi. Mawazo ya utambuzi: * Alert juu ya `CREATE_SUSPENDED` processes ambazo hazitumii kuunda windows za GUI/console kabla eneo la memory linapopewa kama **RWX** (nadra kwa benign code). * Tafuta mfuatano wa wito `NtUnmapViewOfSection ➜ VirtualAllocEx ➜ WriteProcessMemory` kati ya michakato tofauti. ## Hooking - The **SSDT** (**System Service Descriptor Table**) inaonyesha kwa kernel functions (ntoskrnl.exe) au GUI driver (win32k.sys) ili user processes ziweze kuita hizi functions. - Rootkit inaweza kubadilisha pointer hizi kwa anwani anazodhibiti. - The **IRP** (**I/O Request Packets**) hupitisha vipande vya data kutoka sehemu moja hadi nyingine. Karibu kila kitu katika kernel inatumia IRPs na kila device object ina jedwali la function ambalo linaweza ku-hook: DKOM (Direct Kernel Object Manipulation) - The **IAT** (**Import Address Table**) ni muhimu kutatua dependencies. Inawezekana ku-hook table hii ili hijack code ambayo itaitekwa. - **EAT** (**Export Address Table**) Hooks. Hizi hooks zinaweza kufanywa kutoka **userland**. Lengo ni ku-hook exported functions za DLLs. - **Inline Hooks**: Aina hizi ni ngumu kufanikisha. Hii inahusisha kubadilisha code ya functions yenyewe, kwa mfano kwa kuweka jump mwanzoni mwa hizo functions. ## Marejeo - [Unit42 – New Infection Chain and ConfuserEx-Based Obfuscation for DarkCloud Stealer](https://unit42.paloaltonetworks.com/new-darkcloud-stealer-infection-chain/) - [Check Point Research – Under the Pure Curtain: From RAT to Builder to Coder](https://research.checkpoint.com/2025/under-the-pure-curtain-from-rat-to-builder-to-coder/) {{#include ../banners/hacktricks-training.md}}