-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathsentrygun.py
449 lines (303 loc) · 12.7 KB
/
sentrygun.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
#!/usr/bin/env python
# sentrygun
# Gabriel 'solstice' Ryan
# gabriel@solstice.me
# v0.0.1
import random
import requests
import string
import time
import json
import mmh3
import os
import sys
import cPickle
from multiprocessing import Queue, Process
from collections import deque
from configs import *
from argparse import ArgumentParser
from socketIO_client import SocketIO, BaseNamespace
from network_tools import traceroute, wifi_connect
shitlist = Queue()
deauth_list = Queue()
napalm_list = Queue()
def alert_factory(location=None,
bssid=None,
channel=None,
essid=None,
tx=None,
intent=None):
# all arguments are required
assert not any([
location is None,
bssid is None,
channel is None,
essid is None,
tx is None,
intent is None,
])
# return dict from arguments
_id = str(mmh3.hash(''.join([ bssid, str(channel), intent])))
return {
'id' : _id,
'location' : location,
'bssid' : bssid,
'channel' : channel,
'tx' : tx,
'essid' : essid,
'intent' : intent,
'timestamp' : time.time(),
}
def run_canary(iface, essid):
wifi_connect(iface, essid)
last_hops = traceroute('google.com')
try:
while True:
time.sleep(5)
hops = traceroute('google.com')
if hops != last_hops:
alert = alert_factory(location=DEVICE_NAME,
bssid='not applicable',
channel=0,
intent='canary tripped!',
essid=essid)
shitlist.put(alert)
except KeyboardInterrupt:
os.system('ifconfig %s down' % iface)
def rand_essid():
return ''.join(random.SystemRandom().choice(string.ascii_uppercase + string.digits) for _ in xrange(ESSID_LEN))
def deauth(bssid, client='ff:ff:ff:ff:ff:ff'):
while True:
print '[deauth worker] running deauth attack against', bssid
time.sleep(1)
#pckt = Dot11(addr1=client, addr2=bssid, addr3=bssid) / Dot11Deauth()
#while True:
# for i in range(64):
# if i == 0:
# print '[Sentrygun] Deauthing ', bssid
# send(pckt)
def napalm(bssid, client='ff:ff:ff:ff:ff:ff'):
while True:
print '[deauth] running napalm attack against', bssid
time.sleep(1)
# code to connect 100k clients goes here
class PunisherNamespace(BaseNamespace):
def on_napalm_target(self, *args):
alert = args[0]
napalm_list.put(alert)
if 'dismiss' in alert:
print '[punisher] ceasing any existing napalm attacks against', json.dumps(alert, indent=4, sort_keys=True)
else:
print '[punisher] initiating napalm attack against', json.dumps(alert, indent=4, sort_keys=True)
def on_deauth_target(self, *args):
alert = args[0]
deauth_list.put(alert)
if 'dismiss' in alert:
print '[punisher] ceasing any existing deauth attack against', json.dumps(alert, indent=4, sort_keys=True)
else:
print '[punisher] initiating deauth attack against', json.dumps(alert, indent=4, sort_keys=True)
def deauth_scheduler():
try:
deauth_treatments = {}
while True:
alert = deauth_list.get()
_id = alert['id']
if 'dismiss' in alert:
if _id not in deauth_treatments:
continue
deauth_treatments[_id].terminate()
del deauth_treatments[_id]
elif _id in deauth_treatments:
continue
else:
bssid = alert['bssid']
print '[deauth_scheduler] received new target:', bssid
deauth_treatments[_id] = Process(target=deauth, args=(bssid,))
deauth_treatments[_id].daemon = True
deauth_treatments[_id].start()
except KeyboardInterrupt:
pass
def napalm_scheduler():
try:
napalm_treatments = {}
while True:
alert = napalm_list.get()
_id = alert['id']
if 'dismiss' in alert:
if _id not in napalm_treatments:
continue
napalm_treatments[_id].terminate()
del napalm_treatments[_id]
elif _id in napalm_treatments:
continue
else:
bssid = alert['bssid']
print '[napalm_scheduler] received new target:', bssid
napalm_treatments[_id] = Process(target=napalm, args=(bssid,))
napalm_treatments[_id].daemon = True
napalm_treatments[_id].start()
except KeyboardInterrupt:
pass
def punisher(configs):
socket = SocketIO(configs['server_addr'], configs['server_port'])
punisher_ns = socket.define(PunisherNamespace, '/punisher')
try:
socket.wait()
except KeyboardInterrupt:
pass
def listener(configs):
server_uri = 'http://%s:%d/%s' %\
(configs['server_addr'], configs['server_port'], SERVER_ENDPOINT)
try:
while True:
alert = shitlist.get()
print '[alert] %s attack: notifying server at %s' %\
(alert['intent'], server_uri)
response = requests.post(server_uri, json=alert)
print '[alert] server at %s acknowledged notification with status code %d' % (server_uri, response.status_code)
except KeyboardInterrupt:
pass
def detect_rogue_ap_attacks():
import sniffer
responding_aps = {}
try:
probe_responses = sniffer.response_sniffer(interface)
for response in probe_responses:
ssid = response['essid']
bssid = response['addr3'].lower()
channel = response['channel']
tx = response['tx']
print '[probe Response]', ssid, bssid, response['tx'], channel
if configs['evil_twin'] and ssid in whitelist:
if bssid not in whitelist[ssid]:
print '[anomaly] %s has ssid: %s but not in whitelist' % (bssid, ssid)
alert = alert_factory(location=DEVICE_NAME,
bssid=bssid,
channel=response['channel'],
intent='evil twin - whitelist',
tx=response['tx'],
essid=ssid)
shitlist.put(alert)
else:
ap = calibration_table['ssids'][ssid]['bssids'][bssid]
upper_bound = ap['upper_bound']
lower_bound = ap['lower_bound']
if tx > upper_bound or tx < lower_bound:
print '[anomaly] Illegal tx varation: %s ' % bssid
alert = alert_factory(location=DEVICE_NAME,
bssid=bssid,
channel=response['channel'],
intent='evil twin - tx',
tx=response['tx'],
essid=ssid)
shitlist.put(alert)
elif configs['karma']:
if bssid in responding_aps:
responding_aps[bssid].add(ssid)
else:
responding_aps[bssid] = set([])
responding_aps[bssid].add(ssid)
if len(responding_aps[bssid]) > 1:
print '[anomaly] %s has sent probe responses for %d SSIDs' % (bssid, len(responding_aps[bssid]))
alert = alert_factory(location=DEVICE_NAME,
bssid=bssid,
channel=response['channel'],
intent='karma',
tx=response['tx'],
essid=ssid)
shitlist.put(alert)
except KeyboardInterrupt:
pass
def channel_hopper():
import sniffer
while True:
# channel hop from main process
for channel in xrange(1, 14):
if configs['karma']:
for i in xrange(THRESHOLD):
next_essid = rand_essid()
sniffer.send_probe_requests(interface=interface, ssid=next_essid)
print '[channel hopper] Switching to channel', channel
os.system('iwconfig %s channel %d' % (configs['iface'], channel))
time.sleep(6)
def set_configs():
parser = ArgumentParser()
parser.add_argument('-i',
dest='iface',
required=True,
type=str,
help='Specify network interface to use')
parser.add_argument('-a',
dest='server_addr',
required=True,
type=str,
help='Send data to server at this address')
parser.add_argument('-p',
dest='server_port',
required=False,
default=80,
type=int,
help='Send data to server listening on this port')
parser.add_argument('--evil-twin',
dest='evil_twin',
action='store_true',
help='detect evil twin attacks')
parser.add_argument('--karma',
dest='karma',
action='store_true',
help='detect karma attacks')
parser.add_argument('--canary',
dest='canary',
type=str,
default='',
required=False,
help='Use canary to detect network drops (must specify essid and dedicated interface in the form essid:interface )')
return parser.parse_args().__dict__
if __name__ == '__main__':
print '''
_______ _______ _ _________ _______ _______ _
( ____ \( ____ \( ( /|\__ __/( ____ )|\ /|( ____ \|\ /|( ( /|
| ( \/| ( \/| \ ( | ) ( | ( )|( \ / )| ( \/| ) ( || \ ( |
| (_____ | (__ | \ | | | | | (____)| \ (_) / | | | | | || \ | |
(_____ )| __) | (\ \) | | | | __) \ / | | ____ | | | || (\ \) |
) || ( | | \ | | | | (\ ( ) ( | | \_ )| | | || | \ |
/\____) || (____/\| ) \ | | | | ) \ \__ | | | (___) || (___) || ) \ |
\_______)(_______/|/ )_) )_( |/ \__/ \_/ (_______)(_______)|/ )_)
Gabriel Ryan <gryan@gdssecurity.com>
'''
configs = set_configs()
interface = configs['iface']
if configs['evil_twin']:
try:
with open(r'calibration_table.pickle', 'rb') as fd:
calibration_table = cPickle.load(fd)
except IOError:
print '[error] calibration_table.pickle not found'
print '[error] please run sg-calibrator.py before running sentrygun with --evil-twin flag'
sys.exit()
try:
with open(r'whitelist.pickle', 'rb') as fd:
whitelist = cPickle.load(fd)
except IOError:
print '[error] whitelist.pickle not found'
print '[error] please run sg-calibrator.py before running sentrygun with --evil-twin flag'
sys.exit()
daemons = []
try:
daemons.append(Process(target=detect_rogue_ap_attacks, args=()))
if configs['canary']:
canary_configs = configs['canary'].split(':')
canary_essid = canary_configs[0]
canary_iface = canary_configs[1]
daemons.append(Process(target=run_canary, args=(canary_iface, canary_essid,)))
daemons.append(Process(target=listener, args=(configs,)))
daemons.append(Process(target=punisher, args=(configs,)))
daemons.append(Process(target=deauth_scheduler, args=()))
daemons.append(Process(target=napalm_scheduler, args=()))
daemons.append(Process(target=channel_hopper, args=()))
for d in daemons:
d.start()
except KeyboardInterrupt:
for d in running_daemons:
d.terminate()
d.join()