<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: malware-analysis
description: >-
  Malware analysis including static analysis (PE/ELF parsing, string extraction,
  import analysis), dynamic analysis (sandbox execution, API monitoring, network
  capture), behavioral analysis, code deobfuscation, unpacking, YARA rule creation,
  reverse engineering with Ghidra/IDA/radare2, and malware classification. Covers
  commodity malware, APT implants, ransomware, and fileless malware.
domain: cybersecurity
subdomain: malware-analysis
tags:
  - malware-analysis
  - reverse-engineering
  - yara
  - ghidra
  - sandbox
  - static-analysis
  - dynamic-analysis
  - unpacking
  - ransomware
  - fileless-malware
version: "1.0"
author: defconxt
license: AGPL-3.0
compatibility: Designed for Claude Code, GitHub Copilot, OpenAI Codex, Cursor, Gemini CLI, and any agentskills.io-compatible agent.
metadata:
  mitre-attack: ["T1027", "T1055", "T1059", "T1140", "T1204", "T1036"]
  nist-csf: ["DE.CM-4", "DE.AE-2", "RS.AN-1"]
  frameworks: ["MITRE ATT&CK", "CISA Malware Analysis Reports"]
---

# Malware Analysis

## When to Use

Activate when the operator asks about malware analysis, reverse engineering,
YARA rules, sandbox analysis, sample triage, PE/ELF analysis, code deobfuscation,
unpacking, or malware classification.

Mode: `[MODE: BLUE]` for defensive analysis; `[MODE: INCIDENT]` for IR triage; `[MODE: RED]` for payload development context.

## Prerequisites

- Isolated analysis environment (VM or dedicated hardware, no network bridge to production)
- FlareVM or REMnux analysis distribution
- Ghidra, IDA Free, or radare2 for disassembly
- Any.run, Joe Sandbox, or CAPE sandbox access

## Quick Reference

| Phase | Tool / Command | Purpose |
|-------|---------------|---------|
| Triage | `file sample.exe && sha256sum sample.exe` | File type + hash |
| Strings | `strings -a -n 6 sample.exe \| less` | Extract printable strings |
| FLOSS | `floss sample.exe` | Extract obfuscated/stack strings |
| PE analysis | `pestudio sample.exe` / `pefile` Python | Import/export/section analysis |
| ELF analysis | `readelf -a sample && objdump -d sample` | Linux binary analysis |
| Sandbox | `detonate sample.exe --timeout 300` | Dynamic execution |
| Network | `fakenet-ng` / `inetsim` | Simulate network services |
| Process monitor | `procmon.exe /BackingFile log.pml` | API call monitoring |
| YARA scan | `yara -r rules/ samples/` | Pattern matching |
| Unpack | `upx -d packed.exe` / `unipacker packed.exe` | Unpack compressed binaries |
| Ghidra | `analyzeHeadless /project sample -import sample.exe` | Automated disassembly |

## Workflow

### 1. Sample Triage (5 minutes)

```bash
# File identification
file sample.exe
exiftool sample.exe

# Hash generation
md5sum sample.exe
sha256sum sample.exe
ssdeep sample.exe  # Fuzzy hash for similarity

# VirusTotal lookup
curl -s -H "x-apikey: $VT_KEY" \
  "https://www.virustotal.com/api/v3/files/$(sha256sum sample.exe | cut -d' ' -f1)" | jq '.data.attributes.last_analysis_stats'

# Quick string analysis
strings -a -n 6 sample.exe | grep -iE 'http|https|ftp|cmd|powershell|reg|password|key|token|mutex|\.dll|\.exe'
floss sample.exe --no stack_strings  # Deobfuscated strings
```

### 2. Static Analysis

```python
# PE file analysis with pefile
import pefile, hashlib

pe = pefile.PE('sample.exe')

# Compilation timestamp
print(f"Compile time: {pe.FILE_HEADER.TimeDateStamp}")

# Suspicious imports
suspicious_apis = ['VirtualAlloc', 'CreateRemoteThread', 'WriteProcessMemory',
    'NtUnmapViewOfSection', 'WinExec', 'ShellExecute', 'URLDownloadToFile',
    'InternetOpen', 'HttpSendRequest', 'CryptEncrypt', 'RegSetValue']

for entry in pe.DIRECTORY_ENTRY_IMPORT:
    for imp in entry.imports:
        if imp.name and imp.name.decode() in suspicious_apis:
            print(f"⚠ {entry.dll.decode()}: {imp.name.decode()}")

# Section entropy (high entropy = packed/encrypted)
import math
for section in pe.sections:
    name = section.Name.decode().rstrip('\x00')
    entropy = section.get_entropy()
    print(f"{name}: entropy={entropy:.2f} {'⚠ PACKED' if entropy > 7.0 else ''}")

# Check for known packers
# UPX magic: "UPX!" in section names
# Themida: .themida section
# VMProtect: .vmp section
```

### 3. Dynamic Analysis

```bash
# Network simulation (start before executing sample)
sudo inetsim --data-dir /var/lib/inetsim --report-dir /var/log/inetsim

# OR use FakeNet-NG
sudo fakenet-ng

# Process monitoring (Windows)
# Start Procmon with filter: Process Name = sample.exe
procmon.exe /Quiet /Minimized /BackingFile analysis.pml

# Execute sample with timeout
timeout 300 ./sample.exe

# Capture analysis artifacts
# Registry changes:  procmon filter Operation=RegSetValue
# File system:       procmon filter Operation=CreateFile/WriteFile
# Network:           Wireshark/tcpdump capture
# Process creation:  procmon filter Operation=Process Create

# API monitoring with API Monitor or x64dbg
# Key APIs to monitor:
# - Memory: VirtualAlloc, VirtualProtect, NtMapViewOfSection
# - Process: CreateProcess, CreateRemoteThread, NtCreateThreadEx
# - Network: connect, send, recv, InternetOpen, HttpSendRequest
# - Crypto: CryptEncrypt, CryptDecrypt, BCryptEncrypt
# - Persistence: RegSetValue, CreateService, schtasks
```

### 4. YARA Rule Creation

```yara
rule APT_Backdoor_CustomLoader {
    meta:
        description = "Detects custom loader used by APT group"
        author = "NERF"
        date = "2026-03-17"
        hash = "abc123..."
        mitre_attack = "T1055.001"
        severity = "critical"

    strings:
        $mutex = "Global\\CustomMutex_" ascii wide
        $api1 = "VirtualAllocEx" ascii
        $api2 = "WriteProcessMemory" ascii
        $api3 = "CreateRemoteThread" ascii
        $xor_loop = { 80 34 ?? ?? 48 FF C? 48 3B ?? 72 F? }
        $config = { 68 74 74 70 [1-3] 3A 2F 2F }  // "http" + "://"

    condition:
        uint16(0) == 0x5A4D and
        filesize < 500KB and
        $mutex and
        2 of ($api*) and
        ($xor_loop or $config)
}
```

### 5. Deobfuscation & Unpacking

```bash
# UPX unpacking
upx -d packed.exe -o unpacked.exe

# Generic unpacking with unipacker
unipacker packed.exe

# Manual unpacking approach:
# 1. Set breakpoint on VirtualProtect/VirtualAlloc
# 2. Run until OEP (Original Entry Point) is reached
# 3. Dump memory with pe-sieve or Scylla

# PowerShell deobfuscation
# Replace IEX with Write-Output to reveal payload
$encoded | ForEach-Object { $_ -replace 'IEX', 'Write-Output' } | powershell -

# JavaScript deobfuscation
# Use js-beautify + manual eval replacement
cat obfuscated.js | js-beautify | sed 's/eval(/console.log(/g' | node
```

## Verification

- [ ] Sample triaged (hash, file type, VT lookup)
- [ ] Static analysis complete (imports, strings, entropy, sections)
- [ ] Dynamic analysis complete (behavior, network, persistence)
- [ ] YARA rule written and tested against sample set
- [ ] Malware classified (family, capabilities, C2 infrastructure)
- [ ] IOCs extracted (hashes, domains, IPs, mutexes, file paths)
- [ ] Analysis report written with MITRE ATT&CK mapping

## Detection Opportunities

- YARA rules deployed to endpoint and email gateway
- Network IOCs (C2 domains/IPs) added to threat feed
- Behavioral signatures added to EDR policy
- File hashes blocked at endpoint and proxy
- Sigma rules for observed process behaviors
