""" Diagnostic Analyzer for OPNsense/FreeBSD Crash Issues Specifically looking for patterns that cause ~4 day crashes """ import re import os from datetime import datetime, timedelta from pathlib import Path from typing import Dict, List, Any, Tuple, Optional from collections import defaultdict from dateutil import parser as date_parser from config import CRASH_PATTERNS, MEMORY_WARNING_PERCENT, MEMORY_CRITICAL_PERCENT, SWAP_WARNING_PERCENT class CrashAnalyzer: """Analyzes collected data to diagnose crash causes.""" def __init__(self, data_dir: str): self.data_dir = Path(data_dir) self.findings: List[Dict[str, Any]] = [] self.warnings: List[str] = [] self.critical: List[str] = [] def analyze_all(self) -> Dict[str, Any]: """Run all analyses.""" print("\n" + "=" * 60) print("ANALYZING DIAGNOSTIC DATA") print("=" * 60) results = { "memory": self.analyze_memory(), "crashes": self.analyze_crash_dumps(), "logs": self.analyze_logs(), "reboots": self.analyze_reboot_history(), "services": self.analyze_services(), "gateways": self.analyze_gateways(), "states": self.analyze_pf_states(), "cron": self.analyze_cron_jobs(), "summary": None } results["summary"] = self.generate_summary() return results def analyze_memory(self) -> Dict[str, Any]: """Analyze memory usage patterns.""" print("\n[*] Analyzing memory usage...") result = {"status": "unknown", "details": []} # Check vmstat output vmstat_file = self.data_dir / "memory" / "vmstat.txt" if vmstat_file.exists(): content = vmstat_file.read_text() # Parse vmstat - look for high swap usage or low free memory lines = content.strip().split('\n') for line in lines[-3:]: # Last 3 readings parts = line.split() if len(parts) >= 7 and parts[0].isdigit(): # Columns: r b w avm fre si so try: swap_in = int(parts[5]) if parts[5].isdigit() else 0 swap_out = int(parts[6]) if parts[6].isdigit() else 0 if swap_in > 0 or swap_out > 0: self.warnings.append(f"Active swapping detected: si={swap_in}, so={swap_out}") result["details"].append("System is actively swapping - memory pressure") except (ValueError, IndexError): pass # Check swap info swap_file = self.data_dir / "memory" / "swap.txt" if swap_file.exists(): content = swap_file.read_text() for line in content.split('\n'): if '%' in line and 'Device' not in line: # Try to parse swap usage percentage match = re.search(r'(\d+)%', line) if match: swap_pct = int(match.group(1)) if swap_pct > SWAP_WARNING_PERCENT: self.warnings.append(f"High swap usage: {swap_pct}%") result["details"].append(f"Swap usage at {swap_pct}%") # Check top output for memory hogs top_file = self.data_dir / "memory" / "top_mem.txt" if top_file.exists(): content = top_file.read_text() # Look for memory percentage in header mem_match = re.search(r'Mem:.*?(\d+)%', content) if mem_match: mem_pct = int(mem_match.group(1)) result["memory_percent"] = mem_pct if mem_pct > MEMORY_CRITICAL_PERCENT: self.critical.append(f"CRITICAL: Memory usage at {mem_pct}%") elif mem_pct > MEMORY_WARNING_PERCENT: self.warnings.append(f"High memory usage: {mem_pct}%") # Check for ZFS ARC issues (common on FreeBSD) arc_file = self.data_dir / "memory" / "arc_stats.txt" if arc_file.exists(): content = arc_file.read_text() if "No ZFS ARC" not in content: result["details"].append("ZFS ARC in use - check if it's consuming too much RAM") arc_match = re.search(r'arcstats\.size:\s*(\d+)', content) arc_max_match = re.search(r'arc_max:\s*(\d+)', content) if arc_match and arc_max_match: arc_size = int(arc_match.group(1)) arc_max = int(arc_max_match.group(1)) arc_gb = arc_size / (1024**3) result["details"].append(f"ZFS ARC size: {arc_gb:.2f} GB") # Check mbuf usage (network buffers) mbuf_file = self.data_dir / "memory" / "mbuf.txt" if mbuf_file.exists(): content = mbuf_file.read_text() if "denied" in content.lower() or "fail" in content.lower(): self.critical.append("MBUF allocation failures detected - network memory exhaustion") result["details"].append("Network buffer exhaustion detected") if not result["details"]: result["status"] = "ok" elif any("CRITICAL" in w for w in self.critical): result["status"] = "critical" else: result["status"] = "warning" return result def analyze_crash_dumps(self) -> Dict[str, Any]: """Analyze crash dump information.""" print("\n[*] Analyzing crash dumps...") result = {"found": False, "details": []} crash_dir = self.data_dir / "crash" if not crash_dir.exists(): return result # Check crash listing listing_file = crash_dir / "crash_listing.txt" if listing_file.exists(): content = listing_file.read_text() if "vmcore" in content or "core" in content: result["found"] = True self.critical.append("Kernel crash dump found in /var/crash/") result["details"].append("Kernel core dump exists - indicates kernel panic") # Check crash info info_file = crash_dir / "crash_info.txt" if info_file.exists(): content = info_file.read_text() if content.strip(): result["found"] = True result["crash_info"] = content[:2000] # First 2000 chars # Look for common panic types if "page fault" in content.lower(): self.critical.append("Kernel page fault detected") if "double fault" in content.lower(): self.critical.append("Kernel double fault detected") if "out of memory" in content.lower(): self.critical.append("Out of memory kernel panic") # Check panic messages from logs panic_file = crash_dir / "panic_messages.txt" if panic_file.exists(): content = panic_file.read_text() if content.strip(): result["panic_messages"] = content[:2000] result["details"].append("Found panic/fault messages in logs") return result def analyze_logs(self) -> Dict[str, Any]: """Analyze system logs for crash patterns.""" print("\n[*] Analyzing system logs...") result = {"issues_found": [], "pattern_matches": defaultdict(list)} logs_dir = self.data_dir / "logs" if not logs_dir.exists(): return result # Compile crash patterns patterns = [re.compile(p, re.IGNORECASE) for p in CRASH_PATTERNS] for log_file in list(logs_dir.glob("*.log")) + list(logs_dir.glob("*.txt")) + list(logs_dir.glob("messages")): if log_file.stat().st_size == 0: continue try: content = log_file.read_text(errors='replace') lines = content.split('\n') for line in lines: for i, pattern in enumerate(patterns): if pattern.search(line): result["pattern_matches"][CRASH_PATTERNS[i]].append({ "file": log_file.name, "line": line[:200] }) except Exception as e: continue # Summarize findings for pattern, matches in result["pattern_matches"].items(): if len(matches) > 0: issue = f"Found {len(matches)} matches for '{pattern}'" result["issues_found"].append(issue) if len(matches) > 5: self.warnings.append(issue) # Look specifically for gateway/dpinger issues (common cause of "routing stops") dpinger_issues = result["pattern_matches"].get("dpinger.*alarm", []) + \ result["pattern_matches"].get("dpinger.*down", []) + \ result["pattern_matches"].get("gateway.*down", []) if dpinger_issues: self.critical.append(f"Gateway monitoring (dpinger) issues found: {len(dpinger_issues)} events") return result def analyze_reboot_history(self) -> Dict[str, Any]: """Analyze reboot/shutdown history for patterns.""" print("\n[*] Analyzing reboot history...") result = {"reboots": [], "pattern": None, "average_uptime": None} diag_dir = self.data_dir / "diagnostics" last_file = diag_dir / "last_reboot.txt" if last_file.exists(): content = last_file.read_text() lines = content.split('\n') reboot_times = [] for line in lines: if 'reboot' in line or 'shutdown' in line: # Try to parse date from last command output # Format: reboot ~ Mon Dec 2 10:30 match = re.search(r'(Mon|Tue|Wed|Thu|Fri|Sat|Sun)\s+(\w+)\s+(\d+)\s+(\d+:\d+)', line) if match: try: date_str = f"{match.group(1)} {match.group(2)} {match.group(3)} {match.group(4)} {datetime.now().year}" dt = date_parser.parse(date_str) reboot_times.append(dt) result["reboots"].append({ "time": dt.isoformat(), "line": line.strip() }) except: pass # Calculate intervals between reboots if len(reboot_times) >= 2: intervals = [] for i in range(len(reboot_times) - 1): interval = reboot_times[i] - reboot_times[i + 1] intervals.append(interval) if intervals: avg_interval = sum(intervals, timedelta()) / len(intervals) result["average_uptime"] = str(avg_interval) # Check for ~4 day pattern four_day_pattern = any( timedelta(days=3) < interval < timedelta(days=5) for interval in intervals ) if four_day_pattern: self.critical.append(f"CONFIRMED: ~4 day crash pattern detected!") result["pattern"] = "4-day cycle detected" print(f" Average uptime between reboots: {avg_interval}") return result def analyze_services(self) -> Dict[str, Any]: """Analyze service status.""" print("\n[*] Analyzing services...") result = {"running": [], "issues": []} services_file = self.data_dir / "diagnostics" / "services.txt" if services_file.exists(): content = services_file.read_text() for line in content.split('\n'): if line.strip(): result["running"].append(line.strip()) return result def analyze_gateways(self) -> Dict[str, Any]: """Analyze gateway status - often the cause of 'can't route' issues.""" print("\n[*] Analyzing gateways...") result = {"status": "unknown", "gateways": [], "issues": []} # Check gateway status gw_file = self.data_dir / "diagnostics" / "gateway_status.txt" if gw_file.exists(): content = gw_file.read_text() result["raw_status"] = content if "down" in content.lower(): self.critical.append("Gateway marked as DOWN") result["status"] = "down" result["issues"].append("Gateway showing down status") elif "pending" in content.lower(): self.warnings.append("Gateway status pending") # Check dpinger status dpinger_file = self.data_dir / "diagnostics" / "dpinger_status.txt" if dpinger_file.exists(): content = dpinger_file.read_text() if not content.strip(): self.warnings.append("dpinger not running - gateway monitoring disabled") result["issues"].append("dpinger process not found") # Check gateway log gw_log = self.data_dir / "logs" / "gateways.log" if gw_log.exists(): content = gw_log.read_text() down_events = content.count("down") if down_events > 10: self.warnings.append(f"Gateway experienced {down_events} down events in logs") return result def analyze_pf_states(self) -> Dict[str, Any]: """Analyze pf state table - can cause issues if exhausted.""" print("\n[*] Analyzing firewall states...") result = {"state_count": 0, "issues": []} states_file = self.data_dir / "diagnostics" / "pf_states.txt" if states_file.exists(): content = states_file.read_text().strip() try: state_count = int(content) result["state_count"] = state_count # High state counts can cause memory issues if state_count > 500000: self.critical.append(f"Very high PF state count: {state_count}") elif state_count > 200000: self.warnings.append(f"High PF state count: {state_count}") except ValueError: pass pf_info_file = self.data_dir / "diagnostics" / "pf_info.txt" if pf_info_file.exists(): content = pf_info_file.read_text() result["pf_info"] = content # Check for state table exhaustion if "memory" in content.lower() and "fail" in content.lower(): self.critical.append("PF memory allocation failures detected") return result def analyze_cron_jobs(self) -> Dict[str, Any]: """Analyze cron jobs that might cause periodic issues.""" print("\n[*] Analyzing scheduled tasks...") result = {"suspicious_jobs": [], "4_day_jobs": []} cron_dir = self.data_dir / "cron" if not cron_dir.exists(): return result for cron_file in cron_dir.glob("*.txt"): content = cron_file.read_text() # Look for jobs that run every few days # Cron format: min hour day month weekday command for line in content.split('\n'): line = line.strip() if line and not line.startswith('#'): # Check for weekly jobs (could cause 4-7 day patterns) if re.search(r'^\d+\s+\d+\s+\*\s+\*\s+[0-6]', line): result["suspicious_jobs"].append({ "file": cron_file.name, "job": line, "type": "weekly" }) # Check for jobs running every N days if re.search(r'\*/[3-5]', line): result["4_day_jobs"].append({ "file": cron_file.name, "job": line }) self.warnings.append(f"Found cron job running every 3-5 days: {line[:60]}") return result def generate_summary(self) -> Dict[str, Any]: """Generate summary of findings and recommendations.""" print("\n" + "=" * 60) print("DIAGNOSTIC SUMMARY") print("=" * 60) summary = { "critical_issues": self.critical, "warnings": self.warnings, "recommendations": [], "likely_cause": None } # Determine most likely cause causes = [] if any("memory" in c.lower() for c in self.critical): causes.append("memory_exhaustion") summary["recommendations"].append( "Memory exhaustion detected. Consider:\n" " - Reducing PF state table limits\n" " - Limiting ZFS ARC size (add vfs.zfs.arc_max in /boot/loader.conf)\n" " - Adding more RAM\n" " - Checking for memory leaks in services" ) if any("gateway" in c.lower() or "dpinger" in c.lower() for c in self.critical): causes.append("gateway_monitoring") summary["recommendations"].append( "Gateway/dpinger issues detected. Check:\n" " - WAN connection stability\n" " - Gateway monitoring settings (System > Routing > Gateways)\n" " - Consider increasing gateway probe interval\n" " - Check if dpinger is consuming too many resources" ) if any("4 day" in c.lower() or "pattern" in c.lower() for c in self.critical): causes.append("periodic_task") summary["recommendations"].append( "4-day crash pattern confirmed. Investigate:\n" " - Scheduled tasks/cron jobs\n" " - Memory leaks that accumulate over days\n" " - Log rotation or cleanup scripts\n" " - Automatic update checks" ) if any("state" in c.lower() and "pf" in c.lower() for c in self.critical + self.warnings): causes.append("state_table_exhaustion") summary["recommendations"].append( "PF state table issues. Consider:\n" " - Reducing state timeout values\n" " - Increasing state table limits\n" " - Checking for NAT/port forward loops\n" " - Adding state limits to rules" ) if not causes: causes.append("unknown") summary["recommendations"].append( "No obvious cause found. General recommendations:\n" " - Update OPNsense to latest version\n" " - Check hardware (RAM, disk health)\n" " - Review recent configuration changes\n" " - Monitor resource usage leading up to crash" ) summary["likely_cause"] = causes # Print summary print("\nCRITICAL ISSUES:") if self.critical: for c in self.critical: print(f" [!!!] {c}") else: print(" None found") print("\nWARNINGS:") if self.warnings: for w in self.warnings: print(f" [!] {w}") else: print(" None found") print("\nLIKELY CAUSE(S):", ", ".join(causes)) print("\nRECOMMENDATIONS:") for rec in summary["recommendations"]: print(rec) return summary def analyze_data(data_dir: str) -> Dict[str, Any]: """Main function to analyze collected data.""" analyzer = CrashAnalyzer(data_dir) return analyzer.analyze_all() if __name__ == "__main__": import sys if len(sys.argv) < 2: # Find most recent collection output_dir = Path("collected_data") if output_dir.exists(): dirs = sorted(output_dir.iterdir(), reverse=True) if dirs: data_dir = str(dirs[0]) print(f"Analyzing most recent collection: {data_dir}") else: print("No collected data found. Run collector.py first.") sys.exit(1) else: print("No collected data found. Run collector.py first.") sys.exit(1) else: data_dir = sys.argv[1] analyze_data(data_dir)