<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
<!-- NERF is a trademark of defconxt. -->
---
name: performing-malware-intelligence-analysis
description: >-
  Analyze malware samples to extract intelligence including behavioral indicators,
  C2 protocols, evasion techniques, and attribution artifacts. Covers static and
  dynamic analysis, sandbox orchestration, YARA rule development, and malware
  family clustering for intelligence production.
domain: cybersecurity
subdomain: threat-intelligence
tags:
  - malware-analysis
  - yara
  - sandbox
  - reverse-engineering
  - ioc-extraction
  - malware-families
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1587.001"]
---
# Performing Malware Intelligence Analysis

## Overview

Malware intelligence analysis extracts actionable threat intelligence from malware
samples through static analysis, dynamic sandbox execution, behavioral profiling,
and code similarity clustering. This skill covers automated sandbox orchestration,
YARA rule development, C2 protocol extraction, packer identification, and malware
family attribution for intelligence production.

## Prerequisites

| Requirement | Details |
|---|---|
| Python 3.10+ with `yara-python`, `pefile`, `requests`, `ssdeep` libraries | Required |
| Access to malware sandbox (Cape, Any.Run, Hybrid Analysis, or Joe Sandbox) | Required |
| VirusTotal API key for reputation and behavioral data | Required |
| MalwareBazaar API access for sample retrieval | Required |
| Isolated analysis environment (VM or container) | Required |

## Key Concepts

### Analysis Pipeline

1. **Triage**: file type, entropy, packer detection, AV label consensus
2. **Static analysis**: strings, imports, PE headers, embedded resources, certificates
3. **Dynamic analysis**: sandbox execution, API calls, network traffic, file/registry changes
4. **Code analysis**: disassembly, control flow, C2 protocol reverse engineering
5. **Clustering**: ssdeep fuzzy hashing, YARA family signatures, code similarity

### YARA Rule Structure

```yara
rule ExampleRAT_Family {
    meta:
        author = "analyst"
        description = "Detects ExampleRAT malware family"
        reference = "internal-report-001"
        date = "2026-03-01"
        tlp = "amber"
    strings:
        $mutex = "Global\\ExampleMutex" ascii
        $c2_pattern = /https?:\/\/[a-z]{5,12}\.(top|xyz|info)\// ascii
        $xor_key = { 4D 5A 90 00 03 00 00 00 }
    condition:
        uint16(0) == 0x5A4D and (2 of ($mutex, $c2_pattern, $xor_key))
}
```

### Malware Family Attribution

Key indicators for clustering:
- **Code overlap**: shared functions, libraries, unique algorithms
- **Infrastructure patterns**: DGA algorithms, C2 URI patterns, certificate reuse
- **Build artifacts**: compiler version, PDB paths, resource language IDs
- **Behavioral signatures**: unique mutex names, registry keys, named pipes

## Workflow


### Step 1: Sample Triage

```python
import pefile
import hashlib
import math

def triage_sample(filepath: str) -> dict:
    """Perform initial triage on a PE sample."""
    with open(filepath, "rb") as f:
        data = f.read()

    sha256 = hashlib.sha256(data).hexdigest()
    entropy = -sum(
        (c / len(data)) * math.log2(c / len(data))
        for c in bytearray(set(data)) if c > 0
    )

    result = {"sha256": sha256, "size": len(data), "entropy": round(entropy, 2)}

    try:
        pe = pefile.PE(data=data)
        result["imphash"] = pe.get_imphash()
        result["compile_time"] = pe.FILE_HEADER.TimeDateStamp
        result["sections"] = [
            {"name": s.Name.decode().strip("\\x00"), "entropy": round(s.get_entropy(), 2)}
            for s in pe.sections
        ]
    except pefile.PEFormatError:
        result["pe_valid"] = False

    return result
```

### Step 2: Submit to Sandbox

```python
import requests

def submit_to_cape(filepath: str, cape_url: str = "http://cape:8000") -> dict:
    """Submit sample to Cape sandbox for dynamic analysis."""
    with open(filepath, "rb") as f:
        response = requests.post(
            f"{cape_url}/apiv2/tasks/create/file/",
            files={"file": f},
            data={"timeout": 120, "enforce_timeout": True},
        )
    return response.json()

def get_cape_report(task_id: int, cape_url: str = "http://cape:8000") -> dict:
    """Retrieve analysis report from Cape sandbox."""
    response = requests.get(f"{cape_url}/apiv2/tasks/get/report/{task_id}/")
    report = response.json()
    return {
        "network": report.get("network", {}),
        "behavior": report.get("behavior", {}),
        "signatures": report.get("signatures", []),
        "dropped_files": report.get("dropped", []),
    }
```

### Step 3: Extract C2 Infrastructure

```python
def extract_c2_from_report(report: dict) -> list[dict]:
    """Extract C2 indicators from sandbox report."""
    c2_indicators = []
    network = report.get("network", {})

    for dns in network.get("dns", []):
        c2_indicators.append({
            "type": "domain",
            "value": dns["request"],
            "resolved": dns.get("answers", []),
        })

    for http in network.get("http", []):
        c2_indicators.append({
            "type": "url",
            "value": http["uri"],
            "method": http.get("method", "GET"),
            "user_agent": http.get("user-agent", ""),
        })

    for conn in network.get("tcp", []) + network.get("udp", []):
        c2_indicators.append({
            "type": "ip-dst",
            "value": conn["dst"],
            "port": conn["dport"],
        })

    return c2_indicators
```

### Step 4: YARA Rule Generation

```python
import yara

def compile_and_scan(rule_path: str, target_dir: str) -> list[dict]:
    """Compile YARA rules and scan directory for matches."""
    rules = yara.compile(filepath=rule_path)
    matches = []
    import os
    for root, _dirs, files in os.walk(target_dir):
        for fname in files:
            fpath = os.path.join(root, fname)
            try:
                result = rules.match(fpath)
                if result:
                    matches.append({
                        "file": fpath,
                        "rules": [r.rule for r in result],
                        "tags": [t for r in result for t in r.tags],
                    })
            except yara.Error:
                continue
    return matches
```

### Step 5: Fuzzy Hash Clustering

```python
def cluster_by_ssdeep(samples: list[dict]) -> list[list[str]]:
    """Cluster malware samples by ssdeep fuzzy hash similarity."""
    try:
        import ssdeep
    except ImportError:
        return [["ssdeep not installed"]]

    clusters: list[list[str]] = []
    assigned: set[int] = set()

    for i, s1 in enumerate(samples):
        if i in assigned:
            continue
        cluster = [s1["sha256"]]
        assigned.add(i)
        for j, s2 in enumerate(samples):
            if j in assigned:
                continue
            score = ssdeep.compare(s1["ssdeep"], s2["ssdeep"])
            if score > 50:
                cluster.append(s2["sha256"])
                assigned.add(j)
        clusters.append(cluster)
    return clusters
```

## Detection

```yaml
title: Malware Intelligence Analysis Detection
id: 686e1968-4cdc-4479-8525-d8a83be651c2
status: experimental
description: Detects suspicious activity related to performing malware intelligence analysis techniques in threat intelligence context
logsource:
  category: network_connection
  product: firewall
detection:
  selection:
    DestinationPort: 443
    Initiated: "true"
  condition: selection
level: medium
tags:
  - attack.t1587.001
  - attack.reconnaissance
falsepositives:
  - Threat intelligence platform aggregating feeds from approved sources
```


**Detection Opportunities**

| Indicator | Source | Detection Logic |
|---|---|---|
| Malware Intelligence Analysis Detection | firewall/network_connection | Sigma rule (medium) |
| ATT&CK Coverage | MITRE ATT&CK | T1587.001 |

## Verification

- [ ] Sample triage extracts PE metadata, imphash, and section entropy
- [ ] Sandbox submission returns task ID and report retrieves successfully
- [ ] C2 infrastructure extracted from network traffic in sandbox report
- [ ] YARA rules compile and match target malware family samples
- [ ] Fuzzy hash clustering groups related samples by code similarity
- [ ] Intelligence report links samples to malware family and threat actor

## References

- [YARA Documentation](https://yara.readthedocs.io/)
- [MalwareBazaar](https://bazaar.abuse.ch/)
- [Cape Sandbox](https://capev2.readthedocs.io/)
- [VirusTotal API](https://docs.virustotal.com/reference/)
- [pefile Library](https://github.com/erocarrera/pefile)
