-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathairdetect.py
More file actions
executable file
·3492 lines (2976 loc) · 143 KB
/
Copy pathairdetect.py
File metadata and controls
executable file
·3492 lines (2976 loc) · 143 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
"""
Wi-Fi AP Security Scanner (passive)
Detects WLAN security characteristics without associating to the AP by
sniffing beacon and probe response frames (and optionally observing EAPOL
handshakes if they happen on-air). Reports:
• SSID / BSSID
• WPA/WPA2/WPA3/OWE vs WEP/Open (based on RSN & WPA IEs)
• Pairwise & group ciphers
• AKM suites (PSK, 802.1X, SAE, FT, OWE, …)
• PMF/802.11w: capable/required
• 802.11r presence (via FT AKMs)
• Whether a 4-Way Handshake was OBSERVED (passively) for that BSSID
Requirements:
• Linux with a wireless interface in monitor mode (e.g. wlan0mon)
• Python 3.8+
• scapy 2.5+ (pip install scapy)
Usage examples:
sudo ./wifi_ap_security_scanner.py -i wlan0mon -t 30
sudo ./wifi_ap_security_scanner.py -i wlan0mon --eapol --channel 36 -t 60
./wifi_ap_security_scanner.py -r capture.pcap
Notes:
• This tool is passive. It does not transmit or attempt to authenticate.
• "Handshake observed" becomes true only if a client happens to (re)connect
while you are listening — this is informational and not required to
assess AP capabilities.
• For best results, scan several tens of seconds across relevant channels.
"""
from __future__ import annotations
import argparse
import binascii
import os
import struct
import sys
from collections import defaultdict
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Set, Tuple
# Version
VERSION = "1.0.1"
try:
from scapy.all import ( # type: ignore
Dot11,
Dot11Beacon,
Dot11ProbeResp,
Dot11Elt,
EAPOL,
RadioTap,
sniff,
rdpcap,
)
except Exception as e: # pragma: no cover
print("[!] Failed to import scapy. Install with: pip install scapy", file=sys.stderr)
raise
# Try to import CoreWLAN for macOS support
COREWLAN_AVAILABLE = False
if sys.platform == 'darwin':
try:
import CoreWLAN
import CoreLocation
COREWLAN_AVAILABLE = True
except ImportError:
pass # CoreWLAN not available, will fall back to Scapy
# ------------------------------
# ANSI Color Codes
# ------------------------------
class Colors:
"""ANSI color codes for terminal output."""
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
# Signal strength colors (for row-based coloring)
STRONG_SIGNAL = '\033[92m' # Green (≥-60dBm)
MEDIUM_SIGNAL = '\033[93m' # Yellow (-60 to -70dBm)
POOR_SIGNAL = '\033[95m' # Purple/Magenta (-70 to -80dBm)
WEAK_SIGNAL = '\033[91m' # Red (<-80dBm)
# Security colors
WPA3 = '\033[92m' # Green - most secure
WPA2 = '\033[96m' # Cyan - secure
WPA = '\033[93m' # Yellow - less secure
WEP = '\033[91m' # Red - insecure
OPEN = '\033[91m' # Red - insecure
OWE = '\033[92m' # Green - enhanced open
# Feature colors
VENDOR = '\033[95m' # Magenta
SSID = '\033[96m' # Cyan
BSSID = '\033[94m' # Blue
# Visibility colors
GRAY = '\033[90m' # Gray - for invisible/offline APs
DIM = '\033[2m' # Dim text
# ------------------------------
# Helpers: Suite decoding
# ------------------------------
IEEE_OUI = b"\x00\x0F\xAC" # 00-0F-AC
MS_OUI = b"\x00\x50\xF2" # 00-50-F2 (legacy WPA v1 vendor IE)
WPS_OUI = b"\x00\x50\xF2\x04" # WPS Vendor IE
# Load vendor OUI database from external JSON file
def load_vendor_oui() -> Tuple[Dict[str, str], Dict[str, str]]:
"""Load the vendor database from oui-vendors.json (generated by getvendors.py).
Returns a tuple ``(vendor_db, prefix_db)`` where ``vendor_db`` maps 24-bit
OUIs (``XX:XX:XX``) to vendor names and ``prefix_db`` maps 28/36-bit
sub-block prefixes (hex nibbles, length encodes the mask) to vendor names.
"""
vendor_db = {}
prefix_db = {}
# Try to load from new comprehensive JSON file first
json_path = os.path.join(os.path.dirname(__file__), 'oui-vendors.json')
if os.path.exists(json_path):
try:
import json
with open(json_path, 'r') as f:
data = json.load(f)
# Skip metadata/private keys; get all 24-bit OUI entries
vendor_db = {k: v for k, v in data.items() if not k.startswith('_')}
# 28/36-bit sub-blocks live under _prefixes (may be absent)
prefix_db = data.get('_prefixes', {}) or {}
except Exception as e:
print(f"[!] Warning: Could not load oui-vendors.json: {e}", file=sys.stderr)
# Fallback to minimal built-in database if no file found
if not vendor_db:
vendor_db = {
"00:0C:43": "MediaTek",
"08:55:31": "Ubiquiti",
"0C:8E:29": "Cisco Meraki",
"18:A6:F7": "TP-Link",
"2C:91:AB": "TP-Link",
"84:A1:D1": "Sagemcom",
"A0:B5:49": "Cisco Meraki",
"B8:27:EB": "Raspberry Pi",
}
return vendor_db, prefix_db
# Load vendor database at module load time
VENDOR_OUI, VENDOR_PREFIXES = load_vendor_oui()
CIPHER_TYPES = {
# Per IEEE 802.11 (subset of the most common values)
0: "USE-GROUP",
1: "WEP-40",
2: "TKIP",
3: "WRAP",
4: "CCMP-128",
5: "WEP-104",
6: "BIP-CMAC-128", # management frame integrity (group mgmt)
8: "GCMP-128",
9: "GCMP-256",
10: "CCMP-256",
11: "BIP-GMAC-128",
12: "BIP-GMAC-256",
}
AKM_TYPES = {
# OUI 00-0F-AC (standards)
1: "802.1X",
2: "PSK",
3: "FT-802.1X", # 802.11r FT over 802.1X
4: "FT-PSK", # 802.11r FT over PSK
5: "802.1X-SHA256",
6: "PSK-SHA256",
7: "TDLS",
8: "SAE", # WPA3-Personal
9: "FT-SAE", # WPA3-Personal with FT
11: "802.1X-SuiteB-128",
12: "802.1X-SuiteB-192",
13: "802.1X-FT-SHA384",
18: "OWE", # Enhanced Open
# There are more; unknown values will be shown as numeric
}
# ------------------------------
# NEW: Helper functions
# ------------------------------
def get_row_color_by_rssi(rssi: Optional[int], is_visible: bool = True) -> str:
"""Get row color code based on RSSI strength for entire row coloring.
Returns ANSI color code for the entire row:
- Gray: AP not visible in last scan
- Green: Strong signal (≥ -60 dBm)
- Yellow: Good signal (-60 to -70 dBm)
- Purple: Weak signal (-70 to -80 dBm)
- Red: Very weak signal (< -80 dBm)
"""
if not is_visible:
return Colors.GRAY
if rssi is None:
return Colors.GRAY
if rssi >= -60:
return Colors.STRONG_SIGNAL # Green
elif rssi >= -70:
return Colors.MEDIUM_SIGNAL # Yellow
elif rssi >= -80:
return Colors.POOR_SIGNAL # Purple/Magenta
else:
return Colors.WEAK_SIGNAL # Red
def colorize_rssi(rssi: Optional[int], min_rssi: Optional[int] = None, max_rssi: Optional[int] = None) -> str:
"""Colorize RSSI value - now simplified for row-based coloring.
Format: -45dBm (without range, as it will go in separate column)
"""
if rssi is None:
return "-"
# Build base RSSI string (no range here - goes in separate Avg column)
rssi_str = f"{rssi}dBm"
return rssi_str
def colorize_security(sec_type: str) -> str:
"""Colorize security type based on security level."""
if "WPA3" in sec_type:
return f"{Colors.WPA3}{sec_type}{Colors.ENDC}"
elif "WPA2" in sec_type:
return f"{Colors.WPA2}{sec_type}{Colors.ENDC}"
elif "WPA" in sec_type:
return f"{Colors.WPA}{sec_type}{Colors.ENDC}"
elif sec_type == "WEP":
return f"{Colors.WEP}{sec_type}{Colors.ENDC}"
elif sec_type == "Open":
return f"{Colors.OPEN}{sec_type}{Colors.ENDC}"
elif sec_type == "OWE":
return f"{Colors.OWE}{sec_type}{Colors.ENDC}"
else:
return sec_type
def colorize_vendor(vendor: str) -> str:
"""Colorize vendor name."""
return f"{Colors.VENDOR}{vendor}{Colors.ENDC}"
def colorize_ssid(ssid: str, hidden: bool = False) -> str:
"""Colorize SSID."""
if hidden:
return f"{Colors.WARNING}<hidden>{Colors.ENDC}"
return f"{Colors.SSID}{ssid}{Colors.ENDC}"
def colorize_bssid(bssid: str) -> str:
"""Colorize BSSID."""
return f"{Colors.BSSID}{bssid}{Colors.ENDC}"
def get_vendor(bssid: str) -> str:
"""Lookup vendor from a BSSID using longest-prefix match.
Prefers 36-bit then 28-bit IEEE sub-block assignments (MA-S/MA-M) before
falling back to the 24-bit OUI, so sub-block owners resolve to the correct
vendor instead of the shared 24-bit registrant.
"""
hexb = ''.join(c for c in bssid if c in '0123456789abcdefABCDEF').upper()
# 36-bit (9 nibbles) then 28-bit (7 nibbles) sub-blocks, longest first
for n in (9, 7):
if len(hexb) >= n:
vendor = VENDOR_PREFIXES.get(hexb[:n])
if vendor:
return vendor
if len(hexb) >= 6:
return VENDOR_OUI.get(f"{hexb[0:2]}:{hexb[2:4]}:{hexb[4:6]}", "Unknown")
return "Unknown"
def get_band(channel: Optional[int]) -> Optional[str]:
"""Determine frequency band from channel number."""
if channel is None:
return None
if channel <= 14:
return "2.4 GHz"
elif channel <= 177:
return "5 GHz"
return "6 GHz"
def parse_wps_ie(payload: bytes) -> Dict:
"""Parse WPS vendor IE (ID 221, OUI 00:50:F2:04).
Returns dict with: enabled, locked, version, config_methods
"""
out = {"enabled": False, "locked": None, "version": None, "config_methods": None}
try:
if len(payload) < 4:
return out
if payload[:4] != WPS_OUI:
return out
out["enabled"] = True
pos = 4
# WPS uses TLV format: Type(2) + Length(2) + Value(Length)
while pos + 4 <= len(payload):
wps_type = struct.unpack(">H", payload[pos:pos+2])[0]
wps_len = struct.unpack(">H", payload[pos+2:pos+4])[0]
pos += 4
if pos + wps_len > len(payload):
break
wps_value = payload[pos:pos+wps_len]
pos += wps_len
# Type 0x1044 = WPS State
if wps_type == 0x1044 and wps_len == 1:
# 1 = Not configured, 2 = Configured
state = wps_value[0]
out["locked"] = (state == 2)
# Type 0x104A = Version
elif wps_type == 0x104A and wps_len == 1:
ver = wps_value[0]
out["version"] = f"{ver >> 4}.{ver & 0x0F}"
# Type 0x1008 = Config Methods
elif wps_type == 0x1008 and wps_len == 2:
methods = struct.unpack(">H", wps_value)[0]
out["config_methods"] = methods
except Exception:
pass
return out
@dataclass
class APInfo:
bssid: str
ssid: str = ""
channel: Optional[int] = None
privacy_bit: bool = False
rsn_present: bool = False
wpa1_present: bool = False
group_cipher: Optional[str] = None
pairwise_ciphers: Set[str] = field(default_factory=set)
akms: Set[str] = field(default_factory=set)
pmf_capable: Optional[bool] = None
pmf_required: Optional[bool] = None
ft_present: bool = False
owe_present: bool = False
handshake_observed: bool = False
# NEW FIELDS
rssi: Optional[int] = None # Current RSSI value
min_rssi: Optional[int] = None # Weakest RSSI seen
max_rssi: Optional[int] = None # Strongest RSSI seen
vendor: Optional[str] = None
wps_enabled: bool = False
wps_locked: Optional[bool] = None
wps_version: Optional[str] = None
hidden: bool = False
band: Optional[str] = None
channel_width: Optional[int] = None
rrm_enabled: bool = False # 802.11k
bss_transition: bool = False # 802.11v
beacon_interval: Optional[int] = None
deauth_count: int = 0
disassoc_count: int = 0
mode: Optional[str] = None # Infrastructure, Ad-hoc, etc.
rate: Optional[float] = None # Max rate in Mbit/s
# Tracking fields
ap_id: Optional[int] = None # Unique ID assigned at discovery
first_seen: Optional[float] = None # Timestamp when first discovered
last_seen: Optional[float] = None # Timestamp when last seen
currently_visible: bool = True # Whether AP is visible in current scan
rssi_history: List[Tuple[float, int]] = field(default_factory=list) # [(timestamp, rssi), ...]
def security_label(self) -> str:
"""Return simplified, user-friendly security label."""
if self.rsn_present:
# Determine security type based on AKMs
if "SAE" in self.akms or "FT-SAE" in self.akms:
if "PSK" in self.akms or "FT-PSK" in self.akms:
return "WPA3-Transition"
return "WPA3-Personal"
elif any(a.startswith("802.1X") or a == "FT-802.1X" or "SHA256" in a for a in self.akms):
return "WPA2-Enterprise"
elif "OWE" in self.akms:
return "OWE"
elif "PSK" in self.akms or "FT-PSK" in self.akms:
return "WPA2-Personal"
else:
return "WPA2"
elif self.wpa1_present:
return "WPA"
else:
if self.privacy_bit:
return "WEP"
return "Open"
# ------------------------------
# IE parsing
# ------------------------------
def _parse_suite(selector: bytes) -> Tuple[str, int]:
"""Return (OUI_string, suite_type)."""
if len(selector) != 4:
return (binascii.hexlify(selector).decode(), -1)
oui = selector[:3]
stype = selector[3]
return (":".join(f"{b:02x}" for b in oui), stype)
def _cipher_name(oui: bytes, stype: int) -> str:
if oui == IEEE_OUI:
return CIPHER_TYPES.get(stype, f"UNKNOWN({stype})")
elif oui == MS_OUI and stype == 2:
return "TKIP" # legacy mapping
return f"OUI-{binascii.hexlify(oui).decode()}:{stype}"
def _akm_name(oui: bytes, stype: int) -> str:
if oui == IEEE_OUI:
return AKM_TYPES.get(stype, f"AKM-{stype}")
return f"OUI-{binascii.hexlify(oui).decode()}:{stype}"
def parse_rsn_ie(payload: bytes) -> Dict:
"""Parse RSN (ID 48) information element.
Returns a dict with keys: group_cipher, pairwise_ciphers (set), akms (set),
pmf_capable(bool|None), pmf_required(bool|None), group_mgmt_cipher(optional)
"""
out = {
"group_cipher": None,
"pairwise_ciphers": set(),
"akms": set(),
"pmf_capable": None,
"pmf_required": None,
"group_mgmt_cipher": None,
}
try:
# Minimum: version(2) + group cipher(4) + pairwise count(2)
if len(payload) < 8:
return out
pos = 0
version, = struct.unpack_from("<H", payload, pos)
pos += 2
if version != 1:
return out
# Group cipher
gc_sel = payload[pos:pos+4]
pos += 4
oui, stype = gc_sel[:3], gc_sel[3]
out["group_cipher"] = _cipher_name(oui, stype)
# Pairwise cipher list
(pc_count,) = struct.unpack_from("<H", payload, pos)
pos += 2
for _ in range(pc_count):
sel = payload[pos:pos+4]
pos += 4
out["pairwise_ciphers"].add(_cipher_name(sel[:3], sel[3]))
# AKM list
if pos + 2 <= len(payload):
(akm_count,) = struct.unpack_from("<H", payload, pos)
pos += 2
for _ in range(akm_count):
sel = payload[pos:pos+4]
pos += 4
out["akms"].add(_akm_name(sel[:3], sel[3]))
# RSN Capabilities (2 bytes) — contains PMF bits
if pos + 2 <= len(payload):
(rsn_caps,) = struct.unpack_from("<H", payload, pos)
pos += 2
# Per Cisco/IEEE: bit6 = MFPR (required), bit7 = MFPC (capable)
out["pmf_required"] = bool(rsn_caps & (1 << 6))
out["pmf_capable"] = bool(rsn_caps & (1 << 7))
# PMKID count + list (optional)
if pos + 2 <= len(payload):
(pmkid_count,) = struct.unpack_from("<H", payload, pos)
pos += 2 + (16 * pmkid_count)
# Group Management Cipher (optional)
if pos + 4 <= len(payload):
sel = payload[pos:pos+4]
out["group_mgmt_cipher"] = _cipher_name(sel[:3], sel[3])
except Exception:
pass
return out
def parse_wpa1_vendor_ie(payload: bytes) -> Dict:
"""Parse old WPA v1 vendor IE (ID 221, OUI 00:50:F2, type=1)."""
out = {"present": False, "akms": set(), "pairwise_ciphers": set(), "group_cipher": None}
try:
# Expect: OUI(3) + type(1) == 1 + version(2) + group(4) + pairwise count(2) + list + akm count(2) + list
if len(payload) < 8:
return out
if payload[:3] != MS_OUI or payload[3] != 1:
return out
pos = 4
version, = struct.unpack_from("<H", payload, pos)
pos += 2
if version != 1:
return out
sel = payload[pos:pos+4]
pos += 4
out["group_cipher"] = _cipher_name(sel[:3], sel[3])
(pc_count,) = struct.unpack_from("<H", payload, pos)
pos += 2
for _ in range(pc_count):
sel = payload[pos:pos+4]
pos += 4
out["pairwise_ciphers"].add(_cipher_name(sel[:3], sel[3]))
if pos + 2 <= len(payload):
(akm_count,) = struct.unpack_from("<H", payload, pos)
pos += 2
for _ in range(akm_count):
sel = payload[pos:pos+4]
pos += 4
out["akms"].add(_akm_name(sel[:3], sel[3]))
out["present"] = True
except Exception:
pass
return out
# ------------------------------
# Sniffing / Processing
# ------------------------------
def extract_channel(pkt) -> Optional[int]:
# Try DS Parameter Set (ID 3) first; for 5/6GHz vendors often include HT/VHT/HE ops IEs, which we skip here.
ch = None
elt = pkt.firstlayer()
while elt and isinstance(elt, Dot11Elt):
if elt.ID == 3 and elt.len == 1:
ch = elt.info[0]
break
elt = elt.payload if isinstance(elt.payload, Dot11Elt) else None
return ch
def process_mgmt_frame(pkt, aps: Dict[str, APInfo]):
if not (pkt.haslayer(Dot11Beacon) or pkt.haslayer(Dot11ProbeResp)):
return
bssid = pkt[Dot11].addr3 or pkt[Dot11].addr2
if not bssid:
return
if bssid not in aps:
aps[bssid] = APInfo(bssid=bssid, vendor=get_vendor(bssid))
ap = aps[bssid]
# NEW: Extract RSSI from RadioTap
if pkt.haslayer(RadioTap):
try:
if hasattr(pkt[RadioTap], 'dBm_AntSignal'):
rssi = pkt[RadioTap].dBm_AntSignal
# Update RSSI (keep strongest signal)
if ap.rssi is None or rssi > ap.rssi:
ap.rssi = rssi
# Record RSSI history
ap.rssi_history.append((time.time(), rssi))
# Keep history limited to last 100 entries
if len(ap.rssi_history) > 100:
ap.rssi_history = ap.rssi_history[-100:]
except Exception:
pass
# SSID & channel
ssid = None
channel = extract_channel(pkt)
# NEW: Extract beacon interval
if pkt.haslayer(Dot11Beacon):
try:
ap.beacon_interval = pkt[Dot11Beacon].beacon_interval
except Exception:
pass
elt = pkt[Dot11Elt]
while isinstance(elt, Dot11Elt):
if elt.ID == 0: # SSID
try:
ssid = elt.info.decode(errors="ignore")
# NEW: Detect hidden SSID
if ssid == "" or len(elt.info) == 0:
ap.hidden = True
except Exception:
ssid = ""
ap.hidden = True
elif elt.ID == 48: # RSN
ap.rsn_present = True
rsn = parse_rsn_ie(bytes(elt.info))
ap.group_cipher = rsn.get("group_cipher") or ap.group_cipher
ap.pairwise_ciphers.update(rsn.get("pairwise_ciphers", []))
ap.akms.update(rsn.get("akms", []))
ap.pmf_capable = rsn.get("pmf_capable")
ap.pmf_required = rsn.get("pmf_required")
if "OWE" in ap.akms:
ap.owe_present = True
if any(a.startswith("FT-") for a in ap.akms):
ap.ft_present = True
elif elt.ID == 70: # RRM Enabled Capabilities (802.11k)
ap.rrm_enabled = True
elif elt.ID == 127: # Extended Capabilities (contains 802.11v BSS Transition)
try:
if len(elt.info) >= 3:
# Bit 19 (byte 2, bit 3) = BSS Transition
ap.bss_transition = bool(elt.info[2] & 0x08)
except Exception:
pass
elif elt.ID == 61: # HT Operation (channel width for 2.4/5GHz)
try:
if len(elt.info) >= 1:
# Bit 2 of byte 1: 0=20MHz, 1=40MHz
ap.channel_width = 40 if (elt.info[1] & 0x04) else 20
except Exception:
pass
elif elt.ID == 192: # VHT Operation (80/160MHz for 5GHz)
try:
if len(elt.info) >= 1:
ch_width = elt.info[0]
if ch_width == 1:
ap.channel_width = 80
elif ch_width in [2, 3]:
ap.channel_width = 160
except Exception:
pass
elif elt.ID == 221: # Vendor specific
payload = bytes(elt.info)
# Check for WPA v1
wpa = parse_wpa1_vendor_ie(payload)
if wpa.get("present"):
ap.wpa1_present = True
ap.group_cipher = ap.group_cipher or wpa.get("group_cipher")
ap.pairwise_ciphers.update(wpa.get("pairwise_ciphers", []))
ap.akms.update(wpa.get("akms", []))
# NEW: Check for WPS
wps = parse_wps_ie(payload)
if wps.get("enabled"):
ap.wps_enabled = True
ap.wps_locked = wps.get("locked")
ap.wps_version = wps.get("version")
elt = elt.payload if isinstance(elt.payload, Dot11Elt) else None
ap.channel = ap.channel or channel
# NEW: Set band based on channel
if ap.channel:
ap.band = get_band(ap.channel)
# Capability privacy bit (WEP indicator if RSN/WPA absent)
cap = None
if pkt.haslayer(Dot11Beacon):
cap = pkt[Dot11Beacon].cap
elif pkt.haslayer(Dot11ProbeResp):
cap = pkt[Dot11ProbeResp].cap
if cap is not None:
ap.privacy_bit = bool(cap & 0x0010)
if ssid is not None:
ap.ssid = ssid
def process_eapol(pkt, aps: Dict[str, APInfo]):
# Mark handshake observed for BSSID if we see EAPOL-Key frames
if not pkt.haslayer(EAPOL):
return
# Guess the BSSID as the transmitter or receiver if they are AP MACs
# In infrastructure BSS, addr2 is transmitter, addr1 is receiver, addr3 is BSSID.
bssid = pkt[Dot11].addr3
if bssid and bssid in aps:
aps[bssid].handshake_observed = True
def process_deauth_disassoc(pkt, aps: Dict[str, APInfo]):
"""Count deauth and disassociation frames (potential attack indicator)."""
if not pkt.haslayer(Dot11):
return
# Type 0 = Management, Subtype 12 = Deauth, Subtype 10 = Disassoc
if pkt.type == 0:
bssid = pkt[Dot11].addr3
if bssid and bssid in aps:
if pkt.subtype == 12: # Deauth
aps[bssid].deauth_count += 1
elif pkt.subtype == 10: # Disassoc
aps[bssid].disassoc_count += 1
# ------------------------------
# CLI
# ------------------------------
def clear_screen():
"""Clear the terminal screen."""
os.system('clear' if os.name == 'posix' else 'cls')
def move_cursor_up(lines: int):
"""Move terminal cursor up by N lines."""
print(f"\033[{lines}A", end='')
def clear_line():
"""Clear current line in terminal."""
print("\033[2K", end='')
def save_cursor_position():
"""Save current cursor position."""
print("\033[s", end='', flush=True)
def restore_cursor_position():
"""Restore saved cursor position."""
print("\033[u", end='', flush=True)
def get_report_line_count(aps: Dict[str, APInfo]) -> int:
"""Calculate how many lines the report will occupy."""
if not aps:
return 1 # "No APs discovered."
# Header lines: timestamp (1) + blank (1) + separator (1) + header (1) + separator (1) = 5
# AP entries: len(aps)
# Footer: separator (1) + blank (1) + Total APs (1) + WPS (1) + PMF (1) + WPA3 (1) + Hidden (1) = 7
# Potential deauth warning: 1 (if present)
base_lines = 5 + len(aps) + 7
# Check if deauth warning will be shown
deauth_aps = [ap for ap in aps.values() if ap.deauth_count > 10]
if deauth_aps:
base_lines += 1
return base_lines
def print_report(aps: Dict[str, APInfo], show_timestamp: bool = False, show_ids: bool = False, term_width: int = None, selected_index: int = -1, column_settings: dict = None, viewport_offset: int = 0, viewport_limit: int = None):
if not aps:
print("No APs discovered.")
return
# Default column settings if not provided
if column_settings is None:
column_settings = {
'bssid': True, 'rssi': True, 'avg': True, 'ch': True, 'band': True,
'rate_max': True, 'rate_real': True, 'ssid': True, 'vendor': True,
'security': True, 'features': True
}
# Sort by visibility first (visible APs first), then by RSSI (strongest signal first)
# Gray/invisible APs go to the bottom of the list
# Keep internal ID tracking for navigation, but always sort by visibility + RSSI strength
sorted_aps = sorted(
aps.items(),
key=lambda kv: (
not getattr(kv[1], 'currently_visible', True), # False (visible) sorts before True (invisible)
-(kv[1].rssi or -100), # Then by RSSI strength (strongest first)
kv[1].ssid, # Then by SSID
kv[0] # Finally by BSSID
)
)
# Show timestamp if in permanent mode
if show_timestamp:
import datetime
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"\n{Colors.BOLD}Last updated: {Colors.OKCYAN}{timestamp}{Colors.ENDC}")
# Calculate dynamic column widths based on terminal size
import shutil
if term_width is None:
terminal_width = shutil.get_terminal_size(fallback=(120, 24)).columns
else:
terminal_width = term_width
# Fixed column widths (ID column removed from display)
col_widths = {
'bssid': 17,
'rssi': 8,
'avg': 8,
'ch': 3,
'band': 8,
'rate_max': 10,
'rate_real': 10,
'security': 18
}
# Count enabled columns and calculate fixed space
enabled_cols = [k for k, v in column_settings.items() if v and k in col_widths]
num_separators = len(enabled_cols) + 2 # +2 for ssid, vendor (always count for spacing)
fixed_space = sum(col_widths[k] for k in enabled_cols) + (num_separators * 2)
# Available space for SSID, Vendor, and Features
available = max(40, terminal_width - fixed_space - 10) # Min 40, reserve 10 for features
# Distribute available space intelligently
if available >= 70:
# Large terminal - give full space
ssid_width = 32
vendor_width = 30
features_min = available - ssid_width - vendor_width
elif available >= 50:
# Medium terminal - balanced
ssid_width = 24
vendor_width = 20
features_min = available - ssid_width - vendor_width
elif available >= 35:
# Small terminal - prioritize SSID
ssid_width = 20
vendor_width = 15
features_min = max(10, available - ssid_width - vendor_width)
else:
# Very small terminal - minimal
ssid_width = 15
vendor_width = 12
features_min = max(8, available - ssid_width - vendor_width)
# Use full terminal width minus borders (1 char │ + 1 space on each side)
content_width = terminal_width - 4 # Leave space for "│ " and " │"
# Check if CoreWLAN is available (macOS) to show Rate (real) column
show_rate_real = COREWLAN_AVAILABLE and column_settings.get('rate_real', True)
# Build column header dynamically based on enabled columns
header_parts = []
col_names = {
'bssid': 'bssid',
'rssi': 'rssi',
'avg': 'avg',
'ch': 'ch',
'band': 'band',
'rate_max': 'rate(max)',
'rate_real': 'rate(real)',
'ssid': 'ssid',
'vendor': 'vendor',
'security': 'security',
'features': 'features'
}
# Add headers for enabled columns
for col_key, col_name in col_names.items():
if not column_settings.get(col_key, True):
continue
if col_key == 'rate_real' and not COREWLAN_AVAILABLE:
continue
if col_key in col_widths:
header_parts.append(f"{col_name:<{col_widths[col_key]}}")
elif col_key == 'ssid':
header_parts.append(f"{col_name:<{ssid_width}}")
elif col_key == 'vendor':
header_parts.append(f"{col_name:<{vendor_width}}")
elif col_key == 'features':
header_parts.append(col_name)
header = " ".join(header_parts)
# Truncate or pad header to fit content width
if len(header) > content_width:
header = header[:content_width - 3] + "..."
header_padding = max(0, content_width - len(header))
print(f"{Colors.BOLD}{Colors.OKGREEN}│{Colors.ENDC} {Colors.BOLD}{header}{Colors.ENDC}{' ' * header_padding} {Colors.BOLD}{Colors.OKGREEN}│{Colors.ENDC}")
# Separator line
print(f"{Colors.BOLD}{Colors.OKGREEN}├{'─' * (terminal_width - 2)}┤{Colors.ENDC}")
# Calculate viewport range
total_aps = len(sorted_aps)
if viewport_limit is not None:
viewport_end = min(viewport_offset + viewport_limit, total_aps)
viewport_aps = sorted_aps[viewport_offset:viewport_end]
else:
viewport_aps = sorted_aps
viewport_offset = 0
for viewport_idx, (bssid, ap) in enumerate(viewport_aps):
# Calculate actual index in the full list
idx = viewport_offset + viewport_idx
# Check if this line is selected
is_selected = (idx == selected_index and selected_index >= 0)
# Background highlight for selected line
bg_highlight = "\033[48;5;240m" if is_selected else "" # Medium gray background (color 240)
bg_reset = "\033[49m" if is_selected else "" # Reset background
# Check if AP is currently visible - if not, gray out the entire line
is_visible = getattr(ap, 'currently_visible', True) # Default to True for backward compatibility
# Get row color based on RSSI (for entire row)
row_color = get_row_color_by_rssi(ap.rssi, is_visible)
# BSSID - simple text, row color will be applied to entire line
bssid_str = bssid
# RSSI - just current value
rssi_str = colorize_rssi(ap.rssi) if ap.rssi else "-"
# AVG - average/min RSSI value
if ap.min_rssi is not None and ap.min_rssi != ap.rssi:
avg_str = f"{ap.min_rssi}dBm"
else:
avg_str = "-"
# Channel
ch_str = str(ap.channel) if ap.channel else "-"
# Band
band_str = ap.band or "-"
# Rate (max) - theoretical maximum from PHY mode
if ap.rate:
rate_max_str = f"{int(ap.rate)} Mbit"
else:
rate_max_str = "-"
# Rate (real) - RSSI-based estimate (only for macOS/CoreWLAN)
if show_rate_real and ap.rate and ap.rssi:
# Calculate estimated actual rate based on RSSI
if ap.rssi >= -50:
rate_factor = 1.0 # Excellent: 100%
elif ap.rssi >= -60:
rate_factor = 0.75 # Very good: 75%
elif ap.rssi >= -67:
rate_factor = 0.50 # Good: 50%
elif ap.rssi >= -70:
rate_factor = 0.35 # Fair: 35%
elif ap.rssi >= -80:
rate_factor = 0.20 # Poor: 20%
else:
rate_factor = 0.10 # Very poor: 10%
estimated_rate = ap.rate * rate_factor
rate_real_str = f"{int(estimated_rate)} Mbit"
else:
rate_real_str = "-"
# SSID with proper truncation (using dynamic width)
if ap.hidden:
ssid_str = "<hidden>"
elif len(ap.ssid) > ssid_width:
ssid_str = ap.ssid[:ssid_width-3] + "..."
else:
ssid_str = ap.ssid
# Vendor with proper truncation (using dynamic width)
if ap.vendor and len(ap.vendor) > vendor_width:
vendor_str = ap.vendor[:vendor_width-3] + "..."
else:
vendor_str = ap.vendor or "Unknown"
# Security label
sec_str = ap.security_label()
# Features column - plain text, row color will be applied
features = []
if ap.wps_enabled:
wps_status = "WPS!" if ap.wps_locked is False else "WPS"
features.append(wps_status)
if ap.pmf_required:
features.append("PMF:req")
elif ap.pmf_capable:
features.append("PMF:cap")
if ap.ft_present:
features.append("FT")
if ap.rrm_enabled:
features.append("RRM")
if ap.bss_transition:
features.append("BSS-T")
if ap.channel_width:
features.append(f"{ap.channel_width}MHz")
if ap.handshake_observed:
features.append("4WH")
if ap.deauth_count > 10:
features.append(f"⚠️DA:{ap.deauth_count}")
features_str = " ".join(features) if features else "-"
# Build line content dynamically based on enabled columns
line_parts = []
col_data = {