En este modulo

  1. AI and pentesting: state of the art
  2. Reconnaissance with AI
  3. Vulnerability analysis
  4. Exploitation assistance
  5. Report generation
  6. AI for Red Team
  7. AI pentesting tools
  8. Ethical and legal considerations
  9. Ejercicio practico
  10. Puntos clave

AI and pentesting: state of the art

AI does not turn anyone into a hacker. What it does is multiply the productivity of an experienced pentester. The tasks where it has the most impact are: reconnaissance (automating information gathering and analysis), source code review (finding vulnerabilities at machine speed), finding correlation (connecting individual vulnerabilities into attack chains) and report generation (the task every pentester hates).

Where it does not work (yet): complex exploitation requiring creativity, pivoting in networks with unique configurations, social engineering requiring genuine human interaction, and anything requiring judgment about business impact.

Mandatory legal disclaimer

Everything described in this module is exclusively for authorized penetration testing with a signed contract (scope, dates, rules of engagement). Performing these activities without written authorization from the system owner is a criminal offense in most jurisdictions, including Spain (Art. 197 bis CP) and the EU (Directive 2013/40/EU).

Reconnaissance with AI

The reconnaissance phase consumes between 30% and 50% of a pentest's time. The pentester gathers information about the target: domains, subdomains, IPs, exposed services, technologies, employees, public documents, code repositories.

AI-assisted passive reconnaissance

AI can process and correlate passive reconnaissance data much faster than a human:

# AI-powered passive recon pipeline
class AIReconPipeline:
    def __init__(self, target_domain: str):
        self.target = target_domain
        self.findings = []

    async def run_passive_recon(self):
        # 1. Subdomain enumeration
        subdomains = await self.enumerate_subdomains()  # crt.sh, SecurityTrails

        # 2. Detected technologies
        tech_stack = await self.detect_technologies()  # Wappalyzer, headers

        # 3. Public documents
        docs = await self.google_dorking()  # PDFs, XLSX, config files

        # 4. Code repositories
        repos = await self.search_github(self.target)  # Secrets in code

        # 5. AI analyzes and correlates everything
        analysis = llm.analyze(
            prompt=RECON_ANALYSIS_PROMPT,
            data={
                "subdomains": subdomains,
                "technologies": tech_stack,
                "documents": docs,
                "repositories": repos
            }
        )
        # The LLM generates:
        # - Prioritized attack surface map
        # - Potential attack vectors
        # - Critical findings to investigate first
        return analysis

Subdomain and surface analysis

An LLM can analyze a list of 500 subdomains and classify them by interest:

Automated Google Dorking

An LLM can generate target-specific Google dorks and analyze the results:

# Dork generation with LLM
DORK_PROMPT = """
Generate 20 Google dorks to find sensitive information about {target}.
Include dorks for:
- Internal documents (PDF, XLSX, DOCX)
- Exposed configuration files
- Plaintext credentials
- Admin panels
- Directory listings
- Error messages with technical information
- Code repositories with secrets

Format: one dork per line, just the Google query, no explanation.
"""

Vulnerability analysis

AI transforms vulnerability analysis in three areas: source code review, configuration analysis and scanner results correlation.

Code review with LLMs

An LLM can review source code and find vulnerabilities with surprising accuracy for the most common categories (SQLi, XSS, IDOR, path traversal, hardcoded secrets):

# Security code review with LLM
CODE_REVIEW_PROMPT = """
You are a senior security code reviewer. Analyze the following code
for security vulnerabilities.

For each vulnerability found, report:
1. Affected line(s)
2. Vulnerability type (CWE ID if applicable)
3. Severity (critical/high/medium/low)
4. Risk description
5. Exploitation example
6. Recommended remediation with corrected code

Specifically look for:
- SQL injection (missing parameterization)
- XSS (unsanitized output)
- IDOR (missing object-level authorization)
- Path traversal (inputs in file paths)
- Hardcoded secrets (API keys, passwords)
- Insecure deserialization
- SSRF (requests with user-controlled URLs)
- Weak crypto (MD5, SHA1 for passwords)
- Race conditions
- Mass assignment

Code:
{code}
"""

Configuration analysis

Configuration files (nginx.conf, docker-compose.yml, terraform files, .env) frequently contain security errors. An LLM can review them against best practices:

Scanner results correlation

A scan with Nessus, Nuclei or Burp Suite generates hundreds or thousands of findings. Most are noise. An LLM can:

Exploitation assistance

AI can assist (not fully automate) the exploitation phase. The pentester still makes the decisions, but the LLM accelerates the process.

Where AI assists

Where AI fails

Never automate exploitation

Automated exploitation without human oversight can cause unintended damage: corrupt databases, bring down services, escalate beyond the authorized scope. The pentester decides, AI assists. Always.

Report generation

Pentesters hate writing reports. It is the most tedious phase and the one that consumes the most time after reconnaissance. An LLM reduces report writing time by 60-70%.

AI-assisted report structure

PENTEST_REPORT_PROMPT = """
Generate a professional pentest report from the following findings.

Mandatory structure:
1. Executive summary (1 page, no technical jargon, for leadership)
2. Scope and methodology
3. Findings summary (table with severity, CVSS, status)
4. Detailed findings (for each finding):
   - Descriptive title
   - Severity (Critical/High/Medium/Low/Info) + CVSS v3.1
   - Risk description
   - Evidence (reproduction steps)
   - Business impact
   - Remediation (specific, with code if applicable)
   - References (CWE, OWASP, CVE)
5. Prioritized recommendations (top 5)
6. Conclusions

Findings:
{findings_json}

Client context:
{client_context}
"""

What the LLM does well in reports

What requires human review

AI for Red Team

Red team operations are more complex than a classic pentest. They simulate a real attacker with time, resources and creativity. AI assists in specific phases:

Campaign planning

An LLM can generate attack scenarios based on the target's profile and the most relevant threat actors for their sector. "Simulate an APT28 attack against a European energy company. What initial access vectors would they use? What persistence techniques?"

Offensive infrastructure creation

Generate C2 configurations (Cobalt Strike, Sliver, Havoc), redirection profiles, phishing infrastructure. The LLM can generate malleable profiles, configure redirectors and create convincing phishing landing pages.

Pretext generation

For simulated phishing campaigns, the LLM can generate convincing emails adapted to the target's sector and culture. Important: only with explicit client authorization for social engineering.

Defense evasion

Suggest techniques to evade EDR, SIEM and other defenses. Payload obfuscation, AMSI bypass, living-off-the-land techniques. The LLM knows the public techniques but does not invent new ones (that is the limitation).

AI pentesting tools

Legal framework

Ethical limits of AI in pentesting

Ejercicio practico

Ejercicio TS06: AI-assisted pentest

Prerequisite: use exclusively lab environments (HackTheBox, TryHackMe, DVWA, WebGoat) or your own infrastructure. Never third-party systems without authorization.

  1. Choose a practice target (a HackTheBox machine or a local DVWA instance).
  2. Use an LLM to generate a passive reconnaissance plan: what information to look for, what tools to use, what dorks to apply.
  3. Execute reconnaissance and pass the results to the LLM to analyze and prioritize attack vectors.
  4. For a found vulnerability, ask the LLM to generate an adapted payload and explain the exploitation chain.
  5. Generate a complete pentest report with the LLM from your findings. Review the draft and identify what needs adjustment.
  6. Bonus: compare total pentest time with and without AI assistance. Document where AI added the most value and where it was useless.

Puntos clave

Puntos clave from TS06

  1. AI multiplies the pentester's productivity but does not replace experience. Reconnaissance and reports are the phases with the highest AI ROI.
  2. Code review with LLMs finds common vulnerabilities (SQLi, XSS, IDOR) with good accuracy. For business logic vulnerabilities, you need a human.
  3. LLMs reduce report writing time by 60-70%. The pentester reviews, adjusts severities and adds real evidence.
  4. Never automate exploitation without human oversight. AI suggests, the pentester executes and validates.
  5. All AI-assisted pentesting requires written authorization from the system owner. No contract, no pentest.
  6. AI does not invent new exploitation techniques. It applies known ones faster and more systematically.
Guia de estudio — Conceptos clave de TS06

IA y pentesting: estado del arte

  • Aviso legal obligatorio: Todo lo descrito en este modulo es exclusivamente para pruebas de penetracion autorizadas con contrato firmado (scope, fechas, reglas de engagement). Realizar estas actividades sin autorizacion escrita del propietario del sistema es un delito penal en la mayoria de jurisdicciones, incluyendo Espana (Art. 197 bis CP) y la UE (Directiva 2013/40/UE).

Reconocimiento con IA

  • Mapa de superficie de ataque priorizado
  • Vectores de ataque potenciales
  • Hallazgos criticos que investigar primero
  • Alta prioridad:admin.*, staging.*, dev.*, test.*, api-internal.* (posibles entornos de desarrollo expuestos).
  • Media prioridad:vpn.*, mail.*, webmail.* (servicios criticos con superficie de ataque conocida).
  • Baja prioridad:www.*, blog.*, docs.* (sitios publicos con menor superficie).

Analisis de vulnerabilidades

  • SQL injection (parametrizacion faltante)
  • XSS (output sin sanitizar)
  • IDOR (falta de autorizacion por objeto)
  • Path traversal (inputs en rutas de archivos)
  • Hardcoded secrets (API keys, passwords)
  • Deserializacion insegura

Asistencia en explotacion

  • Generar payloads:dado un tipo de vulnerabilidad y el contexto del objetivo, el LLM puede generar payloads adaptados (SQLi para MySQL vs PostgreSQL, XSS para un framework especifico).
  • Adaptar exploits publicos:tomar un PoC de un CVE y adaptarlo al entorno del objetivo (puertos, paths, versiones).
  • Analizar respuestas:interpretar mensajes de error, stack traces y comportamientos anomalos para guiar la explotacion.
  • Sugerir tecnicas de evasion:si un WAF bloquea un payload, el LLM puede sugerir codificaciones alternativas o tecnicas de bypass.
  • Explotacion de zero-days:requiere creatividad y comprension profunda que los LLMs actuales no tienen.
  • Pivoting complejo:moverse lateralmente en una red con configuraciones unicas requiere juicio situacional.

Generacion de informes

  • Titulo descriptivo
  • Severidad (Critica/Alta/Media/Baja/Info) + CVSS v3.1
  • Descripcion del riesgo
  • Evidencia (pasos de reproduccion)
  • Impacto en el negocio
  • Remediacion (especifica, con codigo si aplica)

Herramientas de pentesting con IA

  • - PentestGPT:asistente de pentesting basado en LLMs. Guia al pentester paso a paso, sugiere tecnicas y herramientas. Open source.
  • Nuclei + AI:el scanner de vulnerabilidades Nuclei combinado con LLMs para generar templates personalizados y analizar resultados.
  • Burp Suite + AI extensions:extensiones de Burp que usan LLMs para analizar trafico HTTP, generar payloads y detectar vulnerabilidades en la logica de negocio.
  • ReconFTW:framework de reconocimiento automatizado. No usa IA directamente, pero su output es ideal para alimentar un LLM que correlacione.
  • Claude Code / Cursor:para revision de codigo fuente. El pentester le pide que busque vulnerabilidades especificas en un repositorio.
  • Shannon:herramienta de pentesting automatizado que combina scanners con IA para priorizar y correlacionar hallazgos.

Siguiente: TS07 - Purple Teaming with AI

We bring offense and defense together: how AI powers both attack simulation and detection, creating a continuous improvement cycle.

Ir al modulo TS07