En este modulo

  1. Purple teaming: why and how
  2. Attack simulation with AI
  3. Adaptive defense with AI
  4. Detecting adversarial AI use
  5. Threat hunting with LLMs
  6. MITRE ATT&CK automation
  7. The continuous purple improvement cycle
  8. Tools and frameworks
  9. Ejercicio practico
  10. Puntos clave

Purple teaming: why and how

Red team attacks. Blue team defends. Purple team coordinates both to maximize learning. It is not a separate team: it is a way of working where the red team shares their techniques in real time with the blue team, and the blue team adjusts their detections and responses immediately.

Without purple teaming, the red team finds 20 compromise paths, writes a report, and the blue team takes months to implement the recommendations. With purple teaming, each technique is tested, detected (or not), and detection is improved in the same session.

AI accelerates both sides of the purple team simultaneously: generates more realistic and sophisticated attack simulations, and improves detection and response capability in real time.

The purple maturity model

The real goal of purple team

The goal is not for the red team to "win" or the blue team to "detect everything." It is to measure and improve detection and response capability systematically. Each undetected technique is an improvement opportunity, not a failure.

Attack simulation with AI

AI-powered attack simulation allows executing ATT&CK techniques in an automated, realistic and repeatable way. It is not a vulnerability scanner: it is a behavioral simulation of a real attacker.

Campaign simulation generation

An LLM can generate complete simulation plans based on a real threat actor:

PURPLE_SIMULATION_PROMPT = """
Generate a purple team simulation plan that emulates {threat_actor}
attacking an organization in the {sector} sector in {country}.

Structure:
1. Actor profile (motivation, capability, history)
2. Complete kill chain with ATT&CK techniques
3. For each step:
   - ATT&CK technique (ID + name)
   - Specific command/tool to execute
   - Expected result if the technique succeeds
   - What the blue team should detect
   - Expected Sigma rule or detection query
   - Generated indicators of compromise
4. Success criteria (detection vs non-detection per step)
5. Metrics to measure (MTTD, MTTR, detection coverage)

Actor: APT29 (Cozy Bear)
Sector: European government
Country: Spain
"""

Simulation tools (BAS)

BAS (Breach and Attack Simulation) platforms automate ATT&CK technique execution:

AI for adaptive simulations

The difference between a traditional BAS and an AI-powered one: the traditional one executes the same tests always in the same order. The AI-powered one adapts the simulation based on results:

# Adaptive simulation with AI
class AdaptiveSimulation:
    def __init__(self, actor_profile, target_environment):
        self.actor = actor_profile
        self.env = target_environment
        self.techniques_tried = []
        self.techniques_detected = []

    def next_technique(self):
        # The LLM decides the next technique based on:
        # 1. What techniques were already tried and if they were detected
        # 2. What techniques the real actor would use in this situation
        # 3. The current state of the environment (what access has been gained)
        decision = llm.decide(
            prompt=ADAPTIVE_DECISION_PROMPT,
            context={
                "actor": self.actor,
                "tried": self.techniques_tried,
                "detected": self.techniques_detected,
                "current_access": self.env.current_access_level,
                "available_techniques": self.actor.ttp_repertoire
            }
        )
        return decision.next_technique, decision.reasoning

Adaptive defense with AI

While the red team (or BAS) executes techniques, the blue team uses AI to detect and respond in real time.

Real-time detection with LLMs

An LLM can analyze event sequences from the SIEM and detect patterns that static rules cannot capture:

Automated detection generation

When the red team executes a technique that is not detected, the system can automatically generate a detection rule:

# Auto-generation of detection after miss
def generate_detection_after_miss(technique, execution_log):
    detection = llm.generate(
        prompt="""
        Technique {technique.id} ({technique.name}) was executed
        successfully and was NOT detected by the SOC.

        Execution log:
        {execution_log}

        Generate:
        1. A Sigma rule that detects this specific technique
        2. A more generic rule that detects variants of this technique
        3. Test criteria to verify the rule works
        4. Possible false positives to consider
        """,
        technique=technique,
        execution_log=execution_log
    )
    return detection

The 4-step cycle

Red executes technique. Blue tries to detect. If detected: validate the alert, measure MTTD. If not detected: generate a new rule, deploy it, re-execute the technique. Repeat until detection works. This cycle with AI completes in minutes, not days.

Detecting adversarial AI use

Attackers also use AI. Detecting their use is an emerging capability the blue team needs to develop.

How attackers use AI

Indicators of attacker AI use

AI-generated content detection

For emails and documents, AI-generated text detectors exist (GPTZero, Originality.ai). They are not perfect (high false positives) but can be an additional layer in the email filter. For audio/video deepfakes, tools like Microsoft Video Authenticator or Intel FakeCatcher analyze generation artifacts.

Threat hunting with LLMs

Threat hunting is the proactive search for threats that have evaded existing detections. You do not wait for an alert to fire. You actively search for indicators of compromise based on hypotheses.

Hypothesis generation with AI

An LLM can generate hunting hypotheses based on current threat intelligence:

HUNTING_HYPOTHESIS_PROMPT = """
Given the following context:
- Organization sector: {sector}
- Most active threat actors against this sector: {actors}
- Most used techniques by these actors: {techniques}
- Latest relevant advisories/CVEs: {advisories}
- Current SOC detections (deployed rules): {current_rules}

Generate 5 threat hunting hypotheses, prioritized by probability and impact.

For each hypothesis:
1. Hypothesis (formulated as "If {actor} is in our network, we would expect to see...")
2. Associated ATT&CK technique
3. Data sources to query (logs, EDR, netflow, etc.)
4. Search queries (Splunk SPL or Elastic KQL)
5. Indicators to look for
6. Actions if the hypothesis is confirmed
"""

Log hunting with LLMs

An LLM can analyze logs in natural language, finding patterns that would be difficult to express in a formal query:

The LLM translates these requests into formal queries (SPL, KQL, SQL) and then analyzes the results to identify anomalies.

MITRE ATT&CK automation

MITRE ATT&CK is the central framework of purple teaming. AI automates three key processes with ATT&CK:

1. Coverage evaluation

Given the SIEM rule catalog and SOAR playbooks, an LLM can map each rule to ATT&CK techniques and generate a coverage heatmap. Techniques without coverage are the gaps the purple team should prioritize.

2. Technique prioritization

Not all ATT&CK techniques are equally relevant. AI prioritizes based on: what actors target your sector? What techniques do those actors use? Which of those techniques are you not covering? Those are the ones the red team should simulate first.

3. Automated gap closure

# Automated ATT&CK gap closure
def close_detection_gap(technique_id):
    # 1. Get technique information
    technique = mitre_attack.get_technique(technique_id)

    # 2. Generate simulation tests
    atomic_tests = llm.generate_atomic_tests(technique)

    # 3. Generate detection rules
    sigma_rules = llm.generate_sigma_rules(technique)

    # 4. Execute simulation
    for test in atomic_tests:
        result = execute_atomic_test(test)
        detection = check_if_detected(result)

        if not detection:
            # 5. Deploy rule and re-test
            deploy_sigma_rule(sigma_rules)
            result = execute_atomic_test(test)
            detection = check_if_detected(result)

            if detection:
                log_success(technique_id, sigma_rules)
            else:
                escalate_to_analyst(technique_id, "Auto-detection failed")
        else:
            log_already_covered(technique_id)

The continuous purple improvement cycle

Purple teaming with AI is not a one-time exercise. It is a continuous cycle:

  1. Intel: collect threat intelligence (feeds, reports, dark web). AI filters and prioritizes.
  2. Plan: generate a simulation plan based on the most relevant actors and techniques. AI generates the plan.
  3. Execute: the red team (or BAS) executes the techniques. AI can run atomic tests automatically.
  4. Detect: the blue team analyzes whether each technique was detected. AI measures MTTD (Mean Time To Detect).
  5. Improve: for each gap, generate a new detection, deploy it and verify. AI generates the rules.
  6. Measure: calculate coverage metrics, MTTD, MTTR. AI generates the report and trends.
  7. Repeat: return to step 1 with new intelligence and new capabilities.

With AI, this cycle can run weekly instead of quarterly. Detection coverage improves measurably and continuously.

Tools and frameworks

Ejercicio practico

Ejercicio TS07: Purple team session with AI
  1. Choose a threat actor relevant to your sector (e.g., APT28 for government, FIN7 for retail, Lazarus for finance).
  2. Use an LLM to generate the 10 most likely ATT&CK techniques that actor would use against your organization.
  3. For each technique, generate a simulation test (Atomic Red Team style) and a Sigma detection rule.
  4. If you have a lab (Elastic SIEM + endpoint), execute 3 of the tests and verify whether the rules detect them.
  5. For undetected techniques, ask the LLM to generate improved rules. Repeat the test.
  6. Generate a purple team report with the LLM: tested techniques, detection percentage, gaps, improvements implemented, metrics (MTTD).
  7. Bonus: ask the LLM to generate 3 threat hunting hypotheses based on the gaps found.

Puntos clave

Puntos clave from TS07

  1. Purple teaming is the coordination of red and blue to improve detection in a measurable and systematic way. AI accelerates both sides.
  2. Adaptive simulation with AI adjusts techniques based on what the blue team detects (or not), emulating a real attacker.
  3. Automated detection generation closes gaps in minutes instead of weeks.
  4. Attackers also use AI (phishing, polymorphic malware, deepfakes). Detecting their use is a critical capability.
  5. Threat hunting with LLMs enables generating hypotheses, translating them to queries and analyzing results naturally.
  6. The continuous purple cycle (intel, plan, execute, detect, improve, measure, repeat) is the most effective way to improve your security posture.
Guia de estudio — Conceptos clave de TS07

Purple teaming: por que y como

  • Nivel 0: Sin coordinacion.Red y blue trabajan en silos. El red team hace un pentest anual, entrega un PDF, y nadie lo lee completo.
  • Nivel 1: Debriefs post-engagement.Despues del pentest, red y blue se reunen y discuten los hallazgos. Mejora, pero es reactivo.
  • Nivel 2: Sesiones purple coordinadas.Red ejecuta tecnicas especificas, blue observa si las detecta, y ambos ajustan en tiempo real.
  • Nivel 3: Purple continuo con IA.La simulacion de ataques es continua y automatizada. Las detecciones se ajustan automaticamente basandose en los resultados. El humano supervisa y decide en los casos complejos.
  • El objetivo real del purple team: El objetivo no es que el red team "gane" ni que el blue team "detecte todo". Es medir y mejorar la capacidad de deteccion y respuesta de forma sistematica. Cada tecnica no detectada es una oportunidad de mejora, no un fallo.

Simulacion de ataques con IA

  • Tecnica ATT&CK (ID + nombre)
  • Comando/herramienta especifica para ejecutar
  • Resultado esperado si la tecnica tiene exito
  • Que deberia detectar el blue team
  • Regla Sigma o query de deteccion esperada
  • Indicadores de compromiso generados

Defensa adaptativa con IA

  • Anomalias comportamentales:"Este usuario normalmente accede a 3 shares de red. Hoy ha accedido a 47 en 10 minutos." Una regla estaria basada en un umbral fijo. Un LLM entiende que el contexto importa.
  • Tecnicas de evasion:el atacante usa PowerShell con obfuscacion. Las reglas basadas en strings exactos fallan. Un LLM puede desobfuscar el comando y analizar su intencion.
  • Cadenas de eventos:tres eventos individuales inocuos que juntos forman una cadena de ataque. El LLM correlaciona temporalmente y narrativamente.
  • El ciclo de 4 pasos: Red ejecuta tecnica. Blue intenta detectar. Si detecta: validar la alerta, medir MTTD. Si no detecta: generar nueva regla, desplegarla, re-ejecutar la tecnica. Repetir hasta que la deteccion funcione. Este ciclo con IA se completa en minutos, no en dias.

Detectar uso adversarial de IA

  • Phishing generado por IA:emails sin los errores gramaticales tipicos, personalizados para cada objetivo. Mucho mas dificil de detectar con filtros basados en heuristicas.
  • Malware generado por IA:variantes polimoricas que cambian su firma en cada ejecucion. Los antivirus basados en firmas no lo detectan.
  • Deepfakes de voz:llamadas de "vishing" donde el atacante clona la voz del CEO para autorizar una transferencia.
  • Automatizacion de explotacion:agentes autonomos que escanean, explotan y pivotan sin intervencion humana.
  • CAPTCHA bypass:modelos de vision que resuelven CAPTCHAs automaticamente.
  • Velocidad sobrehumana:reconocimiento y explotacion en minutos cuando un humano tardaria horas.

Threat hunting con LLMs

  • Sector de la organizacion: {sector}
  • Actores de amenaza mas activos contra este sector: {actors}
  • Tecnicas mas usadas por estos actores: {techniques}
  • Ultimos advisories/CVEs relevantes: {advisories}
  • Detecciones actuales del SOC (reglas desplegadas): {current_rules}
  • "Busca procesos que se ejecutaron por primera vez en los ultimos 7 dias desde cuentas de servicio."

El ciclo de mejora continua purple

  • Intel:recopilar inteligencia de amenazas (feeds, informes, dark web). La IA filtra y prioriza.
  • Plan:generar plan de simulacion basado en los actores y tecnicas mas relevantes. La IA genera el plan.
  • Execute:el red team (o BAS) ejecuta las tecnicas. La IA puede ejecutar los tests atomicos automaticamente.
  • Detect:el blue team analiza si detecto cada tecnica. La IA mide MTTD (Mean Time To Detect).
  • Improve:para cada gap, generar nueva deteccion, desplegarla y verificar. La IA genera las reglas.
  • Measure:calcular metricas de cobertura, MTTD, MTTR. La IA genera el informe y las tendencias.

Siguiente: TS08 - Project: AI System Hardening

Final module of the security track: put everything you have learned into practice by securing an AI system end to end.

Ir al modulo TS08