-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathgoatrider.py
481 lines (414 loc) · 15.3 KB
/
goatrider.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
#!/usr/bin/env python2.7b
##################################################################################################
#
# This tool does a comparison of multiple sites to look for abnormal IP addresses or hostnames
#
# Current list checks:
# Alexa Top 1 Million
# Binary Defense Systems Banlist
# Binary Defense Systems Tor List
# OTX AlienVault
#
# Written by Dave Kennedy @ Binary Defense Systems (@BinaryDefense @HackingDave)
# Additional contributions and enhancements from: Scott Nusbaum @TrustedSec
#
###################################################################################################
import sys
import os
import re
import urllib2
import ssl
import socket
import threading
import traceback
import argparse
from zipfile import ZipFile
from StringIO import StringIO
from multiprocessing import Pool
from datetime import datetime
################
# Global data
################
banlist = None
banlist_findings = {}
banlist_findings_lock = threading.RLock()
failed_ips = []
g_download_failed = True
b_stdout_lock = threading.RLock()
################
# Configuration Items
################
CPU_CORES = 16 # Arbitrary number
MAX_LINES = 10000 # Arbitrary number
use_remote = True
BASE_PATH = ''
ALIEN_URL = 'https://reputation.alienvault.com'
BD_URL = 'https://www.binarydefense.com'
AMAZON_URL = 'http://s3.amazonaws.com'
ALIEN_FILE = 'reputation.unix'
TOR_FILE = 'tor.txt'
BANLIST_FILE = 'banlist.txt'
TOP_1M_FILE = 'alexa-static/top-1m.csv'
################
# Helper Functions
################
def printl( msg ):
b_stdout_lock.acquire()
print msg
b_stdout_lock.release()
# unzip something
def download_unzip(input_zip):
content = download_list( input_zip )
unzipped_string = ''
zipfile = ZipFile(StringIO( content ))
for name in zipfile.namelist():
unzipped_string += zipfile.open(name).read()
return unzipped_string
# download something
def download_list(url):
try:
b_stdout_lock.acquire()
print "Downloading %r ... " % url,
req = urllib2.Request( url, None, {'User-agent': 'Mozilla/5.0' } )
response = urllib2.urlopen( req )
print "Complete"
b_stdout_lock.release()
return response.read()
except:
printl( "Error downloading url %r" % url )
return None
def read_file( filename ):
content = None
if os.path.exists( filename ):
fd = open( filename, 'r')
content = fd.read()
fd.close()
return content
################################################################################
# Download the individual lists
################################################################################
# TODO: Move all downloads and compairsons to their own class.
# ie alexa will have a class inherited from a master ip_validator class
# this will intern expose a download function and a search function.
#
# Make a JSON file to hold the time that each file was downloaded.
def downlaod_alexa( ):
if use_remote == True:
url = ("%s/%s.zip" % (AMAZON_URL, TOP_1M_FILE ) )
domains = download_unzip(url)
with open( '%s%s%s' % ( BASE_PATH, os.sep, TOP_1M_FILE.replace('/','_') ), 'w' ) as fd:
fd.write( domains )
else:
domains = read_file( '%s%s%s' % ( BASE_PATH, os.sep, TOP_1M_FILE.replace('/', '_') ) )
return domains
def download_binarybanlist( ):
if use_remote == True:
url = ("%s/%s" % (BD_URL, BANLIST_FILE ) )
bd_banlist = download_list(url)
with open( '%s%s%s' % ( BASE_PATH, os.sep, BANLIST_FILE), 'w' ) as fd:
fd.write( bd_banlist)
else:
bd_banlist = read_file( '%s%s%s' % ( BASE_PATH, os.sep, BANLIST_FILE ) )
return bd_banlist
def download_binarytorlist():
if use_remote == True:
url = ("%s/%s" % ( BD_URL, TOR_FILE ) )
tor = download_list( url )
with open( '%s%s%s' % ( BASE_PATH, os.sep, TOR_FILE ), 'w' ) as fd:
fd.write( tor )
else:
tor = read_file( '%s%s%s' % ( BASE_PATH, os.sep, TOR_FILE) )
return tor
def download_otx():
if use_remote == True:
url = ("%s/%s" % ( ALIEN_URL, ALIEN_FILE ) )
otx = download_list(url)
with open( '%s%s%s' % ( BASE_PATH, os.sep, ALIEN_FILE ), 'w' ) as fd:
fd.write( otx )
else:
otx = read_file( '%s%s%s' % ( BASE_PATH, os.sep, ALIEN_FILE) )
return otx
################################################################################
# Search the individual lists
################################################################################
# TODO Multithread the search ??
# pulls the alexa top 1 million
def search_alexa( hostlist ):
global banlist_findings
global banlist_findings_lock
domains = banlist[ 'alexa' ]
if not 'alexa' in banlist_findings.keys():
banlist_findings_lock.acquire()
banlist_findings[ 'alexa' ] = []
banlist_findings_lock.release()
for hosts in hostlist:
hosts = hosts.rstrip()
if not hosts in domains:
if hosts != "":
banlist_findings_lock.acquire()
banlist_findings[ 'alexa' ].append( hosts )
banlist_findings_lock.release()
# pulls the binary defense banlist
def search_binarybanlist( hostlist ):
global banlist_findings
global banlist_findings_lock
bd_banlist = banlist[ 'banlist' ]
if not 'tor' in banlist_findings.keys():
banlist_findings_lock.acquire()
banlist_findings[ 'banlist' ] = []
banlist_findings_lock.release()
for hosts in hostlist:
hosts = hosts.rstrip()
if hosts in bd_banlist:
if hosts != "":
banlist_findings_lock.acquire()
banlist_findings[ 'banlist' ].append( hosts )
banlist_findings_lock.release()
# pulls the binary defense torlist
def search_binarytorlist( hostlist ):
global banlist_findings
global banlist_findings_lock
bd_tor = banlist[ 'torlist' ]
if not 'tor' in banlist_findings.keys():
banlist_findings_lock.acquire()
banlist_findings[ 'tor' ] = []
banlist_findings_lock.release()
for hosts in hostlist:
hosts = hosts.rstrip()
if hosts in bd_tor:
if hosts != "":
banlist_findings_lock.acquire()
banlist_findings[ 'tor' ].append( hosts )
banlist_findings_lock.release()
# get associated otx list
def search_otx( hostlist ):
global banlist_findings
global banlist_findings_lock
otx = banlist[ 'otxlist' ]
if not 'otx' in banlist_findings.keys():
banlist_findings_lock.acquire()
banlist_findings[ 'otx' ] = []
banlist_findings_lock.release()
# FORMAT: ALL: 46.4.123.15 # Malicious Host
for hosts in hostlist:
hosts = hosts.rstrip()
if hosts in otx:
if hosts != "":
banlist_findings_lock.acquire()
banlist_findings[ 'otx' ].append( hosts )
banlist_findings_lock.release()
################################################################################
# Thread function:
# Processes the file ip and hosts.
# If the input is an ip attempts to resolve the hostname
# If the input is a hostname attmpts to resolve the IP
# Both are stored and search against the lists
# Called from the Pool.map object.
# Input: List of ip or hostnames
################################################################################
def pool_main( items ):
ip_list = []
host_list = []
if not type( items ) == list:
items = [ items ]
for item in items:
item = item.strip()
m = re.search("((\d{1,3}\.){3}\d{1,3})", item )
if not m == None:
# IP address format found add to list and attempt to locate hostname
ip_list.append( m.group(1) )
try:
host_list.append( socket.gethostbyaddr( m.group(1) )[0] )
except:
failed_ips.append( m.group(1) )
else:
# Item was not in the ip format therefore consider it a hostname.
# add hostname to list and try to find it's IP address
m = re.search("(https?://)?(www\.)?(.*)", item )
if not m == None:
host_list.append( m.group(3) )
try:
ip_list.append( socket.getostbyname( m.group(3) ) )
except:
failed_ips.append( m.group(3) )
else:
failed_ips.append( item )
return ( ip_list, host_list )
def search_feeds( ips, hosts=None ):
# check ips to banlist
search_bs_thread = threading.Thread( name='search_bs',
target=search_binarybanlist, args=[ ips ] )
search_bs_thread.setDaemon( True )
search_bs_thread.start()
# check tor to banlist
search_tor_thread = threading.Thread( name='search_tor',
target=search_binarytorlist, args=[ ips ] )
search_tor_thread.setDaemon( True )
search_tor_thread.start()
# check OTX
search_otx_thread = threading.Thread( name='search_otx',
target=search_otx, args=[ ips ] )
search_otx_thread.setDaemon( True )
search_otx_thread.start()
# check alexa hostnames
if not hosts == None:
search_alexa( hosts )
search_otx_thread.join()
search_tor_thread.join()
search_bs_thread.join()
def download_feeds():
global banlist
global g_download_failed
# TODO Add multithreading to the downloads
try:
l_alexa = downlaod_alexa( )
l_banlist = download_binarybanlist( )
l_torlist = download_binarytorlist()
l_otxlist = download_otx()
except:
traceback.print_exc()
return
if l_alexa == None or l_banlist == None or l_torlist == None or l_otxlist == None:
printl( "A download failed" )
return
banlist = {
'alexa': l_alexa,
'banlist': l_banlist,
'torlist': l_torlist,
'otxlist': l_otxlist
}
g_download_failed = False
def print_flaged_ip( ):
for key in banlist_findings.keys():
if len( banlist_findings[ key ] ) == 0:
continue
print "###### %s ######" % key
for i in banlist_findings[ key ]:
print '\t%s' % i
if len( failed_ips ) > 0:
print "###### FAILED TO PROCESS ######"
for ip in failed_ips:
print '\t%s' % ip
def parse_ip_file( fileinput ):
hostlist = []
iplist = []
content_lines = ''
# get IP or host list from file
with open(fileinput, "r") as fd:
content_lines= fd.readlines()
# Set will allow us to create a list of unique ip's
content_lines = list( set( content_lines ) )
printl("[*] This part might take a bit... Converting hostnames " \
"to IPs or IPs to hostnames. Be patient... " \
"file contains [%d] lines" % len( content_lines ))
# Break the contents of the file into manageble chunks.
# This provides the most benifit when processing large files
len_cl = len(content_lines)
max_lines = MAX_LINES
if len_cl < MAX_LINES:
if len_cl/CPU_CORES < 1:
max_lines = 1
else:
max_lines = len_cl/CPU_CORES
tmp = []
for index in range( 0, len_cl, max_lines):
if index+max_lines > len_cl:
tmp.append( content_lines[index:] )
else:
tmp.append( content_lines[index:index+max_lines] )
index += max_lines
content_lines = tmp
pool = Pool( CPU_CORES )
x = pool.map( pool_main, content_lines )
for i in x:
iplist.extend( i[0] )
hostlist.extend( i[1] )
return ( iplist, hostlist )
def main( fileinput ):
try:
# Download the ip files at the same time as processing the
# user supplied list of files. Saves a little time.
download_handle = threading.Thread( name='download',
target=download_feeds )
download_handle.setDaemon( True )
download_handle.start()
ip_list, host_list = parse_ip_file( fileinput )
download_handle.join()
if g_download_failed:
printl( "downloads failed" )
return
printl("[*] Checking Alexa, Artillery, TOR, and OTX...")
search_feeds( ip_list, host_list )
print_flaged_ip()
except:
traceback.print_exc()
def BANNER():
print (r""" /) (\
)\.:::::::::./(
\( o o )/
'-./ / _.-'`-.
( oo ) / _ \
|'--'/\/ ( \ \
\''/ \| \ \ \
ww | ' ) \
|.' .' |
.' .'==|==|
/ .'\ [_]
.-(/\) | /
/.-''''/| |
|| / | |
// | | |
|| |__|___/
\\ [__[___]
// .-'.-' (
||(__(__.-._)""")
print ("\n\nGoatRider is a simple tool for doing a comparison of IP " \
"addresses or hostnames to BDS Artillery Feeds, OTX, Alexa Top " \
"1M, and TOR.")
print ("\nINSTRUCTIONS: Pass a file that has a list of hostnames or IP " \
"addresses and wait for the output to see if there are any matches")
print ("Written by: Dave Kennedy (@HackingDave) from Binary Defense " \
"(@BinaryDefense)")
print
def argParse():
parser = argparse.ArgumentParser( )
parser.add_argument( 'file', help='Input file containing list of IP\'s. One IP per line' )
parser.add_argument( '-l', '--local', help='Use local BDS, OTX, TOR, and Alexa files', action='store_true' )
parser.add_argument( '-i', '--IPData', help='Directory containing the needed files', default="IPData" )
return parser.parse_args()
if __name__=="__main__":
start_time = datetime.now()
BANNER()
try:
# Must have a copy of openssl that supports tlsv1.2. tls_1.0 will
# be rejected by the binarydefense site
# The following should raise an error if running an older version of tls
if ssl.PROTOCOL_TLSv1_2:
pass
except:
print "\n\ngoatrider requires that openssl supports TLSv1.2. Please " \
"upgrade your python openssl\n\n"
sys.exit()
args = argParse()
try:
BASE_PATH = args.IPData
if not os.path.isdir( args.IPData ):
os.mkdir( args.IPData )
if args.local == True:
if not os.path.isfile( '%s%s%s' % ( BASE_PATH, os.sep, TOR_FILE ) ) or \
not os.path.isfile( '%s%s%s' % ( BASE_PATH, os.sep, BANLIST_FILE ) ) or \
not os.path.isfile( '%s%s%s' % ( BASE_PATH, os.sep, ALIEN_FILE ) ) or \
not os.path.isfile( '%s%s%s' % ( BASE_PATH, os.sep, TOP_1M_FILE.replace('/','_') ) ):
print "Needed OTX, TOR, Alexa Top 1 million, or BD Banlist not found. Downloading!"
use_remote = True
else:
use_remote = False
if os.path.isfile( args.file ):
main( args.file )
else:
print "Provided File (%s) could not be found" % args.file
except:
print "Error"
traceback.print_exc()
end_time = datetime.now() - start_time
print "Total execution time (%d.%d)" % ( end_time.seconds, end_time.microseconds )