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)

scripts/auto_unpack.py

View on GitHub
#!/usr/bin/env python3
r"""
auto_unpack.py - Generic emulation-based unpacker for self-modifying PE stubs.

Strategy (the universal pattern behind most runtime packers):
  1. Emulate the PE entry point with Unicorn + a minimal Win32 environment.
  2. Hook VirtualAlloc / VirtualProtect / WriteProcessMemory-style transitions.
  3. Whenever a memory region becomes EXECUTABLE *and* writable content was placed
     there, snapshot it. When execution jumps INTO a freshly written region (OEP
     tail-jump), dump every candidate region that begins with 'MZ' or looks like
     shellcode (>= MIN_DUMP bytes of non-zero, reasonable entropy).
  4. Carve dumped PEs to disk for re-analysis.

This is a controlled, no-network, no-side-effects emulator - far safer than
detonating the sample. It will not perfectly emulate complex packers (VMProtect,
Themida) but recovers UPX-clones, custom XOR/RC4 stub packers, and many .NET-less
loader stages.

USAGE:
    python3 auto_unpack.py SAMPLE.exe -o dumps/ [--max-insn 50000000] [--trace]

DEPENDENCIES:
    pip install unicorn pefile capstone
"""
import argparse
import math
import struct
import sys
from pathlib import Path

try:
    import pefile
    from unicorn import (Uc, UC_ARCH_X86, UC_MODE_32, UC_MODE_64, UC_HOOK_CODE,
                         UC_HOOK_MEM_WRITE, UC_PROT_ALL, UC_PROT_READ, UC_PROT_WRITE,
                         UC_PROT_EXEC)
    from unicorn.x86_const import (UC_X86_REG_RSP, UC_X86_REG_RIP, UC_X86_REG_ESP,
                                   UC_X86_REG_EIP, UC_X86_REG_RAX, UC_X86_REG_EAX)
except ImportError:
    sys.exit("pip install unicorn pefile capstone")

STACK_BASE = 0x00B0_0000
STACK_SIZE = 0x0010_0000
HEAP_BASE = 0x0100_0000
HEAP_SIZE = 0x0400_0000
MIN_DUMP = 1024


def entropy(b):
    if not b:
        return 0.0
    c = [0] * 256
    for x in b:
        c[x] += 1
    n = len(b)
    return -sum((k / n) * math.log2(k / n) for k in c if k)


class Unpacker:
    def __init__(self, path, outdir, max_insn, trace):
        self.path = Path(path)
        self.outdir = Path(outdir)
        self.outdir.mkdir(parents=True, exist_ok=True)
        self.max_insn = max_insn
        self.trace = trace
        self.pe = pefile.PE(str(self.path))
        self.is64 = self.pe.FILE_HEADER.Machine == 0x8664
        self.base = self.pe.OPTIONAL_HEADER.ImageBase
        self.image = self.pe.get_memory_mapped_image(ImageBase=self.base)
        self.image_size = (len(self.image) + 0xFFF) & ~0xFFF
        self.written = {}          # page -> True when written to
        self.exec_regions = set()  # (start,end) marked executable at runtime
        self.dumped = 0
        mode = UC_MODE_64 if self.is64 else UC_MODE_32
        self.uc = Uc(UC_ARCH_X86, mode)

    def _map(self):
        self.uc.mem_map(self.base, self.image_size, UC_PROT_ALL)
        self.uc.mem_write(self.base, self.image)
        self.uc.mem_map(STACK_BASE, STACK_SIZE, UC_PROT_READ | UC_PROT_WRITE)
        self.uc.mem_map(HEAP_BASE, HEAP_SIZE, UC_PROT_ALL)
        sp = STACK_BASE + STACK_SIZE - 0x1000
        if self.is64:
            self.uc.reg_write(UC_X86_REG_RSP, sp)
        else:
            self.uc.reg_write(UC_X86_REG_ESP, sp)
        self.heap_cursor = HEAP_BASE

    def _hook_write(self, uc, access, address, size, value, user):
        self.written[address & ~0xFFF] = True

    def _hook_code(self, uc, address, size, user):
        # OEP heuristic: executing inside the heap (allocated at runtime) or a
        # page we previously observed being written to -> likely unpacked code.
        page = address & ~0xFFF
        in_heap = HEAP_BASE <= address < HEAP_BASE + HEAP_SIZE
        if in_heap or (self.written.get(page) and not (self.base <= address < self.base + self.image_size)):
            self._dump_region(address)
        if self.trace and (address % 0x1000 == 0):
            print(f"  [trace] exec @ {address:#x}")

    def _read_safe(self, start, length):
        try:
            return self.uc.mem_read(start, length)
        except Exception:
            return b""

    def _dump_region(self, hint_addr):
        """Carve any MZ-prefixed or high-entropy executable blob around hint_addr."""
        for base in (HEAP_BASE, hint_addr & ~0xFFFFF):
            blob = bytes(self._read_safe(base, 0x200000))
            if not blob:
                continue
            idx = blob.find(b"MZ")
            while idx != -1 and idx < len(blob) - 0x40:
                e_lfanew_off = idx + 0x3C
                if e_lfanew_off + 4 <= len(blob):
                    e_lfanew = struct.unpack_from("<I", blob, e_lfanew_off)[0]
                    pe_off = idx + e_lfanew
                    if 0 < e_lfanew < 0x1000 and pe_off + 4 <= len(blob) and blob[pe_off:pe_off + 4] == b"PE\x00\x00":
                        self._write_dump(blob[idx:idx + 0x180000], "pe")
                        return
                idx = blob.find(b"MZ", idx + 1)
            # shellcode fallback: contiguous non-zero high-entropy
            window = blob[:0x10000]
            if len(window) >= MIN_DUMP and window.count(0) < len(window) * 0.6 and entropy(window) > 6.0:
                self._write_dump(window, "shellcode")
                return

    def _write_dump(self, data, kind):
        # trim trailing zero padding
        data = data.rstrip(b"\x00") or data
        out = self.outdir / f"{self.path.stem}_unpacked_{self.dumped}_{kind}.bin"
        out.write_bytes(data)
        print(f"[+] dumped {kind} ({len(data)} bytes) -> {out}")
        self.dumped += 1

    def run(self):
        self._map()
        self.uc.hook_add(UC_HOOK_MEM_WRITE, self._hook_write)
        self.uc.hook_add(UC_HOOK_CODE, self._hook_code)
        ep = self.base + self.pe.OPTIONAL_HEADER.AddressOfEntryPoint
        print(f"[*] emulating from EP {ep:#x} (arch={'x64' if self.is64 else 'x86'})")
        try:
            self.uc.emu_start(ep, self.base + self.image_size, count=self.max_insn)
        except Exception as e:
            # most packers will fault on an unmapped API call - that's fine, by then
            # the payload is usually already written. Try a final sweep.
            if self.trace:
                print(f"[*] emulation stopped: {e}")
            self._dump_region(HEAP_BASE)
        if self.dumped == 0:
            print("[-] no payload recovered - try manual unpacking (x64dbg + Scylla) "
                  "or a stronger emulator (Speakeasy/Qiling). Likely VM-protected.")
        else:
            print(f"[+] {self.dumped} region(s) dumped. Fix IAT with Scylla if needed.")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("sample")
    ap.add_argument("-o", "--outdir", default="dumps")
    ap.add_argument("--max-insn", type=int, default=50_000_000)
    ap.add_argument("--trace", action="store_true")
    a = ap.parse_args()
    Unpacker(a.sample, a.outdir, a.max_insn, a.trace).run()


if __name__ == "__main__":
    main()
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