import base64, concurrent.futures, 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"
PROBE = base64.b64encode(b"ctx=" + b"\x00" * 16).decode()
CONTROL = base64.b64encode(b"ctx=" + b"A" * 16).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, url, rs, timeout):
    body = ("SAMLResponse=AAAA&RelayState=" + urllib.parse.quote(rs, safe="")).encode()
    req = urllib.request.Request(url, data=body)
    req.add_header("User-Agent", UA)
    req.add_header("Content-Type", "application/x-www-form-urlencoded")
    try:
        with op.open(req, timeout=timeout) as r:
            return r.status, r.headers.get("Location") or "", r.read(65536).decode("utf-8", "replace")
    except urllib.error.HTTPError as e:
        loc = e.headers.get("Location") or ""
        try:
            body = e.read(65536).decode("utf-8", "replace")
        except Exception:
            body = ""
        return e.code, loc, body
    except Exception:
        return None, "", ""


def check(ip):
    url = "https://%s/cgi/samlauth" % ip
    for attempt in range(2):
        st, loc, body = post(opener(), url, PROBE, 25)
        if st is not None:
            break
    st2, loc2, body2 = post(opener(), url, CONTROL, 25)
    b = " ".join(body.split())[:60]
    b2 = " ".join(body2.split())[:40]
    return "%s\t%s\t%s\t%s\t%s\t%s\t%s" % (ip, st or 0, loc[:40], b, st2 or 0, loc2[:40], b2)


def main():
    src, out = sys.argv[1], sys.argv[2]
    ips = [l.split("\t")[0].strip() for l in open(src) if l.strip()]
    print("targets", len(ips), flush=True)
    with open(out, "w") as f:
        f.write("ip\tst\tloc\tbody\tst_ctrl\tloc_ctrl\tbody_ctrl\n")
        with concurrent.futures.ThreadPoolExecutor(max_workers=30) as pool:
            for i, res in enumerate(pool.map(check, ips), 1):
                f.write(res + "\n")
                f.flush()
                if i % 50 == 0:
                    print("done", i, flush=True)
    print("finished", flush=True)


main()
