<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: performing-malware-hash-enrichment
description: >-
  Enrich malware file hashes using VirusTotal, MalwareBazaar, Hybrid Analysis,
  and sandbox APIs to determine malware family, behavior, and threat context.
domain: cybersecurity
subdomain: threat-intelligence
tags:
  - malware-analysis
  - hash-enrichment
  - virustotal
  - malwarebazaar
  - sandbox
  - yara
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1587.001"]
---
# Performing Malware Hash Enrichment

## Overview

Malware hash enrichment transforms raw file hashes (MD5, SHA1, SHA256) into
contextualized intelligence by querying reputation services, retrieving sandbox
detonation reports, identifying malware families, extracting behavioral IOCs,
and mapping to ATT&CK techniques. This enables rapid triage of suspicious files
without requiring local analysis infrastructure.

## Prerequisites

- Python 3.10+ with `vt-py`, `requests`
- API keys: VirusTotal, MalwareBazaar, Hybrid Analysis
- Understanding of hash types (MD5/SHA1/SHA256) and their limitations
- Optional: YARA for pattern matching, Any.Run for interactive sandbox

```bash
pip install vt-py requests
```

## Key Concepts

### Hash Type Reliability

| Hash | Length | Use Case | Limitation |
|------|--------|----------|-----------|
| MD5 | 32 hex | Legacy lookup | Collision-vulnerable, not unique |
| SHA1 | 40 hex | Cross-referencing | Collision attacks demonstrated |
| SHA256 | 64 hex | Primary identifier | Preferred for malware ID |
| Imphash | 32 hex | Import table hash | Groups malware families by imports |
| SSDEEP | Variable | Fuzzy matching | Finds similar (repacked) samples |

### Enrichment Priority

```
SHA256 → VirusTotal (detection ratio, behavioral report)
       → MalwareBazaar (malware family, tags, YARA matches)
       → Hybrid Analysis (sandbox report, network IOCs)
       → Any.Run (interactive sandbox, MITRE ATT&CK mapping)
```

### Confidence from Detection Ratio

```
50+ engines detect:  HIGH confidence malicious (score 95+)
10-49 engines:       MODERATE confidence (score 70-94)
1-9 engines:         LOW confidence, possible FP (score 40-69)
0 engines:           Unknown — may be novel; submit to sandbox
```

## Workflow

### Step 1: VirusTotal Hash Lookup

```python
import requests

def vt_hash_lookup(sha256: str, api_key: str) -> dict:
    """Query VirusTotal for file hash report."""
    resp = requests.get(
        f"https://www.virustotal.com/api/v3/files/{sha256}",
        headers={"x-apikey": api_key}, timeout=30,
    )
    if resp.status_code == 200:
        attrs = resp.json()["data"]["attributes"]
        stats = attrs.get("last_analysis_stats", {})
        return {
            "source": "virustotal",
            "sha256": sha256,
            "detection_ratio": f"{stats.get('malicious', 0)}/{sum(stats.values())}",
            "malicious": stats.get("malicious", 0),
            "name": attrs.get("meaningful_name", ""),
            "type": attrs.get("type_description", ""),
            "size": attrs.get("size", 0),
            "first_submission": attrs.get("first_submission_date"),
            "tags": attrs.get("tags", []),
            "popular_threat_classification": attrs.get("popular_threat_classification", {}),
        }
    return {"source": "virustotal", "error": resp.status_code}

def vt_behavior_report(sha256: str, api_key: str) -> dict:
    """Get behavioral analysis from VirusTotal sandboxes."""
    resp = requests.get(
        f"https://www.virustotal.com/api/v3/files/{sha256}/behaviour_summary",
        headers={"x-apikey": api_key}, timeout=30,
    )
    if resp.status_code == 200:
        data = resp.json()["data"]
        return {
            "processes_created": data.get("processes_created", [])[:10],
            "dns_lookups": data.get("dns_lookups", [])[:10],
            "http_conversations": data.get("http_conversations", [])[:10],
            "files_written": data.get("files_written", [])[:10],
            "registry_keys_set": data.get("registry_keys_set", [])[:10],
            "mitre_attack_techniques": data.get("mitre_attack_techniques", []),
        }
    return {"error": resp.status_code}
```

### Step 2: MalwareBazaar Lookup

```python
def malwarebazaar_lookup(sha256: str) -> dict:
    """Query MalwareBazaar for sample information."""
    resp = requests.post(
        "https://mb-api.abuse.ch/api/v1/",
        data={"query": "get_info", "hash": sha256}, timeout=30,
    )
    if resp.status_code == 200:
        data = resp.json()
        if data.get("query_status") == "hash_not_found":
            return {"source": "malwarebazaar", "found": False}
        sample = data.get("data", [{}])[0]
        return {
            "source": "malwarebazaar",
            "found": True,
            "file_type": sample.get("file_type", ""),
            "signature": sample.get("signature", ""),
            "tags": sample.get("tags", []),
            "reporter": sample.get("reporter", ""),
            "delivery_method": sample.get("delivery_method", ""),
            "intelligence": sample.get("intelligence", {}),
        }
    return {"source": "malwarebazaar", "error": resp.status_code}
```

### Step 3: ThreatFox IOC Correlation

```python
def threatfox_lookup(sha256: str) -> dict:
    """Check ThreatFox for associated IOCs."""
    resp = requests.post(
        "https://threatfox-api.abuse.ch/api/v1/",
        json={"query": "search_hash", "hash": sha256}, timeout=30,
    )
    if resp.status_code == 200:
        data = resp.json()
        if data.get("query_status") == "no_result":
            return {"source": "threatfox", "found": False}
        return {
            "source": "threatfox",
            "found": True,
            "iocs": [
                {"type": i["ioc_type"], "value": i["ioc"], "threat_type": i["threat_type"],
                 "malware": i.get("malware_printable", "")}
                for i in data.get("data", [])[:20]
            ],
        }
    return {"source": "threatfox", "error": resp.status_code}
```

### Step 4: Aggregate and Score

```python
def aggregate_enrichment(vt: dict, mb: dict, tf: dict) -> dict:
    """Aggregate results and compute confidence score."""
    score = 30
    malware_family = ""

    if vt.get("malicious", 0) > 10:
        score += 40
    elif vt.get("malicious", 0) > 3:
        score += 25

    if mb.get("found"):
        score += 15
        malware_family = mb.get("signature", "")

    if tf.get("found"):
        score += 10

    return {
        "confidence_score": min(score, 100),
        "malware_family": malware_family,
        "detection_ratio": vt.get("detection_ratio", "0/0"),
        "to_ids": score >= 70,
        "sources_consulted": 3,
        "virustotal": vt,
        "malwarebazaar": mb,
        "threatfox": tf,
    }
```

## Detection

```yaml
title: Malware Hash Enrichment Detection
id: f1d22be6-f92f-404f-a5e5-195f400add70
status: experimental
description: Detects suspicious activity related to performing malware hash enrichment 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
```

## Verification

- [ ] SHA256 hash lookup returns detection ratio and file metadata
- [ ] Behavioral report extracts network IOCs and ATT&CK techniques
- [ ] MalwareBazaar provides malware family classification
- [ ] ThreatFox correlates hash to associated network IOCs
- [ ] Confidence score accurately reflects multi-source consensus
- [ ] Results exportable to MISP/OpenCTI with proper tagging

## References

- [VirusTotal API v3](https://docs.virustotal.com/reference/overview)
- [MalwareBazaar API](https://bazaar.abuse.ch/api/)
- [ThreatFox API](https://threatfox.abuse.ch/api/)
- [Hybrid Analysis API](https://www.hybrid-analysis.com/docs/api/v2)
- [Any.Run API](https://any.run/api-documentation/)
