-
-
Notifications
You must be signed in to change notification settings - Fork 76
/
hawkscan.py
1323 lines (1179 loc) · 60.6 KB
/
hawkscan.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 python3
# -*- coding: utf-8 -*-
__version__ = '2.3'
__program__ = 'HawkScan'
__author__ = 'codejump'
__twitter__ = 'https://twitter.com/c0dejump'
__projects__ = 'https://github.com/c0dejump'
#modules in standard library
import requests
import sys, os, re
import time
from datetime import datetime
from time import strftime
import argparse
from bs4 import BeautifulSoup
import json
import traceback
from requests.exceptions import Timeout
from requests.auth import HTTPBasicAuth
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
import signal
import random
# external modules
from config import PLUS, WARNING, INFO, LESS, LINE, FORBI, BACK, EXCL, SERV_ERR, BYP, WAF, EXT_B, MINI_B, ARCH
try:
from Queue import Queue
except:
import queue as Queue
import threading
from threading import Thread
from fake_useragent import UserAgent
try:
UserAgent = UserAgent()
except Exception:
UserAgent = ["Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; LCJB; rv:11.0) like Gecko", "c0dejump", "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0"]
from static.banner import banner
from report.creat_report import create_report
from modules.waf.detect_waf import verify_waf
from modules.waf.bypass_waf import bypass_waf
from modules.before_fuzzing.before_run import before_start
from modules.before_fuzzing.check_subdomain import subdomain
from modules.during_fuzzing.parsing_html import parsing_html
from modules.during_fuzzing.bypass_forbidden import bypass_forbidden
from modules.during_fuzzing.check_backup import scan_backup, vim_backup
from modules.manage_dir import manage_dir
from modules.terminal_size import terminal_size
from modules.output import multiple_outputs
from modules.resume import resume_options
from modules.after_fuzzing.scan_errors import scan_error
try:
from modules.after_fuzzing.send_notify import notify_scan_completed
except:
notify = False
from modules.proxy.check_proxy import check_proxy
from modules.auto_update import auto_update
from run_modules import check_modules
try:
enclosure_queue = Queue()
except:
enclosure_queue = Queue.Queue()
requests.packages.urllib3.disable_warnings(requests.packages.urllib3.exceptions.InsecureRequestWarning)
#requests.packages.urllib3.util.ssl_.DEFAULT_CIPHERS += ':ADH-AES128-SHA256'
import warnings
warnings.filterwarnings("ignore", category=UserWarning, module='bs4')
rec_list = []
#list to append url and then recursif scan
req_p = u""
#for exclude option
stat = 0
tw, th = terminal_size() # determine terminal size
header_parsed = {}
basic_user_agent = {"User-agent": "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; LCJB; rv:11.0) like Gecko"}
class ThreadManager:
"""
Class ThreadManager:
To manage threads (add_thread())
To stop thread (stop_thread())
"""
workers = []
lock = threading.Lock()
def __init__(self, queue):
self.queue = queue
def add_thread(self, i, threads, manager):
"""
add thread from function definded_thread()
"""
#print(self.workers[0])
t_event = threading.Event()
worker = threading.Thread(target=thread_wrapper, args=(i, self.queue, threads, manager, t_event))
worker.daemon = True
worker.start()
self.workers.append((worker, t_event))
def stop_thread(self):
""" for stop thread => #TODO to remake"""
t, e = self.workers[0]
e = e.set() # put event to set True for stop thread
del self.workers[0]
class filterManager:
"""
Class filterManager:
Filter page or response status code for remove false positif
functions:
- check_exclude_code
- check_exclude_page
"""
def exclude_type(self, req_p, s, req, res, directory, forbi, get_date, bp_current, parsing, len_req):
if type(req_p) == list and len(req_p) > 1:
#print(len_req)
self.check_multiple(s, req, res, directory, forbi, get_date, bp_current, parsing, size_bytes=len_req)
elif type(req_p) == int:
self.check_exclude_code(s, res, req, directory, get_date, bp_current, parsing)
else:
#print(req)
self.check_exclude_page(s, req, res, directory, forbi, get_date, bp_current, parsing, size_bytes=len_req)
def check_multiple(self, s, req, res, directory, forbi, HOUR, bp_current, parsing=False, size_bytes=False):
"""
Check_multiple: check multiple exclude, ex:
--exclude 500,1337b,https://www.exemple.com
--exclude 500,403
"""
req_bytes = len(req.content)
exclude_bytes = "[{}b]".format(req_bytes)
list_exclude = {}
for l_exclude in req_p:
list_exclude[l_exclude] = False
#print(list_exclude) #Debug
for m_exclude in req_p:
try:
if int(m_exclude):
#print(m_exclude)
check_code = self.check_exclude_code(s, res, req, directory, HOUR, bp_current, parsing, multiple=True)
if check_code:
list_exclude[m_exclude] = True
except:
check_page = self.check_exclude_page(s, req, res, directory, forbi, HOUR, parsing, size_bytes, multiple=m_exclude)
if check_page:
list_exclude[m_exclude] = True
#print(list_exclude)
if False not in list_exclude.values():
if req.status_code in [403, 401]:
print("{} {} {:<13}{:<10} ".format(HOUR, FORBI, exclude_bytes, res))
bp_current += 1
bypass_forbidden(res, exclude[:-1] if "b" in exclude else False)
bp_current -= 1
elif req.status_code in [400, 500]:
print("{} {} {:<13}{:<10} [{}]".format(HOUR, SERV_ERR, exclude_bytes, res, req.status_code))
elif req.status_code in [301, 302]:
redirect_link = ""
for rh in req.headers:
if "location" in rh or "Location" in rh:
loc = req.headers[rh]
redirect_link = loc if "http" in loc.split("/")[0] else "{}{}".format(url, loc)
req_loc = s.get(loc, verify=False, allow_redirects=False, headers=basic_user_agent)
if "/".join(res.split("/")[1:]) == "/".join(loc.split("/")[1:-1]) and len(req_loc.content) != index_len and not "." in loc:
print(" \033[33m[<>]\033[0m {} redirect to \033[33m{}\033[0m [\033[33mPotential Hidden Directory\033[0m]".format(res, loc))
else:
req_loc = s.get(res, verify=False, allow_redirects=True, headers=basic_user_agent)
redirect_link = req_loc.url
print("{} {} {:<13}{:<10}\033[33m → {}\033[0m {}\r".format(HOUR, LESS, exclude_bytes, res, redirect_link, req.status_code))
elif req.status_code == 404:
pass
else:
print("{} {} {:<13}{:<10} [{}]".format(HOUR, PLUS, exclude_bytes, res, req.status_code))
for l_exclude in req_p:
list_exclude[l_exclude] = False
def check_exclude_code(self, s, res, req, directory, HOUR, bp_current, parsing=False, multiple=False):
"""
check_exclude_code:
You can activate this option to pass the bp_current,response status code, ex:
--exclude 500
"""
req_bytes = len(req.content)
exclude_bytes = "[{}b]".format(req_bytes)
req_st = str(req.status_code) if multiple else req.status_code
if multiple and req_st in req_p:
return False
elif req_st == req_p:
pass
elif req_st == 404:
pass
elif req_st in [403, 401]:
print("{} {} {:<13}{:<10} ".format(HOUR, FORBI, exclude_bytes, res))
bp_current += 1
bypass_forbidden(res)
bp_current -= 1
elif req_st in [500, 400, 422, 423, 424, 425]:
print("{} {} {:<13}{:<10} \033[33m{} Server Error\033[0m".format(HOUR, SERV_ERR, exclude_bytes, res, req.status_code))
if js and req_bytes > 0:
parsing.get_javascript(res, req, directory)
elif req_st in [301, 302]:
redirect_link = ""
for rh in req.headers:
if "location" in rh or "Location" in rh:
loc = req.headers[rh]
redirect_link = loc if "http" in loc.split("/")[0] else "{}{}".format(url, loc)
req_loc = s.get(redirect_link, verify=False, allow_redirects=False, headers=basic_user_agent)
if "/".join(res.split("/")[1:]) == "/".join(loc.split("/")[1:-1]) and len(req_loc.content) != index_len and not "." in loc:
print(" \033[33m[<>]\033[0m {} redirect to \033[33m{}\033[0m [\033[33mPotential Hidden Directory\033[0m]".format(res, loc))
else:
req_loc = s.get(res, verify=False, allow_redirects=True, headers=basic_user_agent)
redirect_link = req_loc.url
print("{} {} {:<13}{:<10}\033[33m → {}\033[0m {}\r".format(HOUR, LESS, exclude_bytes, res, redirect_link, req.status_code))
if js and req_bytes > 0:
parsing.get_javascript(res, req, directory)
else:
if multiple:
return True
else:
print("{} {} {:<13}{:<10}".format(HOUR, PLUS, exclude_bytes, res))
if req_bytes > 0:
html_actions(directory, res, req, parsing)
output_scan(directory, res, req_bytes, 200)
def check_exclude_page(self, s, req, res, directory, forbi, HOUR, bp_current, parsing=False, size_bytes=False, multiple=False):
"""
Check_exclude_page:
If scan blog, or social network etc.. you can activate this option to pass profil/false positive pages or response status code.
Do a percentage btw pages.
for use this option you do defined a profil/false positive page base, ex:
--exclude url.com/profil/codejump
OR
--exclude 240b for just number of bytes
"""
scoring = 0
multiple = multiple if multiple else "0b"
req_bytes = len(req.content)
if multiple and "." in multiple:
print("\n\033[34mHi ! Sorry but multiple excludes with an url doesn't work for the moment, please put a number or bytes number\n(ex: --exclude 404,1337b)\033[0m")
pid = os.getpid()
os.killpg(pid, signal.SIGSTOP)
if "b" in exclude[0][-1] and int(exclude[0][0]) or multiple[-1] == "b" and int(multiple[0]):
#For exclude bytes number
multiple = False if multiple == "0b" else multiple
req_len = int(exclude[0][0:-1]) if not multiple else int(multiple.split('b')[0])
exclude_bytes = "[{}b]".format(req_bytes)
if multiple and req_bytes == req_len:
return False
elif multiple and req_bytes != req_len:
return True
if not multiple:
if req_bytes == req_len:
pass
elif req_bytes != req_len and req.status_code == 200:
print("{} {} {:<13}{:<10}".format(HOUR, PLUS, exclude_bytes, res))
if req_bytes > 0:
html_actions(directory, res, req, parsing)
elif req_bytes != req_len and req.status_code in [401, 403]:
print("{} {} {:<13}{:<10}".format(HOUR, FORBI, exclude_bytes, res))
elif req_bytes != req_len and req.status_code in [500, 502, 400, 422, 423, 424, 425]:
print("{} {} {:<13}{:<10} \033[33m{} Server Error\033[0m".format(HOUR, SERV_ERR, exclude_bytes, res, req.status_code))
elif req_bytes != req_len and req.status_code in [301, 302]:
redirect_link = req.url
print("{} {} {:<13}{:<10}\033[33m → {}\033[0m {}\r".format(HOUR, LESS, exclude_bytes, res, redirect_link, req.status_code))
if js and req_bytes > 0:
parsing.get_javascript(res, req, directory)
else:
### Exclude page ###
## TODO
multiple = False if multiple == "0b" else multiple
if stat == 301 or stat == 302:
req = requests.get(req.url, verify=False, headers=basic_user_agent)
words = req_p
for w in words.split("\n"):
if w in req.text:
scoring += 1
else:
pass
len_wd = [lines for lines in words.split("\n")] #to avoid to do line per line
perc = round(float(scoring) / len(len_wd) * 100)#to do a percentage for check look like page
#print(req.text)
#print(perc) #DEBUG percentage
#print(multiple)
if perc >= 80 or perc == 78:
pass
elif perc > 50 and perc < 80:
print("{} {} {} [Potential exclude page with {}%]".format(HOUR, EXCL, res, perc))
else:
exclude_bytes = "[{}b]".format(len(req.content))
if req.status_code in [403, 401]:
bp_current += 1
print("{} {} {:<13}{:<10} \033[31m{} Forbidden \033[0m".format(HOUR, FORBI, exclude_bytes, res, req.status_code))
bypass_forbidden(res, exclude[:-1] if "b" in exclude else False)
bp_current -= 1
elif req.status_code in [500, 400, 422, 423, 424, 425]:
if multiple:
return True
else:
print("{} {} {:<13}{:<10} \033[33m{} Server Error\033[0m".format(HOUR, SERV_ERR, exclude_bytes, res, req.status_code))
else:
if multiple:
return True
else:
if req_bytes > 0:
html_actions(directory, res, req, parsing)
print("{} {} {:<13}{:<10}".format(HOUR, PLUS, exclude_bytes, res))
#check backup
create_backup(res, directory, forbi)
#output scan.txt
output_scan(directory, res, len(req.content), stats=200)
if res[-1] == "/" and recur:
if ".git" in res:
pass
else:
spl = res.split("/")[3:]
result = "/".join(spl)
rec_list.append(result)
output_scan(directory, res, len(req.content), stats=200)
class runFuzzing:
"""
Class runFuzzing:
Run fuzzing of webpage
functions:
- tryUrl
"""
def light_mode(self, uri, directory, s, forced=False, u_agent=False):
filterM = filterManager()
parsing = parsing_html()
percentage = lambda x, y: float(x) / float(y) * 100.00
waf = False
tested_bypass = False
global bp_current
bp_current = 0
global n_error
n_error = 0
res = uri
page = "/".join(res.split("/")[3:])
#print("{} :: {}".format(res.split("/"), "/".join(res.split("/")[3:]))) #DEBUG
try:
user_agent_r = random.choice(UserAgent) if type(UserAgent) == list else UserAgent.random
user_agent = {'User-agent': u_agent} if u_agent else {'User-agent': user_agent_r} #for a random user-agent
try:
forbi = False
req = requests.get(res, verify=False, timeout=10)
if ts: #if --timesleep option defined
time.sleep(ts)
if req == 404:
status_link = req
elif req != 404 and req.history:
status_link = [histo.status_code for histo in req.history]
else:
status_link = req.status_code
len_req = len(req.content) if req != 404 else False
bytes_len = "[{}b]".format(len_req)
display_res = res if tw > 110 else page
#print(status_link) #DEBUG status response
if status_link == 200:
if exclude:
filterM.exclude_type(req_p, s, req, res, directory, forbi, get_date(), bp_current, parsing, len_req)
else:
if len(req.content) > 0:
html_actions(directory, res, req, parsing)
print("{} {} {:<13}{:<10}".format(get_date(), PLUS, bytes_len, display_res))
output_scan(directory, res, len_req, stats=200) #check backup
create_backup(res, directory, forbi) #add directory for recursif scan
elif status_link in [401, 403]:
if exclude:
filterM.exclude_type(req_p, s, req, res, directory, forbi, get_date(), bp_current, parsing, len_req)
else:
two_verify = requests.get(url, verify=False, headers=basic_user_agent)
if "Generated by cloudfront" in req.text and "Request blocked" in req.text and two_verify.status_code in [403, 401]:
print("{} {} Cloudflare protection activated on {}, wait 60s please".format(get_date(), WARNING, req.url))
time_wait(time_i)
if not forced:
forbi = True
print("{} {} {:<13}{:<10} \033[31m{} Forbidden \033[0m".format(get_date(), FORBI, bytes_len, display_res, status_link))
elif not forced and recur:
pass
else:
"""print("{} {} {:<13}{:<10} \033[31m{} Forbidden \033[0m".format(get_date(), FORBI, bytes_len, display_res, status_link))
output_scan(directory, res, len_req, stats=403)"""
pass
elif status_link == 404:
pass
elif status_link == 405:
if exclude:
filterM.exclude_type(req_p, s, req, res, directory, forbi, get_date(), bp_current, parsing, len_req)
else:
print("{} {} {:<13}{:<10} [405]".format(get_date(), INFO, bytes_len, display_res))
if len(req.content) > 0:
html_actions(directory, res, req, parsing)
#report.create_report_url(status_link, res, directory)
elif status_link in [301, 302]:
if exclude:
filterM.exclude_type(req_p, s, req, res, directory, forbi, get_date(), bp_current, parsing, len_req)
else:
redirect_link = ""
for rh in req.headers:
if "location" in rh or "Location" in rh:
loc = req.headers[rh]
redirect_link = loc if "http" in loc.split("/")[0] else "{}{}".format(url, loc)
req_loc = requests.get(redirect_link, verify=False, allow_redirects=False, headers=basic_user_agent)
if "/".join(res.split("/")[1:]) == "/".join(loc.split("/")[1:-1]) and len(req_loc.content) != index_len and not "." in loc:
print(" \033[33m[<>]\033[0m {} redirect to \033[33m{}\033[0m [\033[33mPotential Hidden Directory\033[0m]".format(res, loc))
else:
req_loc = requests.get(res, verify=False, allow_redirects=True, headers=basic_user_agent)
redirect_link = req_loc.url
print("{} {} {:<13}{:<10}\033[33m → {}\033[0m {}\r".format(get_date(), LESS, bytes_len, display_res, redirect_link, status_link))
if len(req.content) > 0:
html_actions(directory, res, req, parsing)
output_scan(directory, res, len_req, stats=301)
#report.create_report_url(status_link, res, directory) #TODO
elif status_link == 304:
print("{}\033[33m[+] \033[0m {}\033[33m 304 Not modified \033[0m".format(get_date(), display_res))
if len(req.content) > 0:
html_actions(directory, res, req, parsing)
#report.create_report_url(status_link, res, directory) #TODO
elif status_link in [307, 308]:
pass
elif status_link in [400, 500]:
#pass
if exclude:
filterM.exclude_type(req_p, s, req, res, directory, forbi, get_date(), bp_current, parsing, len_req)
else:
if len(req.content) > 0:
html_actions(directory, res, req, parsing)
print("{} {} {:<13}{:<10} \033[33m{} Server Error\033[0m".format(get_date(), SERV_ERR, bytes_len, display_res, status_link))
output_scan(directory, res, len_req, stats=status_link)
elif status_link in [422, 423, 424, 425]:
print("{} {} {} \033[33mError WebDAV\033[0m\r".format(get_date(), LESS, res if tw > 110 else page))
if len(req.content) > 0:
html_actions(directory, res, req, parsing)
#report.create_report_url(status_link, res, directory) #TODO
elif status_link == 405:
print("{} {} {}".format(get_date(), PLUS, display_res))
#output_scan(directory, res, stats=405)
elif status_link == 503:
req_test_index = requests.get(url, verify=False, headers=basic_user_agent) # take origin page url (index) to check if it's really unavailable
if req_test_index.status_code == 503 and not forced:
#manager.stop_thread() #TODO
print("{}{} Service potentialy Unavailable, The site web seem unavailable please wait...\n".format(get_date(), WARNING))
time_wait(time_i)
else:
pass
elif status_link in [429, 522]:
if "Just a moment" in req.text:
print("{} {} Cloudflare protection activated, wait 60s please".format(get_date(), WARNING))
time_wait(time_i)
else:
pass
except Timeout:
n_error += 1
#traceback.print_exc() #DEBUG
with open(directory + "/errors.txt", "a+") as write_error:
write_error.write(res+"\n")
#pass
except Exception:
n_error += 1
if print_error:
traceback.print_exc() #DEBUG
with open(directory + "/errors.txt", "a+") as write_error:
write_error.write(res+"\n")
except Exception:
n_error += 1
if print_error:
traceback.print_exc() #DEBUG
def tryUrl(self, i, q, threads, manager=False, directory=False, forced=False, u_agent=False, nLine=False):
"""
tryUrl:
Test all URL contains in the dictionnary with multi-threading.
This script run functions:
- create_backup()
- dl()
- suffix_backup()
- mail()
"""
global n
n = 0 if not nLine else nLine
global n_error
n_error = 0
global bp_current
bp_current = 0
filterM = filterManager()
parsing = parsing_html()
s = requests.session()
s.verify=False
thread_score = 0
score_next = 0
#waf_score = 0
percentage = lambda x, y: float(x) / float(y) * 100.00
stop_add_thread = False
time_i = 60
waf = False
tested_bypass = False
for numbers in range(len_w):
n += 1
thread_count = threading.active_count() - 1
res = q.get()
page = "/".join(res.split("/")[3:])
#print("{} :: {}".format(res.split("/"), "/".join(res.split("/")[3:]))) #DEBUG
if auto and not stop_add_thread:
thrds, scores = defined_thread(threads, thread_score, score_next)
if scores == 1:
thread_score += 1
if thrds == 1:
threads += 1
score_next += 1
manager.add_thread(i, threads, manager)
#print("{}: {}".format(threading.currentThread().getName() ,thread_score))#DEBUG
try:
user_agent_r = random.choice(UserAgent) if type(UserAgent) == list else UserAgent.random
user_agent = {'User-agent': u_agent} if u_agent else {'User-agent': user_agent_r} #for a random user-agent
try:
forbi = False
if ts: #if --timesleep option defined
time.sleep(ts)
req = defined_connect(s, res, user_agent, header_parsed)
waf = verify_waf(s, req, res, user_agent) if not forced else False
#verfiy_waf function, to check if waf detected, True: detected # False: not detected
if waf:
if not tested_bypass:
try_bypass_waf = bypass_waf(req, res)
#print(try_bypass_waf) #DEBUG
#print(user_agent) #DEBUG
if try_bypass_waf == False: # if not worked not repeat
print("{}\033[31m[-]\033[0m Our tests not bypass it, sorry".format(BYP))
tested_bypass = True
elif try_bypass_waf and type(try_bypass_waf) is not bool:
user_agent.update(try_bypass_waf)
time_wait(time_i)
#TODO: if waf_score == X: manager.stop_thread() & re-create with the bypass or potentialy use TOR (apt install tor, pip install torrequest) for next requests after that.
if req == 404:
status_link = req
elif req != 404 and req.history:
status_link = [histo.status_code for histo in req.history]
else:
status_link = req.status_code
len_req = len(req.content) if req != 404 else False
bytes_len = "[{}b]".format(len_req)
display_res = res if tw > 110 else page
if backup != None:
vim_backup(s, url, res, user_agent, exclude)
scan_backup(s, url, len_req, res, js, req_p, bp_current, exclude, backup, header_parsed, user_agent, directory, forbi, filterM, page, tw, parsing, authent, get_date=get_date())
#print(status_link) #DEBUG status response
if status_link == 200:
if exclude:
filterM.exclude_type(req_p, s, req, res, directory, forbi, get_date(), bp_current, parsing, len_req)
else:
if "robots.txt" in res.split("/")[3:]:
print("{} {} {}".format(get_date(), PLUS, res))
for r in req.text.split("\n"):
print("\t\u251c {}".format(r))
if len(req.content) > 0:
html_actions(directory, res, req, parsing)
print("{} {} {:<13}{:<10}".format(get_date(), PLUS, bytes_len, display_res))
output_scan(directory, res, len_req, stats=200) #check backup
create_backup(res, directory, forbi) #add directory for recursif scan
if res[-1] == "/" and recur:
if ".git" in res:
pass
else:
spl = res.split("/")[3:]
result = "/".join(spl)
rec_list.append(result)
#report.create_report_url(status_link, res, directory) #TODO
elif status_link in [401, 403]:
two_verify = s.get(url, verify=False, headers=basic_user_agent)
if "Generated by cloudfront" in req.text and "Request blocked" in req.text and two_verify.status_code in [403, 401]:
print("{} {} Cloudflare protection activated on {}, wait 60s please".format(get_date(), WARNING, req.url))
time_wait(time_i)
if exclude:
filterM.exclude_type(req_p, s, req, res, directory, forbi, get_date(), bp_current, parsing, len_req)
else:
if res[-1] == "/" and recur and bytes_len != htaccess_len:
bp_current += 1
print("{} {} {:<13}{:<10} \033[31m{} Forbidden \033[0m".format(get_date(), FORBI, bytes_len, display_res, status_link))
bypass_forbidden(res)
bp_current -= 1
if ".htaccess" in res or ".htpasswd" in res or ".git" in res or "wp" in res:
output_scan(directory, res, len_req, stats=403)
else:
spl = res.split("/")[3:]
result = "/".join(spl)
rec_list.append(result)
output_scan(directory, res, len_req, stats=403)
#report.create_report_url(status_link, res, directory)
if not forced:
forbi = True
print("{} {} {:<13}{:<10} \033[31m{} Forbidden \033[0m".format(get_date(), FORBI, bytes_len, display_res, status_link))
bp_current += 1
bypass_forbidden(res)
bp_current -= 1
create_backup(res, directory, forbi)
output_scan(directory, res, len_req, stats=403)
#report.create_report_url(status_link, res, directory)
elif not forced and recur:
pass
else:
"""print("{} {} {:<13}{:<10} \033[31m{} Forbidden \033[0m".format(get_date(), FORBI, bytes_len, display_res, status_link))
output_scan(directory, res, len_req, stats=403)"""
pass
if backup != None:
vim_backup(s, url, res, user_agent, exclude)
scan_backup(s, url, len_req, res, js, req_p, bp_current, exclude, backup, header_parsed, user_agent, directory, forbi, filterM, page, tw, parsing, authent, get_date=get_date())
elif status_link == 404:
pass
elif status_link == 405:
if exclude:
filterM.exclude_type(req_p, s, req, res, directory, forbi, get_date(), bp_current, parsing, len_req)
else:
print("{} {} {:<13}{:<10} [405]".format(get_date(), INFO, bytes_len, display_res))
if len(req.content) > 0:
html_actions(directory, res, req, parsing)
#report.create_report_url(status_link, res, directory)
elif status_link in [301, 302]:
if exclude:
filterM.exclude_type(req_p, s, req, res, directory, forbi, get_date(), bp_current, parsing, len_req)
else:
redirect_link = ""
for rh in req.headers:
if "location" in rh or "Location" in rh:
loc = req.headers[rh]
redirect_link = loc if "http" in loc.split("/")[0] else "{}{}".format(url, loc)
req_loc = s.get(redirect_link, verify=False, allow_redirects=False, headers=basic_user_agent)
if "/".join(res.split("/")[1:]) == "/".join(loc.split("/")[1:-1]) and len(req_loc.content) != index_len and not "." in loc:
print(" \033[33m[<>]\033[0m {} redirect to \033[33m{}\033[0m [\033[33mPotential Hidden Directory\033[0m]".format(res, loc))
else:
req_loc = s.get(res, verify=False, allow_redirects=True, headers=basic_user_agent)
redirect_link = req_loc.url
print("{} {} {:<13}{:<10}\033[33m → {}\033[0m {}\r".format(get_date(), LESS, bytes_len, display_res, redirect_link, status_link))
if len(req.content) > 0:
html_actions(directory, res, req, parsing)
output_scan(directory, res, len_req, stats=301)
#report.create_report_url(status_link, res, directory) #TODO
elif status_link == 304:
print("{}\033[33m[+] \033[0m {}\033[33m 304 Not modified \033[0m".format(get_date(), display_res))
if len(req.content) > 0:
html_actions(directory, res, req, parsing)
#report.create_report_url(status_link, res, directory) #TODO
elif status_link in [307, 308]:
pass
elif status_link in [400, 500]:
#pass
if exclude:
filterM.exclude_type(req_p, s, req, res, directory, forbi, get_date(), bp_current, parsing, len_req)
else:
vim_backup(s, url, res, user_agent, exclude)
if len(req.content) > 0:
html_actions(directory, res, req, parsing)
print("{} {} {:<13}{:<10} \033[33m{} Server Error\033[0m".format(get_date(), SERV_ERR, bytes_len, display_res, status_link))
output_scan(directory, res, len_req, stats=status_link)
elif status_link in [422, 423, 424, 425]:
print("{} {} {} \033[33mError WebDAV\033[0m\r".format(get_date(), LESS, res if tw > 110 else page))
if len(req.content) > 0:
html_actions(directory, res, req, parsing)
#report.create_report_url(status_link, res, directory) #TODO
elif status_link == 405:
print("{} {} {}".format(get_date(), PLUS, display_res))
#output_scan(directory, res, stats=405)
elif status_link == 503:
req_test_index = requests.get(url, verify=False, headers=basic_user_agent) # take origin page url (index) to check if it's really unavailable
if req_test_index.status_code == 503 and not forced:
#manager.stop_thread() #TODO
print("{}{} Service potentialy Unavailable, The site web seem unavailable please wait...\n".format(get_date(), WARNING))
time_wait(time_i)
else:
pass
elif status_link in [429, 522]:
if "Just a moment" in req.text:
print("{} {} Cloudflare protection activated, wait 60s please".format(get_date(), WARNING))
time_wait(time_i)
else:
req_test_many = s.get(url, verify=False, timeout=10, allow_redirects=False, headers=basic_user_agent)
if req_test_many in [429, 522]:
print("{} {} Too many requests, web service seem to be offline".format(get_date(), WARNING))
print("{} {} STOP so many requests, we should wait a little...".format(get_date(), WARNING))
time_wait(time_i)
else:
pass
except Timeout:
n_error += 1
#traceback.print_exc() #DEBUG
with open(directory + "/errors.txt", "a+") as write_error:
write_error.write(res+"\n")
#pass
except Exception:
n_error += 1
if print_error:
traceback.print_exc() #DEBUG
with open(directory + "/errors.txt", "a+") as write_error:
write_error.write(res+"\n")
q.task_done()
except Exception:
n_error += 1
if print_error:
traceback.print_exc() #DEBUG
q.task_done()
Progress(len_w, thread_count, nLine, page, percentage, tw, bp_current)
def time_wait(time_i):
while time_i != 0:
time_i -= 1
time.sleep(1)
sys.stdout.write(" Time Remaining for thread: {}\r".format(time_i))
def html_actions(directory, res, req, parsing):
dl(res, req, directory) # dl files and calcul size
parsing.html_recon(res, req, directory) #try to found S3 buckets
parsing.get_links(req, directory) #scrape all link
if js:
parsing.get_javascript(res, req, directory) #try to found js keyword
def status(r, stat, directory, u_agent, thread, manageDir):
"""
Status:
- Get response status of the website (200, 302, 404...).
- Check if a backup exist before to start the scan.
If exist it restart scan from to the last line of backup.
"""
check_b = manageDir.check_backup(directory)
#check backup before start scan
last_line = ''
if check_b == True:
with open(directory + "/backup.txt", "r") as word:
for ligne in word.readlines():
print("{}{}{}".format(BACK, url, ligne.strip()))
lignes = ligne.split("\n") #take the last line in file
last_line = lignes[-2]
with open(wordlist, "r") as f:
for nLine, line in enumerate(f):
if line.strip() == last_line:
print(LINE)
forced = False
check_words(url, wordlist, directory, u_agent, thread, forced, nLine)
elif not check_b:
try:
os.remove(directory + "/backup.txt")
print("{} Restarting scan...".format(INFO))
except:
pass
print(LINE)
if auth:
r = requests.get(url, allow_redirects=False, verify=False, auth=(auth.split(":")[0], auth.split(":")[1]))
if r.status_code in [200, 302, 301]:
print("{} Authentification successfull\n".format(PLUS))
stat = r.status_code
else:
print("{} Authentification error".format(LESS))
continue_error = input("The authentification seems bad, continue ? [y/N]")
if continue_error not in ["y", "Y"]:
sys.exit()
if stat == 200:
check_words(url, wordlist, directory, u_agent, thread)
elif stat in [301, 302]:
req_red = requests.get(url, verify=False, headers=basic_user_agent)
message_type = "Permanently" if stat == 301 else "Temporarily"
follow = input("{} {} Moved {} → {}\nDo you want follow redirection ? [y/N]".format(PLUS, stat, message_type, req_red.url))
print("")
stat = stat if follow == "y" or follow == "Y" else 0
check_words(url, wordlist, directory, u_agent, thread)
elif stat == 304:
pass
elif stat == 404:
not_found = input("{} URL return 404 response / forced ? [y/N]: ".format(LESS))
if not_found == "y" or not_found == "Y":
forced = True
check_words(url, wordlist, directory, u_agent, thread, forced)
else:
sys.exit()
elif stat in [403, 401]:
fht = input(FORBI + " URL return {} response / forced ? [y/N]: ".format(stat))
if fht == "y" or fht == "Y":
forced = True
check_words(url, wordlist, directory, u_agent, thread, forced)
else:
sys.exit()
else:
not_found = input("{} URL return {} response / forced ? [y/N]: ".format(LESS, stat))
if not_found == "y" or not_found == "Y":
forced = True
check_words(url, wordlist, directory, u_agent, thread, forced)
else:
sys.exit()
def create_backup(res, directory, forbi):
"""Create backup file"""
with open(directory + "/backup.txt", "a+") as words:
#delete url to keep just file or dir
anti_sl = res.split("/")
rep = str(anti_sl[3:])
result = rep.replace("['","").replace("']","").replace("',", "/").replace(" '","")
words.write(result + "\n")
def dl(res, req, directory):
""" Download files """
#extensions = ['.json', '.txt', '.html', '.jsp', '.xml', '.aspx', '.zip', '.old', '.bak',
#'.sql', '.js', '.asp', '.ini', '.rar', '.dat', '.log', '.backup', '.dll', '.save', '.BAK', '.inc', '.md', ".info"]
d_files = directory + "/files/"
if not os.path.exists(d_files):
try:
os.makedirs(d_files)
except:
pass
anti_sl = res.split("/")
rep = anti_sl[3:]
result = rep[-1]
p_file = d_files + result
if "." in result:
with open(p_file, 'w+') as fichier:
try:
fichier.write(str(req.text))
except:
pass
def output_scan(directory, res, size_res, stats):
"""
output_scan:
Output to scan
"""
mo = multiple_outputs()
directory = output if output else directory
if output_type == "csv":
mo.csv_output(directory, res, stats, size_res)
mo.raw_output(directory, res, stats, size_res)
elif output_type == "json":
mo.json_output(directory, res, stats, size_res)
mo.raw_output(directory, res, stats, size_res)
else:
mo.raw_output(directory, res, stats, size_res)
def defined_thread(thread, i, score_next):
"""
Defined_thread: to defined the threads number
"""
#print("score: {}".format(score_next))
thread_count = threading.active_count()
res_time = 0
try:
start = time.time()
req = requests.get(url, verify=False)
end = time.time()
res_time = end - start
except Exception:
pass
if res_time != 0 and res_time < 1 and thread_count < 30:
#automaticly 30 threads MAX
score = 1
if i == 40 and score_next == 0:
return 1, i;
elif i == 160 and score_next == 1:
return 1, i;
elif i == 340 and score_next == 2:
return 1, i;
else:
return 0, score;
else:
return 0, 0;
def defined_connect(s, res, user_agent=False, header_parsed=False):
allow_redirection = True if stat == 301 or stat == 302 else False
global authent
authent = (auth.split(":")[0], auth.split(":")[1]) if auth else False
if header_parsed:
for h in header_parsed:
for u in user_agent:
header = {"{}".format(h):"{}".format(header_parsed[h]), "{}".format(u):"{}".format(user_agent[u])}
else:
if user_agent:
for u in user_agent:
header = {"Connection":"close", "Cache-Control": "no-cache", "{}".format(u):"{}".format(user_agent[u])}
else:
header = {"Connection":"close", "Cache-Control": "no-cache", "Pragma": "no-cache"}
JS_error = ["You need to enable JavaScript to run this app", "JavaScript Required", "without JavaScript enabled",
"This website requires JavaScript", "Please enable JavaScript", "Loading"]
if proxy:
retry_strategy = Retry(
total=2,
status_forcelist=[429, 500, 502, 503, 504],
allowed_methods=["GET"]
)
adapter = HTTPAdapter(max_retries=retry_strategy)
s.mount("https://", adapter)
s.mount("http://", adapter)
ip = random.choice(proxy_list)
if not ip.startswith("http://"):
proxies = {"https": ip}
s.proxies.update(proxies)
else:
proxies = {"https": ip, "http": ip}
s.proxies.update(proxies)
req = s.get(res, headers=header, allow_redirects=allow_redirection, verify=False, timeout=15, auth=authent)
if any(js_e in req.text for js_e in JS_error):
#print("{} This URL need to active JS: {}".format(INFO, res)) #TODO
return 404
else:
return req
def thread_wrapper(i, q, threads, manager, t_event, directory=False, forced=False, u_agent=False):
while not q.empty() and not t_event.isSet():
#print("DEBUG: {}".format(t_event.isSet())) #DEBUG
tryUrl(i, q, threads, manager, directory, forced, u_agent)
def get_date():
now = time.localtime(time.time())
hour_t = time.strftime("%H:%M:%S", now)
HOUR = "\033[36m[{}] \033[0m".format(hour_t)
return HOUR
def Progress(len_w, thread_count, nLine, page, percentage, tw, bp_current):
"""
Progress: just a function to print the scan progress
"""
progress_print = "\033[36m {0}/{1} | T:{2} | Err: {3} | Cb: {4} | {5}\033[0m\r".format(n+nLine, len_w, thread_count, n_error, bp_current, page if len(page) < 55 else page.split("/")[-3:-1])
little_progress_print = "\033[36m {0}/{1} | Err: {2} | Cb: {3} | {4}\033[0m\r".format(n, len_w, n_error, bp_current, page if len(page) < 70 else page.split("/")[-3:-1])
if tw < 110:
sys.stdout.write(little_progress_print)
if len(little_progress_print) > 36: sys.stdout.write("\033[K") #clear line
else:
per = percentage(n+nLine, len_w)
sys.stdout.write("\033[36m {0:.2f}% - {1}/{2} | T:{3} | Err: {4} | Cb: {5} | {6}\033[0m\r".format(per, n+nLine, len_w, thread_count, n_error, bp_current, page if len(page) < 55 else page.split("/")[-3:-1]))
if len(progress_print) > 55: sys.stdout.write("\033[K") #clear line