<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: performing-email-header-forensics
description: >-
  Perform forensic analysis of email headers to trace message origin, identify
  spoofing, reconstruct delivery paths, extract IOCs, and build incident
  timelines from raw email message sources.
domain: cybersecurity
subdomain: email-security
tags:
  - forensics
  - headers
  - ioc-extraction
  - incident-response
  - timeline
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1566", "T1114"]
  tools: [python3, grep, mailutils, sed]
---

# Performing Email Header Forensics

## Overview

Email header forensics involves parsing RFC 5322 headers to trace message
provenance, identify manipulation, extract indicators of compromise, and
reconstruct the delivery chain. Critical for incident response involving
phishing, BEC, and email-borne attacks.

## Prerequisites

- Tools: python3, grep, sed, email (Python stdlib)
- Raw email headers or full EML file
- Understanding of RFC 5322 header format

## Key Concepts

- **Received chain**: Bottom-to-top trace of mail server hops
- **Authentication-Results**: Gateway verdict on SPF/DKIM/DMARC
- **Message-ID**: Unique identifier — domain should match sender
- **X-headers**: Non-standard headers revealing mail infrastructure

## Workflow

### Step 1: Header Extraction and Parsing

```bash
# Extract headers from EML (headers end at first blank line)
sed '/^$/q' message.eml > headers.txt

# Show all Received headers (bottom = origin)
grep "^Received:" headers.txt | cat -n

# Reverse for chronological order
grep "^Received:" headers.txt | tac

# Extract all X-headers
grep "^X-" headers.txt
```

### Step 2: Received Chain Analysis

```python
import re

def parse_received(headers_text: str) -> list[dict]:
    received = []
    current = ""
    for line in headers_text.split("\n"):
        if line.startswith("Received:"):
            if current: received.append(current)
            current = line
        elif current and line and line[0] in (" ", "\t"):
            current += " " + line.strip()
        elif current:
            received.append(current)
            current = ""
    if current: received.append(current)

    hops = []
    for i, r in enumerate(reversed(received)):
        ip = re.search(r'\[(\d+\.\d+\.\d+\.\d+)\]', r)
        frm = re.search(r'from\s+(\S+)', r)
        by = re.search(r'by\s+(\S+)', r)
        hops.append({
            "hop": i+1,
            "from": frm.group(1) if frm else "unknown",
            "by": by.group(1) if by else "unknown",
            "ip": ip.group(1) if ip else "unknown",
        })
    return hops
```

### Step 3: IOC Extraction

```bash
# Extract IPs
grep -oE '\b([0-9]{1,3}\.){3}[0-9]{1,3}\b' headers.txt | sort -u

# Extract domains
grep -oE '[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}' headers.txt | sort -u

# Extract URLs from body
grep -oE 'https?://[^"'"'"'> ]+' message.eml | sort -u

# Extract email addresses
grep -oE '[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}' message.eml | sort -u

# Check Message-ID domain alignment
grep "^Message-ID:" headers.txt
```

### Step 4: Timeline Reconstruction

```bash
# Extract timestamps from Received headers
grep "^Received:" headers.txt | \
  grep -oE '[A-Z][a-z]{2}, [0-9]+ [A-Z][a-z]{2} [0-9]{4} [0-9:]+' | sort

# Calculate transit time between first and last hop
# Large gaps indicate queuing, greylisting, or delayed delivery
```

## Detection Opportunities

| Signal | Source | Description |
|--------|--------|-------------|
| Header manipulation | Gateway | Inconsistent Received chains |
| Forged Message-ID | Gateway | Message-ID domain mismatch with sender |
| Suspicious X-Mailer | SIEM | X-Mailer associated with phishing tools |

```yaml
title: Email with Suspicious X-Mailer Header
id: e5f6a7b8-c9d0-1234-ef01-567890abcdef
status: experimental
description: Detects emails with X-Mailer headers from known phishing tools
logsource:
  category: email
  product: exchange
detection:
  selection:
    x_mailer|contains:
      - "PHPMailer"
      - "King Phisher"
      - "GoPhish"
  condition: selection
falsepositives:
  - Authorized phishing simulation campaigns
level: medium
tags:
  - attack.t1566.001
  - attack.initial_access
```

## Verification

- [ ] Received chain analyzed and origin server identified
- [ ] Authentication results parsed and evaluated
- [ ] IOCs extracted (IPs, domains, URLs, hashes)
- [ ] Timeline reconstructed from header timestamps
- [ ] Findings documented for incident report

## References

- [RFC 5322 — Internet Message Format](https://datatracker.ietf.org/doc/html/rfc5322)
- [MITRE T1566 — Phishing](https://attack.mitre.org/techniques/T1566/)
- [MxToolbox Header Analyzer](https://mxtoolbox.com/EmailHeaders.aspx)
