Repository navigation
Expand file tree
/
Copy pathpfsense_monitor.py
More file actions
1886 lines (1646 loc) · 84 KB
/
Copy pathpfsense_monitor.py
File metadata and controls
1886 lines (1646 loc) · 84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
pfSense Monitor
==========================
Monitors pfSense services and takes corrective actions:
1. WAN Gateway: Auto-detects and pings WAN gateway, restarts interface if needed
2. Unbound DNS: Multi-layer health checking:
- Process state detection (SBWAIT/STOP states)
- Sustained high CPU detection (spinning/livelock)
- DNS responsiveness testing (catches kernel deadlocks)
3. Sends email alerts and logs all actions
Requirements:
- Python 3.6+
- Gmail app password for sending emails
- Root privileges for network and service operations
"""
import subprocess
import time
import logging
import smtplib
import socket
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from datetime import datetime
import os
import sys
import json
from pathlib import Path
class PfSenseMonitor:
def __init__(self, config_file=None):
"""Initialize the pfSense monitor with configuration."""
if config_file is None:
# Use the same directory as the script for config file
script_dir = os.path.dirname(os.path.abspath(__file__))
config_file = os.path.join(script_dir, "pfsense_monitor_config.json")
self.config_file = os.path.abspath(config_file)
self.config = self.load_config()
self.setup_logging()
def load_config(self):
"""Load configuration from JSON file or create default config."""
default_config = {
"email": {
"smtp_server": "smtp.gmail.com",
"smtp_port": 587,
"sender_email": "your-email@gmail.com",
"sender_password": "your-app-password",
"recipient_email": "alert-recipient@gmail.com",
"fallback_dns_servers": ["8.8.8.8", "1.1.1.1"],
"smtp_server_fallback_ips": ["142.250.27.109", "142.250.27.108", "74.125.133.109"]
},
"network": {
"wan_interface": "em0",
"gateway_override": "",
"timeout_seconds": 5,
"retry_attempts": 3,
"retry_delay": 10,
"ping_count": 3
},
"unbound": {
"enabled": True,
"process_name": "unbound",
"bad_states": ["SBWAIT", "STOP"],
"restart_attempts": 2,
"restart_timeout": 30,
"force_reboot_on_failure": True,
"cpu_monitoring": {
"enabled": True,
"threshold_percent": 80.0,
"sample_count": 3,
"sample_interval_seconds": 5
},
"dns_responsiveness": {
"enabled": True,
"test_domains": ["google.com", "cloudflare.com"],
"timeout_seconds": 5,
"require_all": False
},
"pf_lock_contention": {
"wait_for_lock_release": True,
"max_wait_seconds": 90,
"poll_interval_seconds": 15
}
},
"watchdog": {
"enabled": False,
"use_as_last_resort": True,
"timeout_seconds": 60
},
"logging": {
"log_file": "/var/log/pfsense_monitor.log",
"max_log_size_mb": 10
},
"actions": {
"restart_interface_delay": 30,
"reboot_delay": 60
}
}
if os.path.exists(self.config_file):
try:
with open(self.config_file, 'r') as f:
user_config = json.load(f)
# Merge with defaults for any missing keys
merged_config = self.merge_configs(default_config, user_config)
return merged_config
except Exception as e:
print(f"Error loading config from {self.config_file}: {e}")
print("Using default configuration.")
return default_config
else:
# Create default config file
try:
os.makedirs(os.path.dirname(self.config_file), exist_ok=True)
with open(self.config_file, 'w') as f:
json.dump(default_config, f, indent=4)
print(f"Created default config file: {self.config_file}")
print("Please edit the configuration file with your settings before running.")
except Exception as e:
print(f"Could not create config file {self.config_file}: {e}")
print("Using default configuration in memory.")
return default_config
def merge_configs(self, default, user):
"""Recursively merge user config with default config."""
result = default.copy()
for key, value in user.items():
if key in result and isinstance(value, dict) and isinstance(result[key], dict):
result[key] = self.merge_configs(result[key], value)
else:
result[key] = value
return result
def setup_logging(self):
"""Configure logging to file and console."""
log_file = self.config["logging"]["log_file"]
# Ensure log directory exists
Path(log_file).parent.mkdir(parents=True, exist_ok=True)
# Clear any existing handlers
for handler in logging.root.handlers[:]:
logging.root.removeHandler(handler)
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_file),
logging.StreamHandler(sys.stdout)
],
force=True
)
self.logger = logging.getLogger(__name__)
self.logger.info(f"pfSense Monitor initialized")
self.logger.info(f"Config file: {self.config_file}")
self.logger.info(f"WAN Interface: {self.config['network']['wan_interface']}")
def get_wan_gateway(self):
"""Detect the default gateway for the WAN interface."""
wan_interface = self.config["network"]["wan_interface"]
gateway_override = self.config["network"]["gateway_override"]
# Use manual override if specified
if gateway_override:
self.logger.info(f"Using manual gateway override: {gateway_override}")
return gateway_override
try:
# Method 1: Try to get default route using netstat
result = subprocess.run(['netstat', '-rn'], capture_output=True, text=True, timeout=10)
if result.returncode == 0:
lines = result.stdout.split('\n')
for line in lines:
# Look for default route
if line.strip().startswith('default') or line.strip().startswith('0.0.0.0'):
parts = line.split()
if len(parts) >= 2:
gateway = parts[1]
if self.is_valid_ip(gateway):
self.logger.info(f"Detected gateway from netstat: {gateway}")
return gateway
# Method 2: Try route command if available (FreeBSD/pfSense)
try:
result = subprocess.run(['route', '-n', 'get', 'default'],
capture_output=True, text=True, timeout=10)
if result.returncode == 0:
lines = result.stdout.split('\n')
for line in lines:
if 'gateway:' in line.lower():
gateway = line.split(':')[1].strip()
if self.is_valid_ip(gateway):
self.logger.info(f"Detected gateway from route command: {gateway}")
return gateway
except subprocess.CalledProcessError:
pass
# Method 3: Parse /proc/net/route (Linux systems)
try:
with open('/proc/net/route', 'r') as f:
lines = f.readlines()
for line in lines[1:]: # Skip header
fields = line.strip().split('\t')
if len(fields) >= 8:
iface, dest, gateway = fields[0], fields[1], fields[2]
# Check for default route (destination 00000000)
if dest == '00000000' and iface == wan_interface:
# Convert hex gateway to IP
gateway_ip = socket.inet_ntoa(bytes.fromhex(gateway)[::-1])
if self.is_valid_ip(gateway_ip):
self.logger.info(f"Detected gateway from /proc/net/route: {gateway_ip}")
return gateway_ip
except FileNotFoundError:
pass # /proc/net/route doesn't exist on FreeBSD (pfSense)
raise Exception("Could not determine default gateway using any method")
except subprocess.TimeoutExpired:
raise Exception("Timeout while trying to determine gateway")
except Exception as e:
error_msg = f"Failed to detect WAN gateway: {e}"
self.logger.error(error_msg)
raise Exception(error_msg)
def is_valid_ip(self, ip):
"""Validate if string is a valid IP address."""
try:
socket.inet_aton(ip)
# Additional check to ensure it's not invalid gateways
return ip != "0.0.0.0" and not ip.startswith("127.") and ip != "255.255.255.255"
except socket.error:
return False
def test_gateway_connectivity(self):
"""Test connectivity by pinging the WAN gateway."""
try:
gateway = self.get_wan_gateway()
if not gateway:
self.logger.error("No gateway detected, cannot test connectivity")
return False
timeout = self.config["network"]["timeout_seconds"]
ping_count = self.config["network"]["ping_count"]
self.logger.info(f"Testing connectivity to gateway: {gateway}")
# Use ping command for connectivity test
result = subprocess.run([
'ping', '-c', str(ping_count),
'-W', str(timeout * 1000), # timeout in milliseconds
'-i', '0.5', # 0.5 second interval between pings
gateway
], capture_output=True, text=True, timeout=timeout * ping_count + 10)
if result.returncode == 0:
# Parse ping output to get success rate
output = result.stdout
if 'packet loss' in output:
# Extract packet loss info
loss_line = [line for line in output.split('\n') if 'packet loss' in line]
if loss_line:
loss_info = loss_line[0]
self.logger.info(f"Gateway ping result: {loss_info.strip()}")
# Consider successful if less than 100% packet loss
if '100% packet loss' not in loss_info:
return True
else:
self.logger.info(f"Gateway {gateway} is reachable")
return True
self.logger.warning(f"Gateway {gateway} is not reachable")
return False
except subprocess.TimeoutExpired:
self.logger.warning(f"Ping to gateway timed out")
return False
except Exception as e:
self.logger.error(f"Error testing gateway connectivity: {e}")
return False
def restart_wan_interface(self):
"""Restart the WAN interface."""
wan_interface = self.config["network"]["wan_interface"]
delay = self.config["actions"]["restart_interface_delay"]
try:
self.logger.info(f"Bringing down WAN interface: {wan_interface}")
subprocess.run(['ifconfig', wan_interface, 'down'], check=True)
time.sleep(5) # Brief pause
self.logger.info(f"Bringing up WAN interface: {wan_interface}")
subprocess.run(['ifconfig', wan_interface, 'up'], check=True)
self.logger.info(f"Waiting {delay} seconds for interface to stabilize")
time.sleep(delay)
return True
except subprocess.CalledProcessError as e:
error_msg = f"Failed to restart WAN interface {wan_interface}: {e}"
self.logger.error(error_msg)
return False
except Exception as e:
error_msg = f"Unexpected error restarting interface {wan_interface}: {e}"
self.logger.error(error_msg)
return False
def reboot_system(self):
"""Initiate system reboot."""
delay = self.config["actions"]["reboot_delay"]
try:
self.logger.critical("Initiating system reboot due to persistent gateway connectivity issues")
self.send_email_alert("System Reboot Initiated",
"pfSense system is rebooting due to persistent WAN gateway connectivity issues.")
# Schedule reboot with delay
subprocess.run(['shutdown', '-r', f'+{delay//60}'], check=True)
self.logger.info(f"System reboot scheduled in {delay} seconds")
except subprocess.CalledProcessError as e:
error_msg = f"Failed to initiate reboot: {e}"
self.logger.error(error_msg)
self.send_email_alert("Reboot Failed", error_msg)
except Exception as e:
error_msg = f"Unexpected error during reboot: {e}"
self.logger.error(error_msg)
self.send_email_alert("Reboot Error", error_msg)
def _get_unbound_cpu_usage(self):
"""
Get current CPU usage for the unbound process.
Returns CPU percentage as float, or None if process not found or error occurs.
"""
process_name = self.config["unbound"]["process_name"]
try:
result = subprocess.run(['ps', 'aux'], capture_output=True, text=True, timeout=10)
if result.returncode == 0:
lines = result.stdout.split('\n')
for line in lines:
if process_name in line and not 'grep' in line:
# Extract command from ps output (column 10+)
# Check that the executable name (not args) matches process_name
parts = line.split()
if len(parts) >= 11:
# Command is everything from index 10 onwards
command = ' '.join(parts[10:])
# Get just the executable name (first part of command)
executable = command.split()[0] if command else ""
# Extract basename in case it's a full path
executable_name = executable.split('/')[-1]
# Only match if the actual executable is our target process
if executable_name == process_name or executable_name.startswith(process_name + ':'):
# %CPU is at index 2 in ps aux output
cpu_str = parts[2]
try:
cpu_percent = float(cpu_str)
return cpu_percent
except ValueError:
self.logger.error(f"Failed to parse CPU value: {cpu_str}")
return None
# Process not found
return None
else:
self.logger.error("ps command failed while checking CPU")
return None
except subprocess.TimeoutExpired:
self.logger.error("Timeout checking unbound CPU usage")
return None
except Exception as e:
self.logger.error(f"Error getting unbound CPU usage: {e}")
return None
def _test_dns_responsiveness(self):
"""
Test if DNS is actually responding to queries.
This catches cases where the process is running but deadlocked/unresponsive.
Returns True if DNS is responsive, False otherwise.
"""
dns_config = self.config["unbound"].get("dns_responsiveness", {})
# Check if DNS responsiveness testing is enabled
if not dns_config.get("enabled", True):
return True # Skip check if disabled
test_domains = dns_config.get("test_domains", ["google.com", "cloudflare.com"])
timeout = dns_config.get("timeout_seconds", 5)
require_all = dns_config.get("require_all", False)
self.logger.info(f"Testing DNS responsiveness (timeout: {timeout}s, domains: {test_domains})")
successful = 0
failed = 0
for domain in test_domains:
try:
# Try drill first (common on FreeBSD/pfSense)
result = subprocess.run(
['drill', domain, '@127.0.0.1'],
capture_output=True,
text=True,
timeout=timeout
)
if result.returncode == 0 and 'ANSWER SECTION' in result.stdout:
self.logger.info(f"DNS lookup for {domain}: OK")
successful += 1
else:
self.logger.warning(f"DNS lookup for {domain}: FAILED (no answer)")
failed += 1
except subprocess.TimeoutExpired:
self.logger.warning(f"DNS lookup for {domain}: TIMEOUT after {timeout}s")
failed += 1
except FileNotFoundError:
# drill not available, try dig
try:
result = subprocess.run(
['dig', '+short', '+time=2', '+tries=1', domain, '@127.0.0.1'],
capture_output=True,
text=True,
timeout=timeout
)
if result.returncode == 0 and result.stdout.strip():
self.logger.info(f"DNS lookup for {domain}: OK (via dig)")
successful += 1
else:
self.logger.warning(f"DNS lookup for {domain}: FAILED (no answer)")
failed += 1
except subprocess.TimeoutExpired:
self.logger.warning(f"DNS lookup for {domain}: TIMEOUT after {timeout}s")
failed += 1
except FileNotFoundError:
self.logger.error("Neither drill nor dig available for DNS testing")
# Can't test without tools - assume OK to avoid false positives
return True
except Exception as e:
self.logger.warning(f"DNS lookup for {domain}: ERROR ({e})")
failed += 1
except Exception as e:
self.logger.warning(f"DNS lookup for {domain}: ERROR ({e})")
failed += 1
# Evaluate results
total = len(test_domains)
if require_all:
# All domains must resolve successfully
if failed > 0:
self.logger.error(f"DNS responsiveness check FAILED: {failed}/{total} domains failed (require_all=True)")
return False
self.logger.info(f"DNS responsiveness check PASSED: {successful}/{total} domains resolved")
return True
else:
# At least one domain must resolve successfully
if successful == 0:
self.logger.error(f"DNS responsiveness check FAILED: 0/{total} domains resolved")
return False
self.logger.info(f"DNS responsiveness check PASSED: {successful}/{total} domains resolved")
return True
def _check_unbound_cpu_sustained(self):
"""
Check if unbound CPU usage is sustained above threshold.
Takes multiple samples over time to confirm sustained high usage.
Returns True if CPU is OK, False if sustained high CPU detected.
"""
cpu_config = self.config["unbound"].get("cpu_monitoring", {})
# Check if CPU monitoring is enabled
if not cpu_config.get("enabled", False):
return True # Skip check if disabled
threshold = cpu_config.get("threshold_percent", 80.0)
sample_count = cpu_config.get("sample_count", 3)
sample_interval = cpu_config.get("sample_interval_seconds", 5)
self.logger.info(f"Checking unbound CPU usage (threshold: {threshold}%, samples: {sample_count})")
samples = []
samples_above_threshold = 0
for i in range(sample_count):
if i > 0: # Don't sleep before first sample
time.sleep(sample_interval)
cpu_usage = self._get_unbound_cpu_usage()
if cpu_usage is None:
self.logger.warning(f"CPU sample {i+1}/{sample_count}: Process not found or error")
# If process not found, return False (will be caught by state check)
return False
samples.append(cpu_usage)
self.logger.info(f"CPU sample {i+1}/{sample_count}: {cpu_usage}%")
if cpu_usage > threshold:
samples_above_threshold += 1
# Check if majority of samples exceeded threshold
avg_cpu = sum(samples) / len(samples) if samples else 0
if samples_above_threshold >= (sample_count / 2):
self.logger.error(
f"Unbound CPU usage sustained above threshold: "
f"{samples_above_threshold}/{sample_count} samples exceeded {threshold}% "
f"(average: {avg_cpu:.1f}%)"
)
return False
else:
self.logger.info(
f"Unbound CPU usage normal: average {avg_cpu:.1f}% "
f"({samples_above_threshold}/{sample_count} samples above threshold)"
)
return True
def _detect_pf_lock_contention(self, pids=None):
"""
Analyze kernel stack traces to detect pf (packet filter) lock contention.
pf lock contention is a FreeBSD issue where a process (like unbound)
gets stuck spinning on _rm_rlock_hard while trying to pass a packet through
the packet filter. This happens when pfBlocker or filterdns holds the pf
write lock during a table update. The process appears "running" (Rs state)
with high CPU but cannot respond to any requests.
Signature: _rm_rlock_hard (or rw_rlock_hard) + pf_test in the same
kernel stack trace.
Returns a dict:
detected: bool - True if pf lock contention was detected
confidence: str - "high", "medium", or "none"
evidence: list of str - specific findings
stack_traces: dict - pid -> raw stack trace string
pf_search_rate: float or None - pf state searches/sec
suspect_processes: list of str - processes that may hold the pf write lock
"""
detection = {
"detected": False,
"confidence": "none",
"evidence": [],
"stack_traces": {},
"pf_search_rate": None,
"suspect_processes": [],
}
# High confidence: a lock-spin frame AND a pf evaluation frame in the same trace.
HIGH_CONFIDENCE_PAIRS = [
("_rm_rlock_hard", "pf_test"),
("_rm_rlock_hard", "pf_check"),
("rw_rlock_hard", "pf_test"),
("rw_rlock_hard", "pf_check"),
("_rm_rlock", "pf_test"),
("rw_rlock", "pf_test"),
]
# Medium confidence: lock-spin frame with pf references anywhere in trace.
MEDIUM_CONFIDENCE_LOCK_FRAMES = [
"_rm_rlock_hard", "rw_rlock_hard", "rw_wlock_hard",
"_rm_wlock_hard", "pf_lock",
]
process_name = self.config["unbound"]["process_name"]
# Find unbound PIDs if not provided.
if pids is None:
pids = []
try:
ps_result = subprocess.run(
['ps', 'aux'], capture_output=True, text=True, timeout=10
)
if ps_result.returncode == 0:
for line in ps_result.stdout.split('\n'):
if process_name in line and 'grep' not in line:
parts = line.split()
if len(parts) >= 11:
command = ' '.join(parts[10:])
executable = command.split()[0].split('/')[-1] if command else ""
if executable == process_name or executable.startswith(process_name + ':'):
pids.append(parts[1])
except Exception as e:
self.logger.debug(f"Error finding unbound PIDs for lock detection: {e}")
# Analyze kernel stack traces for each unbound PID.
for pid in pids:
try:
stack_result = subprocess.run(
['procstat', '-kk', pid],
capture_output=True, text=True, timeout=5
)
if stack_result.returncode != 0 or not stack_result.stdout.strip():
continue
trace = stack_result.stdout.strip()
detection["stack_traces"][pid] = trace
# Check for high confidence pf lock signature.
for lock_frame, pf_frame in HIGH_CONFIDENCE_PAIRS:
if lock_frame in trace and pf_frame in trace:
detection["detected"] = True
detection["confidence"] = "high"
detection["evidence"].append(
f"PID {pid}: kernel stack contains '{lock_frame}' "
f"waiting on '{pf_frame}' (pf read-lock spin)"
)
break
# Check for medium confidence if not already high.
if detection["confidence"] != "high":
for frame in MEDIUM_CONFIDENCE_LOCK_FRAMES:
if frame in trace and "pf_" in trace:
detection["detected"] = True
if detection["confidence"] == "none":
detection["confidence"] = "medium"
detection["evidence"].append(
f"PID {pid}: kernel stack contains '{frame}' "
f"with pf references"
)
break
except subprocess.TimeoutExpired:
# procstat timeout on a live process can itself indicate severe lock contention.
detection["evidence"].append(
f"PID {pid}: procstat -kk timed out (possible kernel deadlock)"
)
if detection["confidence"] == "none":
detection["confidence"] = "medium"
detection["detected"] = True
except FileNotFoundError:
pass # procstat not available on this system
except Exception as e:
self.logger.debug(f"Error getting stack trace for PID {pid}: {e}")
# Get pf state table search rate from pfctl -si.
# High rates (>1500/s) indicate heavy pf table activity and elevated lock
# contention risk, especially during pfBlocker/filterdns updates.
try:
pfctl_result = subprocess.run(
['pfctl', '-si'], capture_output=True, text=True, timeout=5
)
if pfctl_result.returncode == 0:
for line in pfctl_result.stdout.split('\n'):
if 'searches' in line.lower() and '/s' in line:
for part in line.split():
if part.endswith('/s'):
try:
rate = float(part[:-2])
detection["pf_search_rate"] = rate
if rate > 1500 and not detection["detected"]:
detection["evidence"].append(
f"High pf state search rate: {rate:.0f}/s "
f"(elevated lock contention risk)"
)
except ValueError:
pass
break
except subprocess.TimeoutExpired:
detection["evidence"].append(
"pfctl -si timed out (pf subsystem may be locked)"
)
detection["detected"] = True
detection["confidence"] = "high"
except Exception:
pass
# Identify processes that commonly hold the pf write lock.
# pfBlocker (php_pfb) and filterdns are the most frequent culprits.
SUSPECT_PATTERNS = [
("php_pfb", "pfBlocker"),
("filterdns", "filterdns"),
("pfctl", "pfctl (scripted/manual)"),
]
try:
ps_result = subprocess.run(
['ps', 'aux'], capture_output=True, text=True, timeout=10
)
if ps_result.returncode == 0:
for line in ps_result.stdout.split('\n'):
if 'grep' in line:
continue
for pattern, label in SUSPECT_PATTERNS:
if pattern in line and label not in detection["suspect_processes"]:
detection["suspect_processes"].append(label)
except Exception:
pass
return detection
def _is_filterdns_running(self):
"""Check if filterdns is currently running (common pf write-lock holder)."""
try:
result = subprocess.run(
['pgrep', '-x', 'filterdns'],
capture_output=True, text=True, timeout=5
)
return result.returncode == 0
except Exception:
return False
def _wait_for_pf_lock_release(self, pf_detection):
"""
When pf lock contention is detected, wait for the lock to release naturally
before attempting service restarts.
Restart attempts are futile while the pf write lock is held — unbound-control
and the new unbound process will hit the same lock. Waiting for the lock holder
(typically filterdns during a 5-minute alias refresh) to finish is more effective.
Polls DNS responsiveness every poll_interval_seconds up to max_wait_seconds.
Returns True if Unbound recovered on its own (no restart needed).
Returns False if the wait timed out without recovery.
"""
wait_config = self.config["unbound"].get("pf_lock_contention", {})
if not wait_config.get("wait_for_lock_release", True):
return False
max_wait = wait_config.get("max_wait_seconds", 90)
poll_interval = wait_config.get("poll_interval_seconds", 15)
confidence = pf_detection.get("confidence", "unknown")
suspect = ", ".join(pf_detection.get("suspect_processes", [])) or "filterdns/pfBlocker"
self.logger.info(
f"pf lock contention detected ({confidence} confidence). "
f"Suspected lock holder: {suspect}. "
f"Waiting up to {max_wait}s for lock to release before attempting restart."
)
elapsed = 0
while elapsed < max_wait:
time.sleep(poll_interval)
elapsed += poll_interval
filterdns_running = self._is_filterdns_running()
self.logger.info(
f"pf lock wait: {elapsed}/{max_wait}s elapsed, "
f"filterdns running: {filterdns_running}. Testing DNS responsiveness..."
)
if self._test_dns_responsiveness():
self.logger.info(
f"Unbound recovered after {elapsed}s wait — pf lock released. "
f"No restart needed."
)
return True
self.logger.warning(
f"pf lock wait timed out after {max_wait}s without recovery. "
f"Proceeding with restart attempts."
)
return False
def get_unbound_diagnostics(self):
"""
Collect diagnostic information about unbound and system state.
Returns a formatted string with diagnostic details for email alerts.
"""
diagnostics = []
process_name = self.config["unbound"]["process_name"]
# 1. Get all unbound process details from ps aux
try:
result = subprocess.run(['ps', 'aux'], capture_output=True, text=True, timeout=10)
if result.returncode == 0:
unbound_processes = []
for line in result.stdout.split('\n'):
if process_name in line and 'grep' not in line:
parts = line.split()
if len(parts) >= 11:
command = ' '.join(parts[10:])
executable = command.split()[0] if command else ""
executable_name = executable.split('/')[-1]
if executable_name == process_name or executable_name.startswith(process_name + ':'):
unbound_processes.append({
'user': parts[0],
'pid': parts[1],
'cpu': parts[2],
'mem': parts[3],
'vsz': parts[4],
'rss': parts[5],
'stat': parts[7],
'start': parts[8],
'time': parts[9],
'command': command
})
if unbound_processes:
diagnostics.append(f"Unbound Processes Found: {len(unbound_processes)}")
diagnostics.append("-" * 40)
for proc in unbound_processes:
diagnostics.append(f" PID: {proc['pid']}")
diagnostics.append(f" State: {proc['stat']}")
diagnostics.append(f" CPU: {proc['cpu']}%")
diagnostics.append(f" Memory: {proc['mem']}% (RSS: {proc['rss']} KB)")
diagnostics.append(f" Started: {proc['start']}")
diagnostics.append(f" CPU Time: {proc['time']}")
diagnostics.append(f" Command: {proc['command']}")
diagnostics.append("")
# Collect procstat info for each unbound process
for proc in unbound_processes:
pid = proc['pid']
diagnostics.append(f"Procstat for PID {pid}:")
diagnostics.append("-" * 40)
# Thread info - shows what each thread is waiting on
try:
result = subprocess.run(['procstat', '-t', pid],
capture_output=True, text=True, timeout=5)
if result.returncode == 0 and result.stdout.strip():
diagnostics.append(" Thread Status:")
for line in result.stdout.strip().split('\n')[:15]:
diagnostics.append(f" {line}")
except FileNotFoundError:
diagnostics.append(" procstat not available")
except Exception as e:
diagnostics.append(f" Thread info error: {e}")
# Kernel stack trace - shows what the process is blocked on
try:
result = subprocess.run(['procstat', '-kk', pid],
capture_output=True, text=True, timeout=5)
if result.returncode == 0 and result.stdout.strip():
diagnostics.append(" Kernel Stack Trace:")
for line in result.stdout.strip().split('\n')[:20]:
diagnostics.append(f" {line}")
except FileNotFoundError:
pass # Already reported above
except Exception as e:
diagnostics.append(f" Stack trace error: {e}")
# File descriptors - may show stuck sockets
try:
result = subprocess.run(['procstat', '-f', pid],
capture_output=True, text=True, timeout=5)
if result.returncode == 0 and result.stdout.strip():
lines = result.stdout.strip().split('\n')
# Count fd types
socket_count = sum(1 for l in lines if 'socket' in l.lower())
pipe_count = sum(1 for l in lines if 'pipe' in l.lower())
file_count = sum(1 for l in lines if 'vnode' in l.lower())
diagnostics.append(f" File Descriptors: {len(lines)-1} total "
f"(sockets: {socket_count}, pipes: {pipe_count}, files: {file_count})")
# Show first few socket entries if any
socket_lines = [l for l in lines if 'socket' in l.lower()][:5]
if socket_lines:
diagnostics.append(" Recent sockets:")
for line in socket_lines:
diagnostics.append(f" {line[:100]}")
except FileNotFoundError:
pass
except Exception as e:
diagnostics.append(f" FD info error: {e}")
diagnostics.append("")
else:
diagnostics.append("Unbound Processes Found: 0 (NOT RUNNING)")
except Exception as e:
diagnostics.append(f"Error getting process info: {e}")
# 2. Get system load average
try:
with open('/proc/loadavg', 'r') as f:
load = f.read().strip()
diagnostics.append(f"System Load: {load}")
except FileNotFoundError:
# FreeBSD doesn't have /proc/loadavg, try sysctl
try:
result = subprocess.run(['sysctl', '-n', 'vm.loadavg'],
capture_output=True, text=True, timeout=5)
if result.returncode == 0:
diagnostics.append(f"System Load: {result.stdout.strip()}")
except Exception:
pass
except Exception as e:
diagnostics.append(f"Error getting load average: {e}")
# 3. Get memory usage
try:
result = subprocess.run(['sysctl', '-n', 'hw.physmem', 'hw.usermem'],
capture_output=True, text=True, timeout=5)
if result.returncode == 0:
lines = result.stdout.strip().split('\n')
if len(lines) >= 2:
physmem = int(lines[0]) / (1024 * 1024 * 1024)
usermem = int(lines[1]) / (1024 * 1024 * 1024)
diagnostics.append(f"Physical Memory: {physmem:.2f} GB")
diagnostics.append(f"User Memory: {usermem:.2f} GB")
except Exception:
pass
# 4. Get top memory-consuming processes
try:
result = subprocess.run(['ps', 'aux', '--sort=-rss'],
capture_output=True, text=True, timeout=10)
if result.returncode != 0:
# FreeBSD ps doesn't support --sort, use different approach
result = subprocess.run(['ps', 'auxww'], capture_output=True, text=True, timeout=10)
if result.returncode == 0:
lines = result.stdout.strip().split('\n')
if len(lines) > 1:
diagnostics.append("\nTop Memory Consumers:")
diagnostics.append("-" * 40)
# Parse and sort by RSS (column 5)
procs = []
for line in lines[1:]: # Skip header
parts = line.split()
if len(parts) >= 11:
try:
rss = int(parts[5])
procs.append((rss, parts[0], parts[1], parts[2], parts[3], ' '.join(parts[10:])[:40]))
except ValueError:
continue
procs.sort(reverse=True)
for rss, _user, pid, cpu, mem, cmd in procs[:5]:
diagnostics.append(f" {pid:>6} {cpu:>5}% CPU {mem:>5}% MEM {cmd}")
except Exception as e:
diagnostics.append(f"Error getting top processes: {e}")
# 5. Check recent unbound log entries
unbound_log_paths = [
'/var/log/resolver.log',
'/var/log/unbound.log',
'/var/log/messages'
]
for log_path in unbound_log_paths:
try:
result = subprocess.run(['tail', '-20', log_path],
capture_output=True, text=True, timeout=5)
if result.returncode == 0 and result.stdout.strip():
# Filter for unbound-related entries
unbound_lines = [line for line in result.stdout.split('\n')
if 'unbound' in line.lower() or 'dns' in line.lower()]
if unbound_lines:
diagnostics.append(f"\nRecent DNS Log Entries ({log_path}):")
diagnostics.append("-" * 40)
for line in unbound_lines[-10:]: # Last 10 relevant lines
diagnostics.append(f" {line[:100]}")
break
except Exception:
continue
# 6. Check DNS resolution capability
diagnostics.append("\nDNS Resolution Test:")
diagnostics.append("-" * 40)
test_domains = ['google.com', 'cloudflare.com']
for domain in test_domains:
try:
result = subprocess.run(['drill', domain, '@127.0.0.1'],
capture_output=True, text=True, timeout=5)
if result.returncode == 0 and 'ANSWER SECTION' in result.stdout:
diagnostics.append(f" {domain}: OK")
else:
diagnostics.append(f" {domain}: FAILED (no answer)")
except subprocess.TimeoutExpired:
diagnostics.append(f" {domain}: TIMEOUT")
except FileNotFoundError:
# Try dig if drill not available
try:
result = subprocess.run(['dig', '+short', domain, '@127.0.0.1'],
capture_output=True, text=True, timeout=5)
if result.returncode == 0 and result.stdout.strip():
diagnostics.append(f" {domain}: OK")
else:
diagnostics.append(f" {domain}: FAILED")
except Exception:
diagnostics.append(f" {domain}: Unable to test (no drill/dig)")
except Exception as e:
diagnostics.append(f" {domain}: ERROR ({e})")
# 7. Check unbound service status
try:
result = subprocess.run(['service', 'unbound', 'status'],
capture_output=True, text=True, timeout=10)
diagnostics.append(f"\nService Status:")
diagnostics.append("-" * 40)
diagnostics.append(f" {result.stdout.strip()}")
if result.stderr.strip():
diagnostics.append(f" stderr: {result.stderr.strip()}")
except Exception as e:
diagnostics.append(f"\nService Status: Error checking ({e})")
# 8. Check unbound-control status (direct control interface query)
try:
result = subprocess.run(['unbound-control', 'status'],