forked from nischalbijukchhe/lostools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
xlsNinja.py
1564 lines (1323 loc) · 75.3 KB
/
xlsNinja.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
# This program was created by: AnonKryptiQuz, Coffinxp Hexsh1dow and Naho
from concurrent.futures import ThreadPoolExecutor, as_completed
from curses import panel
import random
import re
from wsgiref import headers
class Color:
BLUE = '\033[94m'
GREEN = '\033[1;92m'
YELLOW = '\033[93m'
RED = '\033[91m'
PURPLE = '\033[95m'
CYAN = '\033[96m'
RESET = '\033[0m'
ORANGE = '\033[38;5;208m'
BOLD = '\033[1m'
UNBOLD = '\033[22m'
ITALIC = '\033[3m'
UNITALIC = '\033[23m'
try:
import os
import sys
import subprocess
from colorama import Fore, Style, init
from time import sleep
from rich import print as rich_print
from rich.panel import Panel
from rich.table import Table
import concurrent.futures
from urllib.parse import urlparse, parse_qs, urlencode, urlunparse
from bs4 import BeautifulSoup
import time
import requests
import urllib3
from prompt_toolkit import prompt
from prompt_toolkit.completion import PathCompleter
import subprocess
import sys
import random
from urllib.parse import urlparse, quote
init(autoreset=True)
def check_and_install_packages(packages):
for package, version in packages.items():
try:
__import__(package)
except ImportError:
subprocess.check_call([sys.executable, '-m', 'pip', 'install', f"{package}=={version}"])
def clear_screen():
os.system('cls' if os.name == 'nt' else 'clear')
def display_menu():
title = """
██╗ ██╗██╗ ███████╗███╗ ██╗██╗███╗ ██╗ ██╗ █████╗
╚██╗██╔╝██║ ██╔════╝████╗ ██║██║████╗ ██║ ██║██╔══██╗
╚███╔╝ ██║ ███████╗██╔██╗ ██║██║██╔██╗ ██║ ██║███████║
██╔██╗ ██║ ╚════██║██║╚██╗██║██║██║╚██╗██║██ ██║██╔══██║
██╔╝ ██╗███████╗███████║██║ ╚████║██║██║ ╚████║╚█████╔╝██║ ██║
╚═╝ ╚═╝╚══════╝╚══════╝╚═╝ ╚═══╝╚═╝╚═╝ ╚═══╝ ╚════╝ ╚═╝ ╚═╝
"""
print(Color.ORANGE + Style.BRIGHT + title.center(63))
print(Fore.WHITE + Style.BRIGHT + "─" * 63)
border_color = Color.CYAN + Style.BRIGHT
option_color = Fore.WHITE + Style.BRIGHT
print(border_color + "┌" + "─" * 61 + "┐")
options = [
"1] LFI Scanner",
"2] OR Scanner",
"3] SQL Scanner",
"4] XSS Scanner",
"5] Exit"
]
for option in options:
print(border_color + "│" + option_color + option.ljust(59) + border_color + "│")
print(border_color + "└" + "─" * 61 + "┘")
authors = "Created by: AnonKryptiQuz, CoffinXP, HexSh1dow, and Naho"
instructions = "Select an option by entering the corresponding number:"
print(Fore.WHITE + Style.BRIGHT + "─" * 63)
print(Fore.WHITE + Style.BRIGHT + authors.center(63))
print(Fore.WHITE + Style.BRIGHT + "─" * 63)
print(Fore.WHITE + Style.BRIGHT + instructions.center(63))
print(Fore.WHITE + Style.BRIGHT + "─" * 63)
def print_exit_menu():
clear_screen()
panel = Panel(
"""
__ _ ___ _
_ __/ /____/ | / (_)___ (_)___ _
| |/_/ / ___/ |/ / / __ \ / / __ `/
_> </ (__ ) /| / / / / / / / /_/ /
/_/|_/_/____/_/ |_/_/_/ /_/_/ /\__,_/
/___/
Credit - AnonKryptiQuz x Coffinxp x Hexsh1dow x Naho
""",
style="bold green",
border_style="blue",
expand=False
)
rich_print(panel)
print(Color.RED + "\n\nSession Off ...\n")
exit()
def run_sql_scanner():
try:
import requests
import logging
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import urllib3
import time
import concurrent.futures
from colorama import Fore, init
import os
from prompt_toolkit import prompt
from prompt_toolkit.completion import PathCompleter
import subprocess
import sys
import random
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
init(autoreset=True)
USER_AGENTS = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Version/14.1.2 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Edge/91.0.864.70",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Firefox/89.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:91.0) Gecko/20100101 Firefox/91.0",
"Mozilla/5.0 (Linux; Android 10; SM-G973F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.120 Mobile Safari/537.36",
"Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Mobile Safari/537.36",
]
WAF_SIGNATURES = {
'Cloudflare': ['cf-ray', 'cloudflare', 'cf-request-id', 'cf-cache-status'],
'Akamai': ['akamai', 'akamai-ghost', 'akamai-x-cache', 'x-akamai-request-id'],
'Sucuri': ['x-sucuri-id', 'sucuri', 'x-sucuri-cache'],
'ModSecurity': ['mod_security', 'modsecurity', 'x-modsecurity-id', 'x-mod-sec-rule'],
'Barracuda': ['barra', 'x-barracuda', 'bnmsg'],
'Imperva': ['x-cdn', 'imperva', 'incapsula', 'x-iinfo', 'x-cdn-forward'],
'F5 Big-IP ASM': ['x-waf-status', 'f5', 'x-waf-mode', 'x-asm-ver'],
'DenyAll': ['denyall', 'sessioncookie'],
'FortiWeb': ['fortiwafsid', 'x-fw-debug'],
'Jiasule': ['jsluid', 'jiasule'],
'AWS WAF': ['awswaf', 'x-amzn-requestid', 'x-amzn-trace-id'],
'StackPath': ['stackpath', 'x-sp-url', 'x-sp-waf'],
'BlazingFast': ['blazingfast', 'x-bf-cache-status', 'bf'],
'NSFocus': ['nsfocus', 'nswaf', 'nsfocuswaf'],
'Edgecast': ['ecdf', 'x-ec-custom-error'],
'Alibaba Cloud WAF': ['ali-cdn', 'alibaba'],
'AppTrana': ['apptrana', 'x-wf-sid'],
'Radware': ['x-rdwr', 'rdwr'],
'SafeDog': ['safedog', 'x-sd-id'],
'Comodo WAF': ['x-cwaf', 'comodo'],
'Yundun': ['yundun', 'yunsuo'],
'Qiniu': ['qiniu', 'x-qiniu'],
'NetScaler': ['netscaler', 'x-nsprotect'],
'Securi': ['x-sucuri-id', 'sucuri', 'x-sucuri-cache'],
'Reblaze': ['x-reblaze-protection', 'reblaze'],
'Microsoft Azure WAF': ['azure', 'x-mswaf', 'x-azure-ref'],
'NAXSI': ['x-naxsi-sig'],
'Wallarm': ['x-wallarm-waf-check', 'wallarm'],
}
def get_random_user_agent():
return random.choice(USER_AGENTS)
def check_and_install_packages(packages):
for package, version in packages.items():
try:
__import__(package)
except ImportError:
subprocess.check_call([sys.executable, '-m', 'pip', 'install', f"{package}=={version}"])
def clear_screen():
os.system('cls' if os.name == 'nt' else 'clear')
def get_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504)):
session = requests.Session()
retry = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
return session
def detect_waf(url, headers, cookies=None):
session = get_retry_session()
waf_detected = None
try:
response = session.get(url, headers=headers, cookies=cookies, verify=False)
for waf_name, waf_identifiers in WAF_SIGNATURES.items():
if any(identifier in response.headers.get('server', '').lower() for identifier in waf_identifiers):
print(f"{Fore.GREEN}[+] WAF Detected: {waf_name}{Fore.RESET}")
waf_detected = waf_name
break
except requests.exceptions.RequestException as e:
logging.error(f"Error detecting WAF: {e}")
if not waf_detected:
print(f"{Fore.GREEN}[+] No WAF detected.{Fore.RESET}")
return waf_detected
def perform_request(url, payload, cookie):
url_with_payload = f"{url}{payload}"
start_time = time.time()
headers = {
'User-Agent': get_random_user_agent()
}
try:
response = requests.get(url_with_payload, headers=headers, cookies={'cookie': cookie} if cookie else None)
response.raise_for_status()
success = True
error_message = None
except requests.exceptions.RequestException as e:
success = False
error_message = str(e)
response_time = time.time() - start_time
return success, url_with_payload, response_time, error_message
def get_file_path(prompt_text):
completer = PathCompleter()
return prompt(prompt_text, completer=completer).strip()
def handle_exception(exc_type, exc_value, exc_traceback):
if issubclass(exc_type, KeyboardInterrupt):
print(f"\n{Fore.YELLOW}Program terminated by the user!")
save_prompt()
sys.exit(0)
else:
print(f"\n{Fore.RED}An unexpected error occurred: {exc_value}")
sys.exit(1)
def save_prompt(vulnerable_urls=[]):
save_choice = input(f"{Fore.CYAN}\n[?] Do you want to save the vulnerable URLs to a file? (y/n, press Enter for n): ").strip().lower()
if save_choice == 'y':
output_file = input(f"{Fore.CYAN}[?] Enter the name of the output file (press Enter for 'vulnerable_urls.txt'): ").strip() or 'vulnerable_urls.txt'
with open(output_file, 'w') as f:
for url in vulnerable_urls:
f.write(url + '\n')
print(f"{Fore.GREEN}Vulnerable URLs have been saved to {output_file}")
os._exit(0)
else:
print(f"{Fore.YELLOW}Vulnerable URLs will not be saved.")
os._exit(0)
def prompt_for_urls():
while True:
try:
url_input = get_file_path("[?] Enter the path to the input file containing the URLs (or press Enter to input a single URL): ")
if url_input:
if not os.path.isfile(url_input):
raise FileNotFoundError(f"File not found: {url_input}")
with open(url_input) as file:
urls = [line.strip() for line in file if line.strip()]
return urls
else:
single_url = input(f"{Fore.CYAN}[?] Enter a single URL to scan: ").strip()
if single_url:
return [single_url]
else:
print(f"{Fore.RED}[!] You must provide either a file with URLs or a single URL.")
input(f"{Fore.YELLOW}\n[i] Press Enter to try again...")
clear_screen()
print(f"{Fore.GREEN}Welcome to the xlsNinja SQL-Injector! -AnonKryptiQuz x Coffinxp x Hexsh1dow x Naho\n")
except Exception as e:
print(f"{Fore.RED}[!] Error reading input file: {url_input}. Exception: {str(e)}")
input(f"{Fore.YELLOW}[i] Press Enter to try again...")
clear_screen()
print(f"{Fore.GREEN}Welcome to the xlsNinja SQL-Injector! -AnonKryptiQuz x Coffinxp x Hexsh1dow x Naho\n")
def prompt_for_payloads():
while True:
try:
payload_input = get_file_path("[?] Enter the path to the payloads file: ")
if not os.path.isfile(payload_input):
raise FileNotFoundError(f"File not found: {payload_input}")
with open(payload_input) as file:
payloads = [line.strip() for line in file if line.strip()]
return payloads
except Exception as e:
print(f"{Fore.RED}[!] Error reading payload file: {payload_input}. Exception: {str(e)}")
input(f"{Fore.YELLOW}[i] Press Enter to try again...")
clear_screen()
print(f"{Fore.GREEN}Welcome to the xlsNinja SQL-Injector! -AnonKryptiQuz x Coffinxp x Hexsh1dow x Naho \n")
def print_scan_summary(total_found, total_scanned, start_time):
print(f"{Fore.YELLOW}\n[i] Scanning finished.")
print(f"{Fore.YELLOW}[i] Total found: {total_found}")
print(f"{Fore.YELLOW}[i] Total scanned: {total_scanned}")
print(f"{Fore.YELLOW}[i] Time taken: {int(time.time() - start_time)} seconds")
def main():
clear_screen()
required_packages = {
'requests': '2.28.1',
'prompt_toolkit': '3.0.36',
'colorama': '0.4.6'
}
check_and_install_packages(required_packages)
time.sleep(3)
clear_screen()
panel = Panel(
"""
___
_________ _/ (_) ______________ _____ ____ ___ _____
/ ___/ __ `/ / / / ___/ ___/ __ `/ __ \/ __ \/ _ \/ ___/
(__ ) /_/ / / / (__ ) /__/ /_/ / / / / / / / __/ /
/____/\__, /_/_/ /____/\___/\__,_/_/ /_/_/ /_/\___/_/
/_/
""",
style="bold green",
border_style="blue",
expand=False
)
rich_print(panel, "\n")
print(Fore.GREEN + "Welcome to the SQL Testing Tool!\n")
urls = prompt_for_urls()
payloads = prompt_for_payloads()
cookie = input("[?] Enter the cookie to include in the GET request (press Enter if none): ").strip() or None
threads = int(input("[?] Enter the number of concurrent threads (0-10, press Enter for 5): ").strip() or 5)
print(f"\n{Fore.YELLOW}[i] Loading, Please Wait...")
time.sleep(3)
clear_screen()
print(f"{Fore.CYAN}[i] Starting scan...")
vulnerable_urls = []
first_vulnerability_prompt = True
single_url_scan = len(urls) == 1
start_time = time.time()
total_scanned = 0
print(f"{Fore.CYAN}[i] Checking for WAF on target URLs...")
for url in urls:
headers = {'User-Agent': get_random_user_agent()}
detect_waf(url, headers, cookies={'cookie': cookie} if cookie else None)
try:
if threads == 0:
for url in urls:
for payload in payloads:
total_scanned += 1
success, url_with_payload, response_time, error_message = perform_request(url, payload, cookie)
if response_time >= 10:
stripped_payload = url_with_payload.replace(url, '')
encoded_stripped_payload = quote(stripped_payload, safe='')
encoded_url = f"{url}{encoded_stripped_payload}"
if single_url_scan:
print(f"{Fore.YELLOW}\n[i] Scanning with payload: {stripped_payload}")
encoded_url_with_payload = encoded_url
else:
list_stripped_payload = url_with_payload
for url in urls:
list_stripped_payload = list_stripped_payload.replace(url, '')
encoded_stripped_payload = quote(list_stripped_payload, safe='')
encoded_url_with_payload = url_with_payload.replace(list_stripped_payload, encoded_stripped_payload)
print(f"{Fore.YELLOW}\n[i] Scanning with payload: {list_stripped_payload}")
print(f"{Fore.GREEN}Vulnerable: {Fore.WHITE}{encoded_url_with_payload}{Fore.CYAN} - Response Time: {response_time:.2f} seconds")
vulnerable_urls.append(url_with_payload)
if single_url_scan and first_vulnerability_prompt:
continue_scan = input(f"{Fore.CYAN}\n[?] Vulnerability found. Do you want to continue testing other payloads? (y/n, press Enter for n): ").strip().lower()
if continue_scan != 'y':
end_time = time.time()
time_taken = end_time - start_time
print(f"{Fore.YELLOW}\n[i] Scanning finished.")
print(f"{Fore.YELLOW}[i] Total found: {len(vulnerable_urls)}")
print(f"{Fore.YELLOW}[i] Total scanned: {total_scanned}")
print(f"{Fore.YELLOW}[i] Time taken: {time_taken:.2f} seconds")
save_prompt(vulnerable_urls)
return
first_vulnerability_prompt = False
else:
stripped_payload = url_with_payload.replace(url, '')
encoded_stripped_payload = quote(stripped_payload, safe='')
encoded_url = f"{url}{encoded_stripped_payload}"
if single_url_scan:
print(f"{Fore.YELLOW}\n[i] Scanning with payload: {stripped_payload}")
encoded_url_with_payload = encoded_url
else:
list_stripped_payload = url_with_payload
for url in urls:
list_stripped_payload = list_stripped_payload.replace(url, '')
encoded_stripped_payload = quote(list_stripped_payload, safe='')
encoded_url_with_payload = url_with_payload.replace(list_stripped_payload, encoded_stripped_payload)
print(f"{Fore.YELLOW}\n[i] Scanning with payload: {list_stripped_payload}")
print(f"{Fore.RED}Not Vulnerable: {Fore.WHITE}{encoded_url_with_payload}{Fore.CYAN} - Response Time: {response_time:.2f} seconds")
else:
with concurrent.futures.ThreadPoolExecutor(max_workers=threads) as executor:
futures = []
for url in urls:
for payload in payloads:
total_scanned += 1
futures.append(executor.submit(perform_request, url, payload, cookie))
for future in concurrent.futures.as_completed(futures):
success, url_with_payload, response_time, error_message = future.result()
if response_time >= 10:
stripped_payload = url_with_payload.replace(url, '')
encoded_stripped_payload = quote(stripped_payload, safe='')
encoded_url = f"{url}{encoded_stripped_payload}"
if single_url_scan:
print(f"{Fore.YELLOW}\n[i] Scanning with payload: {stripped_payload}")
encoded_url_with_payload = encoded_url
else:
list_stripped_payload = url_with_payload
for url in urls:
list_stripped_payload = list_stripped_payload.replace(url, '')
encoded_stripped_payload = quote(list_stripped_payload, safe='')
encoded_url_with_payload = url_with_payload.replace(list_stripped_payload, encoded_stripped_payload)
print(f"{Fore.YELLOW}\n[i] Scanning with payload: {list_stripped_payload}")
print(f"{Fore.GREEN}Vulnerable: {Fore.WHITE}{encoded_url_with_payload}{Fore.CYAN} - Response Time: {response_time:.2f} seconds")
vulnerable_urls.append(url_with_payload)
if single_url_scan and first_vulnerability_prompt:
continue_scan = input(f"{Fore.CYAN}\n[?] Vulnerability found. Do you want to continue testing other payloads? (y/n, press Enter for n): ").strip().lower()
if continue_scan != 'y':
end_time = time.time()
time_taken = end_time - start_time
print(f"{Fore.YELLOW}\n[i] Scanning finished.")
print(f"{Fore.YELLOW}[i] Total found: {len(vulnerable_urls)}")
print(f"{Fore.YELLOW}[i] Total scanned: {total_scanned}")
print(f"{Fore.YELLOW}[i] Time taken: {time_taken:.2f} seconds")
save_prompt(vulnerable_urls)
return
first_vulnerability_prompt = False
else:
stripped_payload = url_with_payload.replace(url, '')
encoded_stripped_payload = quote(stripped_payload, safe='')
encoded_url = f"{url}{encoded_stripped_payload}"
if single_url_scan:
print(f"{Fore.YELLOW}\n[i] Scanning with payload: {stripped_payload}")
encoded_url_with_payload = encoded_url
else:
list_stripped_payload = url_with_payload
for url in urls:
list_stripped_payload = list_stripped_payload.replace(url, '')
encoded_stripped_payload = quote(list_stripped_payload, safe='')
encoded_url_with_payload = url_with_payload.replace(list_stripped_payload, encoded_stripped_payload)
print(f"{Fore.YELLOW}\n[i] Scanning with payload: {list_stripped_payload}")
print(f"{Fore.RED}Not Vulnerable: {Fore.WHITE}{encoded_url_with_payload}{Fore.CYAN} - Response Time: {response_time:.2f} seconds")
print_scan_summary(len(vulnerable_urls), total_scanned, start_time)
save_prompt(vulnerable_urls)
except KeyboardInterrupt:
print(f"\n{Fore.YELLOW}Program terminated by the user!\n")
print(f"{Fore.YELLOW}[i] Total found: {len(vulnerable_urls)}")
print(f"{Fore.YELLOW}[i] Total scanned: {total_scanned}")
print(f"{Fore.YELLOW}[i] Time taken: {time_taken:.2f} seconds")
save_prompt(vulnerable_urls)
sys.exit(0)
if __name__ == "__main__":
sys.excepthook = handle_exception
main()
except KeyboardInterrupt:
print(f"\n{Fore.YELLOW}Program terminated by the user!")
sys.exit(0)
def run_xss_scanner():
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
import argparse
import subprocess
import sys
import time
import aiohttp
import asyncio
import logging
import os
from colorama import Fore, init
from urllib.parse import urlencode, parse_qs, urlsplit, urlunsplit
from prompt_toolkit import prompt
from prompt_toolkit.completion import PathCompleter
from rich import print as rich_print
from rich.panel import Panel
from rich.table import Table
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
from selenium import webdriver
from selenium.webdriver.chrome.service import Service as ChromeService
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from webdriver_manager.chrome import ChromeDriverManager
import logging
logging.getLogger('WDM').setLevel(logging.ERROR)
init(autoreset=True)
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
USER_AGENTS = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Version/14.1.2 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Edge/91.0.864.70",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Firefox/89.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:91.0) Gecko/20100101 Firefox/91.0",
"Mozilla/5.0 (Linux; Android 10; SM-G973F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.120 Mobile Safari/537.36",
"Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Mobile Safari/537.36",
]
WAF_SIGNATURES = {
'Cloudflare': ['cf-ray', 'cloudflare', 'cf-request-id', 'cf-cache-status'],
'Akamai': ['akamai', 'akamai-ghost', 'akamai-x-cache', 'x-akamai-request-id'],
'Sucuri': ['x-sucuri-id', 'sucuri', 'x-sucuri-cache'],
'ModSecurity': ['mod_security', 'modsecurity', 'x-modsecurity-id', 'x-mod-sec-rule'],
'Barracuda': ['barra', 'x-barracuda', 'bnmsg'],
'Imperva': ['x-cdn', 'imperva', 'incapsula', 'x-iinfo', 'x-cdn-forward'],
'F5 Big-IP ASM': ['x-waf-status', 'f5', 'x-waf-mode', 'x-asm-ver'],
'DenyAll': ['denyall', 'sessioncookie'],
'FortiWeb': ['fortiwafsid', 'x-fw-debug'],
'Jiasule': ['jsluid', 'jiasule'],
'AWS WAF': ['awswaf', 'x-amzn-requestid', 'x-amzn-trace-id'],
'StackPath': ['stackpath', 'x-sp-url', 'x-sp-waf'],
'BlazingFast': ['blazingfast', 'x-bf-cache-status', 'bf'],
'NSFocus': ['nsfocus', 'nswaf', 'nsfocuswaf'],
'Edgecast': ['ecdf', 'x-ec-custom-error'],
'Alibaba Cloud WAF': ['ali-cdn', 'alibaba'],
'AppTrana': ['apptrana', 'x-wf-sid'],
'Radware': ['x-rdwr', 'rdwr'],
'SafeDog': ['safedog', 'x-sd-id'],
'Comodo WAF': ['x-cwaf', 'comodo'],
'Yundun': ['yundun', 'yunsuo'],
'Qiniu': ['qiniu', 'x-qiniu'],
'NetScaler': ['netscaler', 'x-nsprotect'],
'Securi': ['x-sucuri-id', 'sucuri', 'x-sucuri-cache'],
'Reblaze': ['x-reblaze-protection', 'reblaze'],
'Microsoft Azure WAF': ['azure', 'x-mswaf', 'x-azure-ref'],
'NAXSI': ['x-naxsi-sig'],
'Wallarm': ['x-wallarm-waf-check', 'wallarm'],
}
def check_and_install_packages(packages):
for package, version in packages.items():
try:
__import__(package)
except ImportError:
subprocess.check_call([sys.executable, '-m', 'pip', 'install', f"{package}=={version}"])
def clear_screen():
os.system('cls' if os.name == 'nt' else 'clear')
def get_random_user_agent():
return random.choice(USER_AGENTS)
def get_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504)):
session = requests.Session()
retry = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
return session
def detect_waf(url, headers):
session = get_retry_session()
waf_detected = None
try:
response = session.get(url, headers=headers, verify=False)
for waf_name, waf_identifiers in WAF_SIGNATURES.items():
if any(identifier in response.headers.get('server', '').lower() for identifier in waf_identifiers):
print(f"{Fore.GREEN}[+] WAF Detected: {waf_name}{Fore.RESET}")
waf_detected = waf_name
break
except requests.exceptions.RequestException as e:
logging.error(f"Error detecting WAF: {e}")
if not waf_detected:
print(f"{Fore.GREEN}[+] No WAF detected.{Fore.RESET}")
return waf_detected
class MassScanner:
def __init__(self, urls, output, concurrency, timeout, payload_file, auto_continue=False):
self.urls = urls
self.output = output
self.payloads = self.load_payloads(payload_file)
self.concurrency = concurrency
self.timeout = timeout
self.auto_continue = auto_continue
self.payload_file = payload_file
self.injectables = []
self.totalFound = 0
self.totalScanned = 0
self.t0 = time.time()
self.first_vulnerability_prompt = True
@staticmethod
def load_payloads(payload_file):
payloads = []
if payload_file:
try:
with open(payload_file, "r") as file:
payloads = [line.strip() for line in file if line.strip()]
if not payloads:
raise ValueError("Payload file is empty.")
print(f"{Fore.YELLOW}\n[i] Payloads loaded from file.")
except Exception as e:
logging.error(f"Error loading payload file: {payload_file}. Exception: {str(e)}\n")
print(f"{Fore.RED}[!] Error loading payload file. Please check the file and try again.")
sys.exit(1)
else:
print(f"{Fore.RED}[!] No payload file provided. Exiting.")
sys.exit(1)
return payloads
def generate_payload_urls(self, url, payload):
url_combinations = []
try:
scheme, netloc, path, query_string, fragment = urlsplit(url)
if not scheme:
scheme = 'http'
query_params = parse_qs(query_string, keep_blank_values=True)
for key in query_params.keys():
modified_params = query_params.copy()
modified_params[key] = [payload]
modified_query_string = urlencode(modified_params, doseq=True)
modified_url = urlunsplit((scheme, netloc, path, modified_query_string, fragment))
url_combinations.append(modified_url)
except Exception as e:
logging.error(f"Error generating payload URL for {url} with payload {payload}: {str(e)}")
return url_combinations
async def fetch(self, sem: asyncio.Semaphore, session: aiohttp.ClientSession, url: str):
async with sem:
try:
response_text = ""
async with session.get(url, allow_redirects=True) as resp:
response_headers = resp.headers
content_type = response_headers.get("Content-Type", "")
content_length = int(response_headers.get("Content-Length", -1))
if "text/html" in content_type and (content_length < 0 or content_length <= 1000000):
content = await resp.read()
encoding = 'utf-8'
response_text = content.decode(encoding, errors="ignore")
else:
logging.info(f"Skipping URL due to content type or size: {url}")
except asyncio.TimeoutError:
logging.warning(f"Request timed out for {url}")
except Exception as e:
logging.error(f"Error fetching {url}: {str(e)}")
await asyncio.sleep(0)
return (response_text, url)
def process_tasks(self, done):
for response_text, url in done:
self.totalScanned += 1
chrome_options = Options()
chrome_options.add_argument("--headless")
service = ChromeService(executable_path=ChromeDriverManager().install())
driver = webdriver.Chrome(service=service, options=chrome_options)
try:
driver.get(url)
try:
WebDriverWait(driver, 1).until(EC.alert_is_present())
alert = driver.switch_to.alert
print(Color.GREEN + f"Vulnerable URL : {url}")
alert.dismiss()
self.injectables.append(url)
except:
print(Color.RED + "Not vulnerable")
finally:
driver.quit()
async def scan(self):
sem = asyncio.Semaphore(self.concurrency)
timeout = aiohttp.ClientTimeout(total=self.timeout)
async with aiohttp.ClientSession(timeout=timeout, connector=aiohttp.TCPConnector(ssl=False, limit=0, enable_cleanup_closed=True)) as session:
for payload in self.payloads:
print(f"{Fore.YELLOW}[i] Scanning with payload: {payload}\n")
pending = []
for url in self.urls:
urls_with_payload = self.generate_payload_urls(url.strip(), payload)
for payload_url in urls_with_payload:
pending.append(asyncio.ensure_future(self.fetch(sem, session, payload_url)))
if len(pending) >= self.concurrency:
done = await asyncio.gather(*pending)
self.process_tasks(done)
pending = []
if pending:
done = await asyncio.gather(*pending)
self.process_tasks(done)
if self.payload_file:
if self.totalFound > 0:
if self.first_vulnerability_prompt and not self.auto_continue:
continue_scan = input(f"{Fore.CYAN}\n[?] Vulnerability found. Do you want to continue testing other payloads? (y/n, press Enter for n): ").strip().lower()
if continue_scan != 'y':
break
self.first_vulnerability_prompt = False
elif not self.auto_continue:
self.first_vulnerability_prompt = False
def save_injectables_to_file(self):
if self.injectables:
with open(self.output, "w") as output_file:
for url in self.injectables:
output_file.write(url + "\n")
print(f"{Fore.GREEN}[+] Vulnerable URLs saved to {self.output}")
def run(self):
asyncio.run(self.scan())
print(f"{Fore.YELLOW}\n[i] Scanning finished.")
print(f"{Fore.YELLOW}[i] Total scanned: {self.totalScanned}")
print(f"{Fore.YELLOW}[i] Time taken: {int(time.time() - self.t0)} seconds\n")
print(f"{Fore.GREEN}[i] Vulnerabilities found: {len(self.injectables)}")
if self.injectables:
save_option = input(f"{Fore.CYAN}[?] Do you want to save the vulnerable URLs to {self.output}? (y/n, press Enter for n): ").strip().lower()
if save_option == 'y':
self.save_injectables_to_file()
os._exit(0)
else:
print(f"{Fore.YELLOW}Vulnerable URLs will not be saved.")
os._exit(0)
else:
print(f"{Fore.YELLOW}No vulnerabilities found. No URLs to save.")
os._exit(0)
def save_injectables_to_file(self):
with open(self.output, "w") as output_file:
for url in self.injectables:
output_file.write(url + "\n")
def get_file_path(prompt_text):
completer = PathCompleter()
return prompt(prompt_text, completer=completer).strip()
def prompt_for_urls():
while True:
try:
url_input = None
if url_input:
if not os.path.isfile(url_input):
raise FileNotFoundError(f"File not found: {url_input}")
with open(url_input) as file:
urls = [line.strip() for line in file if line.strip()]
return urls
else:
single_url = input(f"{Fore.CYAN}[?] Enter a single URL to scan: ").strip()
if single_url:
return [single_url]
else:
print(f"{Fore.RED}[!] You must provide either a file with URLs or a single URL.")
input(f"{Fore.YELLOW}[i] Press Enter to try again...")
clear_screen()
print(f"{Fore.GREEN}Welcome to the xlsNinja XSS-Scanner! - AnonKryptiQuz x Coffinxp x Hexsh1dow x Naho\n")
except Exception as e:
print(f"{Fore.RED}[!] Error reading input file: {url_input}. Exception: {str(e)}")
input(f"{Fore.YELLOW}[i] Press Enter to try again...")
clear_screen()
print(f"{Fore.GREEN}Welcome to the xlsNinja XSS-Scanner! - AnonKryptiQuz x Coffinxp x Hexsh1dow x Naho\n")
def prompt_for_valid_file_path(prompt_text):
while True:
file_path = get_file_path(prompt_text).strip()
if not file_path:
print(f"{Fore.RED}[!] You must provide a file containing the Payloads.")
input(f"{Fore.YELLOW}[i] Press Enter to try again...")
clear_screen()
print(f"{Fore.GREEN}Welcome to the xlsNinja XSS-Scanner! - AnonKryptiQuz x Coffinxp x Hexsh1dow x Naho\n")
continue
if os.path.isfile(file_path):
return file_path
else:
print(f"{Fore.RED}[!] Error reading input file: {file_path}.")
input(f"{Fore.YELLOW}[i] Press Enter to try again...")
clear_screen()
print(f"{Fore.GREEN}Welcome to the xlsNinja XSS-Scanner! - AnonKryptiQuz x Coffinxp x Hexsh1dowx Naho\n")
def main():
clear_screen()
required_packages = {
'aiohttp': '3.8.6',
'requests': '2.28.1',
'prompt_toolkit': '3.0.36',
'colorama': '0.4.6'
}
check_and_install_packages(required_packages)
time.sleep(3)
clear_screen()
panel = Panel("""
_ __________ ____________ _ ___ __________
| |/_/ __/ __/ / __/ ___/ _ | / |/ / |/ / __/ _ |
_> <_\ \_\ \ _\ \/ /__/ __ |/ / / _// , _/
/_/|_/___/___/ /___/\___/_/ |_/_/|_/_/|_/___/_/|_|
""",
style="bold green",
border_style="blue",
expand=False
)
rich_print(panel, "\n")
print(Fore.GREEN + "Welcome to the XSS Testing Tool!\n")
urls = prompt_for_urls()
payload_file = prompt_for_valid_file_path("[?] Enter the path to the payload file: ")
output_file = "vulnerable_urls.txt"
concurrency = int(input("\n[?] Enter the number of concurrent threads (0-10, press Enter for 5): ").strip() or 5)
timeout = float(input("[?] Enter the request timeout in seconds (press Enter for 3): ").strip() or 3)
print(f"\n{Fore.YELLOW}[i] Loading, Please Wait...")
time.sleep(3)
clear_screen()
print(f"{Fore.CYAN}[i] Starting scan...")
print(f"{Fore.CYAN}[i] Checking for WAF on target URLs...")
for url in urls:
headers = {'User-Agent': get_random_user_agent()}
detect_waf(url, headers)
scanner = MassScanner(
urls=urls,
output=output_file,
concurrency=concurrency,
timeout=timeout,
payload_file=payload_file,
auto_continue='n'
)
scanner.run()
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
sys.exit(0)
def run_or_scanner():
try:
import requests
import urllib.parse
import os
import sys
import subprocess
import logging
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from prompt_toolkit import prompt
from prompt_toolkit.completion import PathCompleter
from colorama import Fore, init
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
init(autoreset=True)
USER_AGENTS = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Version/14.1.2 Safari/537.36",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Edge/91.0.864.70",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Firefox/89.0",
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:91.0) Gecko/20100101 Firefox/91.0",
"Mozilla/5.0 (Linux; Android 10; SM-G973F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.120 Mobile Safari/537.36",
"Mozilla/5.0 (Linux; Android 11; Pixel 5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Mobile Safari/537.36",
]
WAF_SIGNATURES = {
'Cloudflare': ['cf-ray', 'cloudflare', 'cf-request-id', 'cf-cache-status'],
'Akamai': ['akamai', 'akamai-ghost', 'akamai-x-cache', 'x-akamai-request-id'],
'Sucuri': ['x-sucuri-id', 'sucuri', 'x-sucuri-cache'],
'ModSecurity': ['mod_security', 'modsecurity', 'x-modsecurity-id', 'x-mod-sec-rule'],
'Barracuda': ['barra', 'x-barracuda', 'bnmsg'],
'Imperva': ['x-cdn', 'imperva', 'incapsula', 'x-iinfo', 'x-cdn-forward'],
'F5 Big-IP ASM': ['x-waf-status', 'f5', 'x-waf-mode', 'x-asm-ver'],
'DenyAll': ['denyall', 'sessioncookie'],
'FortiWeb': ['fortiwafsid', 'x-fw-debug'],
'Jiasule': ['jsluid', 'jiasule'],
'AWS WAF': ['awswaf', 'x-amzn-requestid', 'x-amzn-trace-id'],
'StackPath': ['stackpath', 'x-sp-url', 'x-sp-waf'],
'BlazingFast': ['blazingfast', 'x-bf-cache-status', 'bf'],
'NSFocus': ['nsfocus', 'nswaf', 'nsfocuswaf'],
'Edgecast': ['ecdf', 'x-ec-custom-error'],
'Alibaba Cloud WAF': ['ali-cdn', 'alibaba'],
'AppTrana': ['apptrana', 'x-wf-sid'],
'Radware': ['x-rdwr', 'rdwr'],
'SafeDog': ['safedog', 'x-sd-id'],
'Comodo WAF': ['x-cwaf', 'comodo'],
'Yundun': ['yundun', 'yunsuo'],
'Qiniu': ['qiniu', 'x-qiniu'],
'NetScaler': ['netscaler', 'x-nsprotect'],
'Securi': ['x-sucuri-id', 'sucuri', 'x-sucuri-cache'],
'Reblaze': ['x-reblaze-protection', 'reblaze'],
'Microsoft Azure WAF': ['azure', 'x-mswaf', 'x-azure-ref'],
'NAXSI': ['x-naxsi-sig'],
'Wallarm': ['x-wallarm-waf-check', 'wallarm'],
}
def get_random_user_agent():
return random.choice(USER_AGENTS)
def get_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504)):
session = requests.Session()
retry = Retry(
total=retries,
read=retries,
connect=retries,
backoff_factor=backoff_factor,
status_forcelist=status_forcelist,
)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
return session
def detect_waf(url, headers):
session = get_retry_session()
waf_detected = None
try: