<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
---
name: performing-email-forensics
description: >-
  Email forensic analysis including header examination, SMTP relay tracing,
  PST/OST/MBOX parsing, phishing indicator extraction, attachment analysis,
  DKIM/SPF/DMARC verification, and email timeline reconstruction for
  fraud investigations and business email compromise cases.
domain: cybersecurity
subdomain: digital-forensics
tags:
  - email-forensics
  - email-headers
  - pst-parsing
  - phishing
  - bec
  - dkim
  - spf
  - dmarc
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: ["T1566.001", "T1566.002", "T1114"]
  nist-csf: ["RS.AN-3"]
  frameworks: ["NIST SP 800-86"]
---

# Performing Email Forensics

## Overview

Email forensics examines message headers, body content, attachments, and
metadata to trace origins, identify spoofing, analyze phishing campaigns,
and build timelines for business email compromise (BEC) investigations.
This skill covers SMTP header analysis, PST/MBOX parsing, authentication
verification, and malicious attachment extraction.

## Prerequisites

- Python 3.10+ with `email`, `mailbox` (stdlib), `libpff-python`, `extract-msg`
- `pffexport` (libpff-tools) for PST/OST extraction
- `munpack` for MIME attachment extraction
- `dkimverify` for DKIM signature validation

```bash
pip install extract-msg libpff-python dkimpy
sudo apt install pff-tools mpack
```

## Key Concepts

### Email Header Analysis Order

```
1. Return-Path         — Envelope sender (where bounces go)
2. Received (bottom→top) — SMTP relay chain (earliest at bottom)
3. From / Reply-To     — Display sender (easily spoofed)
4. Message-ID          — Unique identifier, domain reveals origin
5. X-Originating-IP    — Sender IP (webmail clients)
6. Authentication-Results — SPF, DKIM, DMARC verdicts
7. Date                — Sent timestamp
8. X-Mailer / User-Agent — Client software
```

### Authentication Mechanisms

| Mechanism | Verifies | Header Field |
|-----------|----------|-------------|
| SPF | Envelope sender IP authorized for domain | `Received-SPF: pass` |
| DKIM | Message integrity via cryptographic signature | `DKIM-Signature: ...` |
| DMARC | Alignment of SPF/DKIM with From domain | `Authentication-Results: dmarc=pass` |

### Phishing Indicators

```
- Reply-To ≠ From domain
- Display name spoofing: "CEO Name <attacker@evil.com>"
- Lookalike domains: examp1e.com, exarnple.com
- Recently registered domain (< 30 days)
- URL shorteners or redirect chains in body
- Urgency language + credential harvesting links
- Attachment with double extension: invoice.pdf.exe
```

## Workflow

### Step 1: Parse Email Headers

```python
import email
from email.policy import default

def parse_headers(eml_path: str) -> dict:
    with open(eml_path, "rb") as f:
        msg = email.message_from_binary_file(f, policy=default)
    received_chain = []
    for hdr in msg.get_all("Received", []):
        received_chain.append(str(hdr).strip())
    return {
        "from": msg["From"],
        "to": msg["To"],
        "subject": msg["Subject"],
        "date": msg["Date"],
        "reply_to": msg["Reply-To"],
        "return_path": msg["Return-Path"],
        "message_id": msg["Message-ID"],
        "x_originating_ip": msg.get("X-Originating-IP", ""),
        "authentication_results": msg.get("Authentication-Results", ""),
        "received_chain": received_chain,
    }
```

### Step 2: Trace SMTP Relay Path

```python
import re

def trace_relay_path(received_headers: list[str]) -> list[dict]:
    hops = []
    for i, header in enumerate(reversed(received_headers)):
        from_match = re.search(r"from\s+(\S+)", header)
        by_match = re.search(r"by\s+(\S+)", header)
        ip_match = re.search(r"\[(\d+\.\d+\.\d+\.\d+)\]", header)
        date_match = re.search(r";\s*(.+)$", header)
        hops.append({
            "hop": i + 1,
            "from": from_match.group(1) if from_match else "",
            "by": by_match.group(1) if by_match else "",
            "ip": ip_match.group(1) if ip_match else "",
            "timestamp": date_match.group(1).strip() if date_match else "",
        })
    return hops
```

### Step 3: Extract Attachments

```python
def extract_attachments(eml_path: str, output_dir: str = ".") -> list[dict]:
    with open(eml_path, "rb") as f:
        msg = email.message_from_binary_file(f, policy=default)
    attachments = []
    for part in msg.walk():
        if part.get_content_disposition() == "attachment":
            filename = part.get_filename() or "unnamed_attachment"
            content = part.get_payload(decode=True)
            if content:
                import hashlib
                out_path = f"{output_dir}/{filename}"
                with open(out_path, "wb") as out:
                    out.write(content)
                attachments.append({
                    "filename": filename,
                    "size": len(content),
                    "content_type": part.get_content_type(),
                    "sha256": hashlib.sha256(content).hexdigest(),
                    "saved_to": out_path,
                })
    return attachments
```

### Step 4: Parse PST/OST Files

```bash
# Export PST to individual EML files
pffexport -m all -t eml mailbox.pst

# Python PST parsing
python -c "
import pypff
pst = pypff.file()
pst.open('mailbox.pst')
root = pst.get_root_folder()
for folder in root.sub_folders:
    print(f'{folder.name}: {folder.number_of_sub_messages} messages')
"
```

### Step 5: DKIM Verification

```python
import dkim

def verify_dkim(eml_path: str) -> dict:
    with open(eml_path, "rb") as f:
        message = f.read()
    try:
        result = dkim.verify(message)
        return {"dkim_valid": result}
    except dkim.DKIMException as e:
        return {"dkim_valid": False, "error": str(e)}
```

## Detection

```yaml
title: Email Forensics Detection
id: b221fbd9-8a7f-4d6e-ab9b-eced3098427a
status: experimental
description: Detects suspicious activity related to performing email forensics techniques in digital forensics context
logsource:
  category: process_creation
  product: windows
detection:
  selection:
    CommandLine: "*performing*email*"
  condition: selection
level: medium
tags:
  - attack.t1566.001
  - attack.t1566.002
  - attack.t1114
  - attack.collection
falsepositives:
  - Forensic investigation tools used by authorized incident response team
```

## Verification

- [ ] Email headers parsed with complete Received chain
- [ ] SMTP relay path traced from origin to destination
- [ ] SPF/DKIM/DMARC authentication results verified
- [ ] Phishing indicators cataloged (spoofed fields, suspicious URLs)
- [ ] Attachments extracted with hash values for IOC correlation
- [ ] PST/MBOX archives parsed for bulk analysis
- [ ] Email timeline reconstructed for investigation period

## References

- [RFC 5322 — Internet Message Format](https://datatracker.ietf.org/doc/html/rfc5322)
- [RFC 7208 — SPF](https://datatracker.ietf.org/doc/html/rfc7208)
- [RFC 6376 — DKIM](https://datatracker.ietf.org/doc/html/rfc6376)
- [MITRE T1566 — Phishing](https://attack.mitre.org/techniques/T1566/)
- [libpff — PST/OST Parser](https://github.com/libyal/libpff)
