hypnguyen1209/offensive-claude / skills/malware-analysis
malware-analysis
UnverifiedUse 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)
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 9.0 KB |
| references/config-c2-extraction.md | markdown | 7.6 KB |
| references/dynamic-fileless-memory.md | markdown | 7.9 KB |
| references/network-c2-detection.md | markdown | 6.8 KB |
| references/static-triage-capa.md | markdown | 7.2 KB |
| references/unpacking-deobfuscation.md | markdown | 7.8 KB |
| references/yara-detection-engineering.md | markdown | 6.5 KB |
| scripts/auto_unpack.py | script | 6.8 KB |
| scripts/beacon_profiler.py | script | 4.6 KB |
| scripts/cs_config_extract.py | script | 5.0 KB |
| scripts/frida_unpack.js | script | 4.5 KB |
| scripts/mem_triage.py | script | 6.0 KB |
| scripts/triage.py | script | 9.0 KB |
| scripts/yara_gen.py | script | 5.9 KB |
scripts/triage.py
View on GitHub#!/usr/bin/env python3
"""
triage.py - Static triage orchestrator for unknown binaries.
Computes hashes (md5/sha256/imphash/ssdeep/TLSH), parses PE header anomalies,
per-section entropy + packer heuristics, extracts the Rich header, dumps imports,
flags suspicious API combos, and (if installed) shells out to FLOSS / capa / YARA-X.
USAGE:
python3 triage.py SAMPLE [--floss] [--capa] [--yara RULES.yar] [--json OUT.json]
DEPENDENCIES (all optional except pefile):
pip install pefile python-tlsh ssdeep
External (PATH): floss, capa, yara-x (graceful skip if missing)
OPSEC: read-only on the sample, no execution. Safe on an analysis host. ssdeep/TLSH
are imported lazily; the script runs without them.
"""
import argparse
import hashlib
import json
import math
import shutil
import struct
import subprocess
import sys
from pathlib import Path
try:
import pefile
except ImportError:
sys.exit("pip install pefile")
# ---- Suspicious API combinations (capability -> required imports) -------------
SUSPICIOUS_COMBOS = {
"process_injection": ["VirtualAllocEx", "WriteProcessMemory", "CreateRemoteThread"],
"process_hollowing": ["NtUnmapViewOfSection", "ZwUnmapViewOfSection", "SetThreadContext"],
"apc_injection": ["QueueUserAPC", "NtQueueApcThread"],
"dll_injection": ["LoadLibraryA", "GetProcAddress", "CreateRemoteThread"],
"amsi_etw_patch": ["VirtualProtect", "GetProcAddress", "LoadLibraryA"],
"keylogging": ["SetWindowsHookExA", "GetAsyncKeyState", "GetForegroundWindow"],
"anti_debug": ["IsDebuggerPresent", "CheckRemoteDebuggerPresent", "NtQueryInformationProcess"],
"c2_http": ["InternetOpenA", "InternetConnectA", "HttpSendRequestA", "WinHttpConnect"],
"ransomware_crypto": ["CryptEncrypt", "CryptGenKey", "BCryptEncrypt", "CryptAcquireContextA"],
"persistence_registry": ["RegSetValueExA", "RegCreateKeyExA"],
"persistence_task": ["ITaskScheduler", "INetFwPolicy2"],
"process_enum": ["CreateToolhelp32Snapshot", "Process32First", "Process32Next"],
"token_manipulation": ["OpenProcessToken", "AdjustTokenPrivileges", "LookupPrivilegeValueA"],
"dynamic_resolve": ["LoadLibraryA", "LoadLibraryExA", "GetProcAddress"],
}
KNOWN_PACKER_SECTIONS = {
"UPX0", "UPX1", "UPX2", ".vmp0", ".vmp1", ".themida", ".aspack", ".adata",
".petite", ".enigma1", ".enigma2", ".nsp0", ".nsp1", ".MPRESS1", ".MPRESS2",
".pec1", ".pec2", "pebundle", ".y0da", "FSG!",
}
def sha256(p):
h = hashlib.sha256()
h.update(Path(p).read_bytes())
return h.hexdigest()
def md5(p):
return hashlib.md5(Path(p).read_bytes()).hexdigest()
def entropy(data: bytes) -> float:
if not data:
return 0.0
counts = [0] * 256
for b in data:
counts[b] += 1
e = 0.0
n = len(data)
for c in counts:
if c:
p = c / n
e -= p * math.log2(p)
return round(e, 3)
def fuzzy_hashes(p):
out = {}
try:
import ssdeep
out["ssdeep"] = ssdeep.hash_from_file(str(p))
except Exception:
out["ssdeep"] = None
try:
import tlsh
out["tlsh"] = tlsh.hash(Path(p).read_bytes())
except Exception:
out["tlsh"] = None
return out
def rich_header(pe):
"""Decode the undocumented Rich header (compiler/toolchain fingerprint)."""
try:
rich = pe.parse_rich_header()
if not rich:
return None
out = {"checksum": hex(rich.get("checksum", 0)), "comp_id": []}
vals = rich.get("values", [])
for i in range(0, len(vals), 2):
comp = vals[i]
count = vals[i + 1]
prod_id = comp >> 16
build = comp & 0xFFFF
out["comp_id"].append({"prodid": prod_id, "build": build, "count": count})
# richhash (md5 of clear data) is stable across recompiles of same toolchain
clear = struct.pack("<%dI" % len(vals), *vals)
out["rich_hash"] = hashlib.md5(clear).hexdigest()
return out
except Exception:
return None
def analyze_pe(path):
res = {"format": "PE", "warnings": [], "sections": [], "imports": {},
"capabilities": [], "tls_callbacks": 0, "rich_header": None}
pe = pefile.PE(str(path), fast_load=False)
try:
res["imphash"] = pe.get_imphash()
except Exception:
res["imphash"] = None
res["compile_time"] = pe.FILE_HEADER.TimeDateStamp
res["machine"] = hex(pe.FILE_HEADER.Machine)
res["entry_point"] = hex(pe.OPTIONAL_HEADER.AddressOfEntryPoint)
res["rich_header"] = rich_header(pe)
ep = pe.OPTIONAL_HEADER.AddressOfEntryPoint
ep_section = None
for s in pe.sections:
name = s.Name.rstrip(b"\x00").decode("latin1", "replace")
ent = entropy(s.get_data())
rec = {"name": name, "vsize": s.Misc_VirtualSize, "rawsize": s.SizeOfRawData,
"entropy": ent, "exec": bool(s.Characteristics & 0x20000000),
"write": bool(s.Characteristics & 0x80000000)}
res["sections"].append(rec)
if s.VirtualAddress <= ep < s.VirtualAddress + max(s.Misc_VirtualSize, s.SizeOfRawData):
ep_section = name
if ent > 7.0:
res["warnings"].append(f"high entropy section {name} ({ent}) - likely packed/encrypted")
if rec["exec"] and rec["write"]:
res["warnings"].append(f"RWX section {name} - self-modifying/unpacking stub")
if name in KNOWN_PACKER_SECTIONS:
res["warnings"].append(f"known packer section name: {name}")
if ep_section and ep_section not in (".text", "CODE", ".itext"):
res["warnings"].append(f"entry point in non-standard section: {ep_section}")
# Imports
flat = set()
if hasattr(pe, "DIRECTORY_ENTRY_IMPORT"):
for entry in pe.DIRECTORY_ENTRY_IMPORT:
dll = entry.dll.decode("latin1", "replace")
names = []
for imp in entry.imports:
nm = imp.name.decode("latin1", "replace") if imp.name else f"ord_{imp.ordinal}"
names.append(nm)
flat.add(nm)
res["imports"][dll] = names
if len(flat) < 10:
res["warnings"].append(f"very few imports ({len(flat)}) - packed or dynamic resolution")
# TLS callbacks (anti-debug / pre-main exec)
if hasattr(pe, "DIRECTORY_ENTRY_TLS") and pe.DIRECTORY_ENTRY_TLS:
cb = pe.DIRECTORY_ENTRY_TLS.struct.AddressOfCallBacks
if cb:
res["tls_callbacks"] = 1
res["warnings"].append("TLS callbacks present - code runs before entry point")
# Capability matching
for cap, apis in SUSPICIOUS_COMBOS.items():
hit = [a for a in apis if a in flat]
if len(hit) >= max(2, len(apis) - 1):
res["capabilities"].append({"capability": cap, "matched": hit})
pe.close()
return res
def run_tool(args, label):
try:
cp = subprocess.run(args, capture_output=True, text=True, timeout=600)
return {"ran": True, "rc": cp.returncode, "stdout": cp.stdout[-20000:], "stderr": cp.stderr[-2000:]}
except FileNotFoundError:
return {"ran": False, "reason": f"{label} not on PATH"}
except subprocess.TimeoutExpired:
return {"ran": False, "reason": f"{label} timed out"}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("sample")
ap.add_argument("--floss", action="store_true", help="run FLARE FLOSS string extraction")
ap.add_argument("--capa", action="store_true", help="run capa capability detection (JSON)")
ap.add_argument("--yara", help="scan with yara-x rules file")
ap.add_argument("--json", help="write full report JSON to this path")
a = ap.parse_args()
p = Path(a.sample)
if not p.is_file():
sys.exit(f"no such file: {p}")
data = p.read_bytes()
report = {
"file": str(p), "size": len(data),
"md5": md5(p), "sha256": sha256(p),
"overall_entropy": entropy(data),
"magic": data[:4].hex(),
}
report.update(fuzzy_hashes(p))
if data[:2] == b"MZ":
try:
report["pe"] = analyze_pe(p)
except Exception as e:
report["pe_error"] = str(e)
elif data[:4] == b"\x7fELF":
report["format"] = "ELF (use capa --format elf / readelf for detail)"
if a.floss and shutil.which("floss"):
report["floss"] = run_tool(["floss", "-q", str(p)], "floss")
if a.capa:
capa_bin = shutil.which("capa")
if capa_bin:
report["capa"] = run_tool([capa_bin, "-j", str(p)], "capa")
if a.yara:
yx = shutil.which("yara-x") or shutil.which("yr")
if yx:
report["yara"] = run_tool([yx, "scan", a.yara, str(p)], "yara-x")
out = json.dumps(report, indent=2, default=str)
if a.json:
Path(a.json).write_text(out)
print(f"[+] report -> {a.json}")
# terse console summary
if "pe" in report:
print(f" imphash={report['pe'].get('imphash')} caps={[c['capability'] for c in report['pe']['capabilities']]}")
for w in report["pe"]["warnings"]:
print(f" [!] {w}")
else:
print(out)
if __name__ == "__main__":
main()
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| 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: 198k | Updated | Claude CodeCodex | Verified | Install |
| 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: 194k | Updated | Claude CodeCodex | Verified | Install |
| ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report. | Stars: 194k | Updated | Claude CodeCodex | Verified | Install |
| 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: 194k | Updated | Claude CodeCodex | Verified | Install |