APEX/apex.py

471 lines
15 KiB
Python

#!/usr/bin/env python3
"""
APEX - Advanced Penetration and Exploitation eXecution Framework
The Most Powerful Ethical Hacking Tool
Features:
- Multi-stage reconnaissance (passive & active)
- Advanced vulnerability scanning
- Automated exploitation
- Web application security testing
- Network penetration testing
- Wireless security assessment
- Post-exploitation modules
- Advanced reporting and analytics
- Plugin architecture
- Automation and scripting
"""
import sys
import os
import argparse
import json
import asyncio
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Any
import importlib.util
# ANSI Color codes
class Colors:
HEADER = '\033[95m'
BLUE = '\033[94m'
CYAN = '\033[96m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
END = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
class ApexFramework:
"""Main APEX Framework Class"""
VERSION = "1.0.0"
BANNER = f"""
{Colors.CYAN}{Colors.BOLD}
╔═╗╔═╗╔═╗═╗ ╦
╠═╣╠═╝║╣ ╔╩╦╝
╩ ╩╩ ╚═╝╩ ╚═
{Colors.END}{Colors.GREEN}
Advanced Penetration and
Exploitation eXecution Framework
Version: {VERSION}
{Colors.YELLOW}The Ultimate Ethical Hacking Tool{Colors.END}
{Colors.CYAN}═══════════════════════════════════════{Colors.END}
"""
def __init__(self, config_file=None):
"""Initialize APEX Framework"""
self.home_dir = Path.home() / ".apex"
self.home_dir.mkdir(exist_ok=True)
self.config_file = config_file or self.home_dir / "apex.json"
self.plugins_dir = self.home_dir / "plugins"
self.plugins_dir.mkdir(exist_ok=True)
self.results_dir = self.home_dir / "results"
self.results_dir.mkdir(exist_ok=True)
self.wordlists_dir = self.home_dir / "wordlists"
self.wordlists_dir.mkdir(exist_ok=True)
self.config = self.load_config()
self.modules = {}
self.session_data = {}
def load_config(self) -> Dict:
"""Load configuration"""
default_config = {
"version": self.VERSION,
"global": {
"threads": 50,
"timeout": 10,
"user_agent": "APEX/1.0",
"verify_ssl": False,
"proxy": None,
"output_format": "json"
},
"reconnaissance": {
"passive_enum": True,
"active_enum": True,
"deep_scan": False
},
"scanning": {
"service_detection": True,
"os_detection": False,
"vulnerability_scan": True
},
"exploitation": {
"auto_exploit": False,
"safe_mode": True,
"payload_encoding": True
},
"web_testing": {
"sql_injection": True,
"xss_testing": True,
"csrf_testing": True,
"file_inclusion": True,
"command_injection": True,
"authentication_bypass": True
},
"wireless": {
"capture_handshakes": True,
"wps_testing": True,
"evil_twin": False
},
"reporting": {
"auto_report": True,
"report_format": ["html", "json", "pdf"],
"include_screenshots": True
}
}
if self.config_file.exists():
try:
with open(self.config_file, 'r') as f:
loaded = json.load(f)
# Merge with defaults
return {**default_config, **loaded}
except:
pass
# Save default config
with open(self.config_file, 'w') as f:
json.dump(default_config, f, indent=4)
return default_config
def save_config(self):
"""Save configuration"""
with open(self.config_file, 'w') as f:
json.dump(self.config, f, indent=4)
def register_module(self, name: str, module_class):
"""Register a module"""
self.modules[name] = module_class
def print_banner(self):
"""Print APEX banner"""
print(self.BANNER)
def print_info(self, message):
"""Print info message"""
print(f"{Colors.BLUE}[*]{Colors.END} {message}")
def print_success(self, message):
"""Print success message"""
print(f"{Colors.GREEN}[+]{Colors.END} {message}")
def print_warning(self, message):
"""Print warning message"""
print(f"{Colors.YELLOW}[!]{Colors.END} {message}")
def print_error(self, message):
"""Print error message"""
print(f"{Colors.RED}[-]{Colors.END} {message}")
def print_header(self, message):
"""Print section header"""
print(f"\n{Colors.CYAN}{Colors.BOLD}{'' * 50}{Colors.END}")
print(f"{Colors.CYAN}{Colors.BOLD} {message}{Colors.END}")
print(f"{Colors.CYAN}{Colors.BOLD}{'' * 50}{Colors.END}\n")
def load_plugins(self):
"""Load plugins from plugins directory"""
self.print_info("Loading plugins...")
count = 0
for plugin_file in self.plugins_dir.glob("*.py"):
try:
spec = importlib.util.spec_from_file_location(
plugin_file.stem, plugin_file
)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
if hasattr(module, 'register'):
module.register(self)
count += 1
self.print_success(f"Loaded plugin: {plugin_file.stem}")
except Exception as e:
self.print_error(f"Failed to load {plugin_file.stem}: {e}")
self.print_success(f"Loaded {count} plugins")
def save_results(self, module_name: str, results: Dict):
"""Save results to file"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = self.results_dir / f"{module_name}_{timestamp}.json"
with open(filename, 'w') as f:
json.dump(results, f, indent=4)
self.print_success(f"Results saved to: {filename}")
def interactive_mode(self):
"""Interactive console mode"""
self.print_banner()
self.print_info("Entering interactive mode (type 'help' for commands)")
while True:
try:
cmd = input(f"\n{Colors.CYAN}apex>{Colors.END} ").strip()
if not cmd:
continue
if cmd.lower() in ['exit', 'quit', 'q']:
self.print_info("Exiting APEX...")
break
elif cmd.lower() == 'help':
self.show_help()
elif cmd.lower() == 'modules':
self.list_modules()
elif cmd.lower() == 'info':
self.show_info()
elif cmd.startswith('use '):
module_name = cmd[4:].strip()
self.use_module(module_name)
elif cmd.startswith('set '):
parts = cmd[4:].split(None, 1)
if len(parts) == 2:
self.set_option(parts[0], parts[1])
elif cmd.lower() == 'options':
self.show_options()
elif cmd.lower() in ['run', 'execute']:
self.execute_current_module()
elif cmd.lower() == 'back':
self.session_data.pop('current_module', None)
self.print_info("Returned to main menu")
else:
self.print_error(f"Unknown command: {cmd}")
except KeyboardInterrupt:
print()
continue
except EOFError:
print()
break
def show_help(self):
"""Show help menu"""
help_text = f"""
{Colors.BOLD}Available Commands:{Colors.END}
{Colors.CYAN}Core Commands:{Colors.END}
help - Show this help menu
modules - List all available modules
info - Show framework information
exit/quit - Exit APEX
{Colors.CYAN}Module Commands:{Colors.END}
use <module> - Select a module
options - Show module options
set <option> <val>- Set an option value
run/execute - Execute current module
back - Return to main menu
{Colors.CYAN}Example Workflow:{Colors.END}
apex> modules
apex> use recon/subdomain_enum
apex> set TARGET example.com
apex> run
"""
print(help_text)
def list_modules(self):
"""List all available modules"""
self.print_header("Available Modules")
categories = {
"Reconnaissance": [],
"Scanning": [],
"Exploitation": [],
"Web Testing": [],
"Wireless": [],
"Post-Exploitation": [],
"Auxiliary": []
}
# Add built-in modules
modules_list = [
("Reconnaissance", "recon/subdomain_enum", "Subdomain enumeration"),
("Reconnaissance", "recon/dns_enum", "DNS enumeration"),
("Reconnaissance", "recon/port_scan", "Port scanning"),
("Reconnaissance", "recon/network_mapper", "Network mapping"),
("Reconnaissance", "recon/osint", "OSINT gathering"),
("Scanning", "scan/vuln_scan", "Vulnerability scanning"),
("Scanning", "scan/service_detect", "Service detection"),
("Scanning", "scan/ssl_scan", "SSL/TLS analysis"),
("Web Testing", "web/sql_injection", "SQL injection testing"),
("Web Testing", "web/xss_scanner", "XSS vulnerability scanner"),
("Web Testing", "web/lfi_scanner", "LFI/RFI scanner"),
("Web Testing", "web/directory_brute", "Directory bruteforce"),
("Web Testing", "web/api_fuzzer", "API endpoint fuzzing"),
("Exploitation", "exploit/auto_exploit", "Automated exploitation"),
("Exploitation", "exploit/payload_gen", "Payload generator"),
("Exploitation", "exploit/reverse_shell", "Reverse shell generator"),
("Wireless", "wireless/wpa_crack", "WPA/WPA2 cracking"),
("Wireless", "wireless/deauth", "Deauthentication attack"),
("Post-Exploitation", "post/privilege_esc", "Privilege escalation"),
("Post-Exploitation", "post/persistence", "Persistence mechanisms"),
("Auxiliary", "aux/report_gen", "Report generator"),
]
for category, module, description in modules_list:
print(f" {Colors.GREEN}{module:<30}{Colors.END} - {description}")
def show_info(self):
"""Show framework information"""
self.print_header("APEX Framework Information")
info_text = f"""
{Colors.BOLD}Version:{Colors.END} {self.VERSION}
{Colors.BOLD}Home Directory:{Colors.END} {self.home_dir}
{Colors.BOLD}Config File:{Colors.END} {self.config_file}
{Colors.BOLD}Plugins Directory:{Colors.END} {self.plugins_dir}
{Colors.BOLD}Results Directory:{Colors.END} {self.results_dir}
{Colors.BOLD}Loaded Modules:{Colors.END} {len(self.modules)}
{Colors.BOLD}Global Threads:{Colors.END} {self.config['global']['threads']}
{Colors.BOLD}Global Timeout:{Colors.END} {self.config['global']['timeout']}s
"""
print(info_text)
def use_module(self, module_name: str):
"""Use a specific module"""
self.session_data['current_module'] = module_name
self.print_success(f"Module selected: {module_name}")
def set_option(self, option: str, value: str):
"""Set an option value"""
if 'module_options' not in self.session_data:
self.session_data['module_options'] = {}
self.session_data['module_options'][option.upper()] = value
self.print_success(f"Set {option.upper()} => {value}")
def show_options(self):
"""Show current module options"""
if 'current_module' not in self.session_data:
self.print_error("No module selected. Use 'use <module>' first")
return
module = self.session_data['current_module']
self.print_header(f"Options for {module}")
# Display current options
if 'module_options' in self.session_data:
for key, value in self.session_data['module_options'].items():
print(f" {Colors.CYAN}{key:<20}{Colors.END} => {value}")
else:
print(" No options set")
def execute_current_module(self):
"""Execute the current module"""
if 'current_module' not in self.session_data:
self.print_error("No module selected. Use 'use <module>' first")
return
module = self.session_data['current_module']
options = self.session_data.get('module_options', {})
self.print_info(f"Executing {module}...")
self.print_warning("Module execution not yet implemented (framework foundation)")
def main():
"""Main entry point"""
parser = argparse.ArgumentParser(
description="APEX - The Ultimate Ethical Hacking Framework",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
apex.py # Interactive mode
apex.py --module recon/subdomain_enum --target example.com
apex.py --config custom.json
apex.py --list-modules
For more information: https://github.com/apex-framework
"""
)
parser.add_argument(
'--module', '-m',
help='Module to run'
)
parser.add_argument(
'--target', '-t',
help='Target (IP, domain, URL, etc.)'
)
parser.add_argument(
'--config', '-c',
help='Configuration file'
)
parser.add_argument(
'--list-modules', '-l',
action='store_true',
help='List all available modules'
)
parser.add_argument(
'--interactive', '-i',
action='store_true',
help='Start interactive mode'
)
parser.add_argument(
'--version', '-v',
action='version',
version=f'APEX Framework v{ApexFramework.VERSION}'
)
args = parser.parse_args()
# Initialize framework
apex = ApexFramework(config_file=args.config)
# Load plugins
apex.load_plugins()
if args.list_modules:
apex.print_banner()
apex.list_modules()
elif args.interactive or (not args.module and not args.target):
apex.interactive_mode()
else:
apex.print_banner()
if args.module:
apex.use_module(args.module)
if args.target:
apex.set_option('TARGET', args.target)
apex.execute_current_module()
else:
apex.print_error("No module specified")
apex.interactive_mode()
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print(f"\n{Colors.YELLOW}[!] Interrupted by user{Colors.END}")
sys.exit(0)
except Exception as e:
print(f"{Colors.RED}[!] Fatal error: {e}{Colors.END}")
sys.exit(1)