""" Log and Data Collector for OPNsense/FreeBSD """ import os import json from datetime import datetime from pathlib import Path from typing import Dict, Any from ssh_client import SSHConnection from config import LOG_FILES, DIAGNOSTIC_COMMANDS, OUTPUT_DIR class DataCollector: """Collects logs, configs, and diagnostic data from OPNsense.""" def __init__(self, ssh: SSHConnection): self.ssh = ssh self.timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") self.output_dir = Path(OUTPUT_DIR) / self.timestamp self.output_dir.mkdir(parents=True, exist_ok=True) self.collected_data: Dict[str, Any] = {} def collect_all(self) -> Dict[str, Any]: """Collect all diagnostic data.""" print("\n" + "=" * 60) print("COLLECTING DIAGNOSTIC DATA") print("=" * 60) self.collect_system_info() self.collect_diagnostic_commands() self.collect_log_files() self.collect_crash_dumps() self.collect_opnsense_config() self.collect_cron_analysis() self.collect_memory_analysis() # Save summary summary_path = self.output_dir / "collection_summary.json" with open(summary_path, 'w') as f: json.dump(self.collected_data, f, indent=2, default=str) print(f"\n[+] All data saved to: {self.output_dir}") return self.collected_data def collect_system_info(self): """Collect basic system information.""" print("\n[*] Collecting system information...") info = {} commands = { "hostname": "hostname", "opnsense_version": "opnsense-version -v 2>/dev/null || echo 'N/A'", "freebsd_version": "freebsd-version", "kernel": "uname -a", "uptime": "uptime", "boot_time": "sysctl -n kern.boottime", } for name, cmd in commands.items(): stdout, stderr, code = self.ssh.execute(cmd) info[name] = stdout.strip() print(f" {name}: {stdout.strip()[:60]}") self.collected_data["system_info"] = info # Save to file with open(self.output_dir / "system_info.txt", 'w') as f: for k, v in info.items(): f.write(f"{k}: {v}\n") def collect_diagnostic_commands(self): """Run diagnostic commands and save output.""" print("\n[*] Running diagnostic commands...") diag_dir = self.output_dir / "diagnostics" diag_dir.mkdir(exist_ok=True) results = {} for name, cmd in DIAGNOSTIC_COMMANDS.items(): print(f" Running: {name}...") stdout, stderr, code = self.ssh.execute(cmd, timeout=120) results[name] = { "command": cmd, "stdout": stdout, "stderr": stderr, "exit_code": code } # Save individual command output with open(diag_dir / f"{name}.txt", 'w') as f: f.write(f"Command: {cmd}\n") f.write(f"Exit Code: {code}\n") f.write("=" * 60 + "\n") f.write(stdout) if stderr: f.write("\n--- STDERR ---\n") f.write(stderr) self.collected_data["diagnostics"] = results def collect_log_files(self): """Download log files.""" print("\n[*] Collecting log files...") logs_dir = self.output_dir / "logs" logs_dir.mkdir(exist_ok=True) collected = [] for log_path in LOG_FILES: log_name = os.path.basename(log_path) local_path = logs_dir / log_name print(f" Downloading: {log_path}...") # Try to read last 10000 lines (log files can be huge) stdout, stderr, code = self.ssh.execute(f"tail -n 10000 {log_path} 2>/dev/null") if stdout: with open(local_path, 'w') as f: f.write(stdout) collected.append(log_path) print(f" [+] Saved: {log_name} ({len(stdout)} bytes)") else: print(f" [-] Not found or empty: {log_path}") self.collected_data["log_files"] = collected def collect_crash_dumps(self): """Check for crash dumps.""" print("\n[*] Checking for crash dumps...") crash_dir = self.output_dir / "crash" crash_dir.mkdir(exist_ok=True) # List crash directory stdout, stderr, code = self.ssh.execute("ls -la /var/crash/ 2>/dev/null") with open(crash_dir / "crash_listing.txt", 'w') as f: f.write(stdout) # Check for crash info stdout, stderr, code = self.ssh.execute("cat /var/crash/info.* 2>/dev/null | head -200") if stdout: with open(crash_dir / "crash_info.txt", 'w') as f: f.write(stdout) print(f" [!] Found crash info!") # Check for kernel panic messages in logs stdout, stderr, code = self.ssh.execute( "grep -i 'panic\\|fatal\\|trap\\|fault' /var/log/messages /var/log/system.log 2>/dev/null | tail -100" ) if stdout: with open(crash_dir / "panic_messages.txt", 'w') as f: f.write(stdout) print(f" [!] Found potential crash-related messages") self.collected_data["crash_dumps"] = { "listing": stdout, "found_crash_info": bool(stdout) } def collect_opnsense_config(self): """Backup OPNsense configuration.""" print("\n[*] Backing up OPNsense configuration...") config_dir = self.output_dir / "config" config_dir.mkdir(exist_ok=True) # Main config (sanitize passwords) stdout, stderr, code = self.ssh.execute( "cat /conf/config.xml | sed 's/.*<\\/password>/REDACTED<\\/password>/g'" ) if stdout: with open(config_dir / "config.xml", 'w') as f: f.write(stdout) print(" [+] Saved config.xml (passwords redacted)") # Installed packages stdout, stderr, code = self.ssh.execute("pkg info") with open(config_dir / "installed_packages.txt", 'w') as f: f.write(stdout) # rc.conf stdout, stderr, code = self.ssh.execute("cat /etc/rc.conf 2>/dev/null") if stdout: with open(config_dir / "rc.conf", 'w') as f: f.write(stdout) def collect_cron_analysis(self): """Analyze scheduled tasks that might cause issues.""" print("\n[*] Analyzing scheduled tasks...") cron_dir = self.output_dir / "cron" cron_dir.mkdir(exist_ok=True) # System crontab stdout, stderr, code = self.ssh.execute("cat /etc/crontab 2>/dev/null") with open(cron_dir / "etc_crontab.txt", 'w') as f: f.write(stdout) # Root crontab stdout, stderr, code = self.ssh.execute("crontab -l 2>/dev/null") with open(cron_dir / "root_crontab.txt", 'w') as f: f.write(stdout if stdout else "No root crontab") # OPNsense configd cron stdout, stderr, code = self.ssh.execute("cat /var/cron/tabs/root 2>/dev/null") with open(cron_dir / "var_cron_root.txt", 'w') as f: f.write(stdout if stdout else "No /var/cron/tabs/root") # List cron.d stdout, stderr, code = self.ssh.execute("ls -la /etc/cron.d/ 2>/dev/null && cat /etc/cron.d/* 2>/dev/null") with open(cron_dir / "cron.d_contents.txt", 'w') as f: f.write(stdout if stdout else "No cron.d directory") def collect_memory_analysis(self): """Deep dive into memory usage.""" print("\n[*] Analyzing memory usage...") mem_dir = self.output_dir / "memory" mem_dir.mkdir(exist_ok=True) commands = { "vmstat": "vmstat -w 1 5", "top_mem": "top -b -o res -d 1 | head -40", "swap": "swapinfo -h", "vm_stats": "sysctl vm.stats.vm", "vm_page": "sysctl vm.stats.vm.v_page_count vm.stats.vm.v_free_count vm.stats.vm.v_inactive_count", "kern_mem": "sysctl kern.ipc.maxsockbuf kern.maxfiles kern.openfiles", "arc_stats": "sysctl vfs.zfs.arc_max vfs.zfs.arc_min kstat.zfs.misc.arcstats.size 2>/dev/null || echo 'No ZFS ARC'", "mbuf": "netstat -m", } for name, cmd in commands.items(): stdout, stderr, code = self.ssh.execute(cmd) with open(mem_dir / f"{name}.txt", 'w') as f: f.write(f"Command: {cmd}\n") f.write("=" * 60 + "\n") f.write(stdout) def collect_data(ssh: SSHConnection) -> Dict[str, Any]: """Main function to collect all data.""" collector = DataCollector(ssh) return collector.collect_all() if __name__ == "__main__": from ssh_client import SSHConnection conn = SSHConnection() if conn.connect(): try: collect_data(conn) finally: conn.close()