Malware'de Yaygın Kullanılan API

Reading time: 9 minutes

tip

AWS Hacking'i öğrenin ve pratik yapın:HackTricks Training AWS Red Team Expert (ARTE)
GCP Hacking'i öğrenin ve pratik yapın: HackTricks Training GCP Red Team Expert (GRTE) Azure Hacking'i öğrenin ve pratik yapın: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks'i Destekleyin

Genel

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

Birçok loader, TCP akışını SslStream ile sarar ve sunucunun leaf sertifikasını gömülü bir kopyaya karşı pinler (certificate pinning). Bot bilgileri/görevleri sıkıştırılır (ör. GZip). Yanıtlar bir eşik değeri (~1 MB) aştığında, boyuta dayalı heuristiklerden kaçınmak ve serileştirme sırasında bellek ani artışlarını azaltmak için veriler küçük parçalara (ör. 16 KB segmentleri gibi) bölünür.

Persistence

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

Şifreleme

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]

Yerel/Klavye Tabanlı Çalıştırma Koruması

Birçok stealer/loader, araştırmacılardan kaçmak ve threat-actor sınırlamalarına uymak için belirli locale'larda çalışmayı sonlandırır. Tipik kontroller:

  • GetKeyboardLayout ile yüklü klavye düzenlerini (thread/user bazında) listeleme
  • GetLocaleInfoA/W ile ülke/bölge kodlarını çözümleme
  • GetSystemDefaultLangID / GetUserDefaultLangID

Eğer herhangi biri engellenmiş bir listeyle eşleşirse (genellikle CIS countries), loader ağ IOC'leri veya enjeksiyon gerçekleşmeden hemen çıkış yapar.

Savunma/tehdit avlama

  • Yerel/klavye API'lerini erken yürütmede birden fazla kez sorgulayan süreçleri işaretleyin; bu süreçler genellikle gözlemlenebilir faaliyet olmadan sonlanır.
  • Gated execution yakalamak için açık kaynak projelerden yeniden kullanılan anti-VM kontrolleriyle (BIOS strings, PnP devices, disk model, services) korelasyon yapın (ör. VMDetector).

Emulator API fingerprinting & sleep evasion

Malware sıklıkla sandbox emülatörlerini, Defender’ın virtualised exports'larını arayarak fingerprintler (Malware Protection Emulator'da görüldüğü gibi). Bu sembollerden herhangi biri mevcutsa (işlemin küçük/büyük harfe duyarsız taraması), yürütme analiz süresini tüketmek için 10–30 dakika geciktirilir ve tekrar kontrol edilir.

API isimlerinin canary olarak kullanıldığı örnekler:

  • MpVmp32Entry, MpVmp32FastEnter, MpCallPreEntryPointCode, MpCallPostEntryPointCode, MpFinalize, MpReportEvent*, MpSwitchToNextThread*
  • VFS_* familyası: VFS_Open, VFS_Read, VFS_MapViewOfFile, VFS_UnmapViewOfFile, VFS_FindFirstFile/FindNextFile, VFS_CopyFile, VFS_DeleteFile, VFS_MoveFile
  • ThrdMgr_*: ThrdMgr_GetCurrentThreadHandle, ThrdMgr_SaveTEB, ThrdMgr_SwitchThreads

Tipik gecikme primitifi (user-land):

cmd
cmd /c timeout /t %RANDOM_IN_[600,1800]% > nul

Argument gatekeeping

  • Operatörler bazen payload'u çalıştırmadan önce zararsız görünen bir CLI switch'in var olmasını gerektirir (ör. /i:--type=renderer ile Chromium child process'lerini taklit etmek için). Eğer switch yoksa, loader hemen çıkarak basit sandbox çalıştırmasını engeller.

Gizlilik

Name
VirtualAllocAlloc memory (packers)
VirtualProtectChange memory permission (packer giving execution permission to a section)
ReadProcessMemoryInjection into external processes
WriteProcessMemoryA/WInjection into external processes
NtWriteVirtualMemory
CreateRemoteThreadDLL/Process injection...
NtUnmapViewOfSection
QueueUserAPC
CreateProcessInternalA/W

Yürütme

Function Name
CreateProcessA/W
ShellExecute
WinExec
ResumeThread
NtResumeThread

Çeşitli

  • GetAsyncKeyState() -- Klavye kaydı
  • SetWindowsHookEx -- Klavye kaydı
  • GetForeGroundWindow -- Çalışan pencerenin adını alma (veya bir tarayıcıdan web sitesi)
  • LoadLibrary() -- Kütüphane yükleme
  • GetProcAddress() -- Fonksiyon adresi alma
  • CreateToolhelp32Snapshot() -- Çalışan süreçleri listeleme
  • GetDC() -- Ekran görüntüsü
  • BitBlt() -- Ekran görüntüsü
  • InternetOpen(), InternetOpenUrl(), InternetReadFile(), InternetWriteFile() -- İnternete erişim
  • FindResource(), LoadResource(), LockResource() -- Çalıştırılabilir dosyanın kaynaklarına erişim

Malware Techniques

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.

Normal Windows API çağrılarını kullanmadan kötü amaçlı bir DLL yükler. DLL bir sürecin içine eşlenir, import adreslerini çözer, relokasyonları düzeltir ve DllMain fonksiyonunu çağırır.

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.

Portable Executable Injection: Çalıştırılabilir dosya hedef sürecin belleğine yazılır ve oradan yürütülür.

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

Process Hollowing, Windows kötü amaçlı yazılımları tarafından sık kullanılan bir savunma-atlatma / yürütme numarasından biridir. Fikir, meşru bir süreci askıya alınmış durumda başlatmak, belleğinden orijinal görüntüsünü (hollow) kaldırmak ve yerine herhangi bir PE kopyalamaktır. Birincil iş parçacığı yeniden devam ettiğinde, kötü amaçlı giriş noktası genellikle Microsoft tarafından imzalanmış gibi görünen güvenilir bir ikili maskesi altında çalıştırılır.

Tipik iş akışı:

  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.
  • Kötü amaçlı payload'u belleğe okuyun ve PE başlıklarını parse ederek SizeOfImage, bölümleri ve yeni EntryPoint'i elde edin.
  1. NtUnmapViewOfSection / ZwUnmapViewOfSection – unmap the original image base of the suspended process.
  • Askıya alınmış sürecin orijinal image base'ini unmap edin.
  1. VirtualAllocEx – reserve RWX memory of SizeOfImage inside the remote process.
  • Uzak süreç içinde SizeOfImage boyutunda RWX bellek ayırın.
  1. WriteProcessMemory – copy the Headers first, then iterate over sections copying their raw data.
  • Önce Headers'ı kopyalayın, sonra bölümler üzerinde dolaşarak ham verilerini kopyalayın.
  1. SetThreadContext – patch the value of EAX/RAX (RCX on x64) or Rip in the context structure so that EIP points to the payload’s EntryPoint.
  • SetThreadContext ile bağlam yapısındaki EAX/RAX (x64'te RCX) veya Rip değerini yama yaparak EIP'nin payload'un EntryPoint'ine işaret etmesini sağlayın.
  1. ResumeThread – the thread continues, executing the attacker-supplied code.
  • ResumeThread ile iş parçacığı devam eder ve saldırganın sağladığı kodu yürütür.

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) kernel işlevlerine (ntoskrnl.exe) veya GUI sürücüsüne (win32k.sys) işaret eder, böylece user processes bu işlevleri çağırabilir.
  • Bir rootkit bu pointer'ları kendi kontrolündeki adreslere değiştirebilir.
  • IRP (I/O Request Packets) bir bileşenden diğerine veri parçaları iletir. Kernel'deki neredeyse her şey IRP kullanır ve her device object'in hooklanabilecek kendi fonksiyon tablosu vardır: DKOM (Direct Kernel Object Manipulation)
  • The IAT (Import Address Table) bağımlılıkları çözmek için kullanışlıdır. Çağrılacak kodu ele geçirmek amacıyla bu tablo hooklanabilir.
  • EAT (Export Address Table) Hooks. Bu hooklar userland'den yapılabilir. Amaç DLL'lerin export ettiği fonksiyonları hooklamaktır.
  • Inline Hooks: Bu türler gerçekleştirmesi zordur. Bu, fonksiyonların kodunu doğrudan değiştirmeyi içerir. Örneğin başına bir jump koymak gibi.

References

tip

AWS Hacking'i öğrenin ve pratik yapın:HackTricks Training AWS Red Team Expert (ARTE)
GCP Hacking'i öğrenin ve pratik yapın: HackTricks Training GCP Red Team Expert (GRTE) Azure Hacking'i öğrenin ve pratik yapın: HackTricks Training Azure Red Team Expert (AzRTE)

HackTricks'i Destekleyin