-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsentinel.py
3160 lines (2297 loc) · 106 KB
/
sentinel.py
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.
'''
import curses
import queue
import textwindows
import time
import os
import sqlite3
from datetime import datetime # Import only what's needed for clarity
import csv
import subprocess
import re
import json
from collections import Counter, defaultdict
import gps
import inspect
from functools import wraps
from cachetools import TTLCache
import termios, tty, sys
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
#Packet Stuff
current_channel_info = {"channel": None, "band": None, "frequency": None}
displayed_packets_cache = TTLCache(maxsize=10000, ttl=900) #entry expires after 15 minutes
friendly_device_cache = TTLCache(maxsize=10000, ttl=3600) #entry expires after 1 hour
key_count = 0
friendly_devices_dict = None
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 --
#------------------------------------------------------------------------------
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 (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 get_keypress():
"""Read a single keypress without clearing the screen."""
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(fd)
key = sys.stdin.read(1)
if key == '\x1b': # Escape character
key += sys.stdin.read(2) # Read additional characters
finally:
termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
return key
def DisplayHeader():
global HeaderWindow
global StatusWindow
global PacketWindow
global InfoWindow
global DetailsWindow
global RawWindow
global HeaderLines
global oui_dict
global friendly_devices_dict
global current_channel_info
global displayed_packets_cache
global friendly_device_cache
global key_count
global PacketCount
global friendly_key_count
global DBQueue
global PacketsSavedToDBCount
global gps_lock
global gps_data
global console_region
global show_friendly
global ProcessedPacket
try:
#-------------------------------
#-- Update Header
#-------------------------------
band = str(current_channel_info.get('band','0') if current_channel_info else '0')
channel = str(current_channel_info.get('channel','0') if current_channel_info else '0')
packetqueue_size = PacketQueue.qsize()
dbqueue_size = DBQueue.qsize()
# Pre-process values for formatting
packet_count = str(PacketCount)[:8]
friendly = 'Yes' if show_friendly else 'No'
routers = 'Yes' if show_routers else 'No'
time_display = datetime.now().replace(microsecond=0)
latitude = str(current_latitude or "N/A"[:10])
longitude = str(current_longitude or "N/A"[:10])
filler = " "
if current_gpstime:
#convert GPS UTC time to local time
utc_time = datetime.strptime(current_gpstime, "%Y-%m-%dT%H:%M:%S.%fZ")
utc_time = utc_zone.localize(utc_time)
local_time = utc_time.astimezone(local_zone)
thegpsdate = local_time.strftime("%Y-%m-%d %H:%M:%S")
else:
thegpsdate = None
# Define the HeaderLines dictionary with clean formatting
HeaderLines = {
1: f"Packets Processed: {packet_count:<12}" + filler + f"ShowFriendly: {friendly:<5}",
2: f"Band: {band:<12}" + filler + f"ShowRouters: {routers:<5}",
3: f"Channel: {channel:<12}" + filler,
4: f"Packet Queue Size: {packetqueue_size:<12}" + filler,
5: f"DB Queue Size: {dbqueue_size:<12}" + filler,
6: f"Packets Saved to DB: {PacketsSavedToDBCount:<12}" + filler,
7: f"Friendly Devices: {friendly_key_count:<12}" + filler,
8: f"Total Devices: {key_count:<12}" + filler,
9: f"Time: {time_display}" + filler,
10: f"Last GPS signal: {thegpsdate}" + filler,
11: f"Longitude: {longitude}" + filler,
12: f"Latitude: {latitude}" + filler
}
if curses_enabled:
HeaderWindow.set_fixed_lines(HeaderLines,Color=2)
else:
if (show_friendly == True) or (ProcessedPacket.FriendlyDevice == False ):
PrintConsoleHeader(HeaderLines,console_header_start_row)
except Exception as e:
TraceMessage = traceback.format_exc()
if curses_enabled:
InfoWindow.ErrorHandler(str(e), TraceMessage, "**Display Header Error**")
else:
ErrorHandler(TraceMessage)
def ProcessPacketInfo():
global HeaderWindow
global StatusWindow
global PacketWindow
global InfoWindow
global DetailsWindow
global RawWindow
global oui_dict
global friendly_devices_dict
global current_channel_info
global displayed_packets_cache
global friendly_device_cache
global key_count
global PacketCount
global friendly_key_count
global DBQueue
global PacketsSavedToDBCount
global gps_lock
global console_region
global show_friendly
global ProcessedPacket
global DeviceTypeDict
global RouterCount
global MobileCount
global OtherCount
channel = 0
band = 0
timestamp = datetime.now()
regular_color = Fore.GREEN
if not ProcessedPacket:
log_message("ProcessPacketInfo: There was no packet to process!")
return
# Create a unique key for the packet based on important fields
ProcessedPacket.source_mac, ProcessedPacket.ssid, ProcessedPacket.source_vendor, ProcessedPacket.DeviceType = replace_none_with_unknown(ProcessedPacket.source_mac, ProcessedPacket.ssid, ProcessedPacket.source_vendor, ProcessedPacket.DeviceType)
packet_key = (ProcessedPacket.source_mac, ProcessedPacket.ssid, ProcessedPacket.source_vendor, ProcessedPacket.DeviceType)
#Count number of different devices trackes during this session
RouterCount = 0
MobileCount = 0
OtherCount = 0
if PacketCount % HeaderUpdateSpeed == 0:
# Iterate through DeviceTypeDict once
for DeviceType, macs in DeviceTypeDict.items():
mac_count = len(macs)
if "ROUTER" in DeviceType.upper():
RouterCount += len(macs)
elif "MOBILE" in DeviceType.upper():
MobileCount += len(macs)
else:
OtherCount += len(macs)
#RouterCount = sum(len(macs) for DeviceType, macs in DeviceTypeDict.items() if 'ROUTER' in DeviceType.upper())
#MobileCount = sum(len(macs) for DeviceType, macs in DeviceTypeDict.items() if 'MOBILE' in DeviceType.upper())
#OtherCount = sum(len(macs) for DeviceType, macs in DeviceTypeDict.items()) - RouterCount - MobileCount
max_length = max(len(str(count)) for count in [RouterCount, MobileCount, OtherCount])
if(not curses_enabled):
console_region.print_large(f"Routers: {RouterCount:>{max_length}}", font="pagga", color=Fore.YELLOW, start_row=5, start_col=70)
console_region.print_large(f"Mobile: {MobileCount:>{max_length}}", font="pagga", color=Fore.YELLOW, start_row=8, start_col=70)
console_region.print_large(f"Other: {OtherCount:>{max_length}}", font="pagga", color=Fore.YELLOW, start_row=11, start_col=70)
#Check for friendly device
result = search_friendly_devices(ProcessedPacket.source_mac,friendly_devices_dict)
if result:
ProcessedPacket.FriendlyDevice = True
ProcessedPacket.FriendlyName = result.get('FriendlyName', '') or ''
ProcessedPacket.FriendlyType = result.get('Type','') or ''
ProcessedPacket.FriendlyBrand = result.get('Brand','') or ''
# Create a unique key for the friendly packet based on important fields
friendly_device_key = (ProcessedPacket.FriendlyName, ProcessedPacket.FriendlyType)
#add to cache
friendly_device_cache[friendly_device_key] = True
friendly_key_count = len(friendly_device_cache)
# To declutter the screen we don't display items that are in the cache
# the cache expires after X minutes
if packet_key not in displayed_packets_cache:
#add to cache
displayed_packets_cache[packet_key] = True
key_count = len(displayed_packets_cache)
#DetailsWindow.QueuePrint(f"{key_count} - {FriendlyName} - {FriendlyType} - {FriendlyBrand} - {ssid}")
if curses_enabled:
if show_friendly and ProcessedPacket.FriendlyDevice == True:
NameString = f"{str(ProcessedPacket.FriendlyName)} - {str(ProcessedPacket.FriendlyType)}"
FormattedString = format_into_columns(DetailsWindow.columns,
f"{NameString[:30]:<30}",
ProcessedPacket.source_mac,
ProcessedPacket.FriendlyBrand,
ProcessedPacket.ssid,
(f"{ProcessedPacket.band} {ProcessedPacket.channel} {ProcessedPacket.signal}dB"))
DetailsWindow.QueuePrint(FormattedString)
else:
NameString = f"{str(ProcessedPacket.FriendlyName)} - {str(ProcessedPacket.FriendlyType)}"
#Format a string for the Detail Window display
FormattedString = format_into_columns(
DetailsWindow.columns,
f"{NameString[:30]:<30}",
(ProcessedPacket.source_mac if (ProcessedPacket.source_mac != 'UNKNOWN' and ProcessedPacket.source_mac is not None) else ProcessedPacket.source_oui) ,
f"{ProcessedPacket.source_vendor} {ProcessedPacket.source_oui}",
ProcessedPacket.ssid,
(f"{ProcessedPacket.band} {ProcessedPacket.channel} {ProcessedPacket.signal}dB")
)
DetailsWindow.QueuePrint(FormattedString,Color=3)
#Show details in the Info window
InfoWindow.QueuePrint('INTRUDER DETAILS',Color=1)
InfoWindow.QueuePrint(f'CaptureDate: {timestamp}')
InfoWindow.QueuePrint(f'FriendlyName: {ProcessedPacket.FriendlyName}')
InfoWindow.QueuePrint(f'FriendlyType: {ProcessedPacket.FriendlyType}')
InfoWindow.QueuePrint(f'PacketType: {ProcessedPacket.PacketType}')
InfoWindow.QueuePrint(f'DeviceType: {ProcessedPacket.DeviceType}')
InfoWindow.QueuePrint(f'Source MAC: {ProcessedPacket.source_mac}')
InfoWindow.QueuePrint(f'Source Vendor: {ProcessedPacket.source_vendor}')
InfoWindow.QueuePrint(f'Dest MAC: {ProcessedPacket.dest_mac}')
InfoWindow.QueuePrint(f'Dest Vendor: {ProcessedPacket.dest_vendor}')
InfoWindow.QueuePrint(f'SSID: {ProcessedPacket.ssid}')
InfoWindow.QueuePrint(f'Band: {ProcessedPacket.band}')
InfoWindow.QueuePrint(f'channel: {ProcessedPacket.channel}')
InfoWindow.QueuePrint(f'signal: {ProcessedPacket.signal} dB')
InfoWindow.QueuePrint('---------------------------------------------------')
#--------------------------------------
#-- Save processed packet to DB Queue
#--------------------------------------
# For now we save Intruder details to the database
DBPacket = {
'CaptureDate' : ProcessedPacket.timestamp,
'FriendlyName': ProcessedPacket.FriendlyName,
'FriendlyType': ProcessedPacket.FriendlyType,
'PacketType' : ProcessedPacket.PacketType,
'DeviceType' : ProcessedPacket.DeviceType,
'SourceMAC' : ProcessedPacket.source_mac,
'SourceVendor': ProcessedPacket.source_vendor,
'DestMAC' : ProcessedPacket.dest_mac,
'DestVendor' : ProcessedPacket.dest_vendor,
'SSID' : ProcessedPacket.ssid,
'Band' : ProcessedPacket.band,
'Channel' : ProcessedPacket.channel,
'Latitude' : ProcessedPacket.latitude,
'Longitude' : ProcessedPacket.longitude,
'Signal' : ProcessedPacket.signal
}
DBQueue.put(DBPacket)
#insert_packet(DBPacket, db_path=PacketDB)
#print a row of activity to the console print region
color = Fore.GREEN
if (curses_enabled == False) and (show_friendly == True or (show_friendly == False and ProcessedPacket.FriendlyName == None)):
# Create a dense single-line string for console output
if ProcessedPacket.FriendlyName == None:
ProcessedPacket.FriendlyName = '??'
regular_color = Fore.LIGHTRED_EX
if band == None:
band = '??'
BandSignal = f"{ProcessedPacket.band} {ProcessedPacket.channel} {ProcessedPacket.signal}dB | "
ProcessedPacket.PacketType = ProcessedPacket.PacketType.replace("802.11","")
console_output = (
#f"{str(PacketCount)[:8]:<8} "
f"{str(timestamp)[11:19]:<8} "
f"{ProcessedPacket.FriendlyName[:15]:<15} "
f"{ProcessedPacket.PacketType[:15]:<15} "
f"{ProcessedPacket.DeviceType[:15]:<15} "
f"{ProcessedPacket.source_mac[:17]:<17} "
f"{ProcessedPacket.source_vendor[:20]:<20} "
f"{ProcessedPacket.ssid or 'N/A'[:15]:<15} "
f"{BandSignal[:15]:<15} "
#f"{current_latitude or 'N/A'[:10]:<10} | "
#f"{current_longitude or 'N/A'[:10]:<10}"
)
# We will ignore RadioTap packets for now
#if (packet.haslayer(RadioTap)):
# radiotap_header = packet[RadioTap]
# #Print the Radiotap header details
# print(radiotap_header.show())
# # Access the presence mask
# presence_mask = radiotap_header.present
# print(f"Presence Mask: {presence_mask}")
# return
#if ('UNKNOWN' not in ProcessedPacket.source_mac):
console_region.region_print_line(console_output,highlight_color=Fore.WHITE, regular_color=regular_color)
def get_curses_color_pair(fore_color):
color_map = {
Fore.RED: 1, # Maps to curses color pair 1 (COLOR_RED on COLOR_BLACK)
Fore.GREEN: 2, # Maps to curses color pair 2 (COLOR_GREEN on COLOR_BLACK)
Fore.YELLOW: 3, # Maps to curses color pair 3 (COLOR_YELLOW on COLOR_BLACK)
Fore.BLUE: 4, # Maps to curses color pair 4 (COLOR_BLUE on COLOR_BLACK)
Fore.MAGENTA: 5, # Maps to curses color pair 5 (COLOR_MAGENTA on COLOR_BLACK)
Fore.CYAN: 6, # Maps to curses color pair 6 (COLOR_CYAN on COLOR_BLACK)
Fore.WHITE: 7, # Maps to curses color pair 7 (COLOR_WHITE on COLOR_BLACK)
Fore.RESET: 0 # Default/reset color (no color pair applied)
}
# Return the corresponding color pair or default to 0 if not found
return color_map.get(fore_color, 2)
def log_message(message, window=None,color=2,ShowTime=None):
"""Logs a message using curses or standard print."""
if isinstance(color, str):
color = get_curses_color_pair(color)
if ShowTime:
message = f"{str(datetime.now())[11:19]:<8} - {message}"
try:
if curses_enabled:
if window:
window.QueuePrint(message,Color=color)
else:
InfoWindow.QueuePrint(message,Color=color)
else:
console_region.region_print_line(message)
except Exception as e:
# Fallback to standard print if all else fails
print(f"Error logging message: {e}")
print(message)
class PacketInformation():
def __init__(self):
self.source_mac = 'UNKNOWN'
self.dest_mac = 'UNKNOWN'
self.source_vendor = ''
self.dest_vendor = ''
self.source_oui = ''
self.ssid = ''
self.DeviceType = ''
self.PacketType = ''
self.signal = None
self.channel = 0
self.band = 0
self.timestamp = datetime.now()
self.FriendlyDevice = False
self.FriendlyName = None
self.FriendlyType = None
self.FriendlyBrand = None
self.latitude = None
self.longitude = None
self.packet_layers = None
self.packet_info = None
self.packet_details = None
self.mac_details = None
self.Packet = None
self.PacketType = None
def initialize_console_region(start_row, stop_row):
"""
Initialize the global console region with specified start and end rows.
Parameters:
start_row (int): The starting row of the region.
stop_row (int): The ending row of the region.
"""
print("Setting up the console region")
global console_region
console_region = ConsoleRegion(start_row, stop_row)
class ConsoleRegion:
def __init__(self, start_row, stop_row, default_color=Fore.GREEN):
"""
Initialize a console region for printing.
Parameters:
start_row (int): The starting row of the region.
stop_row (int): The ending row of the region.
default_color (str): The default color for printing text.
"""
self.title_row = start_row
self.start_row = start_row + 1
self.stop_row = stop_row
self.current_row = self.start_row
self.previous_row = start_row + 1
self.previous_text = ''
self.previous_color = default_color
self.current_color = default_color # Store the current color
def region_print_line(self, text, align="left", highlight_color=Fore.WHITE,regular_color=Fore.GREEN):
"""
Print a string to the next line in the region, resetting the previous line.
Parameters:
text (str): The text to print.
align (str): Text alignment ('left', 'center', 'right').
color (str): The color to use for this print. Defaults to the last used color.
"""
global console_width # Assuming console_width is defined globally
color = highlight_color or regular_color # Use provided color or fallback to remembered color
self.current_color = color # Remember this color for subsequent prints
# Adjust text alignment
if align == "center":
text = text.center(console_width)
elif align == "right":
text = text.rjust(console_width)
else:
text = text.ljust(console_width)
# Truncate text if it exceeds console width
text = text[:console_width]
# Reset the previous line if it's within bounds
if hasattr(self, "previous_row") and self.previous_row:
print(self.previous_color, end="", flush=True)
print(f"\033[{self.previous_row};1H{self.previous_text}", end="")
print("\033[K", end="") # Clear the rest of the line
#Print the current line
#Current line is highlighted, then goes back to the regular color during the next print
print(highlight_color, end="", flush=True)
print(f"\033[{self.current_row};1H{text}", end="")
print("\033[K", end="") # Clear any leftover content on the line
print(Style.RESET_ALL, end="", flush=True) # Reset to default style
# Store the current line's information for resetting next time
self.previous_row = self.current_row
self.previous_text = text
self.previous_color = regular_color
# Increment the current row and wrap around if it exceeds the stop row
self.current_row += 1
if self.current_row > self.stop_row:
self.current_row = self.start_row
def print_line(self, text, align="left", line=0, color=None):
"""
Print a string to the specified line in the region.
Parameters:
text (str): The text to print.
align (str): Text alignment ('left', 'center', 'right').
line (int): The line to print to (absolute row number).
color (str): The color to use for this print. Defaults to the last used color.
"""
global console_width # Assuming console_width is defined globally
color = color or self.current_color # Use provided color or fallback to remembered color
self.current_color = color # Remember this color for subsequent prints
# Adjust text alignment
if align == "center":
text = text.center(console_width)
elif align == "right":
text = text.rjust(console_width)
else:
text = text.ljust(console_width)
# Truncate text if it exceeds console width
text = text[:console_width]
# Print the specified line
print(color, end="", flush=True)
print(f"\033[{line};1H{text}", end="")
print("\033[K", end="") # Clear any leftover content on the line
print(Style.RESET_ALL, end="", flush=True) # Reset to default style
def print_large(self, number, font="pagga", color=None, start_row=None, start_col=1):
"""
Print a large-format number in the specified region using pyfiglet.
Parameters:
number (str): The number to print.
font (str): The pyfiglet font to use.
color (str): The color to use for the text.
start_row (int): The starting row for the ASCII art.
start_col (int): The starting column for the ASCII art.
"""
color = color or self.current_color # Use provided text color or fallback to remembered color
self.current_color = color # Remember the current text color
# Generate the ASCII art
figlet = pyfiglet.Figlet(font=font)
ascii_art = figlet.renderText(str(number))
# Split the ASCII art into lines
lines = ascii_art.splitlines()
# Determine starting row
start_row = start_row or self.start_row
# Print each line in the correct position
for i, line in enumerate(lines):
row = start_row + i
if row > self.stop_row: # Stop if exceeding the region
break
print(color, end="", flush=True)
print(f"\033[{row};{start_col}H{line}", end="")
print(Style.RESET_ALL, end="", flush=True) # Reset style after each line
def ErrorHandler(ErrorMessage='',TraceMessage='',AdditionalInfo=''):
os.system("stty sane")
CallingFunction = inspect.stack()[1][3]
#FinalCleanup(stdscr)
print("")
print("")
print("--------------------------------------------------------------")
print("ERROR - Function (",CallingFunction, ") has encountered an error. ")
print(ErrorMessage)
print("")
print("")
print("TRACE")
print(TraceMessage)
print("")
print("")
if (AdditionalInfo != ""):
print("Additonal info:",AdditionalInfo)
print("")
print("")
print("--------------------------------------------------------------")
print("")
print("")
def identify_packet_type(packet):
"""
Identifies the type of packet and returns a string indicating the protocol.
:param packet: Scapy packet object to be analyzed.
:return: A string representing the identified packet type.
"""