<!-- Copyright (c) 2026 defconxt. All rights reserved. -->
<!-- Licensed under AGPL-3.0 — see LICENSE file for details. -->
<!-- NERF is a trademark of defconxt. -->
---
name: detecting-email-data-leakage
description: >-
  Detect and prevent data leakage through email channels including
  sensitive data in message bodies, unauthorized attachment exfiltration,
  DLP policy bypass techniques, and covert channel abuse via email headers
  and encoding tricks.
domain: cybersecurity
subdomain: email-security
tags:
  - data-leakage
  - dlp
  - exfiltration
  - sensitive-data
  - classification
  - compliance
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1048.003", "T1567", "T1114"]
  tools: [python3, grep, regex, yara]
---

# Detecting Email Data Leakage

## Overview

Email is the most common data exfiltration channel. Detection requires
content inspection for sensitive patterns (PII, financial data, credentials),
attachment classification, DLP rule enforcement, and monitoring for bypass
techniques like encoding, steganography, and header abuse. Effective DLP
balances detection fidelity with business workflow disruption.

## Prerequisites

| Requirement | Purpose |
|---|---|
| Email gateway with DLP | Content inspection and policy enforcement |
| Data classification labels | Identify sensitivity level of content |
| Regex pattern library | Match PII, credentials, financial data |
| SIEM integration | Correlate DLP events with user behavior |

## Workflow

### Step 1: Define Sensitive Data Patterns

```python
import re
from typing import Any

PATTERNS = {
    "ssn": re.compile(r"\b\d{3}-\d{2}-\d{4}\b"),
    "credit_card": re.compile(r"\b(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|3[47][0-9]{13})\b"),
    "api_key": re.compile(r"\b(?:sk|pk|api)[_-][a-zA-Z0-9]{20,}\b"),
    "aws_key": re.compile(r"\bAKIA[0-9A-Z]{16}\b"),
    "password_in_text": re.compile(r"(?i)password\s*[:=]\s*\S+"),
    "iban": re.compile(r"\b[A-Z]{2}\d{2}[A-Z0-9]{4}\d{7}([A-Z0-9]?){0,16}\b"),
    "email_list": re.compile(r"(?:[\w.+-]+@[\w-]+\.[\w.-]+[,;\s]){5,}"),
}

def scan_content(text: str) -> dict[str, list[str]]:
    matches: dict[str, list[str]] = {}
    for name, pattern in PATTERNS.items():
        found = pattern.findall(text)
        if found:
            # Redact sensitive data in output
            matches[name] = [f"{m[:4]}****" for m in found[:10]]
    return matches
```

### Step 2: Attachment Classification

```bash
# Check for password-protected archives (common DLP bypass)
python3 -c "
import zipfile, sys
try:
    z = zipfile.ZipFile('attachment.zip')
    for info in z.infolist():
        if info.flag_bits & 0x1:
            print(f'WARN: {info.filename} is encrypted — DLP cannot inspect')
        print(f'{info.filename} ({info.file_size} bytes)')
except Exception as e:
    print(f'Error: {e}')
"

# Scan attachments with YARA for data patterns
cat <<'EOF' > dlp_patterns.yar
rule Contains_Credit_Cards {
    strings:
        $cc1 = /4[0-9]{12}([0-9]{3})?/
        $cc2 = /5[1-5][0-9]{14}/
    condition:
        any of ($cc*)
}
rule Contains_SSN {
    strings:
        $ssn = /[0-9]{3}-[0-9]{2}-[0-9]{4}/
    condition:
        $ssn
}
EOF
yara dlp_patterns.yar attachment.xlsx
```

### Step 3: Monitor DLP Bypass Techniques

```python
import base64

def detect_encoding_bypass(body: str) -> list[str]:
    """Detect attempts to bypass DLP via encoding."""
    findings = []
    # Base64 encoded content in body
    b64_pattern = re.compile(r"[A-Za-z0-9+/]{50,}={0,2}")
    b64_matches = b64_pattern.findall(body)
    for match in b64_matches[:5]:
        try:
            decoded = base64.b64decode(match).decode("utf-8", errors="ignore")
            if any(p.search(decoded) for p in PATTERNS.values()):
                findings.append("HIGH: Base64-encoded sensitive data in email body")
                break
        except Exception:
            continue

    # Homoglyph substitution (e.g., replacing digits with lookalikes)
    if re.search(r"[\u0430-\u044f]", body):  # Cyrillic in Latin text
        findings.append("MEDIUM: Cyrillic characters detected — possible homoglyph bypass")

    # Zero-width characters used to break pattern matching
    if re.search(r"[\u200b\u200c\u200d\ufeff]", body):
        findings.append("MEDIUM: Zero-width characters detected — possible DLP evasion")

    return findings
```

### Step 4: Volume and Behavior Analysis

```bash
# KQL — detect unusual outbound email volume
cat <<'EOF'
EmailEvents
| where Timestamp > ago(24h)
| where DeliveryDirection == "Outbound"
| summarize MessageCount=count(), TotalSize=sum(EmailSize),
    UniqueRecipients=dcount(RecipientAddress) by SenderAddress
| where MessageCount > 50 or TotalSize > 50000000
| order by TotalSize desc
EOF
```

## Detection Opportunities

| Signal | Source | Description |
|--------|--------|-------------|
| DLP policy match | Email gateway | Sensitive pattern in body or attachment |
| Encrypted attachment | Email gateway | Password-protected ZIP bypassing inspection |
| Abnormal volume | Mail flow logs | User sending unusually large/many emails |

```yaml
title: Outbound Email with Encrypted Attachment
id: d4e5f6a7-b890-1234-cdef-567890123456
status: experimental
description: Detects outbound emails with password-protected attachments that bypass DLP
logsource:
  category: email
  product: exchange
detection:
  selection:
    DeliveryDirection: "Outbound"
    AttachmentIsPasswordProtected: true
  condition: selection
falsepositives:
  - Legitimate encrypted file sharing with partners
level: medium
tags:
  - attack.t1048.003
  - attack.exfiltration
```

## Verification

- [ ] Sensitive data patterns detect SSN, CC, API keys in body and attachments
- [ ] Encrypted attachments flagged for manual review
- [ ] DLP bypass techniques (encoding, homoglyphs) detected
- [ ] Volume anomaly alerts configured for outbound email
- [ ] DLP rules tested with synthetic sensitive data
- [ ] Incident response procedure for confirmed data leakage

## References

- [MITRE T1048.003 — Exfiltration Over Unencrypted Non-C2 Protocol](https://attack.mitre.org/techniques/T1048/003/)
- [NIST SP 800-122 — Guide to Protecting PII](https://csrc.nist.gov/publications/detail/sp/800-122/final)

---
v1.0 | Validated: 2026-03-18
