Repository navigation
Expand file tree
/
Copy pathsentinel.py
More file actions
executable file
·3913 lines (2983 loc) · 131 KB
/
Copy pathsentinel.py
File metadata and controls
executable file
·3913 lines (2983 loc) · 131 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
'''
Notes:
- Do not write to the windows from multiple threads as this will lead to strange artifacts
- look into generating maps with Folium and serving them up via webserver
- modify scrollprint to add a string to a window_queue (windowname, string)
- a separate thread will read the window_queue and write the string to the correct window
- store raw packets for further processing by A.I. to fingerprint devices that have modified their MAC repeatedly
- find out if friendly cache is working
- look into seeing what we can pull out of RadioTap packet layers
Sentinel Passive Surveillance System
====================================
Description:
------------
This program is a passive network surveillance system designed to capture network packets,
extract detailed information such as MAC addresses, SSIDs, vendors, and protocols,
and display the information in separate text windows.
It utilizes scapy for packet sniffing and curses for displaying the information in a text-based UI.
Additionally, the system performs channel hopping to capture packets across multiple Wi-Fi channels.
Author: Bill (Datagod)
Creation Date: October 2024
Change Log:
-----------
Date | Author | Description
----------------|----------------|-----------------------------------------------------------
2024-11-21 | datagod | Initial version of the program.
2026-08-24 | datagod | E edit mode: freeze details, classify, save friendlies.
2026-08-24 | datagod | IE fingerprint + probe-SSID matching for randomized MACs.
2026-08-27 | datagod | Packet TTL cache size/window from Central (central-cache.json).
'''
import curses
import queue
import textwindows
import time
import os
import sqlite3
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime # Import only what's needed for clarity
import csv
import subprocess
import re
import json
import hashlib
from collections import Counter, defaultdict
import gps
import inspect
from functools import wraps
from cachetools import TTLCache
import termios, tty, sys
import select
import netaddr
import threading
import argparse
from colorama import Fore, Back, Style, init
import pyfiglet
import shutil
import pprint
from typing import List, Tuple
import pytz
from tzlocal import get_localzone
from scapy.all import *
from scapy.layers.l2 import Dot3, Dot1Q, Ether, ARP
from scapy.layers.inet import IP, TCP, UDP, ICMP
from scapy.layers.dhcp import DHCP
from scapy.layers.dot11 import Dot11, Dot11Beacon, Dot11ProbeReq, Dot11ProbeResp, Dot11AssoReq, Dot11AssoResp
# Import the device type dictionary from the other file
from device_type_dict import device_type_dict
#Global Variables
oui_dict = None
vendor_cache = {}
write_lock = threading.Lock()
profile_lock = threading.Lock()
profiling_data = {} # Dictionary to store function run times
HeaderLines = {}
#GPS Structures
gps_lock = threading.Lock() # New lock for GPS synchronization
gps_stop_event = threading.Event()
gps_thread = None
gps_data = {
"latitude": None,
"longitude": None,
"altitude": None,
"speed": None,
"satellites": None,
"timestamp": None
}
#Parameters
curses_enabled = True
show_friendly = True
edit_mode = False
edit_cursor_index = 0
edit_snapshot = []
last_packet_by_mac = {}
curses_stdscr = None
edit_overlay = None
frozen_screen = {}
FRIENDLY_DEVICES_FILE = "FriendlyDevices.json"
CLASSIFICATIONS = ["Friendly", "Router", "Mobile", "IoT", "Camera", "Other"]
F1_KEYS = ("\x1bOP", "\x1b[11~", "\x1b[[A", "\x1b[1P")
UP_KEYS = ("\x1b[A", "\x1bOA")
DOWN_KEYS = ("\x1b[B", "\x1bOB")
ENTER_KEYS = ("\r", "\n")
ESC_KEYS = ("\x1b", "\x1b\x1b")
#Packet Stuff
current_channel_info = {"channel": None, "band": None, "frequency": None}
packet_cache_ttl = 900
packet_cache_maxsize = 10000
displayed_packets_cache = TTLCache(maxsize=packet_cache_maxsize, ttl=packet_cache_ttl)
friendly_device_cache = TTLCache(maxsize=10000, ttl=3600) #entry expires after 1 hour
cache_lock = threading.Lock()
CACHE_SETTINGS_FILE = "central-cache.json"
CENTRAL_URL_FILE = "central-url.txt"
_cache_settings_mtime = None
_cache_settings_etag = None
key_count = 0
friendly_devices_dict = None
probe_history = defaultdict(lambda: {"ssids": set(), "ie_hash": None})
COMMON_SSIDS = {
"xfinitywifi", "xfinity", "attwifi", "att wifi", "eduroam",
"google starbucks", "linksys", "netgear", "dlink", "setup",
"hp-setup", "androidshare", "iphone", "optimumwifi", "spectrumwifi",
"cablewifi", "guest", "public", "hotel", "airport",
}
PacketCount = 0
friendly_key_count = 0
PacketQueue = queue.Queue()
DBQueue = queue.Queue()
PacketDB = "packet.db"
DBConnection = None
DBReports = None
PacketsSavedToDBCount = 0
latitude = None
longitude = None
current_latitude = None
current_longitude = None
current_gpstime = None
ProcessedPacket = None
MobileCount = 0
RouterCount = 0
OtherCount = 0
DeviceTypeDict = defaultdict(set)
#Timers
hop_interval = 1 #Interval in seconds between channel hops
hop_modifier = 5 #divides modifies the hop interval so we don't wait as long on 5Ghz channels
main_interval = 1 #Interval in seconds for the main loop
gps_interval = 1 #Interval in seconds for the GPS check
HeaderUpdateSpeed = 25
last_time = time.time() #time in seconds since the epoch
keyboard_interval = 0.5 #Interval in seconds to check for keypress
#Windows variables
HeaderWindow = None
StatusWindow = None
InfoWindow = None
PacketWindow = None
DetailsWindow = None
RawWindow = None
HorizontalWidthUnits = 5
HeaderHeight = 15
HeaderWidth = 80
ScreenWidthOverride = 240
#Console variables
console_width = shutil.get_terminal_size().columns
console_height = shutil.get_terminal_size().lines
console_region = None
console_start_row = 16
console_stop_row = console_height
console_header_start_row = 4
console_region_title = "Time Friendly PacketType DeviceType SourceMac SourceVendor SSID BandSignal"
#Time Zones
utc_zone = pytz.utc
local_zone = get_localzone()
#--------------------------------------------------------------------
# __ __ _ ___ _ _ --
# | \/ | / \ |_ _| \ | | --
# | |\/| | / _ \ | || \| | --
# | | | |/ ___ \ | || |\ | --
# |_| |_/_/ \_\___|_| \_| --
# --
# ____ ____ ___ ____ _____ ____ ____ ___ _ _ ____ --
# | _ \| _ \ / _ \ / ___| ____/ ___/ ___|_ _| \ | |/ ___| --
# | |_) | |_) | | | | | | _| \___ \___ \| || \| | | _ --
# | __/| _ <| |_| | |___| |___ ___) |__) | || |\ | |_| | --
# |_| |_| \_\\___/ \____|_____|____/____/___|_| \_|\____| --
# --
#--------------------------------------------------------------------
#------------------------------------------------------------------------------
# ASCII Functions --
#------------------------------------------------------------------------------
def clear_screen_ASCII():
print("\033[2J\033[H", end="", flush=True) # Clear screen with ANSI escape code
#------------------------------------------------------------------------------
# Keyboard Functions --
#------------------------------------------------------------------------------
KEYBOARD_HELP_LINES = [
"KEYS ?/F1 this help E edit/classify",
"p/Spc pause 5s q quit",
"f toggle friendly r toggle routers",
"g GPS status c clear windows",
"R restart t windows/raw",
"1 top devices 2 top mobile",
"3 recent intruders",
"EDIT Up/Down move Enter classify Esc/E exit",
]
def show_keyboard_help():
if curses_enabled and StatusWindow is not None:
try:
StatusWindow.Clear()
StatusWindow.ScrollPrint("Keyboard commands", Color=5, TimeStamp=False)
for line in KEYBOARD_HELP_LINES:
StatusWindow.ScrollPrint(line, Color=3, TimeStamp=False)
StatusWindow.refresh()
except Exception:
for line in KEYBOARD_HELP_LINES:
log_message(line, StatusWindow)
else:
print("Keyboard commands")
for line in KEYBOARD_HELP_LINES:
print(f" {line}")
def _restore_curses_input(stdscr=None):
scr = stdscr or curses_stdscr
if scr is None:
return
try:
curses.noecho()
curses.cbreak()
curses.curs_set(0)
scr.keypad(True)
scr.nodelay(True)
curses.flushinp()
except curses.error:
pass
def ProcessKeypress(Key,stdscr):
global show_friendly
global show_routers
global console_region
global StatusWindow
# q = quit
# t = restart in textwindow mode
# r = restart in raw mode
if isinstance(Key, int):
if Key < 0:
return
if 32 <= Key <= 126:
Key = chr(Key)
elif Key in (10, 13, curses.KEY_ENTER):
Key = "\n"
elif Key == 27:
Key = "\x1b"
elif Key == curses.KEY_F1:
show_keyboard_help()
return
else:
return
if Key == "?" or Key in F1_KEYS:
show_keyboard_help()
return
if Key in ("E", "e"):
if curses_enabled and not edit_mode:
run_edit_mode()
_restore_curses_input(stdscr)
return
if (Key == "p" or Key == " "):
time.sleep(5)
#elif (Key == '1'):
# print(Fore.RED,end="", flush=True)
#elif (Key == '2'):
# print(Fore.GREEN,end="", flush=True)
#elif (Key == '3'):
# print(Fore.BLUE,end="", flush=True)
elif (Key == '4'):
print(Fore.YELLOW,end="", flush=True)
elif (Key == '5'):
print(Fore.MAGENTA,end="", flush=True)
elif (Key == '6'):
print(Fore.CYAN,end="", flush=True)
elif (Key == '7'):
print(Fore.WHITE,end="", flush=True)
elif (Key == "q"):
print(f"\033[11;1H",flush=True)
print(Fore.RED,end="", flush=True)
print(pyfiglet.figlet_format(" QUIT ", font='pagga',width=console_width))
print(' ')
print(' ')
print(' ')
print(' ')
print(' ')
exit()
#----------------------------
#-- Toggle Friendly
#----------------------------
elif (Key == "f"):
if show_friendly == False:
if curses_enabled:
log_message("SHOW FRIENDLY ON")
else:
print(f"\033[{console_start_row};1H",flush=True)
print(pyfiglet.figlet_format(" SHOW FRIENDLY ", font='pagga',width=console_width))
else:
if curses_enabled:
log_message("SHOW FRIENDLY OFF")
else:
print(f"\033[{console_start_row};1H")
print(pyfiglet.figlet_format(" HIDE FRIENDLY ", font='pagga',width=console_width))
show_friendly = not(show_friendly)
DisplayHeader()
#----------------------------
#-- Toggle Routers
#----------------------------
elif (Key == "r"):
if show_routers == False:
if curses_enabled:
log_message("SHOW ROUTERS ON")
else:
print(f"\033[{console_start_row};1H")
print(pyfiglet.figlet_format(" SHOW ROUTERS ", font='pagga',width=console_width))
else:
if curses_enabled:
log_message("SHOW ROUTERS OFF")
else:
print(f"\033[{console_start_row};1H")
print(pyfiglet.figlet_format(" HIDE ROUTERS ", font='pagga',width=console_width))
show_routers = not(show_routers)
DisplayHeader()
#----------------------------
#-- GPS Status
#----------------------------
elif Key == 'g':
if curses_enabled:
StatusWindow.CurrentRow = 1
log_message("GPS Status Report",StatusWindow)
display_gps_info()
log_message(" ",StatusWindow)
else:
log_message("==========================================")
display_gps_info()
log_message("==========================================")
#----------------------------
#-- Restart
#----------------------------
elif (Key == "R"):
os.system("stty sane")
print(f"\033[{console_start_row};1H",flush=True)
print(Fore.RED,end='',flush=True)
print(pyfiglet.figlet_format(" RESTART ", font='pagga',width=console_width))
print('')
print('')
os.execl(sys.executable, sys.executable, *sys.argv)
#-----------------------------------
#-- Toggle TextWindows / Raw modes
#-----------------------------------
#Switch from Windows to Raw or Raw to Windows and restart
elif (Key == "t"):
#clear the screen
#os.system('cls' if os.name == 'nt' else 'clear')
clear_screen_ASCII()
os.system("stty sane")
print(f"\033[{console_start_row};1H",flush=True)
print(Fore.RED,end='')
print(pyfiglet.figlet_format(" TOGGLE WINDOWS/RAW ", font='pagga',width=console_width))
if curses_enabled == False:
custom_params = ["--Raw","N"]
else:
custom_params = ["--Raw","Y"]
#change the start parameters
new_argv = [sys.argv[0]] + custom_params
#Restart python program
os.execl(sys.executable, sys.executable, *new_argv)
#----------------------------
#-- Report 1
#----------------------------
elif Key == '1':
ProduceReport_TopDevices(TheCount=25)
#----------------------------
#-- Report 2
#----------------------------
elif Key == '2':
ProduceReport_TopMobile(TheCount=30)
#----------------------------
#-- Report 3
#----------------------------
elif Key == '3':
ProduceReport_RecentIntruders(TheCount=30)
#-----------------------------------
#-- Clear the console
#-----------------------------------
elif (Key == 'c'):
if curses_enabled:
print(f"\033[{1};1H", end="",flush=True)
textwindows.RefreshAllWindows()
HeaderWindow.set_fixed_line_all(HeaderLines,Color=5)
else:
os.system("stty sane")
print(f"\033[1;1H", end="",flush=True)
print("\033[0J", end="")
print(f"\033[0;0H", end="", flush=True) # Explicitly set cursor to row 0, column 0
print(Fore.RED,end="", flush=True)
print(pyfiglet.figlet_format(" SENTINEL PASSIVE SURVEILLANCE ",font='pagga',justify='left',width=console_width))
print(Fore.GREEN,end="", flush=True)
console_region.current_row = console_region.start_row +1
console_region.print_line(text=console_region_title,line=console_region.title_row)
DisplayHeader()
def _edit_windows():
return [w for w in (HeaderWindow, StatusWindow, DetailsWindow, InfoWindow) if w is not None]
def _set_windows_frozen(frozen):
for window in _edit_windows():
window.frozen = frozen
def capture_frozen_screen():
global frozen_screen
frozen_screen = {}
for window in _edit_windows():
win = window.window
height, width = win.getmaxyx()
grid = []
for y in range(height):
row = []
for x in range(width):
try:
row.append(win.inch(y, x))
except curses.error:
row.append(ord(" "))
grid.append(row)
frozen_screen[window.name] = grid
def restore_frozen_screen():
for window in _edit_windows():
grid = frozen_screen.get(window.name)
if not grid:
continue
win = window.window
try:
win.erase()
except curses.error:
pass
for y, row in enumerate(grid):
for x, chtype in enumerate(row):
try:
win.addch(y, x, chtype)
except curses.error:
pass
try:
win.noutrefresh()
except curses.error:
pass
try:
curses.doupdate()
except curses.error:
pass
def snapshot_details_lines():
rows = []
grid = frozen_screen.get("DetailsWindow")
if not grid and DetailsWindow is not None:
capture_frozen_screen()
grid = frozen_screen.get("DetailsWindow")
if not grid:
return rows
start = 1 if DetailsWindow.ShowBorder == "Y" else 0
start_x = 1 if DetailsWindow.ShowBorder == "Y" else 0
end = min(start + DetailsWindow.DisplayRows, len(grid) - (1 if DetailsWindow.ShowBorder == "Y" else 0))
mac_re = re.compile(r"([0-9A-Fa-f]{2}(?::[0-9A-Fa-f]{2}){5})")
for y in range(start, end):
chars = []
for chtype in grid[y][start_x:]:
chars.append(chr(chtype & 0xFF) if (chtype & 0xFF) >= 32 else " ")
text = "".join(chars).rstrip()
if not text.strip():
continue
match = mac_re.search(text)
mac = normalize_mac(match.group(1)) if match else None
info = last_packet_by_mac.get(mac, {}) if mac else {}
rows.append({"row": y, "text": text, "mac": mac, "info": info})
return rows
def _draw_edit_cursor(old_index, new_index):
restore_frozen_screen()
if edit_snapshot and 0 <= new_index < len(edit_snapshot):
DetailsWindow.highlight_row(edit_snapshot[new_index]["row"], enable=True, Color=3)
def _centered_window(height, width):
height = min(height, max(3, curses.LINES - 2))
width = min(width, max(20, curses.COLS - 4))
y = max(0, (curses.LINES - height) // 2)
x = max(0, (curses.COLS - width) // 2)
win = curses.newwin(height, width, y, x)
win.bkgd(" ", curses.color_pair(7))
win.box()
return win, height, width
def dismiss_edit_overlay():
global edit_overlay
if edit_overlay is not None:
try:
edit_overlay.erase()
edit_overlay.refresh()
except Exception:
pass
edit_overlay = None
restore_frozen_screen()
if edit_mode and edit_snapshot:
DetailsWindow.highlight_row(edit_snapshot[edit_cursor_index]["row"], enable=True, Color=3)
def get_curses_key(win=None, timeout_ms=-1):
"""Read one decoded curses key. Arrow keys arrive as KEY_UP/KEY_DOWN, not ESC."""
global curses_stdscr
target = win if win is not None else curses_stdscr
if target is None:
key = get_keypress(timeout=None if timeout_ms < 0 else timeout_ms / 1000.0)
if key in UP_KEYS:
return curses.KEY_UP
if key in DOWN_KEYS:
return curses.KEY_DOWN
if key in ENTER_KEYS:
return curses.KEY_ENTER
if key in ESC_KEYS:
return 27
if key:
return ord(key[0])
return -1
target.keypad(True)
target.timeout(timeout_ms)
target.nodelay(False)
try:
return target.getch()
finally:
if curses_stdscr is not None:
curses_stdscr.nodelay(1)
def _popup_message(text):
global edit_overlay
dismiss_edit_overlay()
win, height, width = _centered_window(5, min(70, curses.COLS - 4))
try:
win.addstr(2, 2, text[: width - 4])
except curses.error:
pass
win.refresh()
edit_overlay = win
def prompt_device_name(default_name):
default_name = (default_name or "device").strip()
win, height, width = _centered_window(7, min(64, curses.COLS - 4))
win.addstr(1, 2, "Friendly name (Enter keeps default)")
win.addstr(2, 2, f"Default: {default_name[: width - 12]}")
win.addstr(4, 2, "> ")
win.refresh()
curses.echo()
curses.curs_set(1)
try:
raw = win.getstr(4, 4, max(8, width - 8))
if isinstance(raw, bytes):
raw = raw.decode("utf-8", "replace")
name = raw.strip()
return name if name else default_name
except curses.error:
return default_name
finally:
curses.noecho()
curses.curs_set(0)
del win
restore_frozen_screen()
def choose_classification():
options = CLASSIFICATIONS + ["Cancel"]
selected = 0
win, height, width = _centered_window(len(options) + 4, 42)
while True:
win.erase()
win.box()
win.addstr(1, 2, "Classify device (Enter/Esc)")
for i, option in enumerate(options):
marker = ">" if i == selected else " "
attr = curses.A_REVERSE if i == selected else curses.A_NORMAL
try:
win.addstr(i + 2, 2, f"{marker} {option}".ljust(width - 4), attr)
except curses.error:
pass
win.refresh()
key = get_curses_key(win)
if key in (curses.KEY_UP,):
selected = (selected - 1) % len(options)
elif key in (curses.KEY_DOWN,):
selected = (selected + 1) % len(options)
elif key in (curses.KEY_ENTER, 10, 13):
choice = options[selected]
del win
restore_frozen_screen()
return None if choice == "Cancel" else choice
elif key in (27, ord("q")):
del win
restore_frozen_screen()
return None
def save_friendly_devices_dict(filename, devices):
with open(filename, "w") as json_file:
json.dump(devices, json_file, indent=2)
def add_or_update_friendly_device(mac, friendly_name, device_type, brand, ie_hash=None, probe_ssids=None):
global friendly_devices_dict
mac = normalize_mac(mac) if mac else None
devices = list(friendly_devices_dict or [])
history = probe_history.get(mac, {}) if mac else {}
ie_hash = ie_hash or history.get("ie_hash")
ssids = set(probe_ssids or []) | set(history.get("ssids") or [])
target = None
for device in devices:
if mac and mac in _device_macs(device):
target = device
break
if ie_hash and device.get("IEHash") == ie_hash:
target = device
break
if target is None:
target = {
"MAC": mac,
"MACs": [mac] if mac else [],
"FriendlyName": friendly_name,
"Type": device_type,
"Brand": brand,
}
devices.append(target)
updated = False
else:
target["FriendlyName"] = friendly_name
target["Type"] = device_type
target["Brand"] = brand
if mac:
target["MAC"] = mac
known = list(target.get("MACs") or [])
if mac not in {normalize_mac(m) for m in known if m}:
known.append(mac)
target["MACs"] = known
updated = True
if ie_hash:
target["IEHash"] = ie_hash
if ssids:
merged = list(dict.fromkeys((target.get("ProbeSSIDs") or []) + sorted(ssids)))
target["ProbeSSIDs"] = merged
friendly_devices_dict = devices
save_friendly_devices_dict(FRIENDLY_DEVICES_FILE, devices)
return updated
def classify_selected_line():
global friendly_key_count
if not edit_snapshot:
return
item = edit_snapshot[edit_cursor_index]
mac = item.get("mac")
if not mac:
_popup_message("No MAC address on this line.")
return
info = item.get("info") or last_packet_by_mac.get(mac, {})
classification = choose_classification()
if not classification:
return
default_name = info.get("FriendlyName") or info.get("SSID") or info.get("Brand") or mac
if default_name in (None, "", "??"):
default_name = mac
ie_hash = info.get("IEHash")
probe_ssids = info.get("ProbeSSIDs") or []
if classification == "Friendly":
friendly_name = prompt_device_name(str(default_name))
device_type = info.get("DeviceType") or info.get("Type") or "Friendly"
brand = info.get("Brand") or ""
add_or_update_friendly_device(mac, friendly_name, device_type, brand, ie_hash=ie_hash, probe_ssids=probe_ssids)
extra = f" hash={ie_hash}" if ie_hash else ""
_popup_message(f"Added {friendly_name}{extra}")
else:
friendly_name = str(default_name)
brand = info.get("Brand") or ""
add_or_update_friendly_device(mac, friendly_name, classification, brand, ie_hash=ie_hash, probe_ssids=probe_ssids)
_popup_message(f"{mac} classified as {classification}")
friendly_key_count = len(friendly_devices_dict or [])
def run_edit_mode():
global edit_mode, edit_cursor_index, edit_snapshot
if not curses_enabled or DetailsWindow is None or edit_mode:
return
edit_mode = True
_set_windows_frozen(True)
capture_frozen_screen()
edit_snapshot = snapshot_details_lines()
if not edit_snapshot:
_set_windows_frozen(False)
edit_mode = False
log_message("EDIT MODE: no device lines to select", StatusWindow)
return
edit_cursor_index = 0
_draw_edit_cursor(0, 0)
try:
while True:
key = get_curses_key()
if key in (-1,):
continue
if key == curses.KEY_UP:
if edit_overlay is not None:
dismiss_edit_overlay()
new_index = (edit_cursor_index - 1) % len(edit_snapshot)
_draw_edit_cursor(edit_cursor_index, new_index)
edit_cursor_index = new_index
elif key == curses.KEY_DOWN:
if edit_overlay is not None:
dismiss_edit_overlay()
new_index = (edit_cursor_index + 1) % len(edit_snapshot)
_draw_edit_cursor(edit_cursor_index, new_index)
edit_cursor_index = new_index
elif key in (curses.KEY_ENTER, 10, 13):
restore_frozen_screen()
classify_selected_line()
elif key in (curses.KEY_F1, ord("?")):
show_keyboard_help()
elif key in (27, ord("q"), ord("E"), ord("e")):
break
finally:
dismiss_edit_overlay()
restore_frozen_screen()
_set_windows_frozen(False)
edit_mode = False
_restore_curses_input()
def get_keypress(timeout=None):
"""Read a single keypress, including function and arrow keys."""
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
if timeout is not None:
ready, _, _ = select.select([fd], [], [], timeout)
if not ready:
return ""
key = sys.stdin.read(1)
if key != "\x1b":
return key
sequence = key
while True:
ready, _, _ = select.select([fd], [], [], 0.05)
if not ready:
break
sequence += sys.stdin.read(1)
if sequence[-1].isalpha() or sequence[-1] == "~":
break
return sequence
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
def _cache_settings_path():
base = os.path.dirname(os.path.abspath(PacketDB)) if PacketDB else os.getcwd()
if not base:
base = os.getcwd()
return os.path.join(base, CACHE_SETTINGS_FILE)
def apply_packet_cache_settings(ttl_seconds, maxsize, *, reason=""):
"""Rebuild the packet duplicate TTL cache if Central sent new values."""
global displayed_packets_cache, packet_cache_ttl, packet_cache_maxsize, key_count
try:
ttl_seconds = int(ttl_seconds)
maxsize = int(maxsize)
except (TypeError, ValueError):
return False
ttl_seconds = max(30, min(ttl_seconds, 86400))
maxsize = max(100, min(maxsize, 1000000))
if ttl_seconds == packet_cache_ttl and maxsize == packet_cache_maxsize:
return False
with cache_lock:
displayed_packets_cache = TTLCache(maxsize=maxsize, ttl=ttl_seconds)
packet_cache_ttl = ttl_seconds
packet_cache_maxsize = maxsize
key_count = 0
msg = f"Packet cache from Central: {ttl_seconds}s window, {maxsize} keys"
if reason:
msg = f"{msg} ({reason})"
try:
if curses_enabled and InfoWindow:
InfoWindow.QueuePrint(msg, Color=5)
else:
log_message(msg, ShowTime=True)
except Exception:
pass
return True
def _central_base_urls():
urls = []
env = (os.environ.get("SENTINEL_CENTRAL_URL") or "").strip()
if env:
urls.append(env.rstrip("/"))
path = os.path.join(os.path.dirname(_cache_settings_path()), CENTRAL_URL_FILE)
try:
with open(path, encoding="utf-8") as handle:
for line in handle:
line = line.strip()
if line and not line.startswith("#"):
urls.append(line.rstrip("/"))
except OSError:
pass
seen = set()
unique = []
for url in urls:
if url not in seen:
seen.add(url)
unique.append(url)
return unique
def _fetch_cache_settings_http():
global _cache_settings_etag
name = (os.environ.get("SENTINEL_CLIENT_NAME") or "").strip()
name_file = os.path.join(os.path.dirname(_cache_settings_path()), "client-name.txt")
if not name:
try:
with open(name_file, encoding="utf-8") as handle:
name = handle.read().strip()
except OSError:
name = ""
query = f"?name={urllib.parse.quote(name)}" if name else ""
for base in _central_base_urls():
url = base + "/api/sensor-cache" + query
try:
req = urllib.request.Request(url, headers={"User-Agent": "Sentinel-sensor"})
with urllib.request.urlopen(req, timeout=3) as resp:
data = json.loads(resp.read().decode("utf-8"))
except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, json.JSONDecodeError, ValueError):
continue
if not isinstance(data, dict):
continue
etag = (
str(data.get("packet_cache_ttl_seconds")),
str(data.get("packet_cache_maxsize")),
str(data.get("updated_at") or ""),
)
if etag == _cache_settings_etag:
return
_cache_settings_etag = etag
apply_packet_cache_settings(
data.get("packet_cache_ttl_seconds", packet_cache_ttl),
data.get("packet_cache_maxsize", packet_cache_maxsize),
reason=base,
)
return
def maybe_reload_cache_settings():
"""Load packet-cache TTL from Central (local JSON, else HTTP)."""
global _cache_settings_mtime
path = _cache_settings_path()
loaded_file = False
try:
mtime = os.path.getmtime(path)
with open(path, encoding="utf-8") as handle:
data = json.load(handle)
if _cache_settings_mtime is None or mtime != _cache_settings_mtime:
_cache_settings_mtime = mtime
if isinstance(data, dict):
apply_packet_cache_settings(
data.get("packet_cache_ttl_seconds", packet_cache_ttl),
data.get("packet_cache_maxsize", packet_cache_maxsize),
reason=os.path.basename(path),
)
loaded_file = True
except (OSError, json.JSONDecodeError, TypeError, ValueError):
pass
if not loaded_file:
_fetch_cache_settings_http()
def DisplayHeader():
global HeaderWindow
global StatusWindow
global PacketWindow
global InfoWindow