Common API used in Malware

Reading time: 8 minutes

tip

Impara e pratica il hacking AWS:HackTricks Training AWS Red Team Expert (ARTE)
Impara e pratica il hacking GCP: HackTricks Training GCP Red Team Expert (GRTE) Impara e pratica il hacking Azure: HackTricks Training Azure Red Team Expert (AzRTE)

Supporta HackTricks

Generic

Networking

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

Molti loader incapsulano il loro stream TCP in SslStream e pinzano il certificato leaf del server contro una copia incorporata (certificate pinning). Le informazioni/attività del bot sono compresse (es., GZip). Quando le risposte superano una soglia (~1 MB), i dati vengono frammentati in piccoli chunk (es., segmenti da 16 KB) per evitare euristiche basate sulla dimensione e ridurre picchi di memoria durante la deserializzazione.

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]

Emulator API fingerprinting & sleep evasion

I malware spesso fingerprintano gli emulatori sandbox cercando le export virtualizzate di Defender (viste nel Malware Protection Emulator). Se uno di questi simboli è presente (scansione case-insensitive del processo), l'esecuzione viene ritardata di 10–30 minuti e poi ricontrollata per sprecare tempo di analisi.

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

Controllo degli argomenti

  • Gli operatori a volte richiedono che un'opzione CLI dall'aspetto benigno sia presente prima di eseguire il payload (es., /i:--type=renderer per mimare i processi child di Chromium). Se lo switch è assente, il loader esce immediatamente, ostacolando l'esecuzione in sandbox naive.

Stealth

Nome
VirtualAllocAlloca memoria (packers)
VirtualProtectCambia i permessi della memoria (packer che assegna permesso di esecuzione a una sezione)
ReadProcessMemoryInjection in processi esterni
WriteProcessMemoryA/WInjection in processi esterni
NtWriteVirtualMemory
CreateRemoteThreadDLL/Process injection...
NtUnmapViewOfSection
QueueUserAPC
CreateProcessInternalA/W

Execution

Function Name
CreateProcessA/W
ShellExecute
WinExec
ResumeThread
NtResumeThread

Miscellaneous

  • GetAsyncKeyState() -- Key logging
  • SetWindowsHookEx -- Key logging
  • GetForeGroundWindow -- Ottiene il nome della finestra attiva (o il sito web dal browser)
  • LoadLibrary() -- Carica libreria
  • GetProcAddress() -- Ottiene l'indirizzo di una funzione importata
  • CreateToolhelp32Snapshot() -- Elenca i processi in esecuzione
  • GetDC() -- Screenshot
  • BitBlt() -- Screenshot
  • InternetOpen(), InternetOpenUrl(), InternetReadFile(), InternetWriteFile() -- Accesso a Internet
  • FindResource(), LoadResource(), LockResource() -- Accesso alle risorse dell'eseguibile

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.

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: L'eseguibile verrà scritto nella memoria del processo vittima e verrà eseguito da lì.

Process Hollowing (a.k.a RunPE)

Process Hollowing è uno dei trucchi preferiti di defence-evasion / execution usati dal malware su Windows. L'idea è lanciare un processo legittimo in stato sospeso, rimuovere (hollow) la sua immagine originale dalla memoria e copiare al suo posto un PE arbitrario. Quando il thread principale viene infine riavviato l'entry-point maligno viene eseguito sotto le sembianze di un binario fidato (spesso firmato da Microsoft).

Flusso tipico:

  1. Avviare un host benigno (es. RegAsm.exe, rundll32.exe, msbuild.exe) sospeso in modo che non venga eseguita alcuna istruzione.
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. Leggere il payload malevolo in memoria e parsare i suoi header PE per ottenere SizeOfImage, le sezioni e il nuovo EntryPoint.
  2. NtUnmapViewOfSection / ZwUnmapViewOfSection – smappare la base dell'immagine originale del processo sospeso.
  3. VirtualAllocEx – riservare memoria RWX di SizeOfImage all'interno del processo remoto.
  4. WriteProcessMemory – copiare prima gli Headers, poi iterare sulle sezioni copiando i loro raw data.
  5. SetThreadContext – patchare il valore di EAX/RAX (RCX su x64) o Rip nella struttura context in modo che EIP punti all'EntryPoint del payload.
  6. ResumeThread – il thread continua, eseguendo il codice fornito dall'attaccante.

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

Note pratiche osservate nella campagna DarkCloud Stealer:

  • Il loader ha scelto RegAsm.exe (parte del .NET Framework) come host — un binario firmato che difficilmente attirerebbe l'attenzione.
  • Il VB6 stealer decrittato (holographies.exe) non viene scritto su disco; esiste solo all'interno del processo hollowed, rendendo più difficile il rilevamento statico.
  • Stringhe sensibili (regexes, paths, Telegram credentials) sono RC4-encrypted per-string e vengono decrittate solo a runtime, complicando ulteriormente la scansione della memoria.

Idee per il rilevamento:

  • Generare allarme su processi CREATE_SUSPENDED che non creano mai finestre GUI/console prima che una regione di memoria venga allocata come RWX (raro per codice benigno).
  • Cercare la sequenza di chiamate NtUnmapViewOfSection ➜ VirtualAllocEx ➜ WriteProcessMemory tra processi differenti.

Hooking

  • La SSDT (System Service Descriptor Table) punta a funzioni del kernel (ntoskrnl.exe) o al driver GUI (win32k.sys) in modo che i processi utente possano chiamare queste funzioni.
  • Un rootkit può modificare questi puntatori verso indirizzi controllati dall'attaccante.
  • Le IRP (I/O Request Packets) trasmettono porzioni di dati da un componente all'altro. Quasi tutto nel kernel usa IRP e ogni device object ha la propria function table che può essere hookata: DKOM (Direct Kernel Object Manipulation)
  • La IAT (Import Address Table) è utile per risolvere le dipendenze. È possibile hookare questa tabella per dirottare il codice che verrà chiamato.
  • Hook alla EAT (Export Address Table). Questi hook possono essere fatti da userland. L'obiettivo è hookare le funzioni esportate dalle DLL.
  • Inline Hooks: questo tipo è difficile da realizzare. Coinvolge la modifica del codice delle funzioni stesse, per esempio inserendo un jump all'inizio.

References

tip

Impara e pratica il hacking AWS:HackTricks Training AWS Red Team Expert (ARTE)
Impara e pratica il hacking GCP: HackTricks Training GCP Red Team Expert (GRTE) Impara e pratica il hacking Azure: HackTricks Training Azure Red Team Expert (AzRTE)

Supporta HackTricks