Buckets:

download
raw
72 kB
""" Security Integrations - Wrappers for 5 top open-source AI security tools. This module provides production-ready async wrappers for: 1. PentestGPT (GreyDGL) - LLM-driven pentest reasoning 2. Nuclei (ProjectDiscovery) - AI template generation, 9000+ templates 3. Garak (leondz/NVIDIA) - LLM vulnerability scanner 4. PyRIT (Microsoft) - AI red teaming framework 5. PentestAgent (GH05TCREW) - Black-box AI agent with MCP Usage: manager = IntegrationManager(config={"openai_api_key": "sk-..."}) results = await manager.run_tool("nuclei", mode="scan", target="example.com") """ import asyncio import hashlib import json import logging import os import shutil import subprocess import tempfile from abc import ABC, abstractmethod from dataclasses import dataclass, field from datetime import datetime from pathlib import Path from typing import Any, Dict, List, Optional, Tuple import aiohttp logger = logging.getLogger(__name__) # ============================================================================ # DATA CLASSES # ============================================================================ @dataclass class IntegrationResult: """Standardized result wrapper for all integration calls.""" tool_name: str mode: str success: bool data: Dict[str, Any] = field(default_factory=dict) raw_output: str = "" error: Optional[str] = None execution_time_ms: float = 0.0 timestamp: str = field(default_factory=lambda: datetime.utcnow().isoformat()) def to_dict(self) -> Dict[str, Any]: """Serialize result to dictionary.""" return { "tool_name": self.tool_name, "mode": self.mode, "success": self.success, "data": self.data, "raw_output": self.raw_output, "error": self.error, "execution_time_ms": self.execution_time_ms, "timestamp": self.timestamp, } @classmethod def error_result(cls, tool_name: str, mode: str, error: str, raw_output: str = "") -> "IntegrationResult": """Factory method for error results.""" return cls( tool_name=tool_name, mode=mode, success=False, error=error, raw_output=raw_output, ) # ============================================================================ # BASE CLASS # ============================================================================ class SecurityIntegration(ABC): """Abstract base class for all security tool integrations. Provides common infrastructure for: - Subprocess execution with timeout - Output parsing (JSON / text) - Error handling and fallback - Installation checking """ def __init__(self, config: Optional[Dict[str, Any]] = None) -> None: self.config: Dict[str, Any] = config or {} self.logger: logging.Logger = logging.getLogger(self.__class__.__name__) self.version: str = "unknown" self.installed: bool = False @abstractmethod async def check_installation(self) -> bool: """Check if the tool binary is available on the system PATH.""" @abstractmethod async def get_version(self) -> str: """Retrieve and cache the tool version string.""" @abstractmethod async def run(self, **kwargs: Any) -> IntegrationResult: """Execute the tool with the given parameters.""" @abstractmethod def get_capabilities(self) -> List[str]: """Return the list of capability identifiers this tool exposes.""" @staticmethod def _which(binary_name: str) -> Optional[str]: """Locate a binary on PATH via shutil.which.""" return shutil.which(binary_name) async def _exec( self, cmd: List[str], cwd: Optional[str] = None, env: Optional[Dict[str, str]] = None, timeout: int = 300, capture_json: bool = False, ) -> Tuple[bool, str, Optional[Any]]: """Async subprocess execution with timeout and optional JSON parsing.""" merged_env = {**os.environ, **(env or {})} self.logger.debug("Executing: %s (timeout=%ds)", " ".join(cmd), timeout) try: proc = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, cwd=cwd, env=merged_env, ) stdout_b, stderr_b = await asyncio.wait_for(proc.communicate(), timeout=timeout) except asyncio.TimeoutError: self.logger.error("Command timed out after %d seconds: %s", timeout, cmd) try: proc.kill() await proc.wait() except Exception: pass return False, f"Timeout after {timeout}s", None except FileNotFoundError: self.logger.error("Binary not found: %s", cmd[0]) return False, f"Binary not found: {cmd[0]}", None except PermissionError: self.logger.error("Permission denied for: %s", cmd[0]) return False, f"Permission denied: {cmd[0]}", None stdout = stdout_b.decode("utf-8", errors="replace").strip() stderr = stderr_b.decode("utf-8", errors="replace").strip() if proc.returncode != 0: combined = f"STDOUT:\n{stdout}\n\nSTDERR:\n{stderr}".strip() self.logger.warning("Non-zero exit code %d for %s", proc.returncode, cmd[0]) return False, combined, None output = stdout if stdout else stderr if capture_json and output: try: parsed = json.loads(output) return True, output, parsed except json.JSONDecodeError: self.logger.debug("Output is not valid JSON for %s", cmd[0]) return True, output, None return True, output, None async def _exec_with_fallback( self, primary_cmd: List[str], fallback_cmd: Optional[List[str]] = None, **kwargs: Any, ) -> Tuple[bool, str, Optional[Any]]: """Execute primary command, falling back to an alternative on failure.""" success, output, json_data = await self._exec(primary_cmd, **kwargs) if not success and fallback_cmd: self.logger.info("Primary command failed, trying fallback: %s", fallback_cmd) return await self._exec(fallback_cmd, **kwargs) return success, output, json_data # ============================================================================ # 1. PENTESTGPT INTEGRATION # ============================================================================ class PentestGPTIntegration(SecurityIntegration): """PentestGPT (GreyDGL/PentestGPT) Integration. LLM-driven pentest reasoning and attack chain generation. Uses GPT-4 / Claude to provide step-by-step pentest guidance. GitHub: https://github.com/GreyDGL/PentestGPT Stars: 4.5K+ | License: MIT """ BINARY_NAMES: List[str] = ["pentestgpt", "pentestGPT"] DEFAULT_TIMEOUT: int = 120 async def check_installation(self) -> bool: """Check if PentestGPT CLI is available on PATH.""" for name in self.BINARY_NAMES: if self._which(name): self.installed = True self.logger.info("PentestGPT found: %s", name) return True self.installed = False self.logger.warning("PentestGPT binary not found on PATH") return False async def get_version(self) -> str: """Retrieve PentestGPT version.""" for name in self.BINARY_NAMES: if self._which(name): success, output, _ = await self._exec([name, "--version"], timeout=15) if success: self.version = output.strip() or "installed" return self.version self.version = "not installed" return self.version async def reasoning(self, context: str, target: str) -> IntegrationResult: """Get AI reasoning for next pentest steps.""" start = datetime.utcnow() if not await self.check_installation(): return self._fallback_reasoning(context, target) env = self._build_env() cmd = ["pentestgpt", "--reasoning", "--target", target, "--context", context] success, output, _ = await self._exec(cmd, env=env, timeout=self.DEFAULT_TIMEOUT) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 if success: return IntegrationResult( tool_name="pentestgpt", mode="reasoning", success=True, data={"reasoning": output, "target": target, "context": context}, raw_output=output, execution_time_ms=elapsed, ) return IntegrationResult.error_result("pentestgpt", "reasoning", output or "Reasoning failed") async def attack_chain(self, recon_data: Dict[str, Any]) -> IntegrationResult: """Generate an attack chain from reconnaissance data.""" start = datetime.utcnow() if not await self.check_installation(): return self._fallback_attack_chain(recon_data) env = self._build_env() with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as tmp: json.dump(recon_data, tmp) tmp_path = tmp.name try: cmd = ["pentestgpt", "--attack-chain", "--recon-file", tmp_path] success, output, json_data = await self._exec(cmd, env=env, timeout=self.DEFAULT_TIMEOUT, capture_json=True) finally: os.unlink(tmp_path) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 if success: return IntegrationResult( tool_name="pentestgpt", mode="attack_chain", success=True, data=json_data or {"attack_chain": output}, raw_output=output, execution_time_ms=elapsed, ) return IntegrationResult.error_result("pentestgpt", "attack_chain", output or "Attack chain generation failed") async def generate_report_section(self, findings: List[Dict[str, Any]]) -> IntegrationResult: """Generate a report section using AI from findings.""" start = datetime.utcnow() if not await self.check_installation(): return self._fallback_report(findings) env = self._build_env() with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as tmp: json.dump({"findings": findings}, tmp) tmp_path = tmp.name try: cmd = ["pentestgpt", "--generate-report", "--findings-file", tmp_path] success, output, _ = await self._exec(cmd, env=env, timeout=self.DEFAULT_TIMEOUT) finally: os.unlink(tmp_path) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 if success: return IntegrationResult( tool_name="pentestgpt", mode="report_section", success=True, data={"report_section": output, "findings_count": len(findings)}, raw_output=output, execution_time_ms=elapsed, ) return IntegrationResult.error_result("pentestgpt", "report_section", output or "Report generation failed") async def assess_cvss(self, vulnerability: str) -> IntegrationResult: """AI-powered CVSS assessment for a vulnerability description.""" start = datetime.utcnow() if not await self.check_installation(): return self._fallback_cvss(vulnerability) env = self._build_env() cmd = ["pentestgpt", "--cvss-assess", "--vulnerability", vulnerability] success, output, json_data = await self._exec(cmd, env=env, timeout=60, capture_json=True) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 if success: return IntegrationResult( tool_name="pentestgpt", mode="cvss_assess", success=True, data=json_data or {"cvss_assessment": output}, raw_output=output, execution_time_ms=elapsed, ) return IntegrationResult.error_result("pentestgpt", "cvss_assess", output or "CVSS assessment failed") async def run(self, mode: str = "reasoning", **kwargs: Any) -> IntegrationResult: """Main execution dispatcher for PentestGPT.""" dispatch = { "reasoning": self.reasoning, "attack_chain": self.attack_chain, "report_section": self.generate_report_section, "cvss_assess": self.assess_cvss, } handler = dispatch.get(mode, self.reasoning) return await handler(**kwargs) def get_capabilities(self) -> List[str]: """Return PentestGPT capability identifiers.""" return [ "pentestgpt_reasoning", "pentestgpt_attack_chain", "pentestgpt_report_section", "pentestgpt_cvss_assess", "pentestgpt_next_steps", "pentestgpt_attack_plan", ] def _build_env(self) -> Dict[str, str]: """Build environment dict with API keys from config.""" env: Dict[str, str] = {} for key in ("OPENAI_API_KEY", "OPENAI_KEY", "PENTESTGPT_API_KEY"): val = self.config.get(key) or os.environ.get(key) if val: env[key] = val model = self.config.get("model", "gpt-4") env["PENTESTGPT_MODEL"] = model return env def _fallback_reasoning(self, context: str, target: str) -> IntegrationResult: """Provide heuristic reasoning when PentestGPT is not installed.""" self.logger.info("Using fallback reasoning for target: %s", target) reasoning_text = ( f"## Pentest Reasoning for {target}\n\n" f"**Context:** {context}\n\n" "### Recommended Next Steps:\n" "1. Perform service enumeration on discovered ports\n" "2. Check for default credentials on exposed services\n" "3. Search for known CVEs matching service versions\n" "4. Test for common misconfigurations\n" "5. Attempt authenticated access if credentials found\n\n" "*Note: Install PentestGPT for AI-powered reasoning.*" ) return IntegrationResult( tool_name="pentestgpt", mode="reasoning", success=True, data={"reasoning": reasoning_text, "target": target, "fallback": True}, raw_output=reasoning_text, ) def _fallback_attack_chain(self, recon_data: Dict[str, Any]) -> IntegrationResult: """Generate basic attack chain when PentestGPT is not installed.""" self.logger.info("Using fallback attack chain") services = recon_data.get("services", []) chain = { "steps": [ {"step": 1, "action": "Reconnaissance", "detail": "Information gathered"}, {"step": 2, "action": "Service Enumeration", "detail": f"Found {len(services)} services"}, {"step": 3, "action": "Vulnerability Scanning", "detail": "Run nuclei/openvas scans"}, {"step": 4, "action": "Exploitation", "detail": "Attempt exploitation of findings"}, {"step": 5, "action": "Post-Exploitation", "detail": "Privilege escalation, data exfiltration"}, ], "fallback": True, } return IntegrationResult( tool_name="pentestgpt", mode="attack_chain", success=True, data=chain, raw_output=json.dumps(chain, indent=2), ) def _fallback_report(self, findings: List[Dict[str, Any]]) -> IntegrationResult: """Generate basic report when PentestGPT is not installed.""" self.logger.info("Using fallback report generation for %d findings", len(findings)) lines = ["# Findings Report\n"] for i, f in enumerate(findings, 1): lines.append(f"## Finding {i}: {f.get('title', 'Unknown')}\n") lines.append(f"- **Severity:** {f.get('severity', 'Unknown')}") lines.append(f"- **Description:** {f.get('description', 'N/A')}") lines.append(f"- **Remediation:** {f.get('remediation', 'N/A')}\n") report_text = "\n".join(lines) return IntegrationResult( tool_name="pentestgpt", mode="report_section", success=True, data={"report_section": report_text, "findings_count": len(findings), "fallback": True}, raw_output=report_text, ) def _fallback_cvss(self, vulnerability: str) -> IntegrationResult: """Estimate CVSS heuristically when PentestGPT is not installed.""" self.logger.info("Using fallback CVSS assessment for: %s", vulnerability[:50]) score = 5.0 vector = "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:L/A:N" vuln_lower = vulnerability.lower() if "rce" in vuln_lower or "remote code" in vuln_lower: score = 9.8 vector = "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H" elif "sql injection" in vuln_lower or "xss" in vuln_lower: score = 8.5 vector = "CVSS:3.1/AV:N/AC:L/PR:N/UI:R/S:C/C:H/I:L/A:N" elif "information disclosure" in vuln_lower: score = 5.3 vector = "CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N" return IntegrationResult( tool_name="pentestgpt", mode="cvss_assess", success=True, data={ "cvss_score": score, "cvss_vector": vector, "severity": self._cvss_to_severity(score), "vulnerability": vulnerability, "fallback": True, }, raw_output=f"CVSS: {score} ({vector})", ) @staticmethod def _cvss_to_severity(score: float) -> str: """Map CVSS score to severity label.""" if score >= 9.0: return "Critical" if score >= 7.0: return "High" if score >= 4.0: return "Medium" if score >= 0.1: return "Low" return "None" # ============================================================================ # 2. NUCLEI INTEGRATION # ============================================================================ class NucleiIntegration(SecurityIntegration): """Nuclei (ProjectDiscovery) Integration with AI template generation. Fast template-driven vulnerability scanner supporting 9000+ templates. GitHub: https://github.com/projectdiscovery/nuclei Stars: 20K+ | License: MIT """ BINARY_NAME: str = "nuclei" DEFAULT_TIMEOUT: int = 600 DEFAULT_RATE_LIMIT: int = 150 TEMPLATE_DIR: str = os.path.expanduser("~/nuclei-templates") async def check_installation(self) -> bool: """Check if nuclei binary is available on PATH.""" if self._which(self.BINARY_NAME): self.installed = True self.logger.info("Nuclei found on PATH") return True self.installed = False self.logger.warning("Nuclei binary not found on PATH") return False async def get_version(self) -> str: """Retrieve nuclei version.""" if not self._which(self.BINARY_NAME): self.version = "not installed" return self.version success, output, _ = await self._exec([self.BINARY_NAME, "-version"], timeout=15) self.version = output.strip() if success else "unknown" return self.version async def scan( self, target: str, templates: Optional[List[str]] = None, severity: Optional[List[str]] = None, rate_limit: int = 150, output_format: str = "json", ) -> IntegrationResult: """Run nuclei scan against a target.""" start = datetime.utcnow() if not await self.check_installation(): return IntegrationResult.error_result("nuclei", "scan", "Nuclei not installed") cmd = [self.BINARY_NAME, "-u", target, "-rate-limit", str(rate_limit)] if templates: for tmpl in templates: cmd.extend(["-t", tmpl]) if severity: cmd.extend(["-severity", ",".join(severity)]) if output_format == "json": cmd.extend(["-jsonl"]) cmd.extend(["-silent"]) success, output, _ = await self._exec(cmd, timeout=self.DEFAULT_TIMEOUT) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 findings = self._parse_nuclei_output(output) if success: return IntegrationResult( tool_name="nuclei", mode="scan", success=True, data={ "target": target, "findings": findings, "findings_count": len(findings), "templates_used": templates, "severity_filter": severity, }, raw_output=output, execution_time_ms=elapsed, ) return IntegrationResult.error_result("nuclei", "scan", output or "Scan failed") async def list_templates(self, category: Optional[str] = None) -> IntegrationResult: """List available nuclei templates.""" start = datetime.utcnow() if not await self.check_installation(): return self._fallback_template_list(category) cmd = [self.BINARY_NAME, "-tl"] if category: cmd.extend(["-tc", category]) success, output, _ = await self._exec(cmd, timeout=60) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 templates = [line.strip() for line in output.splitlines() if line.strip()] if success: return IntegrationResult( tool_name="nuclei", mode="template_list", success=True, data={"templates": templates, "count": len(templates), "category": category}, raw_output=output, execution_time_ms=elapsed, ) return IntegrationResult.error_result("nuclei", "template_list", output or "Template listing failed") async def update_templates(self) -> IntegrationResult: """Update nuclei templates to the latest version.""" start = datetime.utcnow() if not await self.check_installation(): return IntegrationResult.error_result("nuclei", "template_update", "Nuclei not installed") success, output, _ = await self._exec([self.BINARY_NAME, "-ut"], timeout=120) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 return IntegrationResult( tool_name="nuclei", mode="template_update", success=success, data={"updated": success, "details": output}, raw_output=output, execution_time_ms=elapsed, ) async def ai_generate_template(self, cve_description: str, poc_code: Optional[str] = None) -> IntegrationResult: """AI-powered nuclei template generation from CVE description.""" start = datetime.utcnow() self.logger.info("Generating AI template for CVE description") template_yaml = self._construct_template(cve_description, poc_code) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 return IntegrationResult( tool_name="nuclei", mode="ai_generate_template", success=True, data={ "template": template_yaml, "cve_description": cve_description, "has_poc": poc_code is not None, }, raw_output=template_yaml, execution_time_ms=elapsed, ) async def ai_cve_scan(self, cve_id: str, target: str) -> IntegrationResult: """Scan for a specific CVE using nuclei.""" start = datetime.utcnow() if not await self.check_installation(): return IntegrationResult.error_result("nuclei", "ai_cve_scan", "Nuclei not installed") cmd = [self.BINARY_NAME, "-u", target, "-id", cve_id, "-jsonl", "-silent"] success, output, _ = await self._exec(cmd, timeout=self.DEFAULT_TIMEOUT) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 findings = self._parse_nuclei_output(output) if success: return IntegrationResult( tool_name="nuclei", mode="ai_cve_scan", success=True, data={ "cve_id": cve_id, "target": target, "findings": findings, "vulnerable": len(findings) > 0, }, raw_output=output, execution_time_ms=elapsed, ) return IntegrationResult.error_result("nuclei", "ai_cve_scan", output or f"CVE scan for {cve_id} failed") async def custom_template_scan(self, template_yaml: str, target: str) -> IntegrationResult: """Scan with a custom AI-generated template.""" start = datetime.utcnow() if not await self.check_installation(): return IntegrationResult.error_result("nuclei", "custom_template_scan", "Nuclei not installed") with tempfile.NamedTemporaryFile(mode="w", suffix=".yaml", delete=False) as tmp: tmp.write(template_yaml) tmp_path = tmp.name try: cmd = [self.BINARY_NAME, "-u", target, "-t", tmp_path, "-jsonl", "-silent"] success, output, _ = await self._exec(cmd, timeout=self.DEFAULT_TIMEOUT) finally: os.unlink(tmp_path) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 findings = self._parse_nuclei_output(output) if success: return IntegrationResult( tool_name="nuclei", mode="custom_template_scan", success=True, data={"target": target, "findings": findings, "vulnerable": len(findings) > 0}, raw_output=output, execution_time_ms=elapsed, ) return IntegrationResult.error_result("nuclei", "custom_template_scan", output or "Custom template scan failed") async def run(self, mode: str = "scan", **kwargs: Any) -> IntegrationResult: """Main execution dispatcher for Nuclei.""" dispatch = { "scan": self.scan, "template_list": self.list_templates, "template_update": self.update_templates, "ai_generate_template": self.ai_generate_template, "ai_cve_scan": self.ai_cve_scan, "custom_template_scan": self.custom_template_scan, } handler = dispatch.get(mode, self.scan) return await handler(**kwargs) def get_capabilities(self) -> List[str]: """Return Nuclei capability identifiers.""" return [ "nuclei_scan", "nuclei_template_list", "nuclei_template_update", "nuclei_ai_generate_template", "nuclei_ai_cve_scan", "nuclei_custom_template_scan", "nuclei_ratelimit", ] @staticmethod def _parse_nuclei_output(output: str) -> List[Dict[str, Any]]: """Parse nuclei JSONL output into structured findings.""" findings: List[Dict[str, Any]] = [] for line in output.splitlines(): line = line.strip() if not line: continue try: findings.append(json.loads(line)) except json.JSONDecodeError: if "[" in line and "]" in line: findings.append({"raw": line, "parsed": False}) return findings @staticmethod def _construct_template(cve_description: str, poc_code: Optional[str]) -> str: """Construct a nuclei YAML template from CVE description.""" tmpl_id = hashlib.md5(cve_description.encode()).hexdigest()[:8] yaml_lines = [ f"id: ai-generated-{tmpl_id}", "", "info:", f" name: AI Generated Template for {cve_description[:60]}", " author: ai-pentest-suite", " severity: high", " description: |", f" {cve_description}", " tags: ai-generated,cve", "", "http:", " - method: GET", " path:", ' - "{{BaseURL}}/"', " matchers:", " - type: word", " words:", ' - "vulnerable"', " part: body", ] if poc_code: yaml_lines.extend(["", " # POC Reference:"]) for poc_line in poc_code.splitlines(): yaml_lines.append(f" # {poc_line}") return "\n".join(yaml_lines) def _fallback_template_list(self, category: Optional[str]) -> IntegrationResult: """Return common template categories when nuclei is not installed.""" common_templates = [ "cves/", "vulnerabilities/", "misconfiguration/", "exposed-panels/", "technologies/", "dns/", "ssl/", "network/", ] if category: common_templates = [t for t in common_templates if category.lower() in t.lower()] return IntegrationResult( tool_name="nuclei", mode="template_list", success=True, data={"templates": common_templates, "count": len(common_templates), "fallback": True}, raw_output="\n".join(common_templates), ) # ============================================================================ # 3. GARAK INTEGRATION # ============================================================================ class GarakIntegration(SecurityIntegration): """Garak (leondz/NVIDIA) Integration. LLM vulnerability scanner for probing AI systems. GitHub: https://github.com/leondz/garak Stars: 3K+ | License: Apache 2.0 """ BINARY_NAMES: List[str] = ["garak", "python3 -m garak"] DEFAULT_TIMEOUT: int = 300 PROBE_CATEGORIES: Dict[str, List[str]] = { "prompt_injection": ["promptinject", "realtoxicityprompts"], "jailbreak": ["dan", "chatgpt-jailbreak", "knownbadsignatures"], "data_leakage": ["leakreplay", "mc", "PII"], "hallucination": ["hallucination"], "toxicity": ["realtoxicityprompts", "atkgen"], } async def check_installation(self) -> bool: """Check if garak is available on PATH or as a Python module.""" if self._which("garak"): self.installed = True self.logger.info("Garak CLI found on PATH") return True py3 = self._which("python3") if py3: success, _, _ = await self._exec([py3, "-m", "garak", "--help"], timeout=10) if success: self.installed = True self.logger.info("Garak found as python3 module") return True self.installed = False self.logger.warning("Garak not found") return False async def get_version(self) -> str: """Retrieve garak version.""" if self._which("garak"): success, output, _ = await self._exec(["garak", "--version"], timeout=15) if success: self.version = output.strip() or "installed" return self.version py3 = self._which("python3") if py3: success, output, _ = await self._exec([py3, "-m", "garak", "--version"], timeout=15) if success: self.version = output.strip() or "installed" return self.version self.version = "not installed" return self.version async def probe_llm(self, model_name: str, probes: Optional[List[str]] = None) -> IntegrationResult: """Probe an LLM for vulnerabilities using Garak.""" start = datetime.utcnow() if not await self.check_installation(): return self._fallback_probe("llm", model_name) cmd = self._build_cmd(["--model_type", model_name]) if probes: for probe in probes: cmd.extend(["--probes", probe]) success, output, _ = await self._exec(cmd, timeout=self.DEFAULT_TIMEOUT) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 if success: parsed = self._parse_garak_output(output) return IntegrationResult( tool_name="garak", mode="probe_llm", success=True, data={"model": model_name, "probes": probes or "all", "findings": parsed}, raw_output=output, execution_time_ms=elapsed, ) return IntegrationResult.error_result("garak", "probe_llm", output or "LLM probing failed") async def probe_prompt_injection(self, target: str) -> IntegrationResult: """Test for prompt injection vulnerabilities.""" start = datetime.utcnow() if not await self.check_installation(): return self._fallback_probe("prompt_injection", target) cmd = self._build_cmd(["--model_type", target, "--probes", "promptinject"]) success, output, _ = await self._exec(cmd, timeout=self.DEFAULT_TIMEOUT) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 if success: parsed = self._parse_garak_output(output) return IntegrationResult( tool_name="garak", mode="probe_promptinject", success=True, data={"target": target, "probe_type": "prompt_injection", "findings": parsed}, raw_output=output, execution_time_ms=elapsed, ) return IntegrationResult.error_result("garak", "probe_promptinject", output or "Prompt injection test failed") async def probe_jailbreak(self, target: str) -> IntegrationResult: """Test for jailbreak vulnerabilities.""" start = datetime.utcnow() if not await self.check_installation(): return self._fallback_probe("jailbreak", target) cmd = self._build_cmd(["--model_type", target, "--probes", "dan.ChatGPTDAN"]) success, output, _ = await self._exec(cmd, timeout=self.DEFAULT_TIMEOUT) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 if success: parsed = self._parse_garak_output(output) return IntegrationResult( tool_name="garak", mode="probe_jailbreak", success=True, data={"target": target, "probe_type": "jailbreak", "findings": parsed}, raw_output=output, execution_time_ms=elapsed, ) return IntegrationResult.error_result("garak", "probe_jailbreak", output or "Jailbreak test failed") async def probe_data_leakage(self, target: str) -> IntegrationResult: """Test for data leakage vulnerabilities.""" start = datetime.utcnow() if not await self.check_installation(): return self._fallback_probe("data_leakage", target) cmd = self._build_cmd(["--model_type", target, "--probes", "leakreplay"]) success, output, _ = await self._exec(cmd, timeout=self.DEFAULT_TIMEOUT) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 if success: parsed = self._parse_garak_output(output) return IntegrationResult( tool_name="garak", mode="probe_leakage", success=True, data={"target": target, "probe_type": "data_leakage", "findings": parsed}, raw_output=output, execution_time_ms=elapsed, ) return IntegrationResult.error_result("garak", "probe_leakage", output or "Data leakage test failed") async def probe_dan(self, target: str) -> IntegrationResult: """Test with DAN (Do Anything Now) prompts.""" start = datetime.utcnow() if not await self.check_installation(): return self._fallback_probe("dan", target) cmd = self._build_cmd(["--model_type", target, "--probes", "dan.DAN"]) success, output, _ = await self._exec(cmd, timeout=self.DEFAULT_TIMEOUT) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 if success: parsed = self._parse_garak_output(output) return IntegrationResult( tool_name="garak", mode="probe_dan", success=True, data={"target": target, "probe_type": "DAN", "findings": parsed}, raw_output=output, execution_time_ms=elapsed, ) return IntegrationResult.error_result("garak", "probe_dan", output or "DAN probe failed") async def generate_report(self, results: Dict[str, Any]) -> IntegrationResult: """Generate a findings report from Garak results.""" start = datetime.utcnow() lines = ["# Garak LLM Security Assessment Report\n"] findings = results.get("findings", []) lines.append(f"**Total Findings:** {len(findings)}\n") for i, finding in enumerate(findings, 1): lines.append(f"## Finding {i}") for key, val in finding.items(): lines.append(f"- **{key}:** {val}") lines.append("") report_text = "\n".join(lines) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 return IntegrationResult( tool_name="garak", mode="report_findings", success=True, data={"report": report_text, "findings_count": len(findings)}, raw_output=report_text, execution_time_ms=elapsed, ) async def run(self, mode: str = "probe", **kwargs: Any) -> IntegrationResult: """Main execution dispatcher for Garak.""" dispatch = { "probe": self.probe_llm, "probe_llm": self.probe_llm, "probe_promptinject": self.probe_prompt_injection, "probe_jailbreak": self.probe_jailbreak, "probe_leakage": self.probe_data_leakage, "probe_dan": self.probe_dan, "report_findings": self.generate_report, } handler = dispatch.get(mode, self.probe_llm) return await handler(**kwargs) def get_capabilities(self) -> List[str]: """Return Garak capability identifiers.""" return [ "garak_probe_llm", "garak_probe_promptinject", "garak_probe_jailbreak", "garak_probe_leakage", "garak_probe_dan", "garak_report_findings", ] def _build_cmd(self, args: List[str]) -> List[str]: """Build the garak command with proper prefix.""" if self._which("garak"): return ["garak"] + args return ["python3", "-m", "garak"] + args @staticmethod def _parse_garak_output(output: str) -> List[Dict[str, Any]]: """Parse garak CLI output into structured findings.""" findings: List[Dict[str, Any]] = [] current_finding: Dict[str, Any] = {} for line in output.splitlines(): line = line.strip() if not line: if current_finding: findings.append(current_finding) current_finding = {} continue if line.startswith("probe:"): current_finding["probe"] = line.split(":", 1)[1].strip() elif line.startswith("status:"): current_finding["status"] = line.split(":", 1)[1].strip() elif line.startswith("triggered:"): val = line.split(":", 1)[1].strip().lower() current_finding["triggered"] = val in ("true", "yes", "1") elif "x" in line.lower() and "probe" in line.lower(): findings.append({"raw": line, "parsed": False}) if current_finding: findings.append(current_finding) return findings def _fallback_probe(self, probe_type: str, target: str) -> IntegrationResult: """Provide fallback probe results when Garak is not installed.""" self.logger.info("Using fallback %s probe for target: %s", probe_type, target) fallback_findings = [ { "probe": f"{probe_type}_fallback", "target": target, "status": "info", "message": f"Garak not installed. Install for real {probe_type} probing.", "recommendation": "pip install garak", } ] return IntegrationResult( tool_name="garak", mode=f"probe_{probe_type}", success=True, data={"target": target, "probe_type": probe_type, "findings": fallback_findings, "fallback": True}, raw_output=f"Fallback {probe_type} probe for {target}", ) # ============================================================================ # 4. PYRIT INTEGRATION # ============================================================================ class PyRITIntegration(SecurityIntegration): """PyRIT (Microsoft) Integration. AI red teaming framework with 40+ attack strategies. GitHub: https://github.com/Azure/PyRIT Stars: 2K+ | License: MIT """ BINARY_NAMES: List[str] = ["pyrit", "python3 -m pyrit"] DEFAULT_TIMEOUT: int = 300 ATTACK_STRATEGIES: List[str] = [ "jailbreak", "prompt_injection", "base64_injection", "morse_code_injection", "template_injection", "text_continuation", "privilege_escalation", "token_smuggling", "adversarial_suffix", "many_shot_jailbreak", "crescendo", "forced_authentication", "harmful_content", "code_execution", ] async def check_installation(self) -> bool: """Check if PyRIT is available on PATH or as a Python module.""" if self._which("pyrit"): self.installed = True self.logger.info("PyRIT CLI found on PATH") return True py3 = self._which("python3") if py3: success, _, _ = await self._exec([py3, "-m", "pyrit", "--help"], timeout=10) if success: self.installed = True self.logger.info("PyRIT found as python3 module") return True self.installed = False self.logger.warning("PyRIT not found") return False async def get_version(self) -> str: """Retrieve PyRIT version.""" if self._which("pyrit"): success, output, _ = await self._exec(["pyrit", "--version"], timeout=15) if success: self.version = output.strip() or "installed" return self.version py3 = self._which("python3") if py3: success, output, _ = await self._exec([py3, "-m", "pyrit", "--version"], timeout=15) if success: self.version = output.strip() or "installed" return self.version self.version = "not installed" return self.version async def run_attack_strategy(self, target: str, strategy: str = "jailbreak") -> IntegrationResult: """Run a specific PyRIT attack strategy.""" start = datetime.utcnow() if not await self.check_installation(): return self._fallback_attack(target, strategy) if strategy not in self.ATTACK_STRATEGIES: return IntegrationResult.error_result( "pyrit", "attack_strategy", f"Unknown strategy: {strategy}. Available: {', '.join(self.ATTACK_STRATEGIES)}", ) env = self._build_env() cmd = self._build_pyrit_cmd(["attack", "--target", target, "--strategy", strategy]) success, output, _ = await self._exec(cmd, env=env, timeout=self.DEFAULT_TIMEOUT) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 if success: parsed = self._parse_pyrit_output(output) return IntegrationResult( tool_name="pyrit", mode="attack_strategy", success=True, data={"target": target, "strategy": strategy, "results": parsed}, raw_output=output, execution_time_ms=elapsed, ) return IntegrationResult.error_result("pyrit", "attack_strategy", output or f"Attack strategy {strategy} failed") async def orchestrate_redteam(self, target: str, strategies: Optional[List[str]] = None) -> IntegrationResult: """Run a multi-strategy red team assessment.""" start = datetime.utcnow() if not strategies: strategies = ["jailbreak", "prompt_injection", "privilege_escalation"] all_results: List[Dict[str, Any]] = [] for strategy in strategies: self.logger.info("Running red team strategy: %s", strategy) result = await self.run_attack_strategy(target, strategy) all_results.append( { "strategy": strategy, "success": result.success, "data": result.data, "error": result.error, } ) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 total_success = sum(1 for r in all_results if r["success"]) return IntegrationResult( tool_name="pyrit", mode="orchestrate_redteam", success=True, data={ "target": target, "strategies_run": strategies, "results": all_results, "successful_strategies": total_success, "total_strategies": len(strategies), }, raw_output=json.dumps(all_results, indent=2), execution_time_ms=elapsed, ) async def prompt_injection_test(self, target: str) -> IntegrationResult: """Test for prompt injection vulnerabilities.""" return await self.run_attack_strategy(target, strategy="prompt_injection") async def jailbreak_test(self, target: str) -> IntegrationResult: """Test for jailbreak vulnerabilities.""" return await self.run_attack_strategy(target, strategy="jailbreak") async def generate_report(self, results: Dict[str, Any]) -> IntegrationResult: """Generate a red team assessment report.""" start = datetime.utcnow() lines = ["# PyRIT Red Team Assessment Report\n"] target = results.get("target", "Unknown") lines.append(f"**Target:** {target}\n") strategy_results = results.get("results", []) lines.append(f"**Strategies Tested:** {len(strategy_results)}\n") for sr in strategy_results: strategy = sr.get("strategy", "unknown") success = sr.get("success", False) status_icon = "PASS" if success else "FAIL" lines.append(f"## {strategy} - {status_icon}") data = sr.get("data", {}) for key, val in data.items(): lines.append(f"- **{key}:** {val}") lines.append("") report_text = "\n".join(lines) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 return IntegrationResult( tool_name="pyrit", mode="report", success=True, data={"report": report_text, "strategies_tested": len(strategy_results)}, raw_output=report_text, execution_time_ms=elapsed, ) async def run(self, mode: str = "attack", **kwargs: Any) -> IntegrationResult: """Main execution dispatcher for PyRIT.""" dispatch = { "attack": self.run_attack_strategy, "attack_strategy": self.run_attack_strategy, "orchestrate_redteam": self.orchestrate_redteam, "prompt_inject": self.prompt_injection_test, "jailbreak_test": self.jailbreak_test, "report": self.generate_report, } handler = dispatch.get(mode, self.run_attack_strategy) return await handler(**kwargs) def get_capabilities(self) -> List[str]: """Return PyRIT capability identifiers.""" return [ "pyrit_attack_strategy", "pyrit_orchestrate_redteam", "pyrit_prompt_inject", "pyrit_jailbreak_test", "pyrit_report", ] def _build_pyrit_cmd(self, args: List[str]) -> List[str]: """Build PyRIT command with proper prefix.""" if self._which("pyrit"): return ["pyrit"] + args return ["python3", "-m", "pyrit"] + args def _build_env(self) -> Dict[str, str]: """Build environment with Azure OpenAI credentials if configured.""" env: Dict[str, str] = {} for key in ("AZURE_OPENAI_KEY", "AZURE_OPENAI_ENDPOINT", "AZURE_OPENAI_DEPLOYMENT", "OPENAI_API_KEY"): val = self.config.get(key) or os.environ.get(key) if val: env[key] = val return env @staticmethod def _parse_pyrit_output(output: str) -> List[Dict[str, Any]]: """Parse PyRIT CLI output into structured results.""" results: List[Dict[str, Any]] = [] current: Dict[str, Any] = {} for line in output.splitlines(): line = line.strip() if not line: if current: results.append(current) current = {} continue if "attack" in line.lower() and ":" in line: current["attack"] = line.split(":", 1)[1].strip() elif "response" in line.lower() and ":" in line: current["response"] = line.split(":", 1)[1].strip() elif "score" in line.lower() and ":" in line: try: current["score"] = float(line.split(":", 1)[1].strip()) except ValueError: current["score_raw"] = line.split(":", 1)[1].strip() if current: results.append(current) return results def _fallback_attack(self, target: str, strategy: str) -> IntegrationResult: """Provide fallback attack results when PyRIT is not installed.""" self.logger.info("Using fallback %s attack for target: %s", strategy, target) return IntegrationResult( tool_name="pyrit", mode="attack_strategy", success=True, data={ "target": target, "strategy": strategy, "status": "fallback", "message": "PyRIT not installed. Install: pip install pyrit", "note": "This is a simulated fallback result.", "fallback": True, }, raw_output=f"Fallback {strategy} attack for {target}", ) # ============================================================================ # 5. PENTESTAGENT INTEGRATION # ============================================================================ class PentestAgentIntegration(SecurityIntegration): """PentestAgent (GH05TCREW) Integration. Black-box AI agent framework with CrewAI-style orchestration. GitHub: https://github.com/GH05TCREW/PentestAgent Stars: 500+ | License: MIT """ BINARY_NAMES: List[str] = ["pentestagent", "pentest-agent"] DEFAULT_TIMEOUT: int = 300 async def check_installation(self) -> bool: """Check if PentestAgent CLI is available on PATH.""" for name in self.BINARY_NAMES: if self._which(name): self.installed = True self.logger.info("PentestAgent found: %s", name) return True self.installed = False self.logger.warning("PentestAgent binary not found on PATH") return False async def get_version(self) -> str: """Retrieve PentestAgent version.""" for name in self.BINARY_NAMES: if self._which(name): success, output, _ = await self._exec([name, "--version"], timeout=15) if success: self.version = output.strip() or "installed" return self.version self.version = "not installed" return self.version async def run_recon(self, target: str) -> IntegrationResult: """Run reconnaissance agent against target.""" start = datetime.utcnow() if not await self.check_installation(): return self._fallback_recon(target) cmd = ["pentestagent", "--recon", "--target", target] success, output, json_data = await self._exec(cmd, timeout=self.DEFAULT_TIMEOUT, capture_json=True) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 if success: return IntegrationResult( tool_name="pentestagent", mode="recon", success=True, data=json_data or {"recon_output": output, "target": target}, raw_output=output, execution_time_ms=elapsed, ) return IntegrationResult.error_result("pentestagent", "recon", output or "Recon failed") async def run_scan(self, target: str) -> IntegrationResult: """Run scanning agent against target.""" start = datetime.utcnow() if not await self.check_installation(): return self._fallback_scan(target) cmd = ["pentestagent", "--scan", "--target", target] success, output, json_data = await self._exec(cmd, timeout=self.DEFAULT_TIMEOUT, capture_json=True) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 if success: return IntegrationResult( tool_name="pentestagent", mode="scan", success=True, data=json_data or {"scan_output": output, "target": target}, raw_output=output, execution_time_ms=elapsed, ) return IntegrationResult.error_result("pentestagent", "scan", output or "Scan failed") async def run_exploit(self, target: str, findings: List[Dict[str, Any]]) -> IntegrationResult: """Run exploitation agent with discovered findings.""" start = datetime.utcnow() if not await self.check_installation(): return self._fallback_exploit(target, findings) with tempfile.NamedTemporaryFile(mode="w", suffix=".json", delete=False) as tmp: json.dump({"findings": findings, "target": target}, tmp) tmp_path = tmp.name try: cmd = [ "pentestagent", "--exploit", "--target", target, "--findings-file", tmp_path, ] success, output, json_data = await self._exec(cmd, timeout=self.DEFAULT_TIMEOUT, capture_json=True) finally: os.unlink(tmp_path) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 if success: return IntegrationResult( tool_name="pentestagent", mode="exploit", success=True, data=json_data or {"exploit_output": output, "target": target}, raw_output=output, execution_time_ms=elapsed, ) return IntegrationResult.error_result("pentestagent", "exploit", output or "Exploitation failed") async def run_crew_mode(self, target: str) -> IntegrationResult: """Run full crew-based pentest with all agents.""" start = datetime.utcnow() if not await self.check_installation(): return self._fallback_crew(target) cmd = ["pentestagent", "--crew", "--target", target] success, output, json_data = await self._exec(cmd, timeout=self.DEFAULT_TIMEOUT * 2, capture_json=True) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 if success: return IntegrationResult( tool_name="pentestagent", mode="crew_mode", success=True, data=json_data or {"crew_output": output, "target": target}, raw_output=output, execution_time_ms=elapsed, ) return IntegrationResult.error_result("pentestagent", "crew_mode", output or "Crew mode failed") async def get_shadow_graph(self) -> IntegrationResult: """Get the knowledge graph (Shadow Graph) from notes.""" start = datetime.utcnow() if not await self.check_installation(): return self._fallback_shadow_graph() cmd = ["pentestagent", "--shadow-graph"] success, output, json_data = await self._exec(cmd, timeout=60, capture_json=True) elapsed = (datetime.utcnow() - start).total_seconds() * 1000 if success: return IntegrationResult( tool_name="pentestagent", mode="shadow_graph", success=True, data=json_data or {"graph_output": output}, raw_output=output, execution_time_ms=elapsed, ) return IntegrationResult.error_result("pentestagent", "shadow_graph", output or "Shadow graph retrieval failed") async def run(self, mode: str = "recon", **kwargs: Any) -> IntegrationResult: """Main execution dispatcher for PentestAgent.""" dispatch = { "recon": self.run_recon, "scan": self.run_scan, "exploit": self.run_exploit, "crew_mode": self.run_crew_mode, "shadow_graph": self.get_shadow_graph, } handler = dispatch.get(mode, self.run_recon) return await handler(**kwargs) def get_capabilities(self) -> List[str]: """Return PentestAgent capability identifiers.""" return [ "pentestagent_recon", "pentestagent_scan", "pentestagent_exploit", "pentestagent_crew_mode", "pentestagent_shadow_graph", ] def _fallback_recon(self, target: str) -> IntegrationResult: """Provide basic recon data when PentestAgent is not installed.""" self.logger.info("Using fallback recon for target: %s", target) return IntegrationResult( tool_name="pentestagent", mode="recon", success=True, data={ "target": target, "status": "fallback", "message": "PentestAgent not installed. Using basic recon.", "recommendation": "pip install pentestagent", "fallback": True, "suggested_steps": [f"nmap -sV {target}", f"dig {target}", f"whois {target}"], }, raw_output=f"Fallback recon for {target}", ) def _fallback_scan(self, target: str) -> IntegrationResult: """Provide basic scan data when PentestAgent is not installed.""" self.logger.info("Using fallback scan for target: %s", target) return IntegrationResult( tool_name="pentestagent", mode="scan", success=True, data={ "target": target, "status": "fallback", "message": "PentestAgent not installed. Using basic scan.", "recommendation": "pip install pentestagent", "fallback": True, "suggested_steps": [f"nuclei -u {target}", f"nmap --script vuln {target}"], }, raw_output=f"Fallback scan for {target}", ) def _fallback_exploit(self, target: str, findings: List[Dict[str, Any]]) -> IntegrationResult: """Provide basic exploit guidance when PentestAgent is not installed.""" self.logger.info("Using fallback exploit for target: %s", target) return IntegrationResult( tool_name="pentestagent", mode="exploit", success=True, data={ "target": target, "status": "fallback", "message": "PentestAgent not installed. Using basic exploit guidance.", "recommendation": "pip install pentestagent", "fallback": True, "findings_count": len(findings), "suggested_next_steps": [ "Review findings manually", "Search for public exploits on exploit-db", "Use Metasploit for known CVEs", ], }, raw_output=f"Fallback exploit for {target} with {len(findings)} findings", ) def _fallback_crew(self, target: str) -> IntegrationResult: """Provide basic crew mode guidance when PentestAgent is not installed.""" self.logger.info("Using fallback crew mode for target: %s", target) return IntegrationResult( tool_name="pentestagent", mode="crew_mode", success=True, data={ "target": target, "status": "fallback", "message": "PentestAgent not installed. Manual crew mode simulation.", "recommendation": "pip install pentestagent", "fallback": True, "simulated_agents": [ {"agent": "recon", "status": "would_run", "command": f"recon {target}"}, {"agent": "scan", "status": "would_run", "command": f"scan {target}"}, {"agent": "exploit", "status": "would_run", "command": f"exploit {target}"}, ], }, raw_output=f"Fallback crew mode for {target}", ) def _fallback_shadow_graph(self) -> IntegrationResult: """Provide empty shadow graph when PentestAgent is not installed.""" self.logger.info("Using fallback shadow graph") return IntegrationResult( tool_name="pentestagent", mode="shadow_graph", success=True, data={ "nodes": [], "edges": [], "status": "fallback", "message": "PentestAgent not installed. Shadow graph unavailable.", "fallback": True, }, raw_output="Fallback shadow graph (empty)", ) # ============================================================================ # INTEGRATION MANAGER # ============================================================================ class IntegrationManager: """Central manager for all 5 security tool integrations. Provides a unified interface to discover, execute, and manage the five integrated open-source security tools. Example: manager = IntegrationManager(config={"openai_api_key": "sk-xxx"}) status = await manager.check_all_installations() result = await manager.run_tool("nuclei", mode="scan", target="example.com") """ TOOL_NAMES: List[str] = [ "pentestgpt", "nuclei", "garak", "pyrit", "pentestagent", ] def __init__(self, config: Optional[Dict[str, Any]] = None) -> None: self.config: Dict[str, Any] = config or {} self.logger: logging.Logger = logging.getLogger("integration_manager") self.integrations: Dict[str, SecurityIntegration] = {} self._initialize_integrations() def _initialize_integrations(self) -> None: """Instantiate all 5 security tool integrations.""" self.integrations["pentestgpt"] = PentestGPTIntegration(self.config) self.integrations["nuclei"] = NucleiIntegration(self.config) self.integrations["garak"] = GarakIntegration(self.config) self.integrations["pyrit"] = PyRITIntegration(self.config) self.integrations["pentestagent"] = PentestAgentIntegration(self.config) self.logger.info( "Initialized %d integrations: %s", len(self.integrations), ", ".join(self.integrations.keys()), ) async def check_all_installations(self) -> Dict[str, bool]: """Check installation status for all 5 tools.""" results: Dict[str, bool] = {} for name, integration in self.integrations.items(): try: installed = await integration.check_installation() results[name] = installed except Exception as exc: self.logger.error("Error checking %s: %s", name, exc) results[name] = False self.logger.info("Installation status: %s", results) return results async def run_tool(self, tool_name: str, mode: str = "default", **kwargs: Any) -> IntegrationResult: """Run a specific tool by name and mode.""" if tool_name not in self.integrations: self.logger.error("Unknown tool: %s", tool_name) return IntegrationResult.error_result( tool_name, mode, f"Unknown tool: {tool_name}. Available: {', '.join(self.TOOL_NAMES)}" ) integration = self.integrations[tool_name] self.logger.info("Running %s in mode '%s'", tool_name, mode) try: return await integration.run(mode=mode, **kwargs) except Exception as exc: self.logger.exception("Error running %s: %s", tool_name, exc) return IntegrationResult.error_result(tool_name, mode, f"Execution error: {str(exc)}") def get_all_capabilities(self) -> Dict[str, List[str]]: """Get capabilities of all integrations.""" return {name: integration.get_capabilities() for name, integration in self.integrations.items()} def get_tool_info(self, tool_name: str) -> Dict[str, Any]: """Get metadata about a specific tool.""" if tool_name not in self.integrations: return {"error": f"Unknown tool: {tool_name}"} integration = self.integrations[tool_name] return { "name": tool_name, "class": integration.__class__.__name__, "installed": integration.installed, "version": integration.version, "capabilities": integration.get_capabilities(), } def get_all_tool_info(self) -> Dict[str, Dict[str, Any]]: """Get metadata about all tools.""" return {name: self.get_tool_info(name) for name in self.integrations} async def install_tool(self, tool_name: str) -> bool: """Install a tool using its recommended installation method.""" install_commands: Dict[str, List[str]] = { "pentestgpt": ["pip", "install", "pentestgpt"], "nuclei": [ "bash", "-c", "curl -sL https://raw.githubusercontent.com/projectdiscovery/nuclei/main/cmd/nuclei/install.sh | bash", ], "garak": ["pip", "install", "garak"], "pyrit": ["pip", "install", "pyrit"], "pentestagent": ["pip", "install", "pentestagent"], } if tool_name not in install_commands: self.logger.error("No install command for tool: %s", tool_name) return False cmd = install_commands[tool_name] self.logger.info("Installing %s with: %s", tool_name, " ".join(cmd)) try: proc = await asyncio.create_subprocess_exec( *cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, ) stdout_b, stderr_b = await asyncio.wait_for(proc.communicate(), timeout=300) stdout = stdout_b.decode("utf-8", errors="replace") if proc.returncode == 0: self.logger.info("Successfully installed %s", tool_name) integration = self.integrations.get(tool_name) if integration: await integration.check_installation() return True else: self.logger.error("Failed to install %s (exit %d): %s", tool_name, proc.returncode, stdout[:500]) return False except asyncio.TimeoutError: self.logger.error("Installation of %s timed out", tool_name) return False except Exception as exc: self.logger.error("Error installing %s: %s", tool_name, exc) return False async def run_parallel(self, tasks: List[Dict[str, Any]]) -> List[Any]: """Run multiple tool tasks in parallel. Args: tasks: List of task dicts with keys: tool_name, mode, kwargs. Returns: List of IntegrationResult objects. """ coros = [] for task in tasks: tool_name = task.pop("tool_name") mode = task.pop("mode", "default") coros.append(self.run_tool(tool_name, mode=mode, **task)) self.logger.info("Running %d tasks in parallel", len(coros)) return await asyncio.gather(*coros, return_exceptions=True) async def get_health_status(self) -> Dict[str, Any]: """Get comprehensive health status of all integrations.""" installations = await self.check_all_installations() total = len(installations) installed = sum(1 for v in installations.values() if v) return { "total_tools": total, "installed": installed, "missing": total - installed, "healthy": installed == total, "tools": { name: { "installed": status, "capabilities": self.integrations[name].get_capabilities(), } for name, status in installations.items() }, "timestamp": datetime.utcnow().isoformat(), } # ============================================================================ # MODULE EXPORTS # ============================================================================ __all__ = [ "IntegrationResult", "SecurityIntegration", "PentestGPTIntegration", "NucleiIntegration", "GarakIntegration", "PyRITIntegration", "PentestAgentIntegration", "IntegrationManager", ] # ============================================================================ # CLI / SMOKE TEST # ============================================================================ if __name__ == "__main__": logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", ) async def _smoke_test() -> None: """Quick smoke test of all integrations.""" manager = IntegrationManager() print("=== Integration Health Check ===") health = await manager.get_health_status() print(json.dumps(health, indent=2)) print() print("=== All Capabilities ===") caps = manager.get_all_capabilities() for tool, tool_caps in caps.items(): print(f" {tool}: {', '.join(tool_caps)}") asyncio.run(_smoke_test())
"""
Security Integrations - Wrappers for 5 top open-source AI security tools.
This module provides production-ready async wrappers for:
1. PentestGPT (GreyDGL) - LLM-driven pentest reasoning
2. Nuclei (ProjectDiscovery) - AI template generation, 9000+ templates
3. Garak (leondz/NVIDIA) - LLM vulnerability scanner
4. PyRIT (Microsoft) - AI red teaming framework
5. PentestAgent (GH05TCREW) - Black-box AI agent with MCP
Usage:
manager = IntegrationManager(config={"openai_api_key": "sk-..."})
results = await manager.run_tool("nuclei", mode="scan", target="example.com")
"""
import asyncio
import hashlib
import json
import logging
import os
import shutil
import subprocess
import tempfile
from abc import ABC, abstractmethod
from dataclasses import dataclass, field
from datetime import datetime
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
import aiohttp
logger = logging.getLogger(__name__)
# ============================================================================
# DATA CLASSES
# ============================================================================
@dataclass
class IntegrationResult:
"""Standardized result wrapper for all integration calls."""
tool_name: str
mode: str
success: bool
data: Dict[str, Any] = field(default_factory=dict)
raw_output: str = ""
error: Optional[str] = None
execution_time_ms: float = 0.0
timestamp: str = field(default_factory=lambda: datetime.utcnow().isoformat())
def to_dict(self) -> Dict[str, Any]:
"""Serialize result to dictionary."""
return {
"tool_name": self.tool_name,
"mode": self.mode,
"success": self.success,
"data": self.data,
"raw_output": self.raw_output,
"error": self.error,
"execution_time_ms": self.execution_time_ms,
"timestamp": self.timestamp,
}
@classmethod
def error_result(cls, tool_name: str, mode: str, error: str, raw_output: str = "") -> "IntegrationResult":
"""Factory method for error results."""
return cls(
tool_name=tool_name,
mode=mode,
success=False,
error=error,
raw_output=raw_output,
)
# ============================================================================
# BASE CLASS
# ============================================================================
class SecurityIntegration(ABC):
"""Abstract base class for all security tool integrations.
Provides common infrastructure for:
- Subprocess execution with timeout
- Output parsing (JSON / text)
- Error handling and fallback
- Installation checking
"""
def __init__(self, config: Optional[Dict[str, Any]] = None) -> None:
self.config: Dict[str, Any] = config or {}
self.logger: logging.Logger = logging.getLogger(self.__class__.__name__)
self.version: str = "unknown"
self.installed: bool = False
@abstractmethod
async def check_installation(self) -> bool:

Xet Storage Details

Size:
72 kB
·
Xet hash:
0a0fe18c1b38e25c88cc556145bd886ae58efb34bfdad65304ae0d723f6d8b22

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.