Files
AutoPentestX/main.py

395 lines
16 KiB
Python
Executable File

#!/usr/bin/env python3
"""
AutoPentestX - Main Application
Automated Penetration Testing Toolkit
Complete orchestration of all modules
"""
import sys
import os
import argparse
import time
from datetime import datetime
import json
# Add modules directory to path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
# Import all modules
from modules.database import Database
from modules.scanner import Scanner
from modules.vuln_scanner import VulnerabilityScanner
from modules.cve_lookup import CVELookup
from modules.risk_engine import RiskEngine
from modules.exploit_engine import ExploitEngine
from modules.pdf_report import PDFReportGenerator
class AutoPentestX:
"""Main AutoPentestX Application"""
def __init__(self, target, tester_name="AutoPentestX Team", safe_mode=True, skip_web=False, skip_exploit=False):
"""Initialize AutoPentestX"""
self.target = target
self.tester_name = tester_name
self.safe_mode = safe_mode
self.skip_web = skip_web
self.skip_exploit = skip_exploit
self.scan_id = None
self.start_time = None
self.end_time = None
# Results storage
self.scan_results = None
self.vuln_results = None
self.cve_results = None
self.risk_results = None
self.exploit_results = None
# Initialize database
self.db = Database()
print("\n" + "="*70)
print(" "*20 + "AutoPentestX v1.0")
print(" "*10 + "Automated Penetration Testing & Vulnerability Assessment")
print("="*70)
print(f"\n[*] Target: {self.target}")
print(f"[*] Tester: {self.tester_name}")
print(f"[*] Safe Mode: {'ENABLED' if self.safe_mode else 'DISABLED'}")
print(f"[*] Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("\n" + "="*70 + "\n")
def display_banner(self):
"""Display application banner"""
RED = '\033[91m'
GREEN = '\033[92m'
RESET = '\033[0m'
banner = f"""
{RED}╔═══════════════════════════════════════════════════════════════════╗
║ ║
║ █████╗ ██╗ ██╗████████╗ ██████╗ ██████╗ ███████╗███╗ ██╗ ║
║ ██╔══██╗██║ ██║╚══██╔══╝██╔═══██╗██╔══██╗██╔════╝████╗ ██║ ║
║ ███████║██║ ██║ ██║ ██║ ██║██████╔╝█████╗ ██╔██╗ ██║ ║
║ ██╔══██║██║ ██║ ██║ ██║ ██║██╔═══╝ ██╔══╝ ██║╚██╗██║ ║
║ ██║ ██║╚██████╔╝ ██║ ╚██████╔╝██║ ███████╗██║ ╚████║ ║
║ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═════╝ ╚═╝ ╚══════╝╚═╝ ╚═══╝ ║
║ ║{RESET}
{GREEN}║ T E S T X - Penetration Testing Toolkit ║
║ Author: Gowtham Darkseid ║{RESET}
{RED}║ ║
║ ⚠️ WARNING: For AUTHORIZED testing and EDUCATIONAL use ONLY ║
║ Unauthorized access to computer systems is ILLEGAL! ║
║ ║
╚═══════════════════════════════════════════════════════════════════╝{RESET}
"""
print(banner)
def run_full_assessment(self):
"""Execute complete penetration testing workflow"""
self.start_time = time.time()
try:
# Display banner
self.display_banner()
# Step 1: Initialize scan in database
print("\n[STEP 1] Initializing scan...")
self.scan_id = self.db.insert_scan(self.target)
if not self.scan_id:
print("[✗] Failed to initialize scan in database")
return False
print(f"[✓] Scan ID: {self.scan_id}")
# Step 2: Network scanning
print("\n[STEP 2] Network Scanning...")
print("-" * 70)
scanner = Scanner(self.target)
self.scan_results = scanner.run_full_scan()
if not self.scan_results:
print("[✗] Network scan failed")
return False
# Update database with OS detection
self.db.update_scan(self.scan_id,
os_detection=self.scan_results.get('os_detection', 'Unknown'))
# Store ports in database
for port in self.scan_results.get('ports', []):
self.db.insert_port(self.scan_id, port)
# Step 3: Vulnerability Scanning
if not self.skip_web:
print("\n[STEP 3] Vulnerability Scanning...")
print("-" * 70)
vuln_scanner = VulnerabilityScanner(
self.target,
self.scan_results.get('ports', [])
)
self.vuln_results = vuln_scanner.run_full_scan()
# Store vulnerabilities in database
for vuln in self.vuln_results.get('vulnerabilities', []):
self.db.insert_vulnerability(self.scan_id, vuln)
# Store web vulnerabilities
for web_vuln in self.vuln_results.get('web_vulnerabilities', []):
self.db.insert_web_vulnerability(self.scan_id, web_vuln)
else:
print("\n[STEP 3] Vulnerability Scanning... SKIPPED")
self.vuln_results = {
'vulnerabilities': [],
'web_vulnerabilities': [],
'sql_vulnerabilities': []
}
# Step 4: CVE Lookup
print("\n[STEP 4] CVE Database Lookup...")
print("-" * 70)
cve_lookup = CVELookup()
services = self.scan_results.get('services', [])
self.cve_results = cve_lookup.lookup_services(services)
# Store CVEs as vulnerabilities
for cve in self.cve_results:
vuln_data = {
'port': cve.get('port'),
'service': cve.get('service'),
'name': cve.get('cve_id'),
'description': cve.get('description'),
'cve_id': cve.get('cve_id'),
'cvss_score': cve.get('cvss_score'),
'risk_level': cve.get('risk_level'),
'exploitable': cve.get('exploitable', False)
}
self.db.insert_vulnerability(self.scan_id, vuln_data)
# Step 5: Risk Assessment
print("\n[STEP 5] Risk Assessment...")
print("-" * 70)
risk_engine = RiskEngine()
self.risk_results = risk_engine.calculate_overall_risk(
self.scan_results,
self.vuln_results.get('vulnerabilities', []),
self.cve_results,
self.vuln_results.get('web_vulnerabilities', []),
self.vuln_results.get('sql_vulnerabilities', [])
)
# Update scan with risk information
self.db.update_scan(
self.scan_id,
total_ports=len(self.scan_results.get('ports', [])),
open_ports=len(self.scan_results.get('ports', [])),
vulnerabilities_found=self.risk_results.get('total_vulnerabilities', 0),
risk_score=self.risk_results.get('overall_risk_level', 'UNKNOWN'),
status='completed'
)
# Step 6: Exploitation (Safe Mode)
if not self.skip_exploit:
print("\n[STEP 6] Exploitation Assessment (Safe Mode)...")
print("-" * 70)
exploit_engine = ExploitEngine(safe_mode=self.safe_mode)
# Match exploits
matched_exploits = exploit_engine.match_exploits(
self.vuln_results.get('vulnerabilities', []),
self.cve_results
)
# Simulate exploitation
if matched_exploits:
self.exploit_results = exploit_engine.simulate_exploitation(
matched_exploits,
self.target
)
# Store exploit attempts
for exploit in self.exploit_results:
exploit_data = {
'name': exploit.get('exploit_name'),
'status': exploit.get('status'),
'result': json.dumps(exploit)
}
self.db.insert_exploit(self.scan_id, None, exploit_data)
else:
print("[*] No exploits matched")
self.exploit_results = []
else:
print("\n[STEP 6] Exploitation Assessment... SKIPPED")
self.exploit_results = []
# Step 7: Generate PDF Report
print("\n[STEP 7] Generating PDF Report...")
print("-" * 70)
pdf_generator = PDFReportGenerator(self.target, self.scan_id)
report_file = pdf_generator.generate_report(
self.scan_results,
self.vuln_results.get('vulnerabilities', []),
self.cve_results,
self.vuln_results.get('web_vulnerabilities', []),
self.vuln_results.get('sql_vulnerabilities', []),
self.risk_results,
self.exploit_results,
self.tester_name
)
if not report_file:
print("[!] PDF report generation failed, but scan completed successfully")
# Calculate total time
self.end_time = time.time()
duration = self.end_time - self.start_time
# Update scan duration
self.db.update_scan(self.scan_id, scan_duration=duration)
# Display final summary
self.display_final_summary(duration, report_file)
return True
except KeyboardInterrupt:
print("\n\n[!] Scan interrupted by user")
if self.scan_id:
self.db.update_scan(self.scan_id, status='interrupted')
return False
except Exception as e:
print(f"\n[✗] Critical error during assessment: {e}")
import traceback
traceback.print_exc()
if self.scan_id:
self.db.update_scan(self.scan_id, status='failed')
return False
finally:
# Close database connection
self.db.close()
def display_final_summary(self, duration, report_file):
"""Display final assessment summary"""
print("\n\n" + "="*70)
print(" "*20 + "ASSESSMENT COMPLETE")
print("="*70)
print(f"\n[✓] Target: {self.target}")
print(f"[✓] Scan ID: {self.scan_id}")
print(f"[✓] Duration: {duration:.2f} seconds ({duration/60:.2f} minutes)")
print(f"[✓] Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print("\n" + "-"*70)
print("RESULTS SUMMARY")
print("-"*70)
if self.scan_results:
print(f"Open Ports: {len(self.scan_results.get('ports', []))}")
print(f"Services Detected: {len(self.scan_results.get('services', []))}")
if self.risk_results:
print(f"Total Vulnerabilities: {self.risk_results.get('total_vulnerabilities', 0)}")
print(f"Web Vulnerabilities: {self.risk_results.get('web_vulnerabilities', 0)}")
print(f"SQL Injection Points: {self.risk_results.get('sql_vulnerabilities', 0)}")
print(f"CVEs Identified: {len(self.cve_results) if self.cve_results else 0}")
print(f"Overall Risk Level: {self.risk_results.get('overall_risk_level', 'UNKNOWN')}")
print(f"Risk Score: {self.risk_results.get('total_risk_score', 0):.2f}")
if self.exploit_results:
print(f"Exploits Matched: {len(self.exploit_results)}")
print("\n" + "-"*70)
print("OUTPUT FILES")
print("-"*70)
if report_file and os.path.exists(report_file):
print(f"[✓] PDF Report: {report_file}")
print(f"[✓] Database: database/autopentestx.db")
print(f"[✓] Logs: logs/")
print("\n" + "="*70)
print("\n[i] Thank you for using AutoPentestX!")
print("[i] Remember: Use this tool responsibly and ethically.\n")
def main():
"""Main entry point"""
parser = argparse.ArgumentParser(
description='AutoPentestX - Automated Penetration Testing Toolkit',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python main.py -t 192.168.1.100
python main.py -t example.com -n "John Doe"
python main.py -t 10.0.0.1 --skip-web --skip-exploit
WARNING: This tool is for AUTHORIZED testing and EDUCATIONAL purposes ONLY.
Unauthorized access to computer systems is ILLEGAL!
"""
)
parser.add_argument('-t', '--target',
required=True,
help='Target IP address or domain name')
parser.add_argument('-n', '--tester-name',
default='AutoPentestX Team',
help='Name of the penetration tester (default: AutoPentestX Team)')
parser.add_argument('--no-safe-mode',
action='store_true',
help='Disable safe mode (NOT RECOMMENDED)')
parser.add_argument('--skip-web',
action='store_true',
help='Skip web vulnerability scanning (Nikto/SQLMap)')
parser.add_argument('--skip-exploit',
action='store_true',
help='Skip exploitation assessment')
parser.add_argument('--version',
action='version',
version='AutoPentestX v1.0')
args = parser.parse_args()
# Confirmation prompt
print("\n" + "="*70)
print("⚠️ LEGAL WARNING ⚠️")
print("="*70)
print("\nYou are about to run an automated penetration testing tool.")
print("This tool should ONLY be used on systems you own or have")
print("explicit written authorization to test.")
print("\nUnauthorized access to computer systems is ILLEGAL and may")
print("result in criminal prosecution.")
print("\nBy continuing, you confirm that you have proper authorization")
print("to perform security testing on the target system.")
print("="*70)
confirmation = input("\nDo you have authorization to test this target? (yes/no): ")
if confirmation.lower() not in ['yes', 'y']:
print("\n[!] Assessment cancelled. Authorization not confirmed.")
sys.exit(0)
# Initialize and run assessment
safe_mode = not args.no_safe_mode
autopentestx = AutoPentestX(
target=args.target,
tester_name=args.tester_name,
safe_mode=safe_mode,
skip_web=args.skip_web,
skip_exploit=args.skip_exploit
)
success = autopentestx.run_full_assessment()
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()