forked from smittix/intercept
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathintercept_agent.py
More file actions
3824 lines (3261 loc) · 149 KB
/
intercept_agent.py
File metadata and controls
3824 lines (3261 loc) · 149 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
"""
INTERCEPT Agent - Remote node for distributed signal intelligence.
This agent runs on remote nodes and exposes Intercept's capabilities via REST API.
It can push data to a central controller or respond to pull requests.
Usage:
python intercept_agent.py [--port 8020] [--config intercept_agent.cfg]
"""
from __future__ import annotations
import argparse
import configparser
import json
import logging
import os
import queue
import re
import shutil
import signal
import socket
import subprocess
import sys
import threading
import time
from datetime import datetime, timezone
from http.server import HTTPServer, BaseHTTPRequestHandler
from socketserver import ThreadingMixIn
from typing import Any
from urllib.parse import urlparse, parse_qs
# Add parent directory to path for imports
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# Import dependency checking from Intercept utils
try:
from utils.dependencies import check_all_dependencies, check_tool, TOOL_DEPENDENCIES
HAS_DEPENDENCIES_MODULE = True
except ImportError:
HAS_DEPENDENCIES_MODULE = False
# Import TSCM modules for consistent analysis (same as local mode)
try:
from utils.tscm.detector import ThreatDetector
from utils.tscm.correlation import CorrelationEngine
HAS_TSCM_MODULES = True
except ImportError:
HAS_TSCM_MODULES = False
ThreatDetector = None
CorrelationEngine = None
# Import database functions for baseline support (same as local mode)
try:
from utils.database import get_tscm_baseline, get_active_tscm_baseline
HAS_BASELINE_DB = True
except ImportError:
HAS_BASELINE_DB = False
get_tscm_baseline = None
get_active_tscm_baseline = None
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s [%(levelname)s] %(name)s: %(message)s'
)
logger = logging.getLogger('intercept.agent')
# Version
AGENT_VERSION = '1.0.0'
# =============================================================================
# Configuration
# =============================================================================
class AgentConfig:
"""Agent configuration loaded from INI file or defaults."""
def __init__(self):
# Agent settings
self.name: str = socket.gethostname()
self.port: int = 8020
self.allowed_ips: list[str] = []
self.allow_cors: bool = False
# Controller settings
self.controller_url: str = ''
self.controller_api_key: str = ''
self.push_enabled: bool = False
self.push_interval: int = 5
# Mode settings (all enabled by default)
self.modes_enabled: dict[str, bool] = {
'pager': True,
'sensor': True,
'adsb': True,
'ais': True,
'acars': True,
'aprs': True,
'wifi': True,
'bluetooth': True,
'dsc': True,
'rtlamr': True,
'tscm': True,
'satellite': True,
'listening_post': True,
}
def load_from_file(self, filepath: str) -> bool:
"""Load configuration from INI file."""
if not os.path.isfile(filepath):
logger.warning(f"Config file not found: {filepath}")
return False
parser = configparser.ConfigParser()
try:
parser.read(filepath)
# Agent section
if parser.has_section('agent'):
if parser.has_option('agent', 'name'):
self.name = parser.get('agent', 'name')
if parser.has_option('agent', 'port'):
self.port = parser.getint('agent', 'port')
if parser.has_option('agent', 'allowed_ips'):
ips = parser.get('agent', 'allowed_ips')
if ips.strip():
self.allowed_ips = [ip.strip() for ip in ips.split(',')]
if parser.has_option('agent', 'allow_cors'):
self.allow_cors = parser.getboolean('agent', 'allow_cors')
# Controller section
if parser.has_section('controller'):
if parser.has_option('controller', 'url'):
self.controller_url = parser.get('controller', 'url').rstrip('/')
if parser.has_option('controller', 'api_key'):
self.controller_api_key = parser.get('controller', 'api_key')
if parser.has_option('controller', 'push_enabled'):
self.push_enabled = parser.getboolean('controller', 'push_enabled')
if parser.has_option('controller', 'push_interval'):
self.push_interval = parser.getint('controller', 'push_interval')
# Modes section
if parser.has_section('modes'):
for mode in self.modes_enabled.keys():
if parser.has_option('modes', mode):
self.modes_enabled[mode] = parser.getboolean('modes', mode)
logger.info(f"Loaded configuration from {filepath}")
return True
except Exception as e:
logger.error(f"Error loading config: {e}")
return False
def to_dict(self) -> dict:
"""Convert config to dictionary."""
return {
'name': self.name,
'port': self.port,
'allowed_ips': self.allowed_ips,
'allow_cors': self.allow_cors,
'controller_url': self.controller_url,
'push_enabled': self.push_enabled,
'push_interval': self.push_interval,
'modes_enabled': self.modes_enabled,
}
# Global config
config = AgentConfig()
# =============================================================================
# GPS Integration
# =============================================================================
class GPSManager:
"""Manages GPS position via gpsd."""
def __init__(self):
self._client = None
self._position = None
self._lock = threading.Lock()
self._running = False
@property
def position(self) -> dict | None:
"""Get current GPS position."""
with self._lock:
if self._position:
return {
'lat': self._position.latitude,
'lon': self._position.longitude,
'altitude': self._position.altitude,
'speed': self._position.speed,
'heading': self._position.heading,
'fix_quality': self._position.fix_quality,
}
return None
def start(self, host: str = 'localhost', port: int = 2947) -> bool:
"""Start GPS client connection to gpsd."""
try:
from utils.gps import GPSDClient
self._client = GPSDClient(host, port)
self._client.add_callback(self._on_position_update)
success = self._client.start()
if success:
self._running = True
logger.info(f"GPS connected to gpsd at {host}:{port}")
return success
except ImportError:
logger.warning("GPS module not available")
return False
except Exception as e:
logger.error(f"Failed to start GPS: {e}")
return False
def stop(self):
"""Stop GPS client."""
if self._client:
self._client.stop()
self._client = None
self._running = False
def _on_position_update(self, position):
"""Callback for GPS position updates."""
with self._lock:
self._position = position
@property
def is_running(self) -> bool:
return self._running
# Global GPS manager
gps_manager = GPSManager()
# =============================================================================
# Controller Push Client
# =============================================================================
class ControllerPushClient(threading.Thread):
"""Daemon thread that pushes scan data to the controller."""
def __init__(self, cfg: AgentConfig):
super().__init__()
self.daemon = True
self.cfg = cfg
self.queue: queue.Queue = queue.Queue(maxsize=200)
self.running = False
self.stop_event = threading.Event()
def enqueue(self, scan_type: str, payload: dict, interface: str = None):
"""Add data to push queue."""
if not self.cfg.push_enabled or not self.cfg.controller_url:
return
item = {
'agent_name': self.cfg.name,
'scan_type': scan_type,
'interface': interface,
'payload': payload,
'received_at': datetime.now(timezone.utc).isoformat(),
'attempts': 0,
}
try:
self.queue.put_nowait(item)
except queue.Full:
logger.warning("Push queue full, dropping payload")
def run(self):
"""Main push loop."""
import requests
self.running = True
logger.info(f"Push client started, target: {self.cfg.controller_url}")
while not self.stop_event.is_set():
try:
item = self.queue.get(timeout=1.0)
except queue.Empty:
continue
if item is None:
continue
endpoint = f"{self.cfg.controller_url}/controller/api/ingest"
headers = {'Content-Type': 'application/json'}
if self.cfg.controller_api_key:
headers['X-API-Key'] = self.cfg.controller_api_key
body = {
'agent_name': item['agent_name'],
'scan_type': item['scan_type'],
'interface': item['interface'],
'payload': item['payload'],
'received_at': item['received_at'],
}
try:
response = requests.post(endpoint, json=body, headers=headers, timeout=5)
if response.status_code >= 400:
raise RuntimeError(f"HTTP {response.status_code}")
logger.debug(f"Pushed {item['scan_type']} data to controller")
except Exception as e:
item['attempts'] += 1
if item['attempts'] < 3 and not self.stop_event.is_set():
try:
self.queue.put_nowait(item)
except queue.Full:
pass
else:
logger.warning(f"Failed to push after {item['attempts']} attempts: {e}")
finally:
self.queue.task_done()
self.running = False
logger.info("Push client stopped")
def stop(self):
"""Stop the push client."""
self.stop_event.set()
# Global push client
push_client: ControllerPushClient | None = None
# =============================================================================
# Mode Manager - Uses Intercept's existing utilities and tools
# =============================================================================
class ModeManager:
"""
Manages mode state using Intercept's existing infrastructure.
This assumes Intercept (or its utilities) is installed on the agent host.
The agent imports and uses the existing modules rather than reimplementing
tool execution logic.
"""
def __init__(self):
self.running_modes: dict[str, dict] = {}
self.data_snapshots: dict[str, list] = {}
self.locks: dict[str, threading.Lock] = {}
self._capabilities: dict | None = None
# Process tracking per mode
self.processes: dict[str, subprocess.Popen] = {}
self.output_threads: dict[str, threading.Thread] = {}
self.stop_events: dict[str, threading.Event] = {}
# Data queues for each mode (for real-time collection)
self.data_queues: dict[str, queue.Queue] = {}
# WiFi-specific state
self.wifi_networks: dict[str, dict] = {}
self.wifi_clients: dict[str, dict] = {}
# ADS-B specific state
self.adsb_aircraft: dict[str, dict] = {}
# Bluetooth specific state
self.bluetooth_devices: dict[str, dict] = {}
# Lazy-loaded Intercept utilities
self._sdr_factory = None
self._dependencies = None
def _get_sdr_factory(self):
"""Lazy-load SDRFactory from Intercept's utils."""
if self._sdr_factory is None:
try:
from utils.sdr import SDRFactory
self._sdr_factory = SDRFactory
except ImportError:
logger.warning("SDRFactory not available - SDR features disabled")
return self._sdr_factory
def _get_dependencies(self):
"""Lazy-load dependencies module from Intercept's utils."""
if self._dependencies is None:
try:
from utils import dependencies
self._dependencies = dependencies
except ImportError:
logger.warning("Dependencies module not available")
return self._dependencies
def _check_tool(self, tool_name: str) -> bool:
"""Check if a tool is available using Intercept's dependency checker."""
deps = self._get_dependencies()
if deps and hasattr(deps, 'check_tool'):
return deps.check_tool(tool_name)
# Fallback to simple which check
return shutil.which(tool_name) is not None
def _get_tool_path(self, tool_name: str) -> str | None:
"""Get tool path using Intercept's dependency module."""
deps = self._get_dependencies()
if deps and hasattr(deps, 'get_tool_path'):
return deps.get_tool_path(tool_name)
return shutil.which(tool_name)
def detect_capabilities(self) -> dict:
"""Detect available tools and hardware using Intercept's utilities."""
if self._capabilities is not None:
return self._capabilities
capabilities = {
'modes': {},
'devices': [],
'interfaces': {
'wifi_interfaces': [],
'bt_adapters': [],
'sdr_devices': [],
},
'agent_version': AGENT_VERSION,
'gps': gps_manager.is_running,
'gps_position': gps_manager.position,
'tool_details': {}, # Detailed tool status
}
# Detect interfaces using Intercept's TSCM device detection
self._detect_interfaces(capabilities)
# Use Intercept's comprehensive dependency checking if available
if HAS_DEPENDENCIES_MODULE:
try:
dep_status = check_all_dependencies()
# Map dependency status to mode availability
mode_mapping = {
'pager': 'pager',
'sensor': 'sensor',
'aircraft': 'adsb',
'ais': 'ais',
'acars': 'acars',
'aprs': 'aprs',
'wifi': 'wifi',
'bluetooth': 'bluetooth',
'tscm': 'tscm',
'satellite': 'satellite',
}
for dep_mode, cap_mode in mode_mapping.items():
if dep_mode in dep_status:
mode_info = dep_status[dep_mode]
# Check if mode is enabled in config
if not config.modes_enabled.get(cap_mode, True):
capabilities['modes'][cap_mode] = False
else:
capabilities['modes'][cap_mode] = mode_info['ready']
# Store detailed tool info
capabilities['tool_details'][cap_mode] = {
'name': mode_info['name'],
'ready': mode_info['ready'],
'missing_required': mode_info['missing_required'],
'tools': mode_info['tools'],
}
# Handle modes not in dependencies.py
extra_modes = ['dsc', 'rtlamr', 'listening_post']
extra_tools = {
'dsc': ['rtl_fm'],
'rtlamr': ['rtlamr'],
'listening_post': ['rtl_fm'],
}
for mode in extra_modes:
if not config.modes_enabled.get(mode, True):
capabilities['modes'][mode] = False
else:
tools = extra_tools.get(mode, [])
capabilities['modes'][mode] = all(
check_tool(tool) for tool in tools
) if tools else True
except Exception as e:
logger.warning(f"Dependency check failed, using fallback: {e}")
self._detect_capabilities_fallback(capabilities)
else:
self._detect_capabilities_fallback(capabilities)
# Use Intercept's SDR detection
sdr_factory = self._get_sdr_factory()
if sdr_factory:
try:
devices = sdr_factory.detect_devices()
sdr_list = []
for sdr in devices:
sdr_dict = sdr.to_dict()
# Create friendly display name
display_name = sdr.name
if sdr.serial and sdr.serial not in ('N/A', 'Unknown'):
display_name = f'{sdr.name} (SN: {sdr.serial[-8:]})'
sdr_dict['display_name'] = display_name
sdr_list.append(sdr_dict)
capabilities['devices'] = sdr_list
capabilities['interfaces']['sdr_devices'] = sdr_list
except Exception as e:
logger.warning(f"SDR device detection failed: {e}")
self._capabilities = capabilities
return capabilities
def _detect_interfaces(self, capabilities: dict):
"""Detect WiFi interfaces and Bluetooth adapters."""
import platform
interfaces = capabilities.get('interfaces', {})
# Detect WiFi interfaces
if platform.system() == 'Darwin': # macOS
try:
result = subprocess.run(
['networksetup', '-listallhardwareports'],
capture_output=True, text=True, timeout=5
)
lines = result.stdout.split('\n')
for i, line in enumerate(lines):
if 'Wi-Fi' in line or 'AirPort' in line:
port_name = line.replace('Hardware Port:', '').strip()
for j in range(i + 1, min(i + 3, len(lines))):
if 'Device:' in lines[j]:
device = lines[j].split('Device:')[1].strip()
interfaces['wifi_interfaces'].append({
'name': device,
'display_name': f'{port_name} ({device})',
'type': 'internal',
'monitor_capable': False
})
break
except (FileNotFoundError, subprocess.TimeoutExpired, subprocess.SubprocessError):
pass
else: # Linux
try:
result = subprocess.run(
['iw', 'dev'],
capture_output=True, text=True, timeout=5
)
current_iface = None
for line in result.stdout.split('\n'):
line = line.strip()
if line.startswith('Interface'):
current_iface = line.split()[1]
elif current_iface and 'type' in line:
iface_type = line.split()[-1]
interfaces['wifi_interfaces'].append({
'name': current_iface,
'display_name': f'Wireless ({current_iface}) - {iface_type}',
'type': iface_type,
'monitor_capable': True
})
current_iface = None
except (FileNotFoundError, subprocess.TimeoutExpired, subprocess.SubprocessError):
# Fall back to iwconfig
try:
result = subprocess.run(
['iwconfig'],
capture_output=True, text=True, timeout=5
)
for line in result.stdout.split('\n'):
if 'IEEE 802.11' in line:
iface = line.split()[0]
interfaces['wifi_interfaces'].append({
'name': iface,
'display_name': f'Wireless ({iface})',
'type': 'managed',
'monitor_capable': True
})
except (FileNotFoundError, subprocess.TimeoutExpired, subprocess.SubprocessError):
pass
# Detect Bluetooth adapters
if platform.system() == 'Linux':
try:
result = subprocess.run(
['hciconfig'],
capture_output=True, text=True, timeout=5
)
blocks = re.split(r'(?=^hci\d+:)', result.stdout, flags=re.MULTILINE)
for block in blocks:
if block.strip():
first_line = block.split('\n')[0]
match = re.match(r'(hci\d+):', first_line)
if match:
iface_name = match.group(1)
is_up = 'UP RUNNING' in block or '\tUP ' in block
interfaces['bt_adapters'].append({
'name': iface_name,
'display_name': f'Bluetooth Adapter ({iface_name})',
'type': 'hci',
'status': 'up' if is_up else 'down'
})
except (FileNotFoundError, subprocess.TimeoutExpired, subprocess.SubprocessError):
# Try bluetoothctl as fallback
try:
result = subprocess.run(
['bluetoothctl', 'list'],
capture_output=True, text=True, timeout=5
)
for line in result.stdout.split('\n'):
if 'Controller' in line:
parts = line.split()
if len(parts) >= 3:
addr = parts[1]
name = ' '.join(parts[2:]) if len(parts) > 2 else 'Bluetooth'
interfaces['bt_adapters'].append({
'name': addr,
'display_name': f'{name} ({addr[-8:]})',
'type': 'controller',
'status': 'available'
})
except (FileNotFoundError, subprocess.TimeoutExpired, subprocess.SubprocessError):
pass
elif platform.system() == 'Darwin':
try:
result = subprocess.run(
['system_profiler', 'SPBluetoothDataType'],
capture_output=True, text=True, timeout=10
)
bt_name = 'Built-in Bluetooth'
bt_addr = ''
for line in result.stdout.split('\n'):
if 'Address:' in line:
bt_addr = line.split('Address:')[1].strip()
break
interfaces['bt_adapters'].append({
'name': 'default',
'display_name': f'{bt_name}' + (f' ({bt_addr[-8:]})' if bt_addr else ''),
'type': 'macos',
'status': 'available'
})
except (FileNotFoundError, subprocess.TimeoutExpired, subprocess.SubprocessError):
interfaces['bt_adapters'].append({
'name': 'default',
'display_name': 'Built-in Bluetooth',
'type': 'macos',
'status': 'available'
})
def _detect_capabilities_fallback(self, capabilities: dict):
"""Fallback capability detection when dependencies module unavailable."""
tool_checks = {
'pager': ['rtl_fm', 'multimon-ng'],
'sensor': ['rtl_433'],
'adsb': ['dump1090'],
'ais': ['AIS-catcher'],
'acars': ['acarsdec'],
'aprs': ['rtl_fm', 'direwolf'],
'wifi': ['airmon-ng', 'airodump-ng'],
'bluetooth': ['bluetoothctl'],
'dsc': ['rtl_fm'],
'rtlamr': ['rtlamr'],
'satellite': [],
'listening_post': ['rtl_fm'],
'tscm': ['rtl_fm'],
}
for mode, tools in tool_checks.items():
if not config.modes_enabled.get(mode, True):
capabilities['modes'][mode] = False
continue
if not tools:
capabilities['modes'][mode] = True
continue
if mode == 'adsb':
capabilities['modes'][mode] = (
self._check_tool('dump1090') or
self._check_tool('dump1090-fa') or
self._check_tool('readsb')
)
else:
capabilities['modes'][mode] = all(
self._check_tool(tool) for tool in tools
)
def get_status(self) -> dict:
"""Get overall agent status."""
# Build running modes with device info for multi-SDR tracking
running_modes_detail = {}
for mode, info in self.running_modes.items():
params = info.get('params', {})
running_modes_detail[mode] = {
'started_at': info.get('started_at'),
'device': params.get('device', params.get('device_index', 0)),
}
status = {
'running_modes': list(self.running_modes.keys()),
'running_modes_detail': running_modes_detail, # Include device info per mode
'uptime': time.time() - _start_time,
'push_enabled': config.push_enabled,
'push_connected': push_client is not None and push_client.running,
'gps': gps_manager.is_running,
}
# Include GPS position if available
gps_pos = gps_manager.position
if gps_pos:
status['gps_position'] = gps_pos
return status
# Modes that use RTL-SDR devices
SDR_MODES = {'adsb', 'sensor', 'pager', 'ais', 'acars', 'dsc', 'rtlamr', 'listening_post'}
def get_sdr_in_use(self, device: int = 0) -> str | None:
"""Check if an SDR device is in use by another mode.
Returns the mode name using the device, or None if available.
"""
for mode, info in self.running_modes.items():
if mode in self.SDR_MODES:
mode_device = info.get('params', {}).get('device', 0)
# Normalize to int for comparison
try:
mode_device = int(mode_device)
except (ValueError, TypeError):
mode_device = 0
if mode_device == device:
return mode
return None
def start_mode(self, mode: str, params: dict) -> dict:
"""Start a mode with given parameters."""
if mode in self.running_modes:
return {'status': 'error', 'message': f'{mode} already running'}
caps = self.detect_capabilities()
if not caps['modes'].get(mode, False):
return {'status': 'error', 'message': f'{mode} not available (missing tools)'}
# Check SDR device conflicts for SDR-based modes
if mode in self.SDR_MODES:
device = params.get('device', 0)
try:
device = int(device)
except (ValueError, TypeError):
device = 0
in_use_by = self.get_sdr_in_use(device)
if in_use_by:
return {
'status': 'error',
'message': f'SDR device {device} is in use by {in_use_by}. Stop {in_use_by} first or use a different device.'
}
# Initialize lock if needed
if mode not in self.locks:
self.locks[mode] = threading.Lock()
with self.locks[mode]:
try:
# Mode-specific start logic
result = self._start_mode_internal(mode, params)
if result.get('status') == 'started':
self.running_modes[mode] = {
'started_at': datetime.now(timezone.utc).isoformat(),
'params': params,
}
return result
except Exception as e:
logger.exception(f"Error starting {mode}")
return {'status': 'error', 'message': str(e)}
def stop_mode(self, mode: str) -> dict:
"""Stop a running mode."""
if mode not in self.running_modes:
return {'status': 'not_running'}
if mode not in self.locks:
self.locks[mode] = threading.Lock()
with self.locks[mode]:
try:
result = self._stop_mode_internal(mode)
if mode in self.running_modes:
del self.running_modes[mode]
return result
except Exception as e:
logger.exception(f"Error stopping {mode}")
return {'status': 'error', 'message': str(e)}
def get_mode_status(self, mode: str) -> dict:
"""Get status of a specific mode."""
if mode in self.running_modes:
info = {
'running': True,
**self.running_modes[mode]
}
# Add mode-specific stats
if mode == 'adsb':
info['aircraft_count'] = len(self.adsb_aircraft)
elif mode == 'wifi':
info['network_count'] = len(self.wifi_networks)
info['client_count'] = len(self.wifi_clients)
elif mode == 'bluetooth':
info['device_count'] = len(self.bluetooth_devices)
elif mode == 'sensor':
info['reading_count'] = len(self.data_snapshots.get(mode, []))
elif mode == 'ais':
info['vessel_count'] = len(getattr(self, 'ais_vessels', {}))
elif mode == 'aprs':
info['station_count'] = len(getattr(self, 'aprs_stations', {}))
elif mode == 'pager':
info['message_count'] = len(self.data_snapshots.get(mode, []))
elif mode == 'acars':
info['message_count'] = len(self.data_snapshots.get(mode, []))
elif mode == 'rtlamr':
info['reading_count'] = len(self.data_snapshots.get(mode, []))
elif mode == 'tscm':
info['anomaly_count'] = len(getattr(self, 'tscm_anomalies', []))
elif mode == 'satellite':
info['pass_count'] = len(self.data_snapshots.get(mode, []))
elif mode == 'listening_post':
info['signal_count'] = len(getattr(self, 'listening_post_activity', []))
info['current_freq'] = getattr(self, 'listening_post_current_freq', 0)
info['freqs_scanned'] = getattr(self, 'listening_post_freqs_scanned', 0)
return info
return {'running': False}
def get_mode_data(self, mode: str) -> dict:
"""Get current data snapshot for a mode."""
data = {
'mode': mode,
'timestamp': datetime.now(timezone.utc).isoformat(),
}
# Add GPS position
gps_pos = gps_manager.position
if gps_pos:
data['agent_gps'] = gps_pos
# Mode-specific data
if mode == 'adsb':
data['data'] = list(self.adsb_aircraft.values())
elif mode == 'wifi':
data['data'] = {
'networks': list(self.wifi_networks.values()),
'clients': list(self.wifi_clients.values()),
}
elif mode == 'bluetooth':
data['data'] = list(self.bluetooth_devices.values())
elif mode == 'ais':
data['data'] = list(getattr(self, 'ais_vessels', {}).values())
elif mode == 'aprs':
data['data'] = list(getattr(self, 'aprs_stations', {}).values())
elif mode == 'tscm':
data['data'] = {
'anomalies': getattr(self, 'tscm_anomalies', []),
'baseline': getattr(self, 'tscm_baseline', {}),
'wifi_devices': list(self.wifi_networks.values()),
'bt_devices': list(self.bluetooth_devices.values()),
'rf_signals': getattr(self, 'tscm_rf_signals', []),
}
elif mode == 'listening_post':
data['data'] = {
'activity': getattr(self, 'listening_post_activity', []),
'current_freq': getattr(self, 'listening_post_current_freq', 0),
'freqs_scanned': getattr(self, 'listening_post_freqs_scanned', 0),
'signal_count': len(getattr(self, 'listening_post_activity', [])),
}
elif mode == 'pager':
# Return recent pager messages
messages = self.data_snapshots.get(mode, [])
data['data'] = {
'messages': messages[-50:] if len(messages) > 50 else messages,
'total_count': len(messages),
}
elif mode == 'dsc':
# Return DSC messages
messages = getattr(self, 'dsc_messages', [])
data['data'] = {
'messages': messages[-50:] if len(messages) > 50 else messages,
'total_count': len(messages),
}
else:
data['data'] = self.data_snapshots.get(mode, [])
return data
# =========================================================================
# Mode-specific implementations
# =========================================================================
def _start_mode_internal(self, mode: str, params: dict) -> dict:
"""Internal mode start - dispatches to mode-specific handlers."""
logger.info(f"Starting mode {mode} with params: {params}")
# Initialize data structures
self.data_snapshots[mode] = []
self.data_queues[mode] = queue.Queue(maxsize=500)
self.stop_events[mode] = threading.Event()
# Dispatch to mode-specific handler
handlers = {
'sensor': self._start_sensor,
'adsb': self._start_adsb,
'wifi': self._start_wifi,
'bluetooth': self._start_bluetooth,
'pager': self._start_pager,
'ais': self._start_ais,
'acars': self._start_acars,
'aprs': self._start_aprs,
'rtlamr': self._start_rtlamr,
'dsc': self._start_dsc,
'tscm': self._start_tscm,
'satellite': self._start_satellite,
'listening_post': self._start_listening_post,
}
handler = handlers.get(mode)
if handler:
return handler(params)
# Unknown mode
logger.warning(f"Unknown mode: {mode}")
return {'status': 'error', 'message': f'Unknown mode: {mode}'}
def _stop_mode_internal(self, mode: str) -> dict:
"""Internal mode stop - terminates processes and cleans up."""
logger.info(f"Stopping mode {mode}")
# Signal stop
if mode in self.stop_events:
self.stop_events[mode].set()
# Terminate process if running
if mode in self.processes:
proc = self.processes[mode]
if proc and proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=3)
except subprocess.TimeoutExpired:
proc.kill()
del self.processes[mode]
# Wait for output thread
if mode in self.output_threads:
thread = self.output_threads[mode]
if thread and thread.is_alive():
thread.join(timeout=2)
del self.output_threads[mode]
# Clean up
if mode in self.stop_events:
del self.stop_events[mode]
if mode in self.data_queues:
del self.data_queues[mode]
if mode in self.data_snapshots:
del self.data_snapshots[mode]
# Mode-specific cleanup
if mode == 'adsb':
self.adsb_aircraft.clear()
elif mode == 'wifi':
self.wifi_networks.clear()
self.wifi_clients.clear()
elif mode == 'bluetooth':
self.bluetooth_devices.clear()
elif mode == 'tscm':
# Clean up TSCM sub-threads
for sub_thread_name in ['tscm_wifi', 'tscm_bt', 'tscm_rf']:
if sub_thread_name in self.output_threads:
thread = self.output_threads[sub_thread_name]
if thread and thread.is_alive():
thread.join(timeout=2)
del self.output_threads[sub_thread_name]
# Clear TSCM data
self.tscm_anomalies = []
self.tscm_baseline = {}
self.tscm_rf_signals = []
# Clear reported threat tracking sets
if hasattr(self, '_tscm_reported_wifi'):
self._tscm_reported_wifi.clear()
if hasattr(self, '_tscm_reported_bt'):
self._tscm_reported_bt.clear()
elif mode == 'dsc':
# Clear DSC data
if hasattr(self, 'dsc_messages'):
self.dsc_messages = []
elif mode == 'pager':
# Pager uses two processes: multimon-ng (pager) and rtl_fm (pager_rtl)
# Kill the rtl_fm process as well
if 'pager_rtl' in self.processes:
rtl_proc = self.processes['pager_rtl']
if rtl_proc and rtl_proc.poll() is None:
rtl_proc.terminate()
try:
rtl_proc.wait(timeout=3)
except subprocess.TimeoutExpired:
rtl_proc.kill()
del self.processes['pager_rtl']
# Clear pager data
if hasattr(self, 'pager_messages'):
self.pager_messages = []
elif mode == 'aprs':
# APRS uses two processes: decoder (aprs) and rtl_fm (aprs_rtl)
if 'aprs_rtl' in self.processes:
rtl_proc = self.processes['aprs_rtl']
if rtl_proc and rtl_proc.poll() is None:
rtl_proc.terminate()
try:
rtl_proc.wait(timeout=3)
except subprocess.TimeoutExpired:
rtl_proc.kill()