En este modulo
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:
- High priority: admin.*, staging.*, dev.*, test.*, api-internal.* (potentially exposed development environments).
- Medium priority: vpn.*, mail.*, webmail.* (critical services with known attack surfaces).
- Low priority: www.*, blog.*, docs.* (public sites with smaller surface).
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:
- Missing security headers (CSP, HSTS, X-Frame-Options).
- TLS configured with weak versions or ciphers.
- Unnecessary exposed ports.
- Overly broad filesystem permissions.
- Secrets in configuration files (not in vault).
- Containers running as root.
Scanner results correlation
A scan with Nessus, Nuclei or Burp Suite generates hundreds or thousands of findings. Most are noise. An LLM can:
- Deduplicate: the same issue reported by different scanners.
- Prioritize: which findings are actually exploitable in this infrastructure context.
- Chain: combine individual findings into attack chains. "This IDOR + this lack of rate limiting + this unauthenticated API = access to all user data."
- Filter false positives: based on software version and configuration context.
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
- Generate payloads: given a vulnerability type and target context, the LLM can generate adapted payloads (SQLi for MySQL vs PostgreSQL, XSS for a specific framework).
- Adapt public exploits: take a CVE PoC and adapt it to the target environment (ports, paths, versions).
- Analyze responses: interpret error messages, stack traces and anomalous behavior to guide exploitation.
- Suggest evasion techniques: if a WAF blocks a payload, the LLM can suggest alternative encodings or bypass techniques.
Where AI fails
- Zero-day exploitation: requires creativity and deep understanding that current LLMs lack.
- Complex pivoting: moving laterally in a network with unique configurations requires situational judgment.
- Stealthy post-exploitation: maintaining access without detection requires environment knowledge the LLM lacks.
- Social engineering: requires real human interaction, empathy and real-time adaptation.
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
- Translate technical findings into business language for the executive summary.
- Calculate CVSS consistently (with justification for each metric).
- Generate specific and actionable remediation recommendations.
- Maintain a professional and consistent tone throughout the report.
What requires human review
- Verify that evidence is correct and reproducible.
- Adjust severities to the client's specific context.
- Validate that recommendations are feasible for the client's infrastructure.
- Add real screenshots and logs.
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
- PentestGPT: LLM-based pentesting assistant. Guides the pentester step by step, suggests techniques and tools. Open source.
- Nuclei + AI: the Nuclei vulnerability scanner combined with LLMs to generate custom templates and analyze results.
- Burp Suite + AI extensions: Burp extensions using LLMs to analyze HTTP traffic, generate payloads and detect business logic vulnerabilities.
- ReconFTW: automated reconnaissance framework. Does not use AI directly, but its output is ideal for feeding an LLM for correlation.
- Claude Code / Cursor: for source code review. The pentester asks it to find specific vulnerabilities in a repository.
- Shannon: automated pentesting tool combining scanners with AI to prioritize and correlate findings.
Ethical and legal considerations
Legal framework
- Spain: Art. 197 bis and 264 of the Penal Code. Unauthorized access to computer systems is a crime. Pentesting only with written authorization from the owner.
- EU: Directive 2013/40/EU on attacks against information systems. Harmonizes penalties across the EU.
- Pentest contract: must specify scope (systems, IPs, dates), rules of engagement (what is allowed, what is not), emergency communication channels, and liability waiver.
Ethical limits of AI in pentesting
- Do not use AI to create real malware. Generating payloads for testing is acceptable. Creating autonomous malware is not.
- Do not automate attacks without oversight. AI assists, the pentester decides. Always.
- Do not use AI to expand scope. If the contract authorizes testing 10 IPs, do not use AI to discover and attack another 50.
- Responsible disclosure. If AI discovers a critical vulnerability outside the scope, communicate it to the client and stop exploitation.
Ejercicio practico
Prerequisite: use exclusively lab environments (HackTheBox, TryHackMe, DVWA, WebGoat) or your own infrastructure. Never third-party systems without authorization.
- Choose a practice target (a HackTheBox machine or a local DVWA instance).
- Use an LLM to generate a passive reconnaissance plan: what information to look for, what tools to use, what dorks to apply.
- Execute reconnaissance and pass the results to the LLM to analyze and prioritize attack vectors.
- For a found vulnerability, ask the LLM to generate an adapted payload and explain the exploitation chain.
- Generate a complete pentest report with the LLM from your findings. Review the draft and identify what needs adjustment.
- 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
- AI multiplies the pentester's productivity but does not replace experience. Reconnaissance and reports are the phases with the highest AI ROI.
- Code review with LLMs finds common vulnerabilities (SQLi, XSS, IDOR) with good accuracy. For business logic vulnerabilities, you need a human.
- LLMs reduce report writing time by 60-70%. The pentester reviews, adjusts severities and adds real evidence.
- Never automate exploitation without human oversight. AI suggests, the pentester executes and validates.
- All AI-assisted pentesting requires written authorization from the system owner. No contract, no pentest.
- 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