forked from breenmachine/httpscreenshot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpscreenshot.py
executable file
·464 lines (391 loc) · 14.1 KB
/
httpscreenshot.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
#!/usr/bin/python
'''
Installation on Ubuntu:
apt-get install python-requests python-m2crypto phantomjs
If you run into: 'module' object has no attribute 'PhantomJS'
then pip install selenium (or pip install --upgrade selenium)
'''
from selenium import webdriver
from urlparse import urlparse
import multiprocessing
import Queue
import argparse
import sys
import traceback
import os.path
import requests
import ssl
import M2Crypto
import re
from random import shuffle
import time
import Image
import ImageDraw
import ImageFont
import signal
reload(sys)
sys.setdefaultencoding("utf8")
def timeoutFn(func, args=(), kwargs={}, timeout_duration=1, default=None):
import signal
class TimeoutError(Exception):
pass
def handler(signum, frame):
raise TimeoutError()
# set the timeout handler
signal.signal(signal.SIGALRM, handler)
signal.alarm(timeout_duration)
try:
result = func(*args, **kwargs)
except TimeoutError as exc:
result = default
finally:
signal.alarm(0)
return result
def addUrlsForService(host, urlList, servicesList, scheme):
if(servicesList == None or servicesList == []):
return
for service in servicesList:
state = service.findPreviousSibling("state")
if(state != None and state != [] and state['state'] == 'open'):
urlList.append(scheme+host+':'+str(service.parent['portid']))
def detectFileType(inFile):
#Check to see if file is of type gnmap
firstLine = inFile.readline()
secondLine = inFile.readline()
thirdLine = inFile.readline()
#Be polite and reset the file pointer
inFile.seek(0)
if ((firstLine.find('nmap') != -1 or firstLine.find('Masscan') != -1) and thirdLine.find('Host:') != -1):
#Looks like a gnmap file - this wont be true for other nmap output types
#Check to see if -sV flag was used, if not, warn
if(firstLine.find('-sV') != -1 or firstLine.find('-A') != -1):
return 'gnmap'
else:
print("Nmap version detection not used! Discovery module may miss some hosts!")
return 'gnmap'
else:
return None
def parseGnmap(inFile, autodetect):
'''
Parse a gnmap file into a dictionary. The dictionary key is the ip address or hostname.
Each key item is a list of ports and whether or not that port is https/ssl. For example:
>>> targets
{'127.0.0.1': [[443, True], [8080, False]]}
'''
targets = {}
for hostLine in inFile:
currentTarget = []
#Pull out the IP address (or hostnames) and HTTP service ports
fields = hostLine.split(' ')
ip = fields[1] #not going to regex match this with ip address b/c could be a hostname
for item in fields:
#Make sure we have an open port with an http type service on it
if (item.find('http') != -1 or autodetect) and re.findall('\d+/open',item):
port = None
https = False
'''
nmap has a bunch of ways to list HTTP like services, for example:
8089/open/tcp//ssl|http
8000/closed/tcp//http-alt///
8008/closed/tcp//http///
8080/closed/tcp//http-proxy//
443/open/tcp//ssl|https?///
8089/open/tcp//ssl|http
Since we want to detect them all, let's just match on the word http
and make special cases for things containing https and ssl when we
construct the URLs.
'''
port = item.split('/')[0]
if item.find('https') != -1 or item.find('ssl') != -1:
https = True
#Add the current service item to the currentTarget list for this host
currentTarget.append([port,https])
if(len(currentTarget) > 0):
targets[ip] = currentTarget
return targets
def setupBrowserProfile(headless):
browser = None
while(browser is None):
try:
if(not headless):
fp = webdriver.FirefoxProfile()
fp.set_preference("webdriver.accept.untrusted.certs",True)
fp.set_preference("security.enable_java", False)
fp.set_preference("webdriver.load.strategy", "fast");
browser = webdriver.Firefox(fp)
else:
browser = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true','--ssl-protocol=tlsv1'], executable_path="phantomjs")
except Exception as e:
print e
time.sleep(1)
continue
return browser
def writeImage(text, filename, fontsize=40, width=1024, height=200):
image = Image.new("RGBA", (width,height), (255,255,255))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype(os.path.dirname(os.path.realpath(__file__))+"/LiberationSerif-BoldItalic.ttf", fontsize)
draw.text((10, 0), text, (0,0,0), font=font)
image.save(filename)
def worker(urlQueue,tout,debug,headless,doProfile,vhosts,subs,extraHosts,tryGUIOnFail):
if(debug):
print '[*] Starting worker'
browser = None
try:
browser = setupBrowserProfile(headless)
except:
print "[-] Oh no! Couldn't create the browser, Selenium blew up"
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
print ''.join('!! ' + line for line in lines)
return
while True:
#Try to get a URL from the Queue
try:
curUrl = urlQueue.get(timeout=tout)
print '[+] '+str(urlQueue.qsize())+' URLs remaining'
screenshotName = urlparse(curUrl[0]).netloc.replace(":", "-")
if(debug):
print '[+] Got URL: '+curUrl[0]
if(os.path.exists(screenshotName+".png")):
if(debug):
print "[-] Screenshot already exists, skipping"
continue
except Queue.Empty:
if(debug):
print'[-] URL queue is empty, quitting.'
browser.quit()
return
try:
if(doProfile):
[resp,curUrl] = autodetectRequest(curUrl, timeout=tout, vhosts=vhosts, urlQueue=urlQueue, subs=subs, extraHosts=extraHosts)
else:
resp = doGet(curUrl, verify=False, timeout=tout, vhosts=vhosts, urlQueue=urlQueue, subs=subs, extraHosts=extraHosts)
if(resp is not None and resp.status_code == 401):
print curUrl[0]+" Requires HTTP Basic Auth"
f = open(screenshotName+".html",'w')
f.write(resp.headers.get('www-authenticate','NONE'))
f.write('<title>Basic Auth</title>')
f.close()
writeImage(resp.headers.get('www-authenticate','NO WWW-AUTHENTICATE HEADER'),screenshotName+".png")
continue
elif(resp is not None):
browser.set_window_size(1024, 768)
browser.set_page_load_timeout((tout))
old_url = browser.current_url
browser.get(curUrl[0].strip())
if(browser.current_url == old_url):
print "[-] Error fetching in browser but successfully fetched with Requests: "+curUrl[0]
if(headless):
if(debug):
print "[+] Trying with sslv3 instead of TLS - known phantomjs bug: "+curUrl[0]
browser2 = webdriver.PhantomJS(service_args=['--ignore-ssl-errors=true'], executable_path="phantomjs")
old_url = browser2.current_url
browser2.get(curUrl[0].strip())
if(browser2.current_url == old_url):
if(debug):
print "[-] Didn't work with SSLv3 either..."+curUrl[0]
browser2.close()
else:
print '[+] Saving: '+screenshotName
html_source = browser2.page_source
f = open(screenshotName+".html",'w')
f.write(html_source)
f.close()
browser2.save_screenshot(screenshotName+".png")
browser2.close()
continue
if(tryGUIOnFail and headless):
print "[+] Attempting to fetch with FireFox: "+curUrl[0]
browser2 = setupBrowserProfile(False)
old_url = browser2.current_url
browser2.get(curUrl[0].strip())
if(browser2.current_url == old_url):
print "[-] Error fetching in GUI browser as well..."+curUrl[0]
browser2.close()
continue
else:
print '[+] Saving: '+screenshotName
html_source = browser2.page_source
f = open(screenshotName+".html",'w')
f.write(html_source)
f.close()
browser2.save_screenshot(screenshotName+".png")
browser2.close()
continue
else:
continue
print '[+] Saving: '+screenshotName
html_source = browser.page_source
f = open(screenshotName+".html",'w')
f.write(html_source)
f.close()
browser.save_screenshot(screenshotName+".png")
except Exception as e:
print e
print '[-] Something bad happened with URL: '+curUrl[0]
if(curUrl[2] > 0):
curUrl[2] = curUrl[2] - 1;
urlQueue.put(curUrl)
if(debug):
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
print ''.join('!! ' + line for line in lines)
browser.quit()
browser = setupBrowserProfile(headless)
continue
def doGet(*args, **kwargs):
url = args[0]
doVhosts = kwargs['vhosts']
urlQueue = kwargs['urlQueue']
subs = kwargs['subs']
extraHosts = kwargs['extraHosts']
del kwargs['extraHosts']
del kwargs['urlQueue']
del kwargs['vhosts']
del kwargs['subs']
kwargs['allow_redirects']=False
resp = requests.get(url[0],**kwargs)
#If we have an https URL and we are configured to scrape hosts from the cert...
if(url[0].find('https') != -1 and url[1] == True):
#Pull hostnames from cert, add as additional URLs and flag as not to pull certs
host = urlparse(url[0]).hostname
port = urlparse(url[0]).port
if(port is None):
port = 443
cert = ssl.get_server_certificate((host,port),ssl_version=ssl.PROTOCOL_SSLv23)
x509 = M2Crypto.X509.load_cert_string(cert)
subjText = x509.get_subject().as_text()
names = re.findall("CN=([^\s]+)",subjText)
try:
altNames = x509.get_ext('subjectAltName').get_value()
names.extend(re.findall("DNS:([^,]*)",altNames))
except:
pass
for name in names:
if(name.find('*.') != -1):
for sub in subs:
try:
sub = sub.strip()
hostname = name.replace('*.',sub+'.')
if(hostname not in extraHosts):
extraHosts[hostname] = 1
address = socket.gethostbyname(hostname)
urlQueue.put(['https://'+hostname+':'+str(port),False,url[2]])
print '[+] Discovered subdomain '+address
except:
pass
name = name.replace('*.','')
if(name not in extraHosts):
extraHosts[name] = 1
urlQueue.put(['https://'+name+':'+str(port),False,url[2]])
print '[+] Added host '+name
else:
if (name not in extraHosts):
extraHosts[name] = 1
urlQueue.put(['https://'+name+':'+str(port),False,url[2]])
print '[+] Added host '+name
return resp
else:
return resp
def autodetectRequest(url, timeout, vhosts=False, urlQueue=None, subs=None, extraHosts=None):
'''Takes a URL, ignores the scheme. Detect if the host/port is actually an HTTP or HTTPS
server'''
resp = None
host = urlparse(url[0]).hostname
port = urlparse(url[0]).port
if(port is None):
if('https' in url[0]):
port = 443
else:
port = 80
try:
#cert = ssl.get_server_certificate((host,port))
cert = timeoutFn(ssl.get_server_certificate,kwargs={'addr':(host,port),'ssl_version':ssl.PROTOCOL_SSLv23},timeout_duration=3)
if(cert is not None):
if('https' not in url[0]):
url[0] = url[0].replace('http','https')
#print 'Got cert, changing to HTTPS '+url[0]
else:
url[0] = url[0].replace('https','http')
#print 'Changing to HTTP '+url[0]
except Exception as e:
url[0] = url[0].replace('https','http')
#print 'Changing to HTTP '+url[0]
try:
resp = doGet(url,verify=False, timeout=timeout, vhosts=vhosts, urlQueue=urlQueue, subs=subs, extraHosts=extraHosts)
except Exception as e:
print 'HTTP GET Error: '+str(e)
print url[0]
return [resp,url]
def sslError(e):
if('the handshake operation timed out' in str(e) or 'unknown protocol' in str(e) or 'Connection reset by peer' in str(e) or 'EOF occurred in violation of protocol' in str(e)):
return True
else:
return False
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-l","--list",help='List of input URLs')
parser.add_argument("-i","--input",help='nmap gnmap output file')
parser.add_argument("-p","--headless",action='store_true',default=False,help='Run in headless mode (using phantomjs)')
parser.add_argument("-w","--workers",default=1,type=int,help='number of threads')
parser.add_argument("-t","--timeout",type=int,default=10,help='time to wait for pageload before killing the browser')
parser.add_argument("-v","--verbose",action='store_true',default=False,help='turn on verbose debugging')
parser.add_argument("-a","--autodetect",action='store_true',default=False,help='Automatically detect if listening services are HTTP or HTTPS. Ignores NMAP service detction and URL schemes.')
parser.add_argument("-vH","--vhosts",action='store_true',default=False,help='Attempt to scrape hostnames from SSL certificates and add these to the URL queue')
parser.add_argument("-dB","--dns_brute",help='Specify a DNS subdomain wordlist for bruteforcing on wildcard SSL certs')
parser.add_argument("-r","--retries",type=int,default=0,help='Number of retries if a URL fails or timesout')
parser.add_argument("-tG","--trygui",action='store_true',default=False,help='Try to fetch the page with FireFox when headless fails')
args = parser.parse_args()
if(len(sys.argv) < 2):
parser.print_help()
sys.exit(0)
if(args.input is not None):
inFile = open(args.input,'r')
if(detectFileType(inFile) == 'gnmap'):
hosts = parseGnmap(inFile,args.autodetect)
urls = []
for host,ports in hosts.items():
for port in ports:
url=''
if port[1] == True:
url = ['https://'+host+':'+port[0],args.vhosts,args.retries]
else:
url = ['http://'+host+':'+port[0],args.vhosts,args.retries]
urls.append(url)
else:
print 'Invalid input file - must be Nmap GNMAP'
elif (args.list is not None):
f = open(args.list,'r')
lst = f.readlines()
urls = []
for url in lst:
urls.append([url.strip(),args.vhosts,args.retries])
else:
print "No input specified"
sys.exit(0)
#shuffle the url list
shuffle(urls)
#read in the subdomain bruteforce list if specificed
subs = []
if(args.dns_brute != None):
subs = open(args.dns_brute,'r').readlines()
#Fire up the workers
urlQueue = multiprocessing.Queue()
manager = multiprocessing.Manager()
hostsDict = manager.dict()
workers = []
for i in range(args.workers):
p = multiprocessing.Process(target=worker,
args=(urlQueue,args.timeout,args.verbose,args.headless,args.autodetect, args.vhosts,subs,hostsDict,args.trygui))
workers.append(p)
p.start()
for url in urls:
urlQueue.put(url)
for p in workers:
try:
p.join()
except KeyboardInterrupt:
print "[-] Ctrl-C received! Sending kill to threads..."
kill_received = True
for p in workers:
p.terminate()