Buckets:

download
raw
29.1 kB
#!/usr/bin/env python3
"""
Zen AI Pentest - Main Application
Multi-LLM Penetration Testing Intelligence System
Enhanced with Autonomous Mode, Risk Engine, and CI/CD Integration
Author: SHAdd0WTAka
"""
import argparse
import asyncio
import json
import os
import sys
from datetime import datetime
from typing import Any, Dict, Optional
# Add project root to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# Apply Windows/asyncio fixes immediately
from utils.async_fixes import apply_windows_async_fixes, silence_asyncio_warnings
apply_windows_async_fixes()
silence_asyncio_warnings()
from backends.chatgpt_direct import ChatGPTDirectBackend
from backends.claude_direct import ClaudeDirectBackend
from backends.duckduckgo import DuckDuckGoBackend
from backends.openrouter import OpenRouterBackend
from core.orchestrator import ZenOrchestrator
from modules.exploit_assist import ExploitAssistModule
from modules.recon import ReconModule
from modules.report_generator import ReportGenerator
from modules.vuln_scanner import VulnScannerModule
from utils.helpers import banner, colorize, get_severity_color, load_config, validate_target
from utils.stealth import StealthManager
# Try to import new components
try:
AUTONOMOUS_AVAILABLE = True
except ImportError:
AUTONOMOUS_AVAILABLE = False
try:
RISK_ENGINE_AVAILABLE = True
except ImportError:
RISK_ENGINE_AVAILABLE = False
try:
from benchmarks import BenchmarkRunner
BENCHMARK_AVAILABLE = True
except ImportError:
BENCHMARK_AVAILABLE = False
try:
from integrations import load_integrations_from_config
INTEGRATIONS_AVAILABLE = True
except ImportError:
INTEGRATIONS_AVAILABLE = False
class ZenAIPentest:
"""
Main Zen AI Pentest application
"""
def __init__(self, config_path: str = "config.json"):
self.config = load_config(config_path)
self.orchestrator = ZenOrchestrator()
self.stealth = StealthManager(self.config.get("stealth", {}))
# Initialize modules
self.recon = ReconModule(self.orchestrator)
self.vuln_scanner = VulnScannerModule(self.orchestrator)
self.exploit_assist = ExploitAssistModule(self.orchestrator)
self.report_gen = ReportGenerator(self.orchestrator)
self.findings = []
# Initialize new components
self._integrations = {}
if INTEGRATIONS_AVAILABLE:
try:
self._integrations = load_integrations_from_config()
except Exception as e:
print(colorize(f"[!] Failed to load integrations: {e}", "yellow"))
async def initialize_backends(self):
"""Initialize and register LLM backends"""
print(colorize("[*] Initializing LLM backends...", "blue"))
# Always add DuckDuckGo (free, no auth)
ddg = DuckDuckGoBackend()
self.orchestrator.add_backend(ddg)
print(colorize(" [+] DuckDuckGo backend registered (Free)", "green"))
# Add OpenRouter if API key available
or_key = self.config.get("backends", {}).get("openrouter_api_key")
if or_key and or_key != "sk-or-v1-YOUR-KEY-HERE":
or_backend = OpenRouterBackend(api_key=or_key)
self.orchestrator.add_backend(or_backend)
print(colorize(" [+] OpenRouter backend registered", "green"))
# Add ChatGPT Direct if token available
cg_token = self.config.get("backends", {}).get("chatgpt_token")
if cg_token:
cg_backend = ChatGPTDirectBackend(access_token=cg_token)
self.orchestrator.add_backend(cg_backend)
print(colorize(" [+] ChatGPT Direct backend registered", "green"))
# Add Claude Direct if session available
claude_session = self.config.get("backends", {}).get("claude_session")
if claude_session:
claude_backend = ClaudeDirectBackend(session_key=claude_session)
self.orchestrator.add_backend(claude_backend)
print(colorize(" [+] Claude Direct backend registered", "green"))
print(
colorize(
f"[*] Total backends: {len(self.orchestrator.backends)}",
"cyan",
)
)
# Print capabilities
capabilities = self.orchestrator.get_capabilities()
print(colorize("\n[*] Available Capabilities:", "blue"))
for cap, available in capabilities.items():
status = "OK" if available else "NO"
color = "green" if available else "red"
print(colorize(f" [{status}] {cap}", color))
async def run_recon(self, target: str):
"""Run reconnaissance phase"""
print(colorize(f"\n[+] Starting Reconnaissance for {target}", "bold"))
result = await self.recon.analyze_target(target)
print(colorize(f"[+] Target IP: {result.get('ip', 'N/A')}", "cyan"))
print(
colorize(
f"[+] Attack vectors identified: {len(result.get('attack_vectors', []))}",
"cyan",
)
)
return result
async def run_nmap_analysis(self, target: str, nmap_output: str = None):
"""Analyze nmap scan results"""
print(colorize(f"\n[+] Analyzing target {target}", "bold"))
if not nmap_output:
# Generate nmap command suggestion
cmd = await self.recon.generate_nmap_command(target)
print(colorize("[i] Suggested nmap command:", "yellow"))
print(colorize(f" {cmd}", "white"))
print(
colorize(
"[i] Run this command and provide output for analysis",
"yellow",
)
)
return []
# Analyze the nmap output
vulns = await self.vuln_scanner.analyze_nmap_output(nmap_output)
print(colorize(f"[+] Found {len(vulns)} potential vulnerabilities", "green"))
for vuln in vulns[:5]: # Show top 5
color = get_severity_color(vuln.severity)
print(colorize(f" [{vuln.severity}] {vuln.name}", color))
self.findings.extend(vulns)
return vulns
async def run_web_analysis(self, url: str, headers: dict = None, html: str = None):
"""Analyze web application"""
print(colorize(f"\n[+] Analyzing web application {url}", "bold"))
findings = []
if headers:
header_vulns = await self.vuln_scanner.analyze_web_headers(headers, url)
findings.extend(header_vulns)
if html:
page_vulns = await self.vuln_scanner.analyze_web_page(html, url)
findings.extend(page_vulns)
print(colorize(f"[+] Found {len(findings)} web-related issues", "green"))
for vuln in findings[:5]:
color = get_severity_color(vuln.severity)
print(colorize(f" [{vuln.severity}] {vuln.name}", color))
self.findings.extend(findings)
return findings
async def run_exploit_assist(self, vuln_name: str, service: str = "unknown"):
"""Get exploit assistance"""
print(colorize(f"\n[+] Generating exploit suggestions for {vuln_name}", "bold"))
suggestions = await self.exploit_assist.suggest_exploits(vuln_name, service)
for i, sug in enumerate(suggestions[:3], 1):
print(colorize(f"\n [{i}] {sug.name} (Risk: {sug.risk_level})", "yellow"))
print(colorize(f" Type: {sug.exploit_type}", "cyan"))
print(
colorize(
f" Prerequisites: {', '.join(sug.prerequisites[:3])}",
"white",
)
)
return suggestions
# ==================== NEW METHODS ====================
async def run_autonomous_scan(
self,
target: str,
goal: str = "Find vulnerabilities and security issues",
scope: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""
Run autonomous scan mode.
Args:
target: Target domain/IP
goal: Scan goal/purpose
scope: Optional scope restrictions
"""
print(colorize("\n[+] Starting Autonomous Scan Mode", "bold"))
print(colorize(f" Target: {target}", "cyan"))
print(colorize(f" Goal: {goal}", "cyan"))
# Notify integrations
if self._integrations:
await self.orchestrator.notify_integrations("scan_started", {"target": target, "scan_type": "autonomous"})
# Run autonomous scan
result = await self.orchestrator.run_autonomous_scan(target=target, goal=goal, scope=scope)
if result.get("success"):
print(colorize("[+] Autonomous scan completed successfully", "green"))
print(
colorize(
f" Findings: {result.get('findings', {}).get('count', 0)}",
"cyan",
)
)
print(
colorize(
f" Duration: {result.get('execution', {}).get('duration_seconds', 0):.1f}s",
"cyan",
)
)
# Store findings
findings = result.get("findings", {}).get("items", [])
self.findings.extend(findings)
# Notify integrations
if self._integrations:
await self.orchestrator.notify_integrations(
"scan_completed",
{
"target": target,
"findings": findings,
"scan_type": "autonomous",
},
)
else:
print(
colorize(
f"[!] Autonomous scan failed: {result.get('error', 'Unknown error')}",
"red",
)
)
return result
async def run_exploit_validation(
self,
target: str,
exploit_code: str = None,
exploit_type: str = "web_rce",
safe_mode: bool = True,
) -> Dict[str, Any]:
"""
Validate an exploit against a target.
Args:
target: Target URL
exploit_code: Exploit code/payload
exploit_type: Type of exploit
safe_mode: Run in safe mode
"""
print(colorize("\n[+] Validating Exploit", "bold"))
print(colorize(f" Target: {target}", "cyan"))
print(colorize(f" Type: {exploit_type}", "cyan"))
print(colorize(f" Safe Mode: {safe_mode}", "cyan"))
exploit = {
"code": exploit_code or "# No exploit code provided",
"type": exploit_type,
}
result = await self.orchestrator.execute_exploit(exploit=exploit, target=target, safe_mode=safe_mode)
if result.get("success"):
print(colorize("[+] Exploit validation successful", "green"))
print(
colorize(
f" Exploitable: {result.get('exploitable', False)}",
"cyan",
)
)
if result.get("evidence"):
print(colorize(" Evidence collected: Yes", "cyan"))
else:
print(
colorize(
f"[!] Exploit validation failed: {result.get('error', 'Unknown error')}",
"red",
)
)
return result
async def run_benchmark(self, scenarios: list = None) -> Dict[str, Any]:
"""
Run benchmarks against test scenarios.
Args:
scenarios: Optional list of scenario names
"""
print(colorize("\n[+] Running Benchmarks", "bold"))
if not BENCHMARK_AVAILABLE:
print(colorize("[!] Benchmark module not available", "red"))
return {"error": "Benchmark module not available"}
runner = BenchmarkRunner()
results = await runner.run_all_benchmarks()
runner.save_report()
print(colorize(f"[+] Benchmark completed: {len(results)} scenarios", "green"))
return {
"success": True,
"results_count": len(results),
"report_saved": True,
}
async def run_ci_mode(
self,
target: str,
fail_on: str = "critical",
output_format: str = "json",
) -> int:
"""
Run in CI/CD mode with exit codes for pipeline integration.
Args:
target: Target to scan
fail_on: Severity level to fail on (critical, high, medium, low)
output_format: Output format (json, junit, sarif)
Returns:
Exit code (0 = success, 1 = findings detected)
"""
print(colorize("\n[+] Running in CI/CD Mode", "bold"))
print(colorize(f" Target: {target}", "cyan"))
print(colorize(f" Fail on: {fail_on}", "cyan"))
print(colorize(f" Format: {output_format}", "cyan"))
# Run scan
result = await self.run_autonomous_scan(target=target, goal="Security scan for CI/CD pipeline")
findings = result.get("findings", {}).get("items", [])
# Count findings by severity
severity_counts = {
"critical": 0,
"high": 0,
"medium": 0,
"low": 0,
"info": 0,
}
for finding in findings:
sev = finding.get("severity", "info").lower()
if sev in severity_counts:
severity_counts[sev] += 1
# Generate output
output_data = {
"target": target,
"timestamp": datetime.now().isoformat(),
"findings_count": len(findings),
"severity_counts": severity_counts,
"findings": findings,
}
if output_format == "json":
print(json.dumps(output_data, indent=2, default=str))
elif output_format == "junit":
self._output_junit(output_data)
elif output_format == "sarif":
self._output_sarif(output_data)
# Determine exit code
fail_levels = {"critical": 1, "high": 2, "medium": 3, "low": 4}
fail_level = fail_levels.get(fail_on.lower(), 1)
total_failures = sum(count for level, count in severity_counts.items() if fail_levels.get(level, 99) <= fail_level)
if total_failures > 0:
print(
colorize(
f"\n[!] Pipeline failed: {total_failures} {fail_on}+ findings detected",
"red",
)
)
return 1
else:
print(
colorize(
f"\n[+] Pipeline passed: No {fail_on}+ findings detected",
"green",
)
)
return 0
def _output_junit(self, data: Dict[str, Any]):
"""Output findings in JUnit XML format."""
# Safe for internal data generation (not parsing external XML)
import xml.etree.ElementTree as ET # nosec B405
testsuites = ET.Element("testsuites")
testsuite = ET.SubElement(
testsuites,
"testsuite",
name="Security Scan",
tests=str(data["findings_count"]),
failures=str(sum(1 for f in data["findings"] if f.get("severity") in ["critical", "high"])),
)
for finding in data["findings"]:
testcase = ET.SubElement(
testsuite,
"testcase",
name=finding.get("title", "Unknown"),
classname=f"security.{finding.get('type', 'unknown')}",
)
if finding.get("severity") in ["critical", "high"]:
failure = ET.SubElement(testcase, "failure")
failure.text = finding.get("description", "")
print(ET.tostring(testsuites, encoding="unicode"))
def _output_sarif(self, data: Dict[str, Any]):
"""Output findings in SARIF format."""
sarif = {
"$schema": "https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json",
"version": "2.1.0",
"runs": [
{
"tool": {
"driver": {
"name": "Zen AI Pentest",
"version": "2.0.0",
}
},
"results": [
{
"ruleId": f.get("type", "unknown"),
"message": {"text": f.get("description", "")},
"level": f.get("severity", "warning"),
"locations": [{"physicalLocation": {"artifactLocation": {"uri": data["target"]}}}],
}
for f in data["findings"]
],
}
],
}
print(json.dumps(sarif, indent=2))
async def generate_report(self, target: str, output_format: str = "markdown"):
"""Generate final report"""
print(colorize("\n[+] Generating report...", "bold"))
# Generate executive summary
scan_results = {
"target": target,
"date": datetime.now().isoformat(),
"vulnerability_summary": self.vuln_scanner.get_severity_summary(self.findings),
"top_findings": [{"name": f.name, "severity": f.severity} for f in self.findings[:10]],
}
exec_summary = await self.report_gen.generate_executive_summary(scan_results)
# Generate technical report
report = await self.report_gen.generate_technical_report(self.findings, target)
# Save reports
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
# Markdown report
md_filename = f"logs/report_{target.replace('/', '_')}_{timestamp}.md"
with open(md_filename, "w") as f:
f.write(report)
print(colorize(f"[+] Markdown report saved: {md_filename}", "green"))
# JSON export
json_data = {
"target": target,
"date": datetime.now().isoformat(),
"findings": self.findings,
"executive_summary": exec_summary,
}
json_file = self.report_gen.export_json(json_data)
print(colorize(f"[+] JSON export saved: {json_file}", "green"))
# CSV export
if self.findings:
csv_file = self.report_gen.export_csv(self.findings)
print(colorize(f"[+] CSV export saved: {csv_file}", "green"))
return report
async def interactive_mode(self):
"""Run interactive CLI mode"""
print(banner())
print(colorize("[*] Welcome to Zen AI Pentest Interactive Mode", "cyan"))
print(colorize("[*] Type 'help' for commands, 'quit' to exit\n", "cyan"))
while True:
try:
cmd = input(colorize("zen-ai> ", "bold")).strip()
if not cmd:
continue
parts = cmd.split()
command = parts[0].lower()
args = parts[1:]
if command == "quit" or command == "exit":
print(colorize("[*] Goodbye!", "green"))
break
elif command == "help":
self._print_help()
elif command == "target":
if not args:
print(colorize("[!] Usage: target <domain/ip>", "red"))
continue
target = args[0]
validation = validate_target(target)
if validation["valid"]:
print(
colorize(
f"[+] Target set: {target} ({validation['type']})",
"green",
)
)
await self.run_recon(target)
else:
print(colorize("[!] Invalid target format", "red"))
elif command == "analyze":
if not args:
print(colorize("[!] Usage: analyze <nmap_output_file>", "red"))
continue
try:
with open(args[0], "r") as f:
nmap_output = f.read()
# Extract target from filename or use placeholder
target = args[0].replace(".txt", "").replace(".xml", "")
await self.run_nmap_analysis(target, nmap_output)
except FileNotFoundError:
print(colorize(f"[!] File not found: {args[0]}", "red"))
elif command == "exploit":
if len(args) < 1:
print(
colorize(
"[!] Usage: exploit <vulnerability_name> [service]",
"red",
)
)
continue
await self.run_exploit_assist(args[0], args[1] if len(args) > 1 else "unknown")
elif command == "autonomous":
if not args:
print(colorize("[!] Usage: autonomous <target> [goal]", "red"))
continue
target = args[0]
goal = " ".join(args[1:]) if len(args) > 1 else "Find vulnerabilities"
await self.run_autonomous_scan(target, goal)
elif command == "report":
target = args[0] if args else "unknown_target"
await self.generate_report(target)
elif command == "status":
print(colorize(f"[*] Findings: {len(self.findings)}", "cyan"))
print(
colorize(
f"[*] Backends: {self.orchestrator.get_stats()}",
"cyan",
)
)
elif command == "backends":
for backend in self.orchestrator.backends:
print(
colorize(
f" - {backend.name} (Priority: {backend.priority})",
"white",
)
)
else:
print(colorize(f"[!] Unknown command: {command}", "red"))
except KeyboardInterrupt:
print(colorize("\n[*] Use 'quit' to exit", "yellow"))
except Exception as e:
print(colorize(f"[!] Error: {e}", "red"))
def _print_help(self):
"""Print help message"""
help_text = """
Available Commands:
target <domain/ip> - Set target and run reconnaissance
analyze <file> - Analyze nmap scan output
exploit <vuln> [svc] - Get exploit suggestions
autonomous <target> - Run autonomous scan mode
report [target] - Generate final report
status - Show current status
backends - List registered backends
help - Show this help
quit/exit - Exit the program
Examples:
target example.com
analyze nmap_scan.txt
exploit "SQL Injection" "mysql"
autonomous example.com "Find all vulnerabilities"
report example.com
"""
print(help_text)
async def main():
"""Main entry point"""
parser = argparse.ArgumentParser(
description="Zen AI Pentest - Multi-LLM Penetration Testing System",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
%(prog)s --interactive
%(prog)s --target example.com --recon
%(prog)s --analyze nmap_output.txt
%(prog)s --autonomous example.com --goal "Find vulnerabilities"
%(prog)s --target example.com --ci-mode --fail-on critical
""",
)
# Original arguments
parser.add_argument(
"--interactive",
"-i",
action="store_true",
help="Run in interactive mode",
)
parser.add_argument("--target", "-t", type=str, help="Target domain or IP")
parser.add_argument("--recon", "-r", action="store_true", help="Run reconnaissance")
parser.add_argument("--analyze", "-a", type=str, help="Analyze nmap output file")
parser.add_argument(
"--config",
"-c",
type=str,
default="config.json",
help="Configuration file path",
)
parser.add_argument(
"--output",
"-o",
type=str,
default="markdown",
choices=["markdown", "json", "html", "csv"],
help="Output format",
)
# New arguments
parser.add_argument("--autonomous", action="store_true", help="Run autonomous scan mode")
parser.add_argument(
"--goal",
type=str,
default="Find vulnerabilities and security issues",
help="Goal for autonomous scan",
)
parser.add_argument(
"--validate-exploits",
action="store_true",
help="Validate exploits (requires --target)",
)
parser.add_argument(
"--exploit-type",
type=str,
default="web_rce",
help="Type of exploit to validate",
)
parser.add_argument("--benchmark", action="store_true", help="Run benchmarks")
parser.add_argument(
"--ci-mode",
action="store_true",
help="Run in CI/CD mode with exit codes",
)
parser.add_argument(
"--fail-on",
type=str,
default="critical",
choices=["critical", "high", "medium", "low"],
help="Severity level to fail on in CI mode",
)
parser.add_argument(
"--ci-format",
type=str,
default="json",
choices=["json", "junit", "sarif"],
help="CI/CD output format",
)
args = parser.parse_args()
# Print banner
print(banner())
# Initialize app
app = ZenAIPentest(config_path=args.config)
await app.initialize_backends()
# Handle new modes
if args.ci_mode:
if not args.target:
print(colorize("[!] CI mode requires --target", "red"))
sys.exit(1)
exit_code = await app.run_ci_mode(
target=args.target,
fail_on=args.fail_on,
output_format=args.ci_format,
)
sys.exit(exit_code)
elif args.benchmark:
result = await app.run_benchmark()
sys.exit(0 if result.get("success") else 1)
elif args.autonomous:
if not args.target:
print(colorize("[!] Autonomous mode requires --target", "red"))
sys.exit(1)
result = await app.run_autonomous_scan(target=args.target, goal=args.goal)
if result.get("success"):
await app.generate_report(args.target, args.output)
sys.exit(0 if result.get("success") else 1)
elif args.validate_exploits:
if not args.target:
print(colorize("[!] Exploit validation requires --target", "red"))
sys.exit(1)
result = await app.run_exploit_validation(target=args.target, exploit_type=args.exploit_type)
sys.exit(0 if result.get("success") else 1)
elif args.interactive or len(sys.argv) == 1:
await app.interactive_mode()
elif args.target and args.recon:
await app.run_recon(args.target)
await app.generate_report(args.target, args.output)
elif args.analyze:
try:
with open(args.analyze, "r") as f:
nmap_output = f.read()
target = args.analyze.replace(".txt", "").replace(".xml", "")
await app.run_nmap_analysis(target, nmap_output)
await app.generate_report(target, args.output)
except FileNotFoundError:
print(colorize(f"[!] File not found: {args.analyze}", "red"))
else:
parser.print_help()
if __name__ == "__main__":
try:
# Windows/Python 3.13 compatibility
if sys.platform == "win32" and sys.version_info >= (3, 13):
# Use SelectorEventLoop on Windows for better compatibility
loop = asyncio.SelectorEventLoop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(main())
finally:
# Graceful shutdown
try:
loop.run_until_complete(asyncio.sleep(0.25))
except Exception: # nosec B110 - Graceful shutdown, exceptions safe to ignore
pass
loop.close()
else:
asyncio.run(main())
except KeyboardInterrupt:
print(colorize("\n[*] Interrupted by user", "yellow"))
sys.exit(0)
except Exception as e:
print(colorize(f"\n[!] Error: {e}", "red"))
sys.exit(1)

Xet Storage Details

Size:
29.1 kB
·
Xet hash:
00bde0b943f446e908cb53db3215d9a5349d722899e8659b13aac831baeb71b3

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