forked from gotr00t0day/spyhunt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathspyhunt.py
2192 lines (1837 loc) · 89.9 KB
/
spyhunt.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
from colorama import Fore, init, Style
from os import path
from builtwith import builtwith
from modules.favicon import *
from bs4 import BeautifulSoup
from multiprocessing.pool import ThreadPool
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import urlparse, urljoin, urlencode, parse_qs, quote_plus
from modules import useragent_list
from modules import sub_output
from googlesearch import search
from alive_progress import alive_bar
from queue import Queue
from shutil import which
from collections import defaultdict
from datetime import datetime
import threading
import os.path
import concurrent.futures
import multiprocessing
import os.path
import socket
import subprocess
import sys
import socket
import os
import argparse
import time
import codecs
import requests
import mmh3
import urllib3
import warnings
import re
import nmap3
import json
import shodan
import ipaddress
import random
import string
import html
import asyncio
import aiohttp
warnings.filterwarnings(action='ignore',module='bs4')
requests.packages.urllib3.disable_warnings()
banner = """
███████╗██████╗ ██╗ ██╗██╗ ██╗██╗ ██╗███╗ ██╗████████╗
██╔════╝██╔══██╗╚██╗ ██╔╝██║ ██║██║ ██║████╗ ██║╚══██╔══╝
███████╗██████╔╝ ╚████╔╝ ███████║██║ ██║██╔██╗ ██║ ██║
╚════██║██╔═══╝ ╚██╔╝ ██╔══██║██║ ██║██║╚██╗██║ ██║
███████║██║ ██║ ██║ ██║╚██████╔╝██║ ╚████║ ██║
╚══════╝╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝
V 2.4
By c0deninja
"""
print(Fore.CYAN + banner)
print(Fore.WHITE)
def commands(cmd):
try:
subprocess.check_call(cmd, shell=True)
except:
pass
def scan(command: str) -> str:
cmd = command
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, err = p.communicate()
out = out.decode()
return out
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group()
update_group = parser.add_argument_group('Update')
nuclei_group = parser.add_argument_group('Nuclei Scans')
vuln_group = parser.add_argument_group('Vulnerability')
crawlers_group = parser.add_argument_group('Crawlers')
passiverecon_group = parser.add_argument_group('Passive Recon')
fuzzing_group = parser.add_argument_group('Fuzzing')
portscanning_group = parser.add_argument_group('Port Scanning')
group.add_argument('-sv', '--save', action='store',
help="save output to file",
metavar="filename.txt")
group.add_argument('-wl', '--wordlist', action='store',
help="wordlist to use",
metavar="filename.txt")
parser.add_argument('-th', '--threads',
type=str, help='default 25',
metavar='25')
passiverecon_group.add_argument('-s',
type=str, help='scan for subdomains',
metavar='domain.com')
passiverecon_group.add_argument('-t', '--tech',
type=str, help='find technologies',
metavar='domain.com')
passiverecon_group.add_argument('-d', '--dns',
type=str, help='scan a list of domains for dns records',
metavar='domains.txt')
parser.add_argument('-p', '--probe',
type=str, help='probe domains.',
metavar='domains.txt')
parser.add_argument('-r', '--redirects',
type=str, help='links getting redirected',
metavar='domains.txt')
vuln_group.add_argument('-b', '--brokenlinks',
type=str, help='search for broken links',
metavar='domains.txt')
crawlers_group.add_argument('-pspider', '--paramspider',
type=str, help='extract parameters from a domain',
metavar='domain.com')
crawlers_group.add_argument('-w', '--waybackurls',
type=str, help='scan for waybackurls',
metavar='https://domain.com')
crawlers_group.add_argument('-j',
type=str, help='find javascript files',
metavar='domain.com')
crawlers_group.add_argument('-wc', '--webcrawler',
type=str, help='scan for urls and js files',
metavar='https://domain.com')
parser.add_argument('-fi', '--favicon',
type=str, help='get favicon hashes',
metavar='https://domain.com')
parser.add_argument('-fm', '--faviconmulti',
type=str, help='get favicon hashes',
metavar='https://domain.com')
passiverecon_group.add_argument('-na', '--networkanalyzer',
type=str, help='net analyzer',
metavar='https://domain.com')
parser.add_argument('-ri', '--reverseip',
type=str, help='reverse ip lookup',
metavar='IP')
parser.add_argument('-rim', '--reverseipmulti',
type=str, help='reverse ip lookup for multiple ips',
metavar='IP')
parser.add_argument('-sc', '--statuscode',
type=str, help='statuscode',
metavar='domain.com')
vuln_group.add_argument('-ph', '--pathhunt',
type=str, help='check for directory traversal',
metavar='domain.txt')
vuln_group.add_argument('-co', '--corsmisconfig',
type=str, help='cors misconfiguration',
metavar='domains.txt')
vuln_group.add_argument('-hh', '--hostheaderinjection',
type=str, help='host header injection',
metavar='domain.com')
parser.add_argument('-sh', '--securityheaders',
type=str, help='scan for security headers',
metavar='domain.com')
parser.add_argument('-ed', '--enumeratedomain',
type=str, help='enumerate domains',
metavar='domain.com')
vuln_group.add_argument('-smu', '--smuggler',
type=str, help='enumerate domains',
metavar='domain.com')
passiverecon_group.add_argument('-ips', '--ipaddresses',
type=str, help='get the ips from a list of domains',
metavar='domain list')
passiverecon_group.add_argument('-dinfo', '--domaininfo',
type=str, help='get domain information like codes,server,content length',
metavar='domain list')
parser.add_argument('-isubs', '--importantsubdomains',
type=str, help='extract interesting subdomains from a list like dev, admin, test and etc..',
metavar='domain list')
fuzzing_group.add_argument('-nft', '--not_found',
type=str, help='check for 404 status code',
metavar='domains.txt')
portscanning_group.add_argument('-n', '--nmap',
type=str, help='Scan a target with nmap',
metavar='domain.com or IP')
fuzzing_group.add_argument('-api', '--api_fuzzer',
type=str, help='Look for API endpoints',
metavar='domain.com')
passiverecon_group.add_argument('-sho', '--shodan',
type=str, help='Recon with shodan',
metavar='domain.com')
vuln_group.add_argument('-fp', '--forbiddenpass',
type=str, help='Bypass 403 forbidden',
metavar='domain.com')
fuzzing_group.add_argument('-db', '--directorybrute',
type=str, help='Brute force filenames and directories',
metavar='domain.com')
portscanning_group.add_argument('-cidr', '--cidr_notation',
type=str, help='Scan an ip range to find assets and services',
metavar='IP/24')
portscanning_group.add_argument('-ps', '--ports',
type=str, help='Port numbers to scan',
metavar='80,443,8443')
portscanning_group.add_argument('-pai', '--print_all_ips',
type=str, help='Print all ips',
metavar='IP/24')
vuln_group.add_argument('-xss', '--xss_scan',
type=str, help='scan for XSS vulnerabilities',
metavar='https://example.com/page?param=value')
vuln_group.add_argument('-sqli', '--sqli_scan',
type=str, help='scan for SQLi vulnerabilities',
metavar='https://example.com/page?param=value')
passiverecon_group.add_argument('-shodan', '--shodan_api',
type=str, help='shodan api key',
metavar='KEY')
parser.add_argument('-webserver', '--webserver_scan',
type=str, help='webserver scan',
metavar='domain.com')
crawlers_group.add_argument('-javascript', '--javascript_scan',
type=str, help='scan for sensitive info in javascript files',
metavar='domain.com')
crawlers_group.add_argument('-dp', '--depth',
type=str, help='depth of the crawl',
metavar='10')
crawlers_group.add_argument('-je', '--javascript_endpoints',
type=str, help='extract javascript endpoints',
metavar='file.txt')
fuzzing_group.add_argument('-pm', '--param_miner',
type=str, help='param miner',
metavar='domain.com')
fuzzing_group.add_argument('-ch', '--custom_headers',
type=str, help='custom headers',
metavar='domain.com')
vuln_group.add_argument('-or', '--openredirect',
type=str, help='open redirect',
metavar='domain.com')
fuzzing_group.add_argument('-asn', '--automoussystemnumber',
type=str, help='asn',
metavar='AS55555')
parser.add_argument("-v", "--verbose", action="store_true", help="Increase output verbosity")
parser.add_argument("-c", "--concurrency", type=int, default=10, help="Maximum number of concurrent requests")
nuclei_group.add_argument('-nl', '--nuclei_lfi', action='store_true', help="Find Local File Inclusion with nuclei")
passiverecon_group.add_argument('-gs', '--google', action='store_true', help='Google Search')
fuzzing_group.add_argument("-e", "--extensions", help="Comma-separated list of file extensions to scan", default="")
fuzzing_group.add_argument("-x", "--exclude", help="Comma-separated list of status codes to exclude", default="")
update_group.add_argument('-u', '--update', action='store_true', help='Update the script')
parser.add_argument('--shodan-api', help='Shodan API key for subdomain enumeration')
args = parser.parse_args()
user_agent = useragent_list.get_useragent()
header = {"User-Agent": user_agent}
if args.update:
print(Fore.CYAN + "Updating the script...")
commands("git pull")
print(Fore.GREEN + "Script updated!")
sys.exit(0)
if args.s:
current_script_dir = os.path.dirname(os.path.abspath(__file__))
spotter_path = os.path.join(current_script_dir, 'scripts', 'spotter.sh')
certsh_path = os.path.join(current_script_dir, 'scripts', 'certsh.sh')
if args.save:
print(Fore.CYAN + "Saving output to {}...".format(args.save))
cmd = f"subfinder -d {args.s} -silent"
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out, err = p.communicate()
out = out.decode()
with open(f"{args.save}", "a") as subfinder:
subfinder.writelines(out)
if path.exists(f"{args.save}"):
print(Fore.GREEN + "DONE!")
if not path.exists(f"{args.save}"):
print(Fore.RED + "ERROR!")
sys.exit(1)
cmd = f"{spotter_path} {args.s} | uniq | sort"
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
spotterout, err = p.communicate()
spotterout = spotterout.decode()
with open(f"{args.save}", "a") as spotter:
spotter.writelines(spotterout)
cmd = f"{certsh_path} {args.s} | uniq | sort"
p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
certshout, err = p.communicate()
certshout = certshout.decode()
with open(f"{args.save}", "a") as certsh:
certsh.writelines(certshout)
# Shodan subdomain extraction
if args.shodan_api:
api = shodan.Shodan(args.shodan_api)
try:
results = api.search(f'hostname:*.{args.s}')
shodan_subdomains = set()
for result in results['matches']:
hostnames = result.get('hostnames', [])
for hostname in hostnames:
if hostname.endswith(args.s) and hostname != args.s:
shodan_subdomains.add(hostname)
with open(f"{args.save}", "a") as shodan_file:
for subdomain in sorted(shodan_subdomains):
shodan_file.write(f"{subdomain}\n")
print(Fore.GREEN + f"Added {len(shodan_subdomains)} subdomains from Shodan")
except shodan.APIError as e:
print(Fore.RED + f"Error querying Shodan: {e}")
else:
commands(f"subfinder -d {args.s}")
commands(f"assetfinder -subs-only {args.s} | uniq | sort")
commands(f"{spotter_path} {args.s} | uniq | sort")
commands(f"{certsh_path} {args.s} | uniq | sort")
# Shodan subdomain extraction
if args.shodan_api:
api = shodan.Shodan(args.shodan_api)
try:
results = api.search(f'hostname:*.{args.s}')
shodan_subdomains = set()
for result in results['matches']:
hostnames = result.get('hostnames', [])
for hostname in hostnames:
if hostname.endswith(args.s) and hostname != args.s:
shodan_subdomains.add(hostname)
print(Fore.CYAN + "Subdomains found from Shodan:")
for subdomain in sorted(shodan_subdomains):
print(subdomain)
print(Fore.GREEN + f"Found {len(shodan_subdomains)} subdomains from Shodan")
except shodan.APIError as e:
print(Fore.RED + f"Error querying Shodan: {e}")
if args.reverseip:
domain = socket.gethostbyaddr(args.reverseip)
print(f"{Fore.CYAN}Domain: {Fore.GREEN} {domain[0]}")
if args.reverseipmulti:
try:
with open(f"{args.reverseipmulti}") as f:
ipadd = [x.strip() for x in f.readlines()]
for ips in ipadd:
print(f"{socket.gethostbyaddr(ips)}\n")
except socket.herror:
pass
except FileNotFoundError:
print(f"{Fore.RED} File not found!")
if args.webcrawler:
if args.save:
print(Fore.CYAN + f"Saving output to {args.save}")
commands(f"echo {args.webcrawler} | hakrawler >> {args.save}")
else:
commands(f"echo {args.webcrawler} | hakrawler")
if args.statuscode:
commands(f"echo '{args.statuscode}' | httpx -silent -status-code")
if args.favicon:
response = requests.get(f'{args.favicon}/favicon.ico', verify=False)
favicon = codecs.encode(response.content,"base64")
hash = mmh3.hash(favicon)
print(hash)
if args.enumeratedomain:
try:
server = []
r = requests.get(f"{args.enumeratedomain}", verify=False, headers=header)
domain = args.enumeratedomain
if "https://" in domain:
domain = domain.replace("https://", "")
if "http://" in domain:
domain = domain.replace("http://", "")
ip = socket.gethostbyname(domain)
for value, key in r.headers.items():
if value == "Server" or value == "server":
server.append(key)
if server:
print(f"{Fore.WHITE}{args.enumeratedomain}{Fore.MAGENTA}: {Fore.CYAN}[{ip}] {Fore.WHITE}Server:{Fore.GREEN} {server}")
else:
print(f"{Fore.WHITE}{args.enumeratedomain}{Fore.MAGENTA}: {Fore.CYAN}[{ip}]")
except requests.exceptions.MissingSchema as e:
print(e)
if args.faviconmulti:
print(f"{Fore.MAGENTA}\t\t\t FavIcon Hashes\n")
with open(f"{args.faviconmulti}") as f:
domains = [x.strip() for x in f.readlines()]
try:
for domainlist in domains:
response = requests.get(f'{domainlist}/favicon.ico', verify=False, timeout=60, headers=header)
if response.status_code == 200:
favicon = codecs.encode(response.content,"base64")
hash = mmh3.hash(favicon)
hashes = {}
response = requests.get(f'{domainlist}/favicon.ico', verify=False, timeout=5, headers=header)
if response.status_code == 200:
favicon = codecs.encode(response.content,"base64")
hash = mmh3.hash(favicon)
if "https" in domainlist:
domainlist = domainlist.replace("https://", "")
if "http" in domainlist:
domainlist = domainlist.replace("http://", "")
ip = socket.gethostbyname(domainlist)
if hash == "0":
pass
for value, item in fingerprint.items():
if hash == value:
hashes[hash].append(item)
print(f"{Fore.WHITE}{domainlist} {Fore.MAGENTA}: {Fore.CYAN}[{hash}] {Fore.GREEN}[{ip}]{Fore.YELLOW} [{item}]")
print(f"{Fore.WHITE}{domainlist} {Fore.MAGENTA}: {Fore.CYAN}[{hash}] {Fore.GREEN}[{ip}]{Fore.YELLOW}")
for v,i in hashes.items():
print(f"{Fore.MAGENTA}Servers Found")
print()
print(f"{v}:{i}")
else:
print(f"{Fore.WHITE}{domainlist} {Fore.MAGENTA}: {Fore.CYAN}{hash} {Fore.GREEN}{ip}")
else:
pass
except TimeoutError:
pass
except requests.exceptions.ConnectionError:
pass
except urllib3.exceptions.ProtocolError:
pass
except requests.exceptions.ReadTimeout:
pass
except KeyError:
pass
if args.corsmisconfig:
print(f"\\t\\t\\t{Fore.CYAN}CORS {Fore.MAGENTA}Misconfiguration {Fore.GREEN}Module\\n\\n")
with open(args.corsmisconfig, "r") as f:
domains = [x.strip() for x in f.readlines()]
def check_cors(domainlist):
try:
payload = []
payload.append(domainlist)
payload.append("evil.com")
header = {'Origin': ', '.join(payload)} # Constructing the header correctly here
session = requests.Session()
session.max_redirects = 10
resp = session.get(domainlist, verify=False, headers=header, timeout=(5, 10))
for value, key in resp.headers.items():
if value == "Access-Control-Allow-Origin" and key == header['Origin']:
print(f"{Fore.YELLOW}VULNERABLE: {Fore.GREEN}{domainlist} {Fore.CYAN}PAYLOADS: {Fore.MAGENTA}{', '.join(payload)}")
return
print(f"{Fore.CYAN}NOT VULNERABLE: {Fore.GREEN}{domainlist} {Fore.CYAN}PAYLOADS: {Fore.MAGENTA}{', '.join(payload)}")
except requests.exceptions.RequestException as e:
if isinstance(e, requests.exceptions.ConnectionError):
print(f"{Fore.RED}Connection error occurred while processing {domainlist}")
else:
print(f"{Fore.LIGHTBLACK_EX}Error occurred while processing {domainlist}: {str(e)}")
with ThreadPoolExecutor(max_workers=10) as executor:
futures = [executor.submit(check_cors, domain) for domain in domains]
for future in futures:
try:
future.result()
except Exception as e:
print(f"An error occurred: {e}")
if args.hostheaderinjection:
def check_host_header_injection(domainlist):
session = requests.Session()
headers = {
"X-Forwarded-Host": "evil.com",
"Host": "evil.com",
"X-Forwarded-For": "evil.com",
"X-Client-IP": "evil.com",
"X-Remote-IP": "evil.com",
"X-Remote-Addr": "evil.com",
"X-Host": "evil.com"
}
try:
normal_resp = session.get(domainlist, verify=False, timeout=5)
normal_content = normal_resp.text
for header_name, header_value in headers.items():
resp = session.get(domainlist, verify=False, headers={header_name: header_value}, timeout=5)
if resp.status_code in {301, 302, 303, 307, 308}:
location = resp.headers.get('Location', '')
if 'evil.com' in location.lower():
print(f"{Fore.RED}VULNERABLE: {Fore.GREEN}{domainlist} {Fore.YELLOW}(Redirect to evil.com in Location header)")
return
if resp.text != normal_content:
if 'evil.com' in resp.text.lower():
print(f"{Fore.RED}VULNERABLE: {Fore.GREEN}{domainlist} {Fore.YELLOW}(evil.com found in response body)")
return
print(f"{Fore.CYAN}Not Vulnerable: {Fore.GREEN}{domainlist}")
except requests.exceptions.RequestException as e:
print(f"{Fore.LIGHTBLACK_EX}Error occurred while accessing {domainlist}: {e}")
def main(args):
print(f"{Fore.MAGENTA}\t\t Host Header Injection \n")
print(f"{Fore.WHITE}Checking for {Fore.CYAN}X-Forwarded-Host {Fore.WHITE}and {Fore.CYAN}Host {Fore.WHITE}injections.....\n")
with open(args.hostheaderinjection, "r") as f:
domains = [x.strip() for x in f.readlines()]
with ThreadPoolExecutor(max_workers=10) as executor:
executor.map(check_host_header_injection, domains)
if __name__ == "__main__":
if args.hostheaderinjection:
main(args)
if args.securityheaders:
print(f"{Fore.MAGENTA}\t\t Security Headers\n")
security_headers = ["Strict-Transport-Security", "Content-Security-Policy", "X-Frame-Options", "X-Content-Type-Options", "X-XSS-Protection"]
session = requests.Session()
no_sec = []
found_hd = []
no_dup = []
no_dup_found = []
lower = [x.lower() for x in security_headers]
capital = [x.upper() for x in security_headers]
resp = session.get(f"{args.securityheaders}", verify=False)
print(f"{Fore.CYAN}Domain: {Fore.GREEN}{args.securityheaders}\n")
for item, key in resp.headers.items():
for sec_headers in security_headers:
if sec_headers == item or lower == item or capital == item:
found_hd.append(sec_headers)
[no_dup_found.append(x) for x in found_hd if x not in no_dup_found]
print(f"{Fore.CYAN}{item}: {Fore.YELLOW}{key}")
no_dup = ", ".join(no_dup)
print(lower)
print("\n")
print(f"{Fore.GREEN} Found Security Headers: {Fore.YELLOW} {len(no_dup_found)}\n")
no_dup_found = ", ".join(no_dup_found)
print(f"{Fore.YELLOW} {no_dup_found}\n")
no_headers = [item for item in security_headers if item not in no_dup_found]
print(f"{Fore.RED} Found Missing headers: {Fore.YELLOW} {len(no_headers)}\n")
no_headers = ", ".join(no_headers)
print(f"{Fore.YELLOW} {no_headers}")
if args.networkanalyzer:
print(f"{Fore.MAGENTA}\t\t Analyzing Network Vulnerabilities \n")
print(f"{Fore.CYAN}IP Range: {Fore.GREEN}{args.networkanalyzer}\n")
print(f"{Fore.WHITE}")
commands(f"shodan stats --facets port net:{args.networkanalyzer}")
commands(f"shodan stats --facets vuln net:{args.networkanalyzer}")
if args.waybackurls:
if args.save:
print(Fore.CYAN + f"Saving output to {args.save}")
commands(f"waybackurls {args.waybackurls} | anew >> {args.save}")
print(Fore.GREEN + "DONE!")
else:
commands(f"waybackurls {args.waybackurls}")
if args.j:
init(autoreset=True)
async def fetch(session, url):
try:
async with session.get(url, timeout=10) as response:
if response.status == 200:
return await response.text()
elif response.status == 404:
# Silently ignore 404 errors
return None
else:
print(f"{Fore.YELLOW}Warning: {url} returned status code {response.status}{Style.RESET_ALL}")
return None
except aiohttp.ClientError as e:
print(f"{Fore.RED}Error fetching {url}: {e}{Style.RESET_ALL}")
except asyncio.TimeoutError:
print(f"{Fore.RED}Timeout error fetching {url}{Style.RESET_ALL}")
except Exception as e:
print(f"{Fore.RED}Unexpected error fetching {url}: {e}{Style.RESET_ALL}")
return None
def is_valid_url(url):
try:
parsed = urlparse(url)
return bool(parsed.netloc) and bool(parsed.scheme)
except Exception as e:
print(f"{Fore.RED}Error parsing URL {url}: {e}{Style.RESET_ALL}")
return False
def is_same_domain(url, domain):
try:
return urlparse(url).netloc == domain
except Exception as e:
print(f"{Fore.RED}Error comparing domains for {url}: {e}{Style.RESET_ALL}")
return False
async def get_js_links(session, url, domain):
js_links = set()
new_links = set()
html = await fetch(session, url)
if html:
try:
soup = BeautifulSoup(html, 'html.parser')
for script in soup.find_all('script', src=True):
script_url = urljoin(url, script['src'])
if is_valid_url(script_url) and is_same_domain(script_url, domain):
js_links.add(script_url)
for script in soup.find_all('script'):
if script.string:
js_urls = re.findall(r'[\'"]([^\'"]*\.js)[\'"]', script.string)
for js_url in js_urls:
full_js_url = urljoin(url, js_url)
if is_valid_url(full_js_url) and is_same_domain(full_js_url, domain):
js_links.add(full_js_url)
new_links = set(urljoin(url, link['href']) for link in soup.find_all('a', href=True))
except Exception as e:
print(f"{Fore.RED}Error parsing HTML from {url}: {e}{Style.RESET_ALL}")
return js_links, new_links
async def crawl_website(url, max_depth, concurrency):
try:
domain = urlparse(url).netloc
visited = set()
to_visit = {url}
js_files = set()
semaphore = asyncio.Semaphore(concurrency)
async def bounded_get_js_links(session, url, domain):
async with semaphore:
return await get_js_links(session, url, domain)
async with aiohttp.ClientSession() as session:
for depth in range(int(max_depth) + 1):
if not to_visit:
break
tasks = [bounded_get_js_links(session, url, domain) for url in to_visit]
results = await asyncio.gather(*tasks, return_exceptions=True)
visited.update(to_visit)
to_visit = set()
for result in results:
if isinstance(result, Exception):
print(f"{Fore.RED}Error during crawl: {result}{Style.RESET_ALL}")
continue
js_links, new_links = result
js_files.update(js_links)
to_visit.update(link for link in new_links
if is_valid_url(link) and is_same_domain(link, domain) and link not in visited)
print(f"{Fore.CYAN}Depth {depth}: Found {len(js_files)} JS files, {len(to_visit)} new URLs to visit{Style.RESET_ALL}")
return js_files
except Exception as e:
print(f"{Fore.RED}Unexpected error during crawl: {e}{Style.RESET_ALL}")
return set()
async def main():
try:
print(f"{Fore.CYAN}Crawling {Fore.GREEN}{args.j}{Fore.CYAN} for JavaScript files...{Style.RESET_ALL}\n")
js_files = await crawl_website(args.j, args.depth, args.concurrency)
if js_files:
print(f"\n{Fore.YELLOW}Found {len(js_files)} JavaScript files:{Style.RESET_ALL}")
for js_file in sorted(js_files):
print(js_file)
if args.save:
try:
with open(args.save, 'w') as f:
for js_file in sorted(js_files):
f.write(f"{js_file}\n")
print(f"\n{Fore.GREEN}Results saved to {args.save}{Style.RESET_ALL}")
except IOError as e:
print(f"{Fore.RED}Error saving results to file: {e}{Style.RESET_ALL}")
else:
print(f"{Fore.RED}No JavaScript files found.{Style.RESET_ALL}")
except Exception as e:
print(f"{Fore.RED}Unexpected error in main function: {e}{Style.RESET_ALL}")
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
print(f"{Fore.YELLOW}Crawl interrupted by user.{Style.RESET_ALL}")
sys.exit(1)
except Exception as e:
print(f"{Fore.RED}Fatal error: {e}{Style.RESET_ALL}")
sys.exit(1)
if args.dns:
if args.save:
print(Fore.CYAN + "Saving output to {}...".format(args.save))
commands(f"cat {args.dns} | dnsx -silent -a -resp >> {args.save}")
commands(f"cat {args.dns} | dnsx -silent -ns -resp >> {args.save}")
commands(f"cat {args.dns} | dnsx -silent -cname -resp >> {args.save}")
else:
print(Fore.CYAN + "Printing A records...\n")
time.sleep(2)
commands(f"cat {args.dns} | dnsx -silent -a -resp\n")
print(Fore.CYAN + "Printing NS Records...\n")
time.sleep(2)
commands(f"cat {args.dns} | dnsx -silent -ns -resp\n")
print(Fore.CYAN + "Printing CNAME records...\n")
time.sleep(2)
commands(f"cat {args.dns} | dnsx -silent -cname -resp\n")
if args.probe:
if args.save:
print(Fore.CYAN + "Saving output to {}...".format(args.save))
commands(f'cat {args.probe} | httprobe -c 100 | anew >> {args.save}')
if path.exists(f"{args.save}"):
print(Fore.GREEN + "DONE!")
if not path.exists(f"{args.save}"):
print(Fore.RED + "ERROR!")
else:
commands(f'sudo cat {args.probe} | httprobe | anew')
if args.redirects:
if args.save:
print(Fore.CYAN + "Saving output to {}}..".format(args.save))
if which("httpx"):
print("Please uninstall httpx and install httpx-toolkit from https://github.com/projectdiscovery/httpx-toolkit")
sys.exit()
commands(f"cat {args.redirects} | httpx -silent -location -mc 301,302 | anew >> redirects.txt")
if path.exists(f"{args.save}"):
print(Fore.GREEN + "DONE!")
if not path.exists(f"{args.save}"):
print(Fore.RED + "ERROR!")
else:
commands(f"cat {args.redirects} | httpx -silent -location -mc 301,302")
if args.brokenlinks:
if args.save:
print(Fore.CYAN + "Saving output to {}".format(args.save))
commands(f"blc -r --filter-level 2 {args.brokenlinks}")
if path.exists(f"{args.save}"):
print(Fore.CYAN + "DONE!")
if not path.exists(f"{args.save}"):
print(Fore.CYAN + "ERROR!")
else:
commands(f"blc -r --filter-level 2 {args.brokenlinks}")
if args.tech:
try:
print("\n")
print (Fore.CYAN + "Scanning..." + "\n")
info = builtwith(f"{args.tech}")
for framework, tech in info.items():
print (Fore.GREEN + framework, ":", tech)
except UnicodeDecodeError:
pass
if args.smuggler:
smug_path = os.path.abspath(os.getcwd())
commands(f"python3 {smug_path}/tools/smuggler/smuggler.py -u {args.smuggler} -q")
if args.ipaddresses:
ip_list = []
with open(f"{args.ipaddresses}", "r") as f:
domains = [x.strip() for x in f.readlines()]
def scan(domain: str):
try:
ips = socket.gethostbyname(domain)
ip_list.append(ips)
print(f"{Fore.GREEN} {domain} {Fore.WHITE}- {Fore.CYAN}{ips}")
except socket.gaierror:
pass
except UnicodeError:
pass
with ThreadPoolExecutor(max_workers=50) as executor:
futures = [executor.submit(scan, domain) for domain in domains]
for future in futures:
future.result()
with open("ips.txt", "w") as file:
ip_list = list(dict.fromkeys(ip_list))
for iplist in ip_list:
file.write(f"{iplist}\n")
if args.domaininfo:
with open(f"{args.domaininfo}", "r") as f:
domains = [x.strip() for x in f.readlines()]
ip_list = []
server = []
new_server = set()
for domain_list in domains:
try:
sessions = requests.Session()
r = sessions.get(domain_list, verify=False, headers=header)
if "https://" in domain_list:
domain_list = domain_list.replace("https://", "")
if "http://" in domain_list:
domain_list = domain_list.replace("https://", "")
for v, k in r.headers.items():
if "Server" in v:
server.append(k)
soup = BeautifulSoup(r.text, "html.parser")
title = soup.find("title")
ips = socket.gethostbyname(domain_list)
ip_check = os.system(f"ping -c1 -W1 {ips} > /dev/null")
if ip_check == 0:
ip_list.append(ips)
else:
pass
with open(f"ips.txt", "w") as f:
for ipaddresses in ip_list:
f.writelines(f"{ipaddresses}\n")
new_server.update(server)
if r.status_code == 200:
print(f"{Fore.GREEN} {domain_list} {Fore.WHITE}- {Fore.YELLOW}[{ips}]{Fore.BLUE}[{title.get_text()}]{Fore.GREEN}[{r.status_code}]{Fore.LIGHTMAGENTA_EX}[{', '.join(map(str,new_server))}]")
if r.status_code == 403:
print(f"{Fore.GREEN} {domain_list} {Fore.WHITE}- {Fore.YELLOW}[{ips}]{Fore.BLUE}[{title.get_text()}]{Fore.RED}[{r.status_code}]{Fore.LIGHTMAGENTA_EX}[{', '.join(map(str,new_server))}]")
else:
print(f"{Fore.GREEN} {domain_list} {Fore.WHITE}- {Fore.YELLOW}[{ips}]{Fore.BLUE}[{title.get_text()}]{Fore.CYAN}[{r.status_code}]{Fore.LIGHTMAGENTA_EX}[{', '.join(map(str,new_server))}]")
except socket.gaierror:
pass
except requests.exceptions.MissingSchema:
print(f"{Fore.RED} Please use http:// or https://")
except requests.exceptions.SSLError:
pass
except requests.exceptions.ConnectionError:
pass
except AttributeError:
print(f"{Fore.GREEN} {domain_list} {Fore.WHITE}- {Fore.YELLOW}[{ips}]{Fore.BLUE}[No title]{Fore.CYAN}[{r.status_code}]{Fore.LIGHTMAGENTA_EX}[{', '.join(map(str,new_server))}]")
except UnicodeDecodeError:
pass
except requests.exceptions.InvalidURL:
pass
except KeyboardInterrupt:
sys.exit()
except:
pass
if args.importantsubdomains:
with open(f"{args.importantsubdomains}", "r") as f:
important_subs = []
subdomains = [x.strip() for x in f.readlines()]
for subdomain_list in subdomains:
if "admin" in subdomain_list:
important_subs.append(f"{subdomain_list}")
if "dev" in subdomain_list:
important_subs.append(f"{subdomain_list}")
if "test" in subdomain_list:
important_subs.append(f"{subdomain_list}")
if "api" in subdomain_list:
important_subs.append(f"{subdomain_list}")
if "staging" in subdomain_list:
important_subs.append(f"{subdomain_list}")
if "prod" in subdomain_list:
important_subs.append(f"{subdomain_list}")
if "beta" in subdomain_list:
important_subs.append(f"{subdomain_list}")
if "manage" in subdomain_list:
important_subs.append(f"{subdomain_list}")
if "jira" in subdomain_list:
important_subs.append(f"{subdomain_list}")
if "github" in subdomain_list:
important_subs.append(f"{subdomain_list}")
for pos, value in enumerate(important_subs):
print(f"{Fore.CYAN}{pos}: {Fore.GREEN}{value}")
with open("juice_subs.txt", "w") as f:
for goodsubs in important_subs:
f.writelines(f"{goodsubs}\n")
if args.not_found:
session = requests.Session()
session.headers.update(header)
def check_status(domain):
try:
r = session.get(domain, verify=False, headers=header, timeout=10)
if r.status_code == 404:
return domain
except requests.exceptions.RequestException:
pass
def get_results(links, output_file):
pool = ThreadPool(processes=multiprocessing.cpu_count())
results = pool.imap_unordered(check_status, links)
with open(output_file, "w") as f:
for result in results:
if result:
f.write(f"{result}\n")
print(result)
pool.close()
pool.join()
with open(args.not_found, "r") as f:
links = (f"{x.strip()}" for x in f.readlines())
output_file = "results.txt"
get_results(links, output_file)
if args.paramspider:
commands(f"paramspider -d {args.paramspider}")
if args.pathhunt:
def commands(cmd):
try:
subprocess.check_call(cmd, shell=True)
except:
pass
pathhunt_path = os.path.abspath(os.getcwd())
commands(f"python3 {pathhunt_path}/tools/pathhunt.py -t {args.pathhunt}")
if args.nmap:
print(f"{Fore.WHITE}Scanning {Fore.CYAN}{args.nmap}\n")
nmap = nmap3.Nmap()
results = nmap.nmap_version_detection(f"{args.nmap}")
with open("nmap_results.json", "w") as f:
json.dump(results, f, indent=4)
with open('nmap_results.json', 'r') as file:
data = json.load(file)
for host, host_data in data.items():
if host != "runtime" and host != "stats" and host != "task_results":
ports = host_data.get("ports", [])
for port in ports:
portid = port.get("portid")
service = port.get("service", {})
product = service.get("product")
print(f"{Fore.WHITE}Port: {Fore.CYAN}{portid}, {Fore.WHITE}Product: {Fore.CYAN}{product}")
if args.api_fuzzer:
s = requests.Session()
with open("payloads/api-endpoints.txt", "r") as file:
api_endpoints = [x.strip() for x in file.readlines()]