Skip to content

Repository files navigation

🤖⚔️ AI RED TEAM vs BLUE TEAM LAB

🔴 GPT-4o ATTACKS · 🔵 GPT-5.2 DEFENDS · 🧠 AI ORCHESTRATES

AI Red Team vs Blue Team
Typing animation


⚔️ Two AI agents. Two different models. One attacks. One defends.

Fully autonomous closed-loop security testing. Under 2 minutes · ~$0.08 · Zero human intervention



🔴⚔️🔵 THE AI CYBER BATTLE

                 ┌──────────────────────────────┐
                 │      🧠 AI ARENA             │
                 │                              │
                 │   🔴 RED        🔵 BLUE     │
                 │   GPT-4o   ⚔️   GPT-5.2     │
                 │                              │
                 │    ATTACK         DEFEND    │
                 └──────────────┬───────────────┘
                                │
                                ▼
                    ┌─────────────────────┐
                    │   🌐 TARGET APP     │
                    │   Flask + SQLite    │
                    │   Docker Container  │
                    └──────────┬──────────┘
                               │
                     ┌─────────▼─────────┐
                     │   💥 EXPLOIT      │
                     │   SQLi + XSS      │
                     └─────────┬─────────┘
                               │
                               ▼
                     🧠 THREAT REPORT
                               │
                               ▼
                     🔵 PATCH & HARDEN
                               │
                               ▼
                       🐳 REBUILD
                               │
                               ▼
                     🔴 VERIFY AGAIN
                               │
                      ┌────────┴────────┐
                      │                 │
                    BYPASS           SECURE
                      │                 │
                      ▼                 ▼
                   🔁 LOOP          🏆 DONE

📊 BATTLE STATS

⚔️ Metric 🔴 Red Team 🔵 Blue Team
AI Model GPT-4o GPT-5.2
Primary Role Attack Defend
Recon nmap
Exploitation sqlmap · curl
Vulnerability Analysis
Patching
Verification
Containerization 🐳 Docker

🏆 Result Value
💥 Full Attack Cycle ~70 seconds
🛡️ Patch + Redeploy ~30 seconds
🔁 Verification Autonomous
⏱️ Full End-to-End Cycle < 2 minutes
💰 Total API Cost ~$0.08
👤 Human Intervention Zero

🎯 WHAT IS THIS?

A fully autonomous AI cybersecurity research lab where two different AI models go head-to-head in a real:

ATTACK → ANALYZE → PATCH → REBUILD → VERIFY → LOOP

cycle.

🔴 Red Agent — GPT-4o

The offensive side:

  • Performs reconnaissance with nmap
  • Executes SQL Injection testing
  • Uses sqlmap for automated exploitation
  • Tests Stored XSS
  • Analyzes discovered vulnerabilities
  • Generates a structured threat intelligence report
  • Re-tests the application after patching

🔵 Blue Agent — GPT-5.2

The defensive side:

  • Builds the vulnerable target application
  • Reads the Red Agent's threat report
  • Analyzes vulnerable source code
  • Applies Defense-in-Depth fixes
  • Rewrites the vulnerable application
  • Saves the original source as a backup
  • Triggers a Docker rebuild

🧠 Orchestrator

orchestrator.py connects everything into a fully autonomous closed-loop pipeline.

The critical design decision is that the Red Agent does not simply rerun the original attack. During verification it receives the patched source code and reasons about whether previous attack paths can still succeed.


⚔️ THE RULES OF THE ARENA

🔴 RED TEAM

Find the weakness.

⬇️

💥 EXPLOIT

Prove the weakness exists.

⬇️

🧠 THREAT REPORT

Explain what happened.

⬇️

🔵 BLUE TEAM

Fix the vulnerability.

⬇️

🐳 REBUILD

Deploy the patched system.

⬇️

🔴 RED TEAM — VERIFICATION MODE

Try to break it again.

⬇️

🏆 SECURE

Or send it back into the loop.


🏗️ SYSTEM ARCHITECTURE

flowchart TD

    U([👤 User / Single Command]) --> O

    subgraph ORCH["🧠 AI ORCHESTRATOR"]
        O[orchestrator.py]
    end

    O -->|Phase 1: Launch Attack| R

    subgraph RED["🔴 RED AGENT — GPT-4o"]
        R[Recon: nmap]
        R --> R2[Exploit: SQLi + XSS]
        R2 --> R3[Threat Intelligence Report]
    end

    R3 -->|Attack Report + Raw Logs| O

    O -->|Phase 2: Report + Vulnerable Source| B

    subgraph BLUE["🔵 BLUE AGENT — GPT-5.2"]
        B[Analyze Attack Vectors]
        B --> B2[Rewrite app.py]
        B2 --> B3[Defense-in-Depth]
        B3 --> B4[Parameterized Queries + html.escape + CSP]
    end

    B4 -->|Patched app.py| O

    O -->|Phase 3: Rebuild| D

    subgraph DOCKER["🐳 DOCKER ISOLATION"]
        D[docker compose down]
        D --> D2[docker compose up --build]
        D2 --> D3[Secure Web App]
    end

    D3 -->|Phase 4: Audit| V

    subgraph VERIFY["🔴 RED AGENT — VERIFICATION"]
        V[Reason About Patched Source]
        V --> Q{Bypass Found?}
        Q -->|YES| LOOP[🔁 Re-engage Blue Agent]
        Q -->|NO| SEC[🏆 SECURE]
    end

    LOOP --> B

    style O fill:#1a1a2e,color:#fff,stroke:#FFD43B
    style RED fill:#2d0000,color:#fff,stroke:#ff4444
    style BLUE fill:#001a2d,color:#fff,stroke:#4488ff
    style DOCKER fill:#002d1a,color:#fff,stroke:#44ff88
    style VERIFY fill:#2d1a00,color:#fff,stroke:#ffaa44
    style SEC fill:#004400,color:#fff,stroke:#44ff44
    style LOOP fill:#2d0000,color:#fff,stroke:#ff4444
Loading

💥 THE BATTLE IN ONE IMAGE

┌───────────────────────────────────────────────────────────────┐
│                                                               │
│       🔴 RED AGENT                    🔵 BLUE AGENT           │
│          GPT-4o                           GPT-5.2              │
│                                                               │
│        ┌─────────┐                    ┌─────────┐             │
│        │ ATTACK  │                    │ DEFEND  │             │
│        └────┬────┘                    └────▲────┘             │
│             │                              │                  │
│             ▼                              │                  │
│        ┌─────────┐                         │                  │
│        │  SQLi   │ ──────── ⚔️ ────────── │                  │
│        │   XSS   │                         │                  │
│        └────┬────┘                         │                  │
│             │                              │                  │
│             ▼                              │                  │
│        🧠 REPORT ────────────────────────► │                  │
│                                            │                  │
│                                     ┌──────┴─────┐            │
│                                     │   PATCH    │            │
│                                     └──────┬─────┘            │
│                                            │                  │
│                                            ▼                  │
│                                     🐳 REBUILD                │
│                                            │                  │
│             ◄──────────────────────────────┘                  │
│             VERIFY                                            │
│                                                               │
│                  🏆 SYSTEM SECURE                             │
│                                                               │
└───────────────────────────────────────────────────────────────┘

🚀 QUICK START

Prerequisites

  • Kali Linux (nmap + sqlmap pre-installed)

  • Docker + Docker Compose

  • Azure OpenAI resource

  • Two deployments:

    • GPT-4o
    • GPT-5.2
  • Python 3.11+


1. Clone & Setup

git clone https://github.com/YOUR_USERNAME/ai-red-blue-lab.git
cd ai-red-blue-lab

python3 -m venv venv
source venv/bin/activate

pip install -r requirements.txt

2. Configure Credentials

cp .env.example .env
nano .env

Then verify both model connections:

python3 test_connection.py

Expected:

🔴 Red Agent (GPT-4o):  ✅ Connection successful
🔵 Blue Agent (gpt-5.2): ✅ Connection successful

🥊 PHASE 1 — PROOF OF CONCEPT

🔵 ACT I — BLUE BUILDS THE TARGET

Blue Agent (gpt-5.2) builds a Flask/SQLite web application and intentionally leaves two vulnerabilities for the experiment.

Vulnerability #1 — SQL Injection

# ❌ Vulnerable
query = f"SELECT * FROM users WHERE username='{user}' AND password='{pwd}'"
cur.execute(query)

Vulnerability #2 — Stored XSS

# ❌ Vulnerable
comments_html = "".join(f"<p>{r[0]}</p>" for r in rows)

The database was pre-seeded with:

admin:secret123
alice:pass456

From script execution to the vulnerable container being live:

~15 seconds.


🔴 ACT II — RED ATTACKS

Red Agent (GPT-4o) automatically executes a four-phase attack.

Phase 1 — Reconnaissance

nmap
↓
5000/tcp open
Werkzeug 3.1.8
Python 3.11.15

Phase 2 — SQL Injection

Payload:
admin' OR '1'='1

Result:
✅ Authentication bypass

Phase 3 — Automated SQLi

sqlmap identified multiple injection techniques and successfully dumped the users table.

Database: SQLite
Table: users

+----+-----------+----------+
| id | password  | username |
+----+-----------+----------+
| 1  | secret123 | admin    |
| 2  | pass456   | alice    |
+----+-----------+----------+

Phase 4 — Stored XSS

Payload:
<script>alert("XSS_PWNED")</script>

Result:
✅ Stored and reflected

⚠️ Attack Result

Vulnerability Severity Impact
SQL Injection Critical Authentication bypass + database compromise
Stored XSS High Arbitrary JavaScript execution

Total attack time: ~70 seconds.


🔵 ACT III — BLUE PATCHES

The Red Agent's report is passed directly to Blue Agent.

No human reads the report.

No human writes the patch.

Fix #1 — Parameterized Queries

# ✅ Secure
cur.execute(
    "SELECT * FROM users WHERE username=? AND password=?",
    (user, pwd)
)

Fix #2 — Output Encoding

# ✅ Secure
import html

comments_html = "".join(
    f"<p>{html.escape(r[0])}</p>"
    for r in rows
)

Fix #3 — Content Security Policy

Content-Security-Policy: script-src 'self'

The Blue Agent applies Defense-in-Depth rather than relying on a single mitigation.


🐳 ACT IV — THE SYSTEM REBUILDS

The orchestrator automatically:

docker compose down
        ↓
replace vulnerable source
        ↓
docker compose up --build
        ↓
secure application online

The original vulnerable source is preserved as:

app.py.backup

🔴 ACT V — THE REMATCH

Same attacker. Same payloads. New target.

SQL Injection

Payload:
admin' OR '1'='1

Result:
❌ Invalid credentials

sqlmap

[WARNING] POST parameter 'username'
does not seem to be injectable

[CRITICAL] all tested parameters
do not appear to be injectable.

Stored XSS

Input:
<script>alert("XSS_PWNED")</script>

Output:
&lt;script&gt;alert(&quot;XSS_PWNED&quot;)&lt;/script&gt;

Legitimate Login

admin / secret123
        ↓
✅ Welcome admin!

🏆 BEFORE vs AFTER

Attack 🔴 Before 🛡️ After
SQL Injection — Manual ❌ Exploited ✅ Blocked
SQL Injection — sqlmap ❌ DB Dumped ✅ Not Injectable
Stored XSS ❌ Executed ✅ Escaped
Legitimate Login ✅ Works ✅ Still Works

🔴 ATTACK FAILED

🛡️ SYSTEM SECURE


🤖 PHASE 2 — FULLY AUTONOMOUS

Phase 1 proved the concept.

Phase 2 removes the manual handoffs completely.

python3 orchestrator.py

One command launches the entire operation:

┌─────────────────────────────────────────────────────────────┐
│                    🧠 JOINT OPERATIONS                      │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  🔥 PHASE 1                                                 │
│  GPT-4o launches attack                                     │
│                         ↓                                   │
│  📝 Threat intelligence generated                           │
│                         ↓                                   │
│  🛡️ PHASE 2                                                 │
│  GPT-5.2 receives report                                    │
│                         ↓                                   │
│  🛠️ Vulnerabilities patched                                │
│                         ↓                                   │
│  🐳 PHASE 3                                                 │
│  Docker rebuilt                                             │
│                         ↓                                   │
│  🎯 PHASE 4                                                 │
│  GPT-4o performs verification                               │
│                         ↓                                   │
│              ┌──────────┴──────────┐                        │
│              │                     │                        │
│          BYPASS FOUND          NO BYPASS                    │
│              │                     │                        │
│              ▼                     ▼                        │
│          🔁 LOOP              🏆 SECURE                     │
│                                                             │
└─────────────────────────────────────────────────────────────┘

🧠 WHY TWO DIFFERENT MODELS?

Using GPT-4o for offense and GPT-5.2 for defense creates genuine asymmetry.

Each model brings different reasoning patterns to its role.

A single model playing both sides could introduce bias because the same reasoning process would be responsible for creating and defeating its own attack.

This experiment intentionally separates:

OFFENSIVE REASONING
        ≠
DEFENSIVE REASONING

🧪 LIVE ORCHESTRATOR OUTPUT

🚀 Starting Joint Operations Room: Red Team vs Blue Team...
==================================================

🔥 [Phase 1] Launching Red Agent (GPT-4o)...
📝 Red Agent successfully generated attack report!

🛡️ [Phase 2] Orchestrator hands report to Blue Agent (gpt-5.2)...
🛠️ Blue Agent patched the code and rewrote app.py automatically!

🐳 [Phase 3] Orchestrator rebuilds Docker with patched code...
🔄 Container updated. Secure version now live.

🎯 [Phase 4] Calling Red Agent for verification audit...

==================================================
🏁 Final Verification Report:

1. SQL Injection Analysis:
   Result: ❌ BLOCKED

2. Stored XSS Analysis:
   Result: ❌ BLOCKED

System Status: SECURE 🛡️
==================================================

🛡️ DEFENSE-IN-DEPTH

One of the more interesting outcomes is that the Blue Agent applied multiple defensive layers.

Layer 1

html.escape()

Neutralizes HTML/JavaScript payloads before rendering.

Layer 2

Content-Security-Policy: script-src 'self'

Instructs the browser to reject inline JavaScript.

Combined

           XSS PAYLOAD
                │
                ▼
        ┌───────────────┐
        │ html.escape() │
        └───────┬───────┘
                │
                ▼
          HTML encoded
                │
                ▼
        ┌───────────────┐
        │      CSP      │
        └───────┬───────┘
                │
                ▼
             🛡️ SAFE

⏱️ THE COMPLETE TIMELINE

18:36:58  🔵 Blue Agent builds app
          └── ~15 seconds

18:37:06  🔴 Red Agent begins attack
          ├── nmap fingerprint
          ├── SQLi authentication bypass
          ├── sqlmap database dump
          └── XSS payload

18:37:16  🧠 GPT-4o analyzes findings
          └── structured threat report

          🔵 GPT-5.2 reads report
          └── patches app.py

          🐳 Docker rebuild
          └── secure application live

18:37:36  🔴 GPT-4o verification
          ├── SQLi blocked
          └── XSS escaped

────────────────────────────────────────────

⏱️ Full cycle:          < 2 minutes
💰 Azure OpenAI cost:   ~$0.08
👤 Human intervention:  ZERO

📁 PROJECT STRUCTURE

ai-red-blue-lab/
├── 📄 README.md
├── 📄 requirements.txt
├── 📄 .env.example
├── 📄 test_connection.py
├── 🧠 orchestrator.py
│
├── 🌐 webapp/
│   ├── app.py
│   ├── app.py.backup
│   ├── Dockerfile
│   └── docker-compose.yml
│
├── 🔴 red_agent/
│   ├── red_agent.py
│   ├── attack.sh
│   └── retest.sh
│
├── 🔵 blue_agent/
│   └── blue_agent.py
│
└── 📊 logs/
    ├── red_team_report.txt
    ├── ai_red_analysis.txt
    ├── blue_patch_report.txt
    ├── retest_report.txt
    └── sqlmap/

📖 WRITE-UP — WHEN AI ATTACKS ITSELF

Date: June 22, 2026 Environment: Kali Linux VM · Azure OpenAI · Docker Tags: AI Security Penetration Testing AppSec Autonomous Agents GPT-4o GPT-5.2


💭 THE IDEA

What if two AI agents fought each other?

One builds and defends a web application.

The other tries to break into it.

Two different models.

No human intervention.

No waiting.

No manual terminal commands.

I ran the experiment.

The results were more interesting than expected — not simply because both the attack and defense worked, but because of how quickly the entire cycle happened.


🔵 THE SETUP

Two models. Two roles. One isolated Kali Linux VM.

Agent Model Role
🔴 Red Agent GPT-4o Attack, analyze findings, verify patch
🔵 Blue Agent GPT-5.2 Build target app, patch vulnerabilities

Target stack:

Flask
SQLite
Werkzeug 3.1.8
Python 3.11.15
Docker

Why two different models?

Using GPT-4o for offense and GPT-5.2 for defense creates genuine asymmetry.

A single model playing both sides would make the experiment less scientifically interesting because the same reasoning process would be responsible for both attacking and defending the system.


🔴 ACT I — THE ATTACK

Reconnaissance

PORT     STATE SERVICE VERSION
5000/tcp open  http    Werkzeug httpd 3.1.8

The framework version was fingerprinted.

The attack surface was identified.

Then the attack began.


SQL Injection

Payload:
admin' OR '1'='1

Response:
✅ Welcome admin!

The authentication mechanism was bypassed on the first attempt.


Automated SQL Injection

sqlmap identified multiple injection techniques:

boolean-based blind
time-based blind
UNION query

It then dumped the users table.

+----+-----------+----------+
| id | password  | username |
+----+-----------+----------+
| 1  | secret123 | admin    |
| 2  | pass456   | alice    |
+----+-----------+----------+

Stored XSS

Payload:
<script>alert("XSS_PWNED")</script>

Result:
✅ Stored and reflected

🔴 Attack Summary

SQL Injection    → CRITICAL
Stored XSS       → HIGH

Attack duration  → ~70 seconds
HTTP requests    → 100

🔵 ACT II — THE DEFENSE

The Red Agent generated a structured threat report.

That report was passed directly to the Blue Agent.

No human intervention.


SQL Injection Fix

# ❌ Before
query = f"SELECT * FROM users WHERE username='{user}' AND password='{pwd}'"

# ✅ After
cur.execute(
    "SELECT * FROM users WHERE username=? AND password=?",
    (user, pwd)
)

User input is now treated as data rather than SQL syntax.


XSS Fix

# ❌ Before
comments_html = "".join(f"<p>{r[0]}</p>" for r in rows)

# ✅ After
import html

comments_html = "".join(
    f"<p>{html.escape(r[0])}</p>"
    for r in rows
)

Defense-in-Depth

The Blue Agent additionally introduced:

Content-Security-Policy: script-src 'self'

This provides a second defensive layer against inline JavaScript execution.


🐳 ACT III — THE REBUILD

The orchestrator automatically triggered:

docker compose down
docker compose up --build

Result:

✔ Image rebuilt
✔ Container restarted
✔ Patched application live

🔴 ACT IV — THE REMATCH

Same attacker.

Same payloads.

Different result.

SQL Injection

admin' OR '1'='1

❌ Invalid credentials

sqlmap

[CRITICAL] all tested parameters
do not appear to be injectable.

XSS

<script>alert("XSS_PWNED")</script>

↓

&lt;script&gt;alert(&quot;XSS_PWNED&quot;)&lt;/script&gt;

Legitimate Login

admin / secret123

↓

✅ Welcome admin!

The patch did not break the intended functionality.


⚔️ PHASE 2 — THE CLOSED LOOP

Phase 1 demonstrated the concept.

Phase 2 turned it into an autonomous security loop.

             🔴 ATTACK
                  │
                  ▼
           💥 EXPLOIT
                  │
                  ▼
          🧠 ANALYZE
                  │
                  ▼
           🔵 PATCH
                  │
                  ▼
           🐳 REBUILD
                  │
                  ▼
           🔴 VERIFY
                  │
            ┌─────┴─────┐
            │           │
         BYPASS       SECURE
            │           │
            ▼           ▼
         🔁 LOOP       🏆

The important engineering decision is that verification receives the actual patched Python source code.

The Red Agent reasons about whether its previous attack paths can still succeed.

This is code-level security analysis rather than blindly repeating the same tool execution.


🧠 WHAT THIS ACTUALLY MEANS

⚡ Speed Is the Real Shift

What traditionally requires:

Red Team
   ↓
Security Report
   ↓
Developer
   ↓
Patch
   ↓
Review
   ↓
Deployment
   ↓
Verification

was compressed into:

ATTACK
  ↓
PATCH
  ↓
VERIFY

in under two minutes.

Not because AI is inherently smarter than a human security engineer.

Because the agents do not stop for context switching, meetings, handoffs, or waiting for a response.


⚔️ Two Models Beat One

GPT-4o on offense and GPT-5.2 on defense created genuine asymmetry.

That separation makes the experiment more interesting and reduces the bias of one model judging its own work.


🧩 Ditch the Framework When It Fights You

The project initially used AutoGen for orchestration.

A library conflict appeared between AutoGen's bundled openai v0.x dependency and the modern openai v1.x SDK.

Instead of spending time debugging the abstraction, the project moved to direct Azure OpenAI API calls.

Sometimes the simplest architecture wins.


🧠 AI Doesn't Invent — It Compresses

SQL Injection is well documented.

sqlmap is public.

Parameterized queries are standard security practice.

The interesting part is not that AI invented these techniques.

It is that AI compressed the time between knowing and doing.


🔥 THE REAL IMPLICATION

If an attacker can automate a:

RECON
  ↓
EXPLOIT
  ↓
REPORT

cycle in seconds and at very low cost, defensive response windows become dramatically smaller.

The logical response is not simply "more manual security."

It is security automation capable of matching the speed of automated offense.

That is what this project explores.


🚧 WHAT'S NEXT

  • Add CSRF and IDOR to the target app
  • Test whether Red Agent discovers vulnerabilities it was not explicitly told about
  • Pit GPT-4o vs GPT-5.2 in both roles and compare outcomes
  • Build a real-time terminal dashboard
  • Extend the system to DAST scanning with OWASP ZAP
  • Add automatic rollback when a generated patch fails smoke tests
  • Implement true Red → Blue → Red feedback loops
  • Track token usage and cost per phase
  • Benchmark patch quality across multiple models

🤝 CONTRIBUTING

Contributions are welcome.

🔴 Red Team

  • Add CSRF, IDOR, Path Traversal, and Command Injection modules
  • Integrate OWASP ZAP
  • Improve autonomous vulnerability discovery
  • Add additional attack scenarios

🔵 Blue Team

  • Compare patch quality across models
  • Add automatic rollback
  • Generate WAF rules
  • Add security regression tests

🧠 Orchestrator

  • Build a real-time terminal dashboard
  • Implement automatic feedback loops
  • Track token usage
  • Track cost per operation
  • Add persistent experiment history

📊 Research

  • Benchmark GPT-4o against other models
  • Measure attack effectiveness
  • Measure patch quality
  • Study over-patching vs under-patching
  • Test against more complex multi-service applications

Contributing

git checkout -b feature/your-idea
git commit -m "feat: your improvement"
git push origin feature/your-idea

Then open a Pull Request.


⚠️ DISCLAIMER

This project is for educational and research purposes only.

All tests were conducted in a completely isolated VM environment.

Never use these techniques against systems without explicit written permission.


📺 DEMO

Watch Demo



🔴 ATTACK → ⚔️ BATTLE → 🔵 DEFEND → 🏆 SECURE


🏁 FINAL SCORE

╔══════════════════════════════════════════════════════╗
║                                                      ║
║             🔴 RED TEAM vs BLUE TEAM 🔵              ║
║                                                      ║
║                  FINAL RESULT                        ║
║                                                      ║
║       💥 Attack       →       🛡️ Defended            ║
║       🔓 SQLi        →       🔒 Blocked              ║
║       💀 XSS         →       🛡️ Escaped              ║
║                                                      ║
║             ⏱️ < 2 MINUTES                           ║
║             💰 ~$0.08                                ║
║             👤 ZERO HUMAN INTERVENTION               ║
║                                                      ║
║                  🏆 SECURE                           ║
║                                                      ║
╚══════════════════════════════════════════════════════╝

🔴 GPT-4o attacks · 🔵 GPT-5.2 defends · 🧠 Python orchestrates · 🐳 Docker isolates


AI doesn't replace the Red Team. AI doesn't replace the Blue Team.

⚔️ It makes the battle happen faster.


Red vs Blue Footer

About

An autonomous, closed-loop multi-agent security lab using AutoGen, GPT-4o, and gpt-5.2 for automated Red Team exploitation and self-healing Blue Team code patching.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages