API za kawaida zinazotumika katika Malware

Reading time: 9 minutes

tip

Jifunze na fanya mazoezi ya AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Jifunze na fanya mazoezi ya GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE) Jifunze na fanya mazoezi ya Azure Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Support HackTricks

Msingi

Mtandao

Raw SocketsWinAPI Sockets
socket()WSAStratup()
bind()bind()
listen()listen()
accept()accept()
connect()connect()
read()/recv()recv()
write()send()
shutdown()WSACleanup()

TLS pinning and chunked transport

Loaders nyingi huweka mtiririko wao wa TCP ndani ya SslStream na ku-pin cheti la leaf la server dhidi ya nakala iliyowekwa ndani (certificate pinning). Taarifa/misheni za bot hupigwa 압 (e.g., GZip). Wakati majibu yanapozidi kikomo (~1 MB), data hugawanywa kuwa vipande vidogo (e.g., segimenti za 16 KB) ili kuepuka heuristics zinazotegemea ukubwa na kupunguza mfumuko wa kumbukumbu wakati wa deserialisation.

Persistence

RegistryFileService
RegCreateKeyEx()GetTempPath()OpenSCManager
RegOpenKeyEx()CopyFile()CreateService()
RegSetValueEx()CreateFile()StartServiceCtrlDispatcher()
RegDeleteKeyEx()WriteFile()
RegGetValue()ReadFile()

Encryption

Name
WinCrypt
CryptAcquireContext()
CryptGenKey()
CryptDeriveKey()
CryptDecrypt()
CryptReleaseContext()

Anti-Analysis/VM

Function NameAssembly Instructions
IsDebuggerPresent()CPUID()
GetSystemInfo()IN()
GlobalMemoryStatusEx()
GetVersion()
CreateToolhelp32Snapshot [Check if a process is running]
CreateFileW/A [Check if a file exist]

Locale/keyboard-based execution guard

Stealers/loaders wengi huacha kutekeleza kwenye locale fulani ili kuepuka watafiti na kufuata vikwazo vya threat-actor. Uthibitisho wa kawaida:

  • GetKeyboardLayout kutorosha layouts zilizowekwa (per-thread/user)
  • GetLocaleInfoA/W kutatua codes za nchi/eneo
  • GetSystemDefaultLangID / GetUserDefaultLangID

Kama yoyote yao inafanana na orodha iliyozuia (kwa kawaida nchi za CIS), loader inatoka mara moja kabla ya IOCs za mtandao au injection.

Ulinzi/kuchunguza

  • Kuweka alama kwa mchakato unaouliza API nyingi za locale/keyboard mapema katika utekelezaji kisha kuondoka bila shughuli zinazoonekana.
  • Kuunganisha na ukaguzi wa anti-VM (miongozo ya BIOS, vifaa vya PnP, mfano wa disk, services) zilizoreuse kutoka kwa miradi ya open-source (e.g., VMDetector) ili kugundua utekelezaji uliogated.

Emulator API fingerprinting & sleep evasion

Malware mara nyingi hufanya fingerprint ya sandbox emulators kwa kutafuta exports zilizohudumiwa za Defender (zinazoonekana katika Malware Protection Emulator). Ikiwa moja ya simboli hizi ipo (skana isiyojali case ya mchakato), utekelezaji umecheleweshwa kwa dakika 10–30 na kuteuliwa tena ili kuchosha muda wa uchambuzi.

Mifano ya majina ya API zinazotumika kama 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 wakati mwingine wanahitaji swichi ya CLI inayofanana na ya kiafya kuwepo kabla ya kukimbiza payload (mfano, /i:--type=renderer kuiga Chromium child processes). Ikiwa swichi haipo, loader inatoka mara moja, ikizuia utekelezaji wa sandbox rahisi.

Kuficha

Jina
VirtualAllocKutenga kumbukumbu (packers)
VirtualProtectBadilisha ruhusa za kumbukumbu (packer hutoa ruhusa za utekelezaji kwa sehemu)
ReadProcessMemoryUingizaji kwenye michakato ya nje
WriteProcessMemoryA/WUingizaji kwenye michakato ya nje
NtWriteVirtualMemory
CreateRemoteThreadDLL/Process injection...
NtUnmapViewOfSection
QueueUserAPC
CreateProcessInternalA/W

Utekelezaji

Function Name
CreateProcessA/W
ShellExecute
WinExec
ResumeThread
NtResumeThread

Mengine

  • GetAsyncKeyState() -- Kurekodi vitufe
  • SetWindowsHookEx -- Kurekodi vitufe
  • GetForeGroundWindow -- Pata jina la dirisha linalokimbia (au tovuti kutoka kwa browser)
  • LoadLibrary() -- Pakia maktaba
  • GetProcAddress() -- Pata anwani ya proc
  • CreateToolhelp32Snapshot() -- Orodhesha michakato inayokimbia
  • GetDC() -- Picha ya skrini
  • BitBlt() -- Picha ya skrini
  • InternetOpen(), InternetOpenUrl(), InternetReadFile(), InternetWriteFile() -- Ufikiaji wa Internet
  • FindResource(), LoadResource(), LockResource() -- Kupata rasilimali za executable

Mbinu za Malware

DLL Injection

Execute an arbitrary DLL inside another process

  1. Locate the process to inject the malicious DLL: CreateToolhelp32Snapshot, Process32First, Process32Next
  2. Open the process: GetModuleHandle, GetProcAddress, OpenProcess
  3. Write the path to the DLL inside the process: VirtualAllocEx, WriteProcessMemory
  4. Create a thread in the process that will load the malicious DLL: CreateRemoteThread, LoadLibrary

Other functions to use: 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. Find a target thread: CreateToolhelp32Snapshot, Thread32First, Thread32Next
  2. Open the thread: OpenThread
  3. Suspend the thread: SuspendThread
  4. Write the path to the malicious DLL inside the victim process: VirtualAllocEx, WriteProcessMemory
  5. Resume the thread loading the library: 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).

Typical workflow:

  1. Spawn a benign host (e.g. RegAsm.exe, rundll32.exe, msbuild.exe) suspended so that no instructions run yet.
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);
  1. Read the malicious payload into memory and parse its PE headers to obtain SizeOfImage, sections and the new EntryPoint.
  2. NtUnmapViewOfSection / ZwUnmapViewOfSection – ondoa base ya image ya awali ya mchakato uliosimamishwa.
  3. VirtualAllocEx – tenga kumbukumbu ya RWX ya SizeOfImage ndani ya mchakato ya mbali.
  4. WriteProcessMemory – nakili Headers kwanza, kisha pitia sections ukinakili data yao ghafi.
  5. SetThreadContext – rekebisha thamani ya EAX/RAX (RCX on x64) au Rip katika muundo wa context ili EIP iwe ikielekeza kwa EntryPoint ya payload.
  6. ResumeThread – thread inaendelea, ikitekeleza msimbo uliotolewa na mashambulizi.

Minimal proof-of-concept (x86) skeleton:

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

Practical notes observed in the DarkCloud Stealer campaign:

  • The loader picked RegAsm.exe (part of the .NET Framework) as host – a signed binary unlikely to draw attention.
  • The decrypted VB6 stealer (holographies.exe) is not dropped on disk; it only ever exists inside the hollowed process making static detection harder.
  • Sensitive strings (regexes, paths, Telegram credentials) are RC4-encrypted per-string and only decrypted at runtime, further complicating memory scanning.

Detection ideas:

  • Alert on CREATE_SUSPENDED processes that never create GUI/console windows before a memory region is allocated as RWX (rare for benign code).
  • Look for a call sequence NtUnmapViewOfSection ➜ VirtualAllocEx ➜ WriteProcessMemory across different processes.
  • Unusual use of trusted developer utilities as hollowing hosts, especially MSBuild.exe, RegAsm.exe, rundll32.exe, parented by short-lived loaders.
  • Hunt for msbuild.exe spawned from user-writable paths or without corresponding .sln/.proj context then making outbound connections (ATT&CK T1127.001 + T1055.012).

Common host processes and path resolution

  • MSBuild.exe is frequently chosen as a hollowing host to blend with developer tooling. Loaders often search architecture-appropriate locations:
  • C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe
  • C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe
  • C:\Windows\System32\MSBuild.exe
  • C:\Windows\SysWOW64\MSBuild.exe
  • Select the host matching the current payload/OS architecture before calling CreateProcess(..., CREATE_SUSPENDED, ...).

Hooking

  • The SSDT (System Service Descriptor Table) points to kernel functions (ntoskrnl.exe) or GUI driver (win32k.sys) so user processes can call these functions.
  • A rootkit may modify these pointer to addresses that he controls
  • IRP (I/O Request Packets) transmit pieces of data from one component to another. Almost everything in the kernel uses IRPs and each device object has its own function table that can be hooked: DKOM (Direct Kernel Object Manipulation)
  • The IAT (Import Address Table) is useful to resolve dependencies. It's possible to hook this table in order to hijack the code that will be called.
  • EAT (Export Address Table) Hooks. This hooks can be done from userland. The goal is to hook exported functions by DLLs.
  • Inline Hooks: This type are difficult to achieve. This involve modifying the code of the functions itself. Maybe by putting a jump at the beginning of this.

References

tip

Jifunze na fanya mazoezi ya AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Jifunze na fanya mazoezi ya GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE) Jifunze na fanya mazoezi ya Azure Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Support HackTricks