forked from aryanguenthner/365
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunctions.py
2532 lines (1937 loc) · 107 KB
/
functions.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
import os
import sys
import shutil
import tarfile
import platform
import subprocess
import signal
import re
import time
import threading
import traceback
import colorsys
import socket
import shelve
import datetime
from PIL import Image # logo size, histogram, and list of Exif tags for file enum
from warnings import simplefilter
from urlparse import urlparse
from glob import glob
from Queue import Queue
from lxml import html, etree
from multiprocessing import Process, Pipe
# Local Imports
import requests
from lib.requests.auth import HTTPProxyAuth, HTTPDigestAuth
from lib.constants import *
from conf.modules import *
from conf.settings import fuzzdb, useragent, flist, timeout, ss_delay, nthreads, allow_redir, use_ghost
from lib.rawr_meta import *
import lib.rdp as rdp
import lib.vnc as vnc
meta_parser = Meta_Parser()
# Non stdlib
try:
from lxml import html
if use_ghost:
from ghost import Ghost, Session
except Exception, e:
from lib.banner import *
print(banner)
if isinstance(e, ImportError) or str(e) == "Ghost.py requires PySide or PyQt4":
print("\t%s[x]%s - Run install.sh to get set up. " % (TC.RED, TC.END) + str(e))
else:
print(e)
exit(1)
try:
import pygraphviz as pgv
except Exception, e:
print("\n\t%s[!]%s - pygraphviz - %s\n\n * Diagrams will not be available. *" %
(TC.YELLOW, TC.END, str(e)))
timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
platform_type = platform.machine()
simplefilter("ignore") # ignore warnings
dns_cache = {} # DNS lookup result cache - to avoid duplicate records
binging = False # to make sure one bing happens at a time
outs = [] # list of urls that have already been added to the HTML/CSV docs
crawling = 0 # a count of the number of crawls happening simultaneously
threads = [] # contains handles for each thread
q = Queue() # The main queue. Holds db reference for each target.
rd = Queue() # The RD screenshot. Holds RDP/VNC screenshot targets.
output = Queue() # The output queue - prevents output overlap
class RD_Screenshot_Thread(threading.Thread): # Worker class that screenshots RDP/VNC services from the queue 'rd'.
def __init__(self, queue, logdir, output):
threading.Thread.__init__(self)
self.queue = queue
self.logdir = logdir
self.output = output
def run(self):
while not self.queue.empty():
ip, port, t = self.queue.get()
ipnum = get_ipnum(ip)
if t == 'vnc':
f = vnc.get_screenshot(ip, port, self.logdir)
self.output.put(" %s[+]%s VNC Screenshot [ %s:%s ]" % (TC.CYAN, TC.END, ip, port))
else:
f = rdp.get_screenshot(ip, port, self.logdir)
self.output.put(" %s[+]%s RDP Screenshot [ %s:%s ]" % (TC.CYAN, TC.END, ip, port))
hist = get_histval(f)
write_to_html(timestamp, (str(hist), str(ipnum), t, ip, port))
self.queue.task_done()
class OutThread(threading.Thread): # Worker class that displays msgs in the 'output' queue in order and one at a time.
def __init__(self, queue, logfile, opts):
threading.Thread.__init__(self)
self.queue = queue
self.logfile = logfile
self.opts = opts
def run(self):
while True:
writelog(self.queue.get(), self.logfile, self.opts)
self.queue.task_done()
class SiThread(threading.Thread): # Threading class that enumerates hosts contained in the 'q' queue.
def __init__(self, db, timestamp, scriptpath, pjs_path, logfile, logdir, o, opts):
threading.Thread.__init__(self)
self.timestamp = timestamp
self.scriptpath = scriptpath
self.logfile = logfile
self.logdir = logdir
self.output = o
self.opts = opts
self.pjs_path = pjs_path
self.terminate = False
self.busy = False
self.db = db
def run(self):
global dns_cache
global binging
global crawling
global q
global outs
while not self.terminate:
time.sleep(0.5)
if q and not q.empty():
task = q.get()
self.busy = True
target = dict(self.db[task[0]][task[1]]) # the dict, rather than a link to the db...
if task[1] == '.':
hostname = target['ipv4']
else:
hostname = task[1]
port = ''
try:
prefix = "http://"
if 'service_tunnel' in target:
if target['service_tunnel'] == 'ssl':
prefix = "https://"
if not target['port'] in ["80", "443"]:
port = ":" + target['port']
if self.opts.dns and ('is_dns_result' not in target):
hostnames = []
# Don't do Bing>DNS lookups for non-routable IPs
if not re.findall(NRIP_REGEX, target['ipv4']):
if target['ipv4'] in dns_cache:
self.output.put(" %s[.]%s RevDNS\t: %s (%s) - pulling from cache..." %
(TC.PURPLE, TC.END, target['ipv4'], target['hostnames'][0]))
hostnames = dns_cache[target['ipv4']]
else:
while binging: # The intention here is to avoid flooding Bing with requests.
time.sleep(0.5)
binging = True
self.output.put(" %s[@]%s Bing RevDNS\t: %s" % (TC.PURPLE, TC.END, target['ipv4']))
cookies = dict(SRCHHPGUSR='NRSLT=50')
nxt, old_res, hostnames = (1, [], [])
while True:
try:
bing_res = requests.get("https://www.bing.com/search?q=ip%3a" + target['ipv4'] +
'&format=rss&first=%s' % nxt,
verify=False,
timeout=timeout,
allow_redirects=allow_redir,
proxies=self.opts.proxy_dict,
auth=self.opts.proxy_auth,
cookies=cookies).content
except:
error = traceback.format_exc().splitlines()
error_msg("\n".join(error))
self.output.put(
" %s[x]%s Bing RevDNS:\n\t%s\n" % (TC.RED, TC.END, "\n\t".join(error)))
break
if "No results found for ip:" + target['ipv4'] in bing_res:
break
res = re.findall(r"\<link\>(.*?)\<\/link\>", bing_res)
if res == old_res or not res:
break
else:
old_res = res
for r in res:
if 'bing.com' not in r:
r = re.sub("http[s]?\:\/\/", '', r)
hostnames.append(r.split('/')[0])
nxt += 50
dns_cache[target['ipv4']] = list(set(hostnames))
binging = False
if len(hostnames) > 0:
# remove any duplicates from our list of domains...
hostnames = list(set(hostnames))
self.output.put(" %s[+]%s RevDNS\t: found %s DNS names for %s" %
(TC.CYAN, TC.END, len(hostnames), target['ipv4']))
# distribute the load
for hostname in hostnames:
hn = hostname.strip(': ')
if hn not in [target['ipv4'], "https", "http", '']:
if hn not in self.db[task[0]]:
target['is_dns_result'] = True
target['hostnames'] = [hostname.strip()]
self.db[task[0]][hn] = target
q.put((task[0], hn))
self.output.put(" %s[+]%s RevDNS\t: [ %s:%s ] injected into queue." %
(TC.CYAN, TC.END, hn, target['port']))
else:
self.output.put(
" %s[x]%s RevDNS\t: found no DNS entries for %s" % (TC.YELLOW, TC.END, target['ipv4']))
if 'url' not in target:
target['url'] = prefix + hostname + port
elif hostname not in target['url']:
o = urlparse(target['url'])
target['url'] = target['url'].replace(o.scheme + "://" + o.netloc, prefix + hostname + port)
self.output.put(" %s[>]%s Pulling\t: %s" % (TC.GREEN, TC.END, target['url']))
try:
target['res'] = requests.get(target['url'],
headers={"user-agent": target['useragent']},
verify=False,
timeout=timeout,
allow_redirects=allow_redir,
proxies=self.opts.proxy_dict,
auth=self.opts.proxy_auth)
msg = [" %s[+]%s Finished" % (TC.CYAN, TC.END), ""]
except requests.ConnectionError:
try:
if '[401]' in target['res']:
open('%s/4_Exploitation/401_failed_auth.lst' % self.logdir, 'a').write(target['url'])
except:
pass
msg = [" %s[x]%s Not found" % (TC.RED, TC.END), ""]
except socket.timeout:
msg = [" %s[x]%s Timed out" % (TC.RED, TC.END), ""]
except requests.Timeout:
msg = [" %s[x]%s Timed out" % (TC.RED, TC.END), ""]
except:
error = traceback.format_exc().splitlines()
error_msg("\n".join(error))
msg = [" %s[x]%s Error " % (TC.RED, TC.END), ":\n\t%s\n" % ("\n\t".join(error))]
if 'res' in target:
wordlist = []
if not self.opts.json_min:
wl = list(set(target['res'].content.split()))
for w in wl:
if len(w) > 3 and re.search('^[a-zA-Z0-9]+$', w):
if w not in ELEMENT_NAMES:
wordlist.append(w)
if self.opts.getoptions:
try:
res = (requests.options(target['url'],
headers={"user-agent": target['useragent']},
verify=False,
timeout=timeout,
allow_redirects=allow_redir,
proxies=self.opts.proxy_dict,
auth=self.opts.proxy_auth))
if 'allow' in res.headers:
target['options'] = res.headers['allow'].replace(",", " | ")
self.output.put(" %s[o]%s pulled OPTIONS: [ %s:%s ]" %
(TC.PURPLE, TC.END, hostname, target['port']))
except requests.ConnectionError:
msg = [" %s[x]%s Not Found" % (TC.RED, TC.END), ""]
except socket.timeout:
self.output.put(" %s[x]%s Timed out pulling OPTIONS: [ %s:%s ]" %
(TC.RED, TC.END, hostname, target['port']))
except requests.Timeout:
msg = [" %s[x]%s Timed out" % (TC.RED, TC.END), ""]
except:
error = traceback.format_exc().splitlines()
error_msg("\n".join(error))
self.output.put(" %s[x]%s Failed pulling OPTIONS: [ %s:%s ]\n\t%s\n" %
(TC.RED, TC.END, hostname, target['port'], "\n\t".join(error)))
if not self.opts.json_min:
if False and self.opts.dorks and GOOGLE_API_KEY != "X":
# query google dorks for fnames, return list
try:
res = requests.get("https://www.google.com/?gws_rd=ssl#" +
"q=site:" + hostname + "+filetype:" +
'+OR+filetype:'.join(DORKS_FILETYPES) +
"&format=rss&first=" + str(nxt),
headers={"user-agent": target['useragent']},
verify=False,
timeout=timeout,
allow_redirects=allow_redir,
proxies=self.opts.proxy_dict,
auth=self.opts.proxy_auth,
cookies=cookies).content
except:
error = traceback.format_exc().splitlines()
error_msg("\n".join(error))
self.output.put(
" %s[x]%s Google Dorks:\n\t%s\n" % (TC.RED, TC.END, "\n\t".join(error)))
break
docs = re.findall(r"<link>(.*?)</link>", res)
for doc in docs:
fname = urlparse(doc).filename
fpath = '%s/3_Enumeration/meta/%s_%s_files' % (self.logdir, hostname, target['port'])
fn = '%s/%s' % (fpath, fname)
try:
os.makedirs(fpath)
except:
pass
with open(doc, 'wb') as wf:
for chunk in dat.iter_content(200):
wf.write(chunk)
report_fname = '%s/5_Reporting/meta_report_%s.html' % (self.logdir, timestamp)
ret = meta_parser.parse(fn)
try:
target['wordlist'] += ret['words']
except:
target['wordlist'] = [ret['words']]
del ret['words'] # save space on the report
meta_parser.add_to_report(fn, report_fname, ret, url_t2)
if ret:
self.output.put(" %s[#]%s Meta logged: %s" %
(TC.PURPLE, TC.END, os.path.basename(fn)))
target['hist'] = 256
if not (self.opts.noss or self.opts.json_min) and 'res' in target:
parent_conn, child_conn = Pipe()
proc = Process(target=screenshot,
args=(child_conn, target['url'], target['port'],
self.logfile, self.logdir, self.timestamp,
self.scriptpath, self.opts.proxy_dict,
target['useragent'], self.pjs_path,
(self.opts.json or self.opts.json_min),
timeout, use_ghost, self.opts.useragent[target['useragent']]))
proc.start()
r = parent_conn.recv()
proc.join()
if r[0]:
target['hist'] = int(r[1])
self.output.put(
" %s[+]%s Screenshot : [ %s ]" % (TC.CYAN, TC.END, target['url']))
else:
target['hist'] = 0
self.output.put(
" %s[x]%s Screenshot : [ %s ] Failed - %s" % \
(TC.RED, TC.END, target['url'], r[1]))
parent_conn, child_conn = None, None
if self.opts.getcrossdomain:
try:
res = requests.get("%s/crossdomain.xml" % target['url'],
headers={"user-agent": target['useragent']},
verify=False,
timeout=timeout,
allow_redirects=allow_redir,
proxies=self.opts.proxy_dict,
auth=self.opts.proxy_auth)
if res.status_code == 200:
if not self.opts.json_min:
try:
os.makedirs("./3_Enumeration/cross_domain")
except:
pass
open("./3_Enumeration/cross_domain/%s_%s_crossdomain.xml" %
(hostname, target['port']), 'w').write(safe_string(res.content))
self.output.put(" %s[c]%s Pulled crossdomain.xml : [ %s:%s ]" %
(TC.PURPLE, TC.END, hostname, target['port']))
target['crossdomain'] = "y"
except requests.ConnectionError:
msg = [" %s[x]%s Not found: %s" % (TC.RED, TC.END, hostname), ""]
except socket.timeout:
self.output.put(" %s[x]%s Timed out pulling crossdomain.xml : [ %s:%s ]" %
(TC.RED, TC.END, hostname, target['port']))
except requests.Timeout:
msg = [" %s[x]%s Timed out" % (TC.RED, TC.END), ""]
except:
error = traceback.format_exc().splitlines()
error_msg("\n".join(error))
self.output.put(" %s[x]%s Failed pulling crossdomain.xml :\n\t%s\n" %
(TC.RED, TC.END, "\n\t".join(error)))
if self.opts.getrobots:
try:
res = requests.get("%s/robots.txt" % target['url'],
headers={"user-agent": target['useragent']},
verify=False,
timeout=timeout,
allow_redirects=allow_redir,
proxies=self.opts.proxy_dict,
auth=self.opts.proxy_auth)
if res.status_code == 200 and "llow:" in res.content:
if not self.opts.json_min:
try:
os.makedirs("./3_Enumeration/robots")
except:
pass
open("./3_Enumeration/robots/%s_%s_robots.txt" %
(hostname, target['port']), 'w').write(safe_string(res.content))
self.output.put(" %s[r]%s Pulled robots.txt : [ %s:%s ]" %
(TC.PURPLE, TC.END, hostname, target['port']))
target['robots.txt'] = "y"
except requests.ConnectionError:
msg = [" %s[x]%s Not found" % (TC.RED, TC.END), ""]
except socket.timeout:
self.output.put(" %s[x]%s Timed out pulling robots.txt : [ %s:%s ]" %
(TC.RED, TC.END, hostname, target['port']))
except requests.Timeout:
msg = [" %s[x]%s Timed out" % (TC.RED, TC.END), ""]
except:
error = traceback.format_exc().splitlines()
error_msg("\n".join(error))
self.output.put(" %s[x]%s Failed pulling robots.txt :\n\t%s\n" %
(TC.RED, TC.END, "\n\t".join(error)))
if (self.opts.crawl or self.opts.mirror) and not self.opts.json_min:
while crawling >= self.opts.spider_thread_limit:
time.sleep(0.1)
crawling += 1
wordlist += crawl(target, self.logdir, self.timestamp, self.opts)
crawling -= 1
target = parse_data(task, target, self.timestamp, self.scriptpath, self.opts)
wordlist = list(set(wordlist))
try:
wordlist += target['wordlist'] # add our wordlist to all words from crawl
del target['wordlist']
except Exception, ex:
pass
if not self.opts.json_min:
try:
os.makedirs("./4_Exploitation/wordlists/")
except:
pass
with open('./4_Exploitation/wordlists/%s_%s.wl' %
(hostname, target['port']), 'w') as of:
of.write('\n'.join(wordlist))
wordlist = None
if self.opts.json or self.opts.json_min:
output.put(target)
i = target['url'] + "_" + str(self.opts.useragent[target['useragent']])
if not (self.opts.json or self.opts.json_min or i in outs):
outs.append(i)
write_to_html(timestamp, target)
write_to_csv(timestamp, target)
# remove redundant / potentially large entries before adding to db
for x in [x for x in ('defpass', 'res') if x in target]:
del target[x]
self.db[task[0]][task[1]] = target
self.output.put("%s [ %s:%s ]%s" % (msg[0], hostname, target['port'], msg[1]))
except:
error = traceback.format_exc().splitlines()
error_msg("\n".join(error))
self.output.put(" %s[x]%s Failed : [ %s:%s ]\n\t%s\n" %
(TC.RED, TC.END, hostname, target['port'], "\n\t".join(error)))
self.busy = False
busy_count = 0
for t in threads:
if t.busy:
busy_count += 1
self.output.put(" %s[i]%s Main queue size [ %s ] - Threads Busy/Total [ %s/%s ]" %
(TC.BLUE, TC.END, str(q.qsize()), busy_count, nthreads))
q.task_done()
def glob_recurse(f):
files = []
for i in glob(f):
if os.path.isfile(i):
files.append(os.path.abspath(i))
elif os.path.isdir(i):
for x in glob_recurse(i + "/*"):
files.append(os.path.abspath(x))
return files
def init(o):
global db
db = shelve.open('rawr_%s.shelvedb' % timestamp, writeback=True)
db['idx'] = {}
global unix_ts
unix_ts = datetime.datetime.now().strftime("%s")
global ints
ints = {}
global opts
opts = o
return db, ints, opts
def safe_string(s):
try:
r = str(s)
except UnicodeEncodeError:
r = unicode(s).encode('unicode_escape')
return r
def get_histval(fn):
rgb, c = (0, 0, 0), 0
img = Image.open(fn).resize((150, 150)) # taking our hist from a downsized sample
hsv = (0, 0, sum(img.histogram()))
for x in xrange(img.size[0]):
for y in xrange(img.size[1]):
t = img.load()[x, y]
rgb = tuple(map(sum, zip(rgb, t)))
c += 1
rgb = tuple((x / c) for x in rgb)
hsv = colorsys.rgb_to_hsv(*rgb)
return hsv[2]
def screenshot(conn, url, port, logfile, logdir, timestamp, scriptpath, proxy, useragent, pjs_path, silent, timeout,
use_ghost, ua_cksum):
filename = "%s/5_Reporting/images/%s_%s_%s_%s.png" % (logdir, urlparse(url).netloc.split(':')[0], timestamp, port, ua_cksum)
if use_ghost:
ghost = Ghost()
with ghost.start():
session = Session(ghost, wait_timeout=timeout, user_agent=useragent, viewport_size=(640, 480),
show_scrollbars=False, ignore_ssl_errors=True, java_enabled=True, plugins_enabled=True)
if proxy:
session.set_proxy('default', proxy['host'], proxy['port'])
page, res = session.open(url)
if page:
session.capture_to(filename, region=(0, 0, 640, 480))
else:
pass # ERROR MSG
else:
if not os.path.exists(filename): # the picture hasn't already been taken
lp = "/dev/null" # not logging (json, json-min)
if not silent:
lp = logfile
with open(lp, 'ab') as log_pipe:
start = datetime.datetime.now()
cmd = [pjs_path]
if proxy:
cmd.append("--proxy=%s" % proxy['http']) # Same ip:port is used for both http and https.
cmd += "--web-security=no", "--ignore-ssl-errors=yes", "--ssl-protocol=any", \
(scriptpath + "/data/screenshot.js"), url, filename, useragent, str(ss_delay)
try:
process = subprocess.Popen(cmd, stdout=log_pipe, stderr=log_pipe)
while process.poll() is None:
time.sleep(0.1)
now = datetime.datetime.now()
if (now - start).seconds > timeout + 1:
try:
sig = getattr(signal, 'SIGKILL', signal.SIGTERM)
os.kill(process.pid, sig)
os.waitpid(-1, os.WNOHANG)
except:
pass
conn.send( (False, ' Timed Out.') )
conn.close()
except:
conn.send( (False, "\n\t\t".join(traceback.format_exc().splitlines())) )
conn.close()
if not os.path.isfile(filename):
shutil.copy(scriptpath + "/data/error.png", "%s/5_Reporting/images/error.png" % logdir)
conn.send( (False, '.png not created') )
conn.close()
elif os.stat(filename).st_size > 0:
try: # histogram time!
hist = get_histval(filename)
conn.send( (True, hist) )
conn.close()
except Exception, ex: # histogram failed
conn.send( (True, 0) )
conn.close()
else:
shutil.copy(scriptpath + "/data/error.png", "%s/5_Reporting/images/error.png" % logdir)
conn.send( (False, '0 byte file. [Deleted]') )
conn.close()
def crawl(target, logdir, timestamp, opts): # Our Spidering function.
output.put(" %s[>]%s Spidering : [ %s ]" % (TC.GREEN, TC.END, target['url']))
from PIL.ExifTags import TAGS
def recurse(url_t1, urls_t2, tabs, depth):
url_t1 = url_t1.strip('"/\; ()')
for url_t2 in urls_t2:
url_t2 = url_t2.strip('"/\; ()').replace("/#", "")
if opts.verbose:
output.put(" %s[i]%s [%s] threads %s/%s - depth %s/%s - sec %d/%s - urls %s/%s" %
(TC.BLUE, TC.END, target['url'], crawling,
opts.spider_thread_limit, depth, opts.spider_depth,
(datetime.datetime.now() - time_start).seconds,
opts.spider_timeout, len(list(set(urls_visited))), opts.spider_url_limit))
if len(list(set(urls_visited))) > opts.spider_url_limit:
if opts.verbose:
output.put(" %s[!]%s Spidering stopped at depth - %s: [ %s ] - URL limit reached" %
(TC.YELLOW, TC.END, str(depth), target['url']))
break
elif (datetime.datetime.now() - time_start).seconds > opts.spider_timeout:
if opts.verbose:
output.put(" %s[!]%s Spidering stopped at depth - %s: [ %s ] - Timed out" %
(TC.YELLOW, TC.END, str(depth), target['url']))
break
if url_t2 not in ("https://ssl", "http://www", "http://", "http://-", "http:", "https:"): # ga junk
coll.append((url_t1.replace(":", "-"), url_t2.replace(":", "-")))
if not (url_t2 in urls_visited or (opts.spider_url_blacklist and (url_t2 in url_blacklist))):
with open('%s/5_Reporting/diagrams/links_%s_%s__%s.txt' % (logdir, hname, target['port'], timestamp),
'a') as of:
of.write("%s%s\n" % (tabs, safe_string(url_t2)))
if not (url_t2 in urls_visited or (opts.spider_url_blacklist and (url_t2 in url_blacklist))):
try:
p = urlparse(url_t2)
urls_visited.append(url_t2)
if opts.spider_follow_subdomains:
url_t2_hn = ".".join(p.netloc.split(".")[-2:])
else:
url_t2_hn = p.netloc
if url_t2_hn in url_t1 or opts.alt_domains and url_t2_hn in opts.alt_domains.split(','):
urls_t3 = []
try:
doc_f = '%s/3_Enumeration/meta/%s_%s_%s_findings.csv' %\
(logdir, hname, target['port'], timestamp)
dat = session.get(url_t2,
headers={"user-agent": useragent, "referer": url_t1},
verify=False,
timeout=opts.spider_url_timeout,
allow_redirects=False,
proxies=opts.proxy_dict,
auth=opts.proxy_auth)
if dat.status_code == 201:
open('%s/4_Exploitation/201_pages.lst' % logdir, 'a').write(url_t2 + '\n')
elif dat.status_code == (300, 301, 302, 303, 305, 306, 307, 308):
if "location" in dat.headers.keys():
for l in dat.headers['location']:
if url_t2_hn in l:
urls_t3.append(l)
elif dat.status_code in (401, 403):
open('%s/4_Exploitation/auth_sites.lst' % logdir, 'a').write('[' + str(dat.status_code) + '] ' + url_t2 + '\n')
elif dat.content and dat.status_code != 404:
l = list(set(target['res'].content.split()))
for w in l:
if len(w) > 3 and re.search('^[a-zA-Z0-9]+$', w):
wl.append(w)
page = p.path.split('/')[-1]
if opts.mirror:
if not page:
page = '/' + "root_page"
fpath = '%s/3_Enumeration/mirrored_sites/%s_%s%s' %\
(logdir, hname, target['port'], p.path.replace(page, ''))
fn = fpath + page
try:
os.makedirs(fpath)
except:
pass
with open(fn, 'wb') as wf:
for chunk in dat.iter_content(200):
wf.write(chunk)
else:
fpath = '%s/3_Enumeration/meta/%s_%s_files' % (logdir, hname, target['port'])
fn = '%s/%s' % (fpath, page)
ext = p.path.split(".")[-1].lower()
# parse for meta
if ext in DOC_TYPES and url_t2 not in target['docs']:
if not opts.mirror:
fpath = '%s/3_Enumeration/meta/%s_%s_files' % (logdir, hname, target['port'])
fn = '%s/%s' % (fpath, page)
try:
os.makedirs(fpath)
except:
pass
with open(fn, 'wb+') as wf:
for chunk in dat.iter_content(200):
wf.write(chunk)
target['docs'].append(str(url_t2))
try:
os.makedirs('%s/3_Enumeration/meta/' % logdir)
except:
pass
with open(doc_f, 'a+') as ofn:
ofn.write('DOC,%s\n' % safe_string(url_t2))
try:
report_fname = '%s/5_Reporting/meta_report_%s.html' % (logdir, timestamp)
ret = meta_parser.parse(fn)
try:
target['wordlist'] += ret['words']
except:
target['wordlist'] = ret['words']
del ret['words'] # save space on the report
meta_parser.add_to_report(fn, report_fname, ret, url_t2)
if ret:
output.put(" %s[#]%s Meta logged: %s" %
(TC.PURPLE, TC.END, os.path.basename(fn)))
try:
os.system('rm -rf ./tmp')
except:
pass
except:
e = traceback.format_exc().splitlines()
print(" [spider] processing document:\n\t%s\n\t%s" % (url_t2, e))
elif ext in OTHER_TYPES:
try:
os.makedirs(fpath)
except:
pass
with open(doc_f, 'a+') as ofn:
ofn.write('OTHER,%s\n' % safe_string(url_t2))
for u in list(set(re.findall(URL_REGEX, dat.content, re.I))):
urls_t3.append(u.split('"')[0].split("'")[0].split(
"<")[0].split("--")[0].rstrip('%)/.')) # supplement the regex
if dat.content.rstrip():
try: # parse the html for tags w/ href or source
cxt = html.fromstring(str(dat.content))
for el in cxt.iter():
try:
if str(el.tag).strip().lower() in ['link', 'a', 'script', 'iframe',
'applet', 'area', 'object',
'embed', 'form']:
for i, v in el.items():
if i in ("src", "href"):
if "mailto" in v:
x = safe_string(v.split(":")[1]).strip()
try:
if x not in target['email_addresses']:
target['email_addresses'].append(x)
except:
target['email_addresses'] = [x]
else:
if not v.split("//")[0] in ("http:", "https:"):
v = v.replace("../", '')
if not v.startswith("/"):
v = "/" + v
v = p.scheme + "://" + p.netloc + v
urls_t3.append(v)
except:
# pass
e = traceback.format_exc().splitlines()
error_msg(" [spider] parsing HTML element:\n\t%s\n\t%s" %
(url_t2, e))
except:
pass
# e = traceback.format_exc().splitlines()[-1]
# error_msg(" [spider] parsing HTML from:\n\t%s\n\t%s" % (url_t2, e))
urls_t3 = list(set(urls_t3))
if len(urls_t3) > 0:
if not len(list(set(urls_visited))) > opts.spider_url_limit:
if not depth >= opts.spider_depth:
d = (datetime.datetime.now() - time_start).seconds
if not d > opts.spider_timeout:
if opts.spider_breadth_first:
urls_to_crawl.put([url_t2, urls_t3, "\t", depth + 1])
else:
recurse(url_t2, urls_t3, tabs + "\t", depth + 1)
except:
# pass
e = traceback.format_exc().splitlines()
error_msg(" [spider] pulling [ %s ]:\n\t%s" % (target['url'], e))
except:
pass # problem parsing the url
if opts.spider_url_blacklist:
if os.path.isfile(opts.spider_url_blacklist):
url_blacklist = open(opts.spider_url_blacklist).read().split('\n')
output.put(" %s[i]%s Spidering - blacklisting %s urls." % (TC.BLUE, TC.END, len(url_blacklist) - 1))
else:
output.put(" %s[i]%s Spidering - unable to find blacklist file - %s" %
(TC.BLUE, TC.END, opts.spider_url_blacklist))
coll, urls_visited, target['docs'], target['exif_docs'] = [], [], [], []
hname = urlparse(target['url']).netloc
wl = []
time_start = datetime.datetime.now()
session = requests.Session()
if not (opts.json_min or os.path.exists("./5_Reporting/diagrams")):
try:
os.makedirs("./5_Reporting/diagrams")
except:
pass
if opts.spider_breadth_first:
urls_to_crawl = Queue()
urls_to_crawl.put([target['url'], [target['url']], "\t", 1])
while not urls_to_crawl.empty():
x, y, t, d = urls_to_crawl.get()
recurse(x, y, t, d)
urls_to_crawl = None
else: # length first
recurse(target['url'], [target['url']], "\t", 1)
session = None
target['doc_count'] = len(target['docs'])
if len(coll) < 2:
output.put(
" %s[+]%s Finished spider: [ %s ] - no links, skipping graph..." % (TC.CYAN, TC.END, target['url']))
else:
try:
output.put(" %s[+]%s Finished spider: [ %s ] - building graph..." % (TC.CYAN, TC.END, target['url']))
# Graph creation
gr = pgv.AGraph(splines='ortho', rankdir='LR')
gr.node_attr['shape'] = 'rect'
c = []
for x, y in coll: # Add nodes and edges
if x not in c:
c.append(x)
if not (x == y or y in c):
c.append(y)
if opts.verbose:
output.put(" %s[i]%s Processing data for [ %s ]: %s nodes / %s unique" %
(TC.BLUE, TC.END, target['url'], len(c), len(list(set(c)))))
for node in c[:50]:
if node == target['url'].replace(':', '-'):
gr.add_node(node, root=True, shape=ROOT_NODE_SHAPE, color=ROOT_NODE_COLOR)
elif not urlparse(target['url']).netloc in node:
gr.add_node(node, shape=EXTERNAL_NODE_SHAPE, color=EXTERNAL_NODE_COLOR)
else:
gr.add_node(node)
if opts.verbose:
output.put(" %s[i]%s Processing colls for [ %s ]: %s colls" %
(TC.BLUE, TC.END, target['url'], len(coll)))
for x, y in [z for z in coll if z[0] != z[1]]:
gr.add_edge((x, y))
# Draw as PNG
gr.layout(prog=LAYOUT_TYPE)
# will get a warning if the graph is too large - not fatal
f = '%s/5_Reporting/diagrams/diagram_%s_%s__%s_%s.png' %\
(logdir, urlparse(target['url']).netloc, target['port'], timestamp, opts.useragent[target['useragent']])
if opts.verbose:
output.put(" %s[i]%s Drawing diagram for [ %s ]: %s" % (TC.BLUE, TC.END, target['url'], f))