<!-- 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-endpoint-data-exfiltration
description: >-
  Detect data exfiltration from endpoints through multiple channels including
  cloud storage uploads, DNS tunneling, encrypted archive creation, clipboard
  abuse, print operations, and network-based staging. Covers behavioral
  analysis, volume anomalies, and protocol abuse detection.
domain: cybersecurity
subdomain: endpoint-security
tags:
  - data-exfiltration
  - dlp
  - dns-tunneling
  - cloud-upload
  - staging
  - behavioral-analysis
version: "1.0"
author: defconxt
license: AGPL-3.0
metadata:
  mitre-attack: ["T1048", "T1041", "T1567", "T1071.004", "T1560"]
  tools: [python3, powershell, sysmon, wireshark]
---

# Detecting Endpoint Data Exfiltration

## Overview

Data exfiltration is the ultimate objective of many attacks. Detection
requires monitoring multiple egress channels: web uploads to cloud storage,
DNS tunneling, encrypted archive creation preceding network transfers,
unusual outbound data volumes, and abuse of legitimate protocols. Effective
detection combines endpoint telemetry with network flow analysis.

## Prerequisites

| Requirement | Purpose |
|---|---|
| Sysmon | File creation, process creation, DNS queries |
| Network flow data | Outbound volume analysis and anomaly detection |
| Proxy logs | Cloud storage upload detection |
| EDR platform | Behavioral detection of staging and exfil |

## Workflow

### Step 1: Detect Data Staging (Archive Creation)

```powershell
# Sysmon EID 11 — detect archive creation in temp directories
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Sysmon/Operational';Id=11} |
  Where-Object {
    $_.Properties[5].Value -match '\.(zip|rar|7z|tar\.gz)$' -and
    $_.Properties[5].Value -match '(Temp|tmp|AppData)'
  }

# Detect password-protected archive creation
Get-WinEvent -FilterHashtable @{LogName='Microsoft-Windows-Sysmon/Operational';Id=1} |
  Where-Object {
    $_.Properties[4].Value -match '(7z|rar|zip)' -and
    $_.Properties[10].Value -match '-p|-password|SecureString'
  }
```

### Step 2: Detect Cloud Storage Exfiltration

```bash
# Monitor web uploads to known cloud storage
# KQL for proxy/firewall logs
cat <<'EOF'
DeviceNetworkEvents
| where Timestamp > ago(24h)
| where RemoteUrl has_any (
    "drive.google.com", "dropbox.com", "onedrive.live.com",
    "mega.nz", "file.io", "transfer.sh", "gofile.io"
)
| where ActionType == "ConnectionSuccess"
| summarize TotalBytes=sum(SentBytes), UploadCount=count() by DeviceName, RemoteUrl
| where TotalBytes > 10000000
| order by TotalBytes desc
EOF
```

### Step 3: Detect DNS Tunneling

```python
import re
from typing import Any

def analyze_dns_for_tunneling(log_path: str) -> dict[str, Any]:
    """Analyze DNS query logs for tunneling indicators."""
    try:
        with open(log_path) as f:
            lines = f.readlines()
    except FileNotFoundError:
        return {"error": f"File not found: {log_path}"}

    findings = []
    domain_lengths: dict[str, list[int]] = {}

    for line in lines:
        match = re.search(r"query:\s+(\S+)", line)
        if not match:
            continue
        query = match.group(1).rstrip(".")
        parts = query.split(".")
        if len(parts) < 3:
            continue

        base_domain = ".".join(parts[-2:])
        subdomain = ".".join(parts[:-2])
        domain_lengths.setdefault(base_domain, []).append(len(subdomain))

    for domain, lengths in domain_lengths.items():
        avg_len = sum(lengths) / len(lengths)
        if avg_len > 30:
            findings.append(f"HIGH: {domain} avg subdomain length {avg_len:.0f} — DNS tunneling likely")
        elif len(lengths) > 100 and avg_len > 15:
            findings.append(f"MEDIUM: {domain} high query volume ({len(lengths)}) with long subdomains")

    return {
        "action": "dns_tunneling_analysis",
        "total_domains": len(domain_lengths),
        "findings": findings,
    }
```

### Step 4: Volume Anomaly Detection

```python
def detect_volume_anomaly(flow_path: str, threshold_mb: float = 100.0) -> dict[str, Any]:
    """Detect endpoints sending abnormally large outbound data."""
    try:
        with open(flow_path) as f:
            lines = f.readlines()
    except FileNotFoundError:
        return {"error": f"File not found: {flow_path}"}

    host_bytes: dict[str, int] = {}
    for line in lines:
        parts = line.strip().split(",")
        if len(parts) < 3:
            continue
        src, _dst, bytes_str = parts[0], parts[1], parts[2]
        try:
            host_bytes[src] = host_bytes.get(src, 0) + int(bytes_str)
        except ValueError:
            continue

    anomalies = []
    threshold_bytes = int(threshold_mb * 1024 * 1024)
    for host, total in sorted(host_bytes.items(), key=lambda x: x[1], reverse=True):
        if total > threshold_bytes:
            anomalies.append({
                "host": host,
                "bytes_sent": total,
                "mb_sent": round(total / (1024 * 1024), 2),
            })

    return {
        "action": "volume_anomaly",
        "threshold_mb": threshold_mb,
        "anomalies": anomalies[:20],
    }
```

## Detection Opportunities

| Signal | Source | Description |
|--------|--------|-------------|
| Archive creation in temp | Sysmon EID 11 | Staging compressed data for exfil |
| Cloud upload spike | Proxy logs | Large upload to file-sharing service |
| DNS tunneling | DNS logs | Long subdomain queries to single domain |

```yaml
title: Password-Protected Archive Created in Temp Directory
id: c9d0e1f2-a345-6789-hijk-012345678901
status: experimental
description: Detects creation of encrypted archives in temporary directories indicating staging
logsource:
  category: file_event
  product: windows
detection:
  selection:
    EventType: FileCreate
    TargetFilename|endswith:
      - '.zip'
      - '.7z'
      - '.rar'
    TargetFilename|contains:
      - '\Temp\'
      - '\tmp\'
      - '\AppData\'
  condition: selection
falsepositives:
  - Software installers creating temporary archives
level: medium
tags:
  - attack.t1560.001
  - attack.collection
```

## Verification

- [ ] Archive creation in staging directories detected
- [ ] Cloud storage upload volume anomalies trigger alerts
- [ ] DNS tunneling detection identifies long subdomain patterns
- [ ] Outbound volume baseline established per host
- [ ] Protocol abuse (HTTP POST, ICMP data) monitoring active
- [ ] Exfiltration via USB correlated with file access logs

## References

- [MITRE T1048 — Exfiltration Over Alternative Protocol](https://attack.mitre.org/techniques/T1048/)
- [MITRE T1567 — Exfiltration Over Web Service](https://attack.mitre.org/techniques/T1567/)
- [SANS — Detecting DNS Tunneling](https://www.sans.org/white-papers/detecting-dns-tunneling/)

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