#!/usr/bin/env python3 """ OPNsense Diagnostic Tool Connects to OPNsense/FreeBSD firewall via SSH, collects diagnostic data, and analyzes for crash patterns (specifically ~4 day crash cycles). Usage: python diagnose.py # Full diagnostic (collect + analyze) python diagnose.py --collect # Only collect data python diagnose.py --analyze # Only analyze existing data python diagnose.py --test # Test SSH connection only """ import argparse import sys import json from pathlib import Path from datetime import datetime from ssh_client import SSHConnection, test_connection from collector import DataCollector, collect_data from analyzer import CrashAnalyzer, analyze_data from config import OUTPUT_DIR def print_banner(): print(""" ╔═══════════════════════════════════════════════════════════════╗ ║ OPNsense Crash Diagnostic Tool v1.0 ║ ║ Analyzing ~4 day crash pattern ║ ╚═══════════════════════════════════════════════════════════════╝ """) def run_full_diagnostic(): """Run full diagnostic: collect data and analyze.""" print_banner() print("[*] Starting full diagnostic...") print(f"[*] Timestamp: {datetime.now().isoformat()}") # Connect and collect conn = SSHConnection() if not conn.connect(): print("\n[!] Failed to connect. Check config.py settings:") print(" - SSH_HOST: IP/hostname of OPNsense") print(" - SSH_USERNAME: Usually 'root'") print(" - SSH_PASSWORD or SSH_KEY_PATH: Authentication") return False try: # Collect data collector = DataCollector(conn) collected = collector.collect_all() data_dir = collector.output_dir finally: conn.close() # Analyze collected data print("\n[*] Analyzing collected data...") analyzer = CrashAnalyzer(str(data_dir)) results = analyzer.analyze_all() # Save full results results_file = data_dir / "full_analysis.json" with open(results_file, 'w') as f: json.dump(results, f, indent=2, default=str) print(f"\n[+] Full results saved to: {results_file}") # Generate report report_file = data_dir / "DIAGNOSTIC_REPORT.txt" generate_report(results, report_file) print(f"[+] Human-readable report: {report_file}") return True def run_collect_only(): """Only collect data, don't analyze.""" print_banner() print("[*] Running data collection only...") conn = SSHConnection() if not conn.connect(): print("[!] Failed to connect") return False try: collector = DataCollector(conn) collector.collect_all() print(f"\n[+] Data collected to: {collector.output_dir}") print("[*] Run 'python diagnose.py --analyze' to analyze") finally: conn.close() return True def run_analyze_only(data_dir: str = None): """Analyze existing collected data.""" print_banner() if not data_dir: # Find most recent collection output_path = Path(OUTPUT_DIR) if not output_path.exists(): print("[!] No collected data found. Run with --collect first.") return False dirs = sorted([d for d in output_path.iterdir() if d.is_dir()], reverse=True) if not dirs: print("[!] No collected data found. Run with --collect first.") return False data_dir = str(dirs[0]) print(f"[*] Analyzing most recent collection: {data_dir}") results = analyze_data(data_dir) # Save results results_file = Path(data_dir) / "analysis_results.json" with open(results_file, 'w') as f: json.dump(results, f, indent=2, default=str) # Generate report report_file = Path(data_dir) / "DIAGNOSTIC_REPORT.txt" generate_report(results, report_file) print(f"\n[+] Report saved to: {report_file}") return True def generate_report(results: dict, output_file: Path): """Generate human-readable diagnostic report.""" with open(output_file, 'w') as f: f.write("=" * 70 + "\n") f.write("OPNSENSE CRASH DIAGNOSTIC REPORT\n") f.write(f"Generated: {datetime.now().isoformat()}\n") f.write("=" * 70 + "\n\n") summary = results.get("summary", {}) # Critical Issues f.write("CRITICAL ISSUES\n") f.write("-" * 70 + "\n") critical = summary.get("critical_issues", []) if critical: for issue in critical: f.write(f" [!!!] {issue}\n") else: f.write(" None found\n") f.write("\n") # Warnings f.write("WARNINGS\n") f.write("-" * 70 + "\n") warnings = summary.get("warnings", []) if warnings: for warn in warnings: f.write(f" [!] {warn}\n") else: f.write(" None found\n") f.write("\n") # Likely Cause f.write("LIKELY CAUSE(S)\n") f.write("-" * 70 + "\n") causes = summary.get("likely_cause", ["unknown"]) for cause in causes: f.write(f" - {cause}\n") f.write("\n") # Recommendations f.write("RECOMMENDATIONS\n") f.write("-" * 70 + "\n") for rec in summary.get("recommendations", []): f.write(f"{rec}\n\n") # Memory Analysis if "memory" in results: f.write("\nMEMORY ANALYSIS\n") f.write("-" * 70 + "\n") mem = results["memory"] f.write(f" Status: {mem.get('status', 'unknown')}\n") for detail in mem.get("details", []): f.write(f" - {detail}\n") # Reboot History if "reboots" in results: f.write("\nREBOOT HISTORY\n") f.write("-" * 70 + "\n") reboots = results["reboots"] if reboots.get("average_uptime"): f.write(f" Average uptime: {reboots['average_uptime']}\n") if reboots.get("pattern"): f.write(f" Pattern detected: {reboots['pattern']}\n") for rb in reboots.get("reboots", [])[:10]: f.write(f" - {rb.get('line', rb.get('time', 'unknown'))}\n") # Gateway Status if "gateways" in results: f.write("\nGATEWAY STATUS\n") f.write("-" * 70 + "\n") gw = results["gateways"] f.write(f" Status: {gw.get('status', 'unknown')}\n") for issue in gw.get("issues", []): f.write(f" - {issue}\n") # Log Analysis if "logs" in results: f.write("\nLOG ANALYSIS\n") f.write("-" * 70 + "\n") logs = results["logs"] for issue in logs.get("issues_found", []): f.write(f" - {issue}\n") f.write("\n" + "=" * 70 + "\n") f.write("END OF REPORT\n") f.write("=" * 70 + "\n") def main(): parser = argparse.ArgumentParser( description="OPNsense Crash Diagnostic Tool", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=""" Examples: python diagnose.py # Full diagnostic python diagnose.py --test # Test connection only python diagnose.py --collect # Collect data only python diagnose.py --analyze # Analyze existing data python diagnose.py --analyze collected_data/20231207_120000 """ ) parser.add_argument('--test', action='store_true', help='Test SSH connection only') parser.add_argument('--collect', '--collect-only', action='store_true', help='Only collect data, do not analyze') parser.add_argument('--analyze', '--analyze-only', nargs='?', const=True, help='Only analyze existing data (optionally specify data directory)') args = parser.parse_args() try: if args.test: success = test_connection() elif args.collect: success = run_collect_only() elif args.analyze: data_dir = args.analyze if isinstance(args.analyze, str) else None success = run_analyze_only(data_dir) else: success = run_full_diagnostic() sys.exit(0 if success else 1) except KeyboardInterrupt: print("\n[*] Interrupted by user") sys.exit(130) except Exception as e: print(f"\n[!] Error: {e}") import traceback traceback.print_exc() sys.exit(1) if __name__ == "__main__": main()