Chuyển đến nội dung chính

Bài 20: AI-powered Pentesting 2026

LLM-assisted reconnaissance, AI vulnerability analysis, automated exploit generation, AI-driven defense evasion, ethical considerations.

🔒 DevSecOps — Bài 20 Bài 20: AI-powered Pentesting 2026

Performance Testing & Pentest: Quy trình Chuẩn Doanh nghiệp 2026

Phần 4: Pentest Nâng cao — Cloud, Container & AI

xdev.asia

1. AI trong Pentesting — Bức tranh 2026

AI-Powered Pentest Evolution:

2020: Automated scanning (Burp, ZAP)
2022: ML-based anomaly detection
2024: LLM-assisted code review, recon
2025: AI agents for pentest workflows  
2026: Autonomous pentest copilots

AI Application Areas:
  ┌─────────────────────────────────────────┐
  │          Pentest Lifecycle              │
  ├──────────┬──────────┬──────────────────┤
  │ Recon    │ Exploit  │ Report           │
  ├──────────┼──────────┼──────────────────┤
  │ OSINT    │ Vuln     │ Auto-generate    │
  │ analysis │ analysis │ findings         │
  │          │          │                  │
  │ Attack   │ Payload  │ CVSS scoring     │
  │ surface  │ crafting │ assistance       │
  │ mapping  │          │                  │
  │          │ Evasion  │ Remediation      │
  │ Pattern  │ strategy │ recommendations  │
  │ discovery│          │                  │
  └──────────┴──────────┴──────────────────┘

Key Tools 2026:
  ├── PentestGPT: LLM pentest assistant
  ├── ReconAIzer: AI recon analysis (Burp extension)
  ├── Nuclei AI: Smart template generation
  ├── GitHub Copilot: Code review for security
  └── Custom AI agents: Task-specific automation

2. AI-assisted Reconnaissance

# AI-assisted OSINT analysis
# Combine traditional tools with LLM analysis

import openai
import subprocess
import json

class AIRecon:
    def __init__(self, target: str):
        self.target = target
        self.client = openai.OpenAI()
        self.findings = []

    def passive_recon(self) -> dict:
        """Gather data from passive sources"""
        # Subdomain enumeration
        subs = subprocess.run(
            ["subfinder", "-d", self.target, "-silent"],
            capture_output=True, text=True
        ).stdout.strip().split("\n")

        # Technology detection
        techs = subprocess.run(
            ["httpx", "-l", "-", "-tech-detect", "-silent", "-json"],
            input="\n".join(subs),
            capture_output=True, text=True
        ).stdout

        return {
            "subdomains": subs,
            "technologies": techs,
            "total_subdomains": len(subs)
        }

    def analyze_with_ai(self, recon_data: dict) -> str:
        """Use LLM to analyze recon data and suggest attack vectors"""
        prompt = f"""
        Analyze the following reconnaissance data for {self.target}.
        Identify potential attack vectors and prioritize them.

        Subdomains found: {recon_data['total_subdomains']}
        Sample subdomains: {recon_data['subdomains'][:20]}
        Technologies detected: {recon_data['technologies'][:2000]}

        Provide:
        1. Attack surface summary
        2. High-priority targets (with reasoning)
        3. Suggested testing methodology
        4. Technology-specific vulnerabilities to check
        """

        response = self.client.chat.completions.create(
            model="gpt-4o",
            messages=[
                {"role": "system", "content": "You are a senior penetration tester. Analyze recon data and provide actionable security assessment guidance."},
                {"role": "user", "content": prompt}
            ],
            temperature=0.3
        )
        return response.choices[0].message.content

# Usage
recon = AIRecon("example.com")
data = recon.passive_recon()
analysis = recon.analyze_with_ai(data)
print(analysis)

3. AI Vulnerability Analysis

# AI-powered code review for security vulnerabilities

class AICodeReviewer:
    def __init__(self):
        self.client = openai.OpenAI()

    def review_code(self, code: str, language: str) -> dict:
        """Review code for security vulnerabilities"""
        prompt = f"""
        Review the following {language} code for security vulnerabilities.
        
        For each vulnerability found, provide:
        1. Vulnerability type (OWASP category)
        2. Severity (Critical/High/Medium/Low)
        3. Line number(s)
        4. Description
        5. Remediation code

        Code to review:
        ```{language}
        {code}
        ```
        
        Respond in JSON format:
        {{
          "vulnerabilities": [
            {{
              "type": "SQL Injection",
              "owasp": "A03:2021",
              "severity": "Critical",
              "lines": [15, 16],
              "description": "...",
              "remediation": "..."
            }}
          ],
          "overall_risk": "High",
          "summary": "..."
        }}
        """

        response = self.client.chat.completions.create(
            model="gpt-4o",
            messages=[
                {"role": "system", "content": "You are a security code reviewer. Find vulnerabilities accurately. No false positives."},
                {"role": "user", "content": prompt}
            ],
            temperature=0.1,
            response_format={"type": "json_object"}
        )
        return json.loads(response.choices[0].message.content)

# Scan entire project
import glob

reviewer = AICodeReviewer()
for filepath in glob.glob("src/**/*.py", recursive=True):
    with open(filepath) as f:
        code = f.read()
    results = reviewer.review_code(code, "python")
    if results["vulnerabilities"]:
        print(f"\n[!] {filepath}: {len(results['vulnerabilities'])} issues")
        for vuln in results["vulnerabilities"]:
            print(f"  - [{vuln['severity']}] {vuln['type']}: {vuln['description']}")

4. AI-generated Nuclei Templates

# Generate custom Nuclei templates with AI

def generate_nuclei_template(
    vulnerability_type: str,
    target_tech: str,
    description: str
) -> str:
    """Generate Nuclei template using AI"""
    prompt = f"""
    Create a Nuclei YAML template for detecting the following vulnerability:
    
    Type: {vulnerability_type}
    Technology: {target_tech}
    Description: {description}
    
    Requirements:
    - Follow Nuclei template syntax v3
    - Include proper matchers (status, word, regex)
    - Add extractors where relevant
    - Set appropriate severity
    - Include remediation reference
    
    Return ONLY the YAML template, no explanations.
    """

    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {"role": "system", "content": "You are a Nuclei template expert. Generate accurate, working templates."},
            {"role": "user", "content": prompt}
        ],
        temperature=0.2
    )
    
    template = response.choices[0].message.content
    # Strip markdown code blocks if present
    template = template.replace("```yaml", "").replace("```", "").strip()
    return template

# Example usage
template = generate_nuclei_template(
    vulnerability_type="Exposed Environment File",
    target_tech="Laravel PHP",
    description="Detect exposed .env files containing database credentials and API keys"
)

# Save and validate
with open("custom-templates/laravel-env-exposure.yaml", "w") as f:
    f.write(template)

# Validate template
# nuclei -validate -t custom-templates/laravel-env-exposure.yaml

5. AI-assisted Report Generation

# Automated pentest report with AI

class AIReportGenerator:
    def __init__(self):
        self.client = openai.OpenAI()

    def generate_finding_report(self, finding: dict) -> str:
        """Generate detailed finding report from raw data"""
        prompt = f"""
        Generate a professional pentest finding report for:
        
        Title: {finding['title']}
        Severity: {finding['severity']}
        Affected: {finding['affected_url']}
        Evidence: {finding['evidence']}
        Tool: {finding['tool']}
        
        Include:
        1. Description (technical + business impact)
        2. Steps to reproduce (numbered)
        3. Proof of Concept (if applicable)
        4. CVSS v4.0 score calculation
        5. Remediation (specific, actionable)
        6. References (CWE, OWASP, vendor docs)
        
        Write in professional tone for executive + technical audience.
        """

        response = self.client.chat.completions.create(
            model="gpt-4o",
            messages=[
                {"role": "system", "content": "You are a senior pentest report writer."},
                {"role": "user", "content": prompt}
            ],
            temperature=0.3
        )
        return response.choices[0].message.content

    def generate_executive_summary(self, findings: list) -> str:
        """Generate executive summary from all findings"""
        summary_data = [
            {"title": f["title"], "severity": f["severity"]}
            for f in findings
        ]

        prompt = f"""
        Generate an executive summary for a penetration test with these findings:
        {json.dumps(summary_data, indent=2)}
        
        Total findings: {len(findings)}
        Critical: {sum(1 for f in findings if f['severity'] == 'Critical')}
        High: {sum(1 for f in findings if f['severity'] == 'High')}
        Medium: {sum(1 for f in findings if f['severity'] == 'Medium')}
        Low: {sum(1 for f in findings if f['severity'] == 'Low')}
        
        Include:
        1. Overall security posture assessment
        2. Key risks (business language)
        3. Priority remediation roadmap
        4. Comparison with industry benchmarks
        """

        response = self.client.chat.completions.create(
            model="gpt-4o",
            messages=[
                {"role": "system", "content": "You are a CISO advisor writing for C-level executives."},
                {"role": "user", "content": prompt}
            ],
            temperature=0.3
        )
        return response.choices[0].message.content

6. AI trong Defensive Security

AI-powered Defense Tools 2026:

Threat Detection:
  ├── Anomaly detection in network traffic
  ├── User behavior analytics (UEBA)
  ├── Log analysis at scale (SIEM + AI)
  └── Zero-day pattern recognition

Vulnerability Management:
  ├── Auto-prioritize vulnerabilities (context-aware)
  ├── Predict exploit likelihood
  ├── Suggest remediation based on codebase
  └── Continuous security posture assessment

Incident Response:
  ├── Automated triage and classification
  ├── Root cause analysis assistance
  ├── Playbook recommendation
  └── Post-incident report generation

Challenges:
  ├── AI hallucinations → false positives
  ├── Adversarial prompt injection
  ├── Model poisoning in training data
  ├── Privacy concerns with code analysis
  └── Over-reliance on AI judgment

7. Ethical Considerations

AI Pentesting Ethics:

✅ Acceptable use:
  ├── Authorized security testing
  ├── Code review for vulnerabilities
  ├── Generating test cases and payloads
  ├── Report writing assistance
  └── Training and education

❌ Unacceptable use:
  ├── Generating malware
  ├── Attacking without authorization
  ├── Creating zero-day exploits for sale
  ├── Mass exploitation campaigns
  └── Bypassing legal restrictions

Best Practices:
  1. AI is an assistant, not a replacement
  2. Always verify AI findings manually
  3. Human judgment for impact assessment
  4. Document AI tool usage in reports
  5. Stay updated on AI security regulations
  6. Use AI responsibly — enhance, don't automate everything

8. Tổng kết

  • AI Recon: LLM analysis of OSINT data, attack surface mapping
  • Code Review: AI-powered vulnerability detection in source code
  • Template Generation: Auto-create Nuclei templates for specific vulns
  • Reporting: AI-assisted finding reports, executive summaries
  • Defense: Anomaly detection, UEBA, automated incident response
  • Ethics: AI enhances human judgment, never replaces it

Bài tiếp theo sẽ chuyển sang Red Team — Adversary Simulation.