Skip to content

hypnguyen1209/offensive-claude / skills/malware-analysis

malware-analysis

Unverified

Use when reverse-engineering or detecting malware — static triage + capa/YARA-X, emulation/DBI/.NET unpacking, dynamic/fileless/Volatility 3 memory analysis, C2 config extraction (Cobalt Strike/CAPE), C2 traffic detection (JA4+, beaconing)

references/unpacking-deobfuscation.md

View on GitHub
# Unpacking & Deobfuscation

Goal: recover the real payload from packed/crypted/obfuscated loaders so it can be statically and
dynamically analyzed. Modern commodity loaders (Latrodectus, MintsLoader, CastleLoader) and RAT
chains (AsyncRAT, Remcos, XWorm) layer compression + encryption + dynamic API resolution + in-memory
execution specifically to defeat naive unpacking.

## Theory / mechanism

Almost every runtime packer follows the **self-modifying stub pattern**:

1. Stub acquires **writable+executable** memory (`VirtualAlloc(...,PAGE_EXECUTE_READWRITE)` or
   `VirtualProtect(...,PAGE_EXECUTE_*)` on an existing region).
2. Stub **decrypts/decompresses** the real payload into that region.
3. Stub **transfers control** (the "tail jump" to OEP) into the freshly written region.

So the universal unpacking oracle is: **watch for memory that becomes executable, then dump it the
moment code executes inside it.** Flags `0x10/0x20/0x40/0x80` on `flProtect`/`flNewProtect` are the
trigger. This holds for UPX-clones, custom XOR/RC4 crypters, and most loader stages.

Three escalating approaches:

- **Static emulation** (Unicorn/Speakeasy/Qiling/unipacker) — emulate the stub with a faked Win32
  env, hook the memory APIs, dump. Fast, safe, no detonation; struggles on VM-protected
  (VMProtect/Themida/Enigma) and heavily API-dependent stubs.
- **Dynamic instrumentation** (Frida DBI) — detonate in an isolated VM, hook the same APIs live,
  dump each region as it is written. Handles API-heavy + .NET loaders the emulator can't.
- **Manual debugging** (x64dbg + Scylla) — hardware/memory breakpoints to reach OEP, dump, rebuild
  the IAT. The fallback that always works but is slow.

## Modern 2024-2026 variants (verified)

- **Latrodectus 1.4** (post-Operation Endgame downloader, MaaS-trending, per-campaign group IDs):
  moved string obfuscation from XOR to **AES-256-CTR** with a **hardcoded key + per-string IV**. The
  crypter loads a final DLL whose **multiple exported functions all share the same RVA** (so the
  entry export is irrelevant), and the infection JS is padded with thousands of comments to bloat
  and slow analysis. → Static string recovery needs the AES key+IV; emulate/decrypt rather than grep.
- **AsyncRAT fileless loader chains** (dominant RAT 2025): multi-stage **in-memory** .NET loaders
  that call `PatchAMSI()` + `PatchETW()` and resolve APIs dynamically via
  `GetModuleHandle`/`GetProcAddress` to defeat static analysis; persistence via a scheduled task
  masquerading as "Skype Updater". Delivered via LNK→JS→BAT through TryCloudflare tunnels and
  malicious PyPI packages. → Disk artifacts are minimal; dump from memory (Frida / Volatility).
- **garble-obfuscated Go malware** — symbol/string mangling; recover with **GoStringUngarbler**
  (added to FLARE-VM 2025).
- **Python/pyc malware** — marshalled bytecode; FLARE-VM 2025 ships `uncompyle6` + decompiler libs.

## Complete working unpacking

### A. Static emulation (preferred first attempt — no detonation)

```bash
# Generic emulation unpacker: hooks VirtualAlloc/Protect/WriteProcessMemory, dumps OEP regions
python3 scripts/auto_unpack.py sample.exe -o out/dumps/ --max-insn 50000000
# carved PEs land as out/dumps/<name>_unpacked_N_pe.bin -> re-run triage.py on each

# unipacker (known + unknown packers; for unknown you supply start/end addrs)
unipacker sample.exe -d out/   # interactive; emits a runnable rebuilt binary
```

### B. Dynamic Frida unpacking (when emulation fails; isolated VM only)

```bash
# isolated, snapshotted VM with FakeNet-NG/INetSim, no real internet
frida -f C:\sample.exe -l scripts/frida_unpack.js --no-pause
# dumps: dump_<tag>_<addr>_<size>.bin  (pe / wpm_pe / rwx_pe / code)
```

`scripts/frida_unpack.js` hooks `VirtualAlloc` (tracks RWX allocs), `VirtualProtect` (dumps on
transition to executable), `WriteProcessMemory` (dumps the injection buffer pre-write), `LdrLoadDll`,
and detects a managed (CLR) process so you know to pivot to .NET tooling.

### C. Manual x64dbg → OEP → Scylla (the reliable fallback)

```text
1. bp VirtualAlloc ; bp VirtualProtect ; bp NtWriteVirtualMemory
2. Run. On VirtualProtect with flNewProtect = PAGE_EXECUTE_READ(WRITE):
     - Follow the target address in the dump
3. Set a hardware EXEC breakpoint on that region's start.
4. Run -> break = you are at (or near) OEP.
5. Scylla: pick the process -> IAT Autosearch -> Get Imports -> Fix Dump on the memory dump.
6. Re-analyze the rebuilt PE in IDA/Ghidra.
```

### D. .NET loaders (ConfuserEx / .NET Reactor / custom)

```bash
# Stage 1: de4dot handles string encryption, control flow, proxy calls, anti-tamper
de4dot sample.exe -o cleaned.exe
# Stage 2 (de4dot fails): dnSpyEx -> break at module .cctor (unpack often here) -> dump module
# Stage 3 (custom loader): the key API is [Reflection.Assembly]::Load(byte[]).
#   Hook it to capture the real payload byte[]; ExtremeDumper dumps managed assemblies from memory.
```

For PowerShell/JS layers: replace `IEX`/`eval` with `Write-Output`/`console.log` and iteratively
decode. **PowerShell ScriptBlock logging (Event ID 4104)** captures the deobfuscated final layer for
free if it ran on a logged host.

## Detection

- **Sigma (in-memory unpack / AMSI-ETW patch primitives)** — detonation of these loaders touches
  predictable telemetry:

```yaml
title: Process Allocating RWX Then Self-Executing (Unpack Stub Behavior)
logsource: { product: windows, category: process_access }
detection:
  selection:
    CallTrace|contains: 'UNKNOWN'        # Sysmon EID 10 - call from unbacked memory
    GrantedAccess: '0x1FFFFF'
  condition: selection
level: medium
tags: [attack.defense_evasion, attack.t1027.002, attack.t1055]
```

- **ETW / EDR**: RWX private-commit allocations followed by execution from unbacked memory; image
  load of `clr.dll`/`coreclr.dll` in an unexpected parent; `amsi.dll` loaded then `AmsiScanBuffer`
  prologue modified (memory scan).
- **IOCs from unpacking**: the recovered OEP payload's sha256/imphash, the decrypt key/IV (e.g.
  Latrodectus AES key), embedded C2 (feed to config cluster), mutex/pipe names, the "Skype Updater"
  scheduled-task name for AsyncRAT.

## OPSEC

- Static emulation (`auto_unpack.py`, unipacker, Speakeasy, Qiling) touches **no disk-outside-output
  and no network** — preferred for stealth and safety.
- Frida/x64dbg detonation **executes the malware**. Mandatory: isolated VM, pre-execution snapshot,
  no host network (FakeNet-NG/INetSim), revert after. Many loaders self-delete (Latrodectus adapted
  a public self-delete PoC) — capture dumps *before* the process exits.
- Anti-analysis to expect: sandbox/VM checks, sleep-skipping needed, `rdtsc` timing, debugger checks
  (`IsDebuggerPresent`, PEB.BeingDebugged, `NtGlobalFlag`); use ScyllaHide/TitanHide to mask the
  debugger during manual unpacking.
- Cleanup: revert the VM snapshot; never let a detonation VM route to production networks.

## References

- Virus Bulletin VB2025 — *Arachnid alert: Latrodectus loader crawls through defences*: https://www.virusbulletin.com/conference/vb2025/abstracts/arachnid-alert-latrodectus-loader-crawls-through-defences/
- securityonline.info — *Latrodectus Malware Evolves: New Payload Features* (AES-256 strings): https://securityonline.info/latrodectus-malware-evolves-new-payload-features-enhance-evasion-and-control/
- LevelBlue — *AsyncRAT in action: fileless malware techniques* (PatchAMSI/PatchETW, dynamic resolution): https://www.levelblue.com/blogs/levelblue-blog/asyncrat-in-action-fileless-malware-techniques-and-analysis-of-a-remote-access-trojan
- lopqto — *Automated malware unpacking with binary emulation* (VirtualAlloc/Protect oracle): https://lopqto.me/posts/automated-malware-unpacking
- Medium/Mantutorcodes — *Dynamic Malware Unpacking & Analysis with Frida and Qiling* (2025): https://medium.com/@mantutorcodes/dynamic-malware-unpacking-analysis-with-frida-and-qiling-4232ca017054
- unipacker: https://github.com/unipacker/unipacker
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall