Red Team vs Blue Team

Run a red team vs blue team exercise: plan attacks, defend, and learn where your security gaps hide. Hands-on steps for developers.

Focus: simulate a red team vs blue team exercise

Sponsored

Staring at a network diagram, you know your application feels secure — but feeling isn't evidence. The only way to truly uncover where an attacker would strike is to stop guessing and start simulating. In this lesson, you'll learn how to simulate a red team vs blue team exercise: plan a realistic attack, defend against it in real time, and extract the kind of security gaps that vulnerability scanners silently miss. By the end, you'll have a repeatable, hands-on process you can run in your own environment — no expensive tools required.

The problem this lesson solves

Most security testing falls into two extremes: automated scans that overwhelm you with false positives, and theoretical checklists that never touch a live system. Neither tells you how your application would actually hold up when someone with time, motivation, and skill decides to break in. The result? You deploy features with hidden weaknesses, discover them only after an incident, and spend frantic weekends patching holes you never knew existed.

The red team vs blue team exercise closes that gap. It's a structured, adversarial simulation where one group (the red team) attacks and another (the blue team) defends. The exercise forces you to answer hard questions: What would an attacker target first? How fast can we detect an intrusion? Do our logs actually help us? It transforms security from a passive checklist into an active, measurable practice.

Core concept / mental model

Think of a red team vs blue team exercise as a fire drill for your security posture. A fire drill doesn't start a real fire — it simulates one in a controlled way so everyone knows their role when a real emergency hits. Similarly, the red team simulates an attacker's behavior (reconnaissance, exploitation, persistence) while the blue team practices detection, response, and recovery.

Pro tip: The goal is not for the red team to "win." It's to expose blind spots so the blue team can learn and improve. Treat every finding as a training opportunity, not a scoreboard.

Key roles

  • Red team — the attackers. They mimic real-world adversary tactics: scanning for open ports, exploiting misconfigurations, attempting privilege escalation, covering tracks.
  • Blue team — the defenders. They monitor logs, watch for anomalies, respond to alerts, and patch or isolate compromised systems.
  • White team — the referees. They define rules of engagement, set the scenario, and ensure the exercise stays safe (no production data harmed, no legal issues).

A useful analogy: the red team is the boxer throwing punches, the blue team is the fighter learning to block them, and the white team is the referee making sure nobody gets knocked out for real.

How it works step by step

A red team vs blue team exercise follows a repeatable cycle. Here’s the logical sequence:

  1. Define scope and rules. What systems are in bounds? What actions are allowed? Can the red team use social engineering, or only technical attacks? Set a time limit and a stop condition (e.g., when critical data is accessed).
  2. Reconnaissance (red team). Gather intel: open ports, service versions, exposed endpoints, public user names. Document everything — this becomes the blueprint for the attack.
  3. Initial exploitation (red team). Attempt to gain a foothold using the weakest entry point found in recon. This could be an unpatched service, a default credential, or an unauthenticated API endpoint.
  4. Detection (blue team). As soon as the attack begins, monitor logs, network traffic, and system integrity. The faster you detect, the less damage an attacker can do.
  5. Response (blue team). Contain the breach: isolate the affected system, revoke access, patch the vulnerability, and preserve evidence for analysis.
  6. Debrief. Both teams review what happened. Red team explains the attack path; blue team discusses what detection methods worked and which failed. Document lessons learned.

Pro tip: Start with a white-box exercise (both teams know the environment) before attempting a black-box one (red team knows nothing). It builds muscle memory faster.

Hands-on walkthrough

Let's run a mini red team vs blue team exercise on a local machine. You'll simulate a web application with a known vulnerability, then defend it. For this, we'll use Python's http.server as a stand-in for a real service (in production, you'd use something like Nginx or Django).

Step 1: Set up a vulnerable target

Create a simple HTTP server that exposes a directory with a secrets.txt file, but also opens port 8000 to any request — a classic misconfiguration.

# vulnerable_server.py
from http.server import SimpleHTTPRequestHandler, HTTPServer
import os

# Simulate a default secret file
with open("secrets.txt", "w") as f:
    f.write("admin_password=fluffy_bunny_2024")

handler = SimpleHTTPRequestHandler
httpd = HTTPServer(("127.0.0.1", 8000), handler)
print("Vulnerable server running on port 8000...")
httpd.serve_forever()

Run it: python vulnerable_server.py.

Step 2: Red team — Reconnaissance

As the red team, you want to find entry points. Use nmap (or Python's socket module) to scan open ports, then probe for hidden files.

# recon.py
import nmap

nm = nmap.PortScanner()
results = nm.scan("127.0.0.1", "8000", arguments="-sV")

for host in results["scan"]:
    for proto in results["scan"][host]:
        ports = results["scan"][host][proto]
        for port in ports:
            print(f"Open port {port}: {ports[port]['name']} {ports[port]['version']}")

Expected output (simplified):

Open port 8000: http SimpleHTTP 0.6

Then curl for hidden files:

curl http://127.0.0.1:8000/secrets.txt

Response: admin_password=fluffy_bunny_2024 — the red team just compromised a credential using zero exploits.

Step 3: Blue team — Detect and respond

As the blue team, you need to detect that request. Set up simple logging on the server (our vulnerable server didn't log, a glaring omission). Modify the server to capture IPs and requested paths, then use a Python script to watch for suspicious patterns.

# secure_server.py
import http.server
import socketserver
import time

LOG_FILE = "access.log"

def log_request(handler):
    with open(LOG_FILE, "a") as f:
        f.write(f"{time.asctime()} {handler.client_address[0]} {handler.path}\n")

class LogHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        log_request(self)
        super().do_GET()

with socketserver.TCPServer(("", 8443), LogHandler) as httpd:
    print("Secure server on 8443, logging all requests...")
    httpd.serve_forever()

Now, as blue team, write a detection script:

# detect.py
import re

suspicious_patterns = ["secrets", "admin", "password", ".env"]

with open("access.log") as f:
    for line in f:
        timestamp, ip, path = line.strip().split(" ", 2)
        if any(pattern in path for pattern in suspicious_patterns):
            print(f"🚨 ALERT: {ip} hit {path} at {timestamp}")

Expected output when an attacker requests the secret:

🚨 ALERT: 127.0.0.1 hit /secrets.txt at Mon Jan 15 12:00:00 2024

You've successfully simulated one attack and one defense. The next step in a real exercise would be isolating the server and rotating credentials — but for the lesson, detection is the win.

Compare options / when to choose what

Not all exercises are equal. Here's how common formats compare:

Exercise type Best for Cost Control Realism Typical tools
Tabletop simulation Training new team members, policy testing Low High Low Sticky notes, whiteboard
White-box red team exercise Finding known blind spots in a known environment Medium Medium Medium Nmap, curl, custom scripts
Full red team engagement Testing overall detection and response readiness High Medium High Metasploit, Cobalt Strike, EDR tools
Purple team exercise Improving collaboration between red and blue Medium High Medium Same as red/blue, plus joint debriefs

When to choose what?

  • Choose a tabletop when you need to validate incident response plans under budget.
  • Choose a white-box exercise when you suspect specific misconfigurations but want a safe, repeated environment.
  • Choose a full red team engagement when you need to test your entire security stack (SIEM, SOC, endpoint protection) end-to-end.
  • Choose a purple team when red and blue aren't communicating — it fosters collaboration.

Pro tip: Start with tabletop, move to white-box, graduate to full red team. Each builds on the last without overwhelming your team.

Troubleshooting & edge cases

Even a simulated exercise hits snags. Here are common issues and fixes:

  • Port 8000 already in use. Change the port in vulnerable_server.py to 8001, or kill the process with pkill -f vulnerable_server.py.
  • Nmap not installed. Install via pip install python-nmap or use your OS package manager (apt install nmap for Debian/Ubuntu).
  • Detection script produces no alerts. Check that the log file exists and is being written — ensure secure_server.py was started, not the vulnerable one.
  • Red team gets blocked by firewall during recon. Use sudo nmap or explicitly allow localhost traffic. For remote exercises, ensure both teams have network line-of-sight.
  • Exercise goes out of scope. An attacker accidentally pivots to an off-limits system. The white team must pause the exercise immediately, then redefine boundaries.
  • Blue team misses the alert. This happens when logs are too verbose or not monitored in real time. Add threshold-based detection (like our pattern match) to reduce noise.

Pro tip: Add a rule: the exercise stops immediately if the red team touches anything outside the defined scope. No exceptions.

What you learned & what's next

You've learned to simulate a red team vs blue team exercise: defined roles, walked through a controlled attack and defense, and saw firsthand how misconfigurations and blind spots surface. You can now:

  • Explain the core idea behind red vs blue teaming.
  • Complete a practical exercise on your own machine.
  • Identify the strongest defense-in-depth improvements from your findings.

This skill is just one piece of your security mindset. In the next lesson, you'll explore threat modelling lite — learning how to map attack surfaces systematically before you ever run an exercise. The class will also connect to the CIA triad you've studied earlier: the red team exercises often target confidentiality (data theft), integrity (data tampering), and availability (DoS attacks). You're building a full security vocabulary, one simulated attack at a time.

Practice recap

Run a 10-minute mini exercise: start the vulnerable server from the lesson, act as the red team to fetch /secrets.txt, then switch to the blue team and implement the logging server and detection script. Try changing the secret file name (e.g., passwords.yaml) and see if your detection script catches it — if not, update the patterns. This repetition builds reflexes: attack, detect, fix, repeat.

Common mistakes

  • No rules of engagement: teams attack production systems and cause real outages. Always define scope and stop conditions first.
  • Red team skips reconnaissance and jumps straight to exploitation, missing easy wins like default credentials or exposed files.
  • Blue team only checks alerts after the exercise ends, so detection speed is never measured. Enable real-time log monitoring.
  • Treating the debrief as optional. Without a structured after-action review, the same gaps will reappear next quarter.

Variations

  1. Purple team exercise: red and blue work side-by-side, sharing insights in real time to accelerate learning.
  2. Use dedicated frameworks like MITRE ATT&CK to map exercise steps to real-world adversary tactics.
  3. Automate part of the red team with offensive security tools (e.g., Metasploit) to simulate advanced attacks.

Real-world use cases

  • A startup runs a quarterly tabletop exercise to test its incident response plan before hiring a dedicated SOC.
  • An e-commerce platform hires an external red team to attack their staging environment and find API misconfigurations.
  • A bank's security team runs a purple team exercise before deploying a new transaction monitoring system.

Key takeaways

  • A red team vs blue team exercise simulates attacks and defenses in a controlled way, exposing exploitable gaps.
  • The exercise cycle runs: scope, recon, exploit, detect, respond, debrief — each step is critical.
  • Reconnaissance is where most attackers win; blue teams must prioritize logging and monitoring.
  • Choosing the right exercise type depends on your budget, control needs, and team maturity.
  • Troubleshooting common issues (port conflicts, missing logs, scope creep) keeps exercises safe and productive.
  • After the simulation, document lessons learned and feed them into your threat modelling process.

Sponsored

Sponsored

Discussion

Questions, corrections, and tips help everyone reading this page.

0 comments

Add a comment

Shown publicly with your comment.

Be constructive · max 4,000 characters

No comments yet — start the thread.

Related tutorials, quizzes, and articles for this topic.