import base64, concurrent.futures, 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"
PATH = "/cgi/samlauth"
PROBE = base64.b64encode(b"ctx=" + b"\x00" * 16).decode()   # 20 bytes decoded
CONTROL = base64.b64encode(b"ctx=" + b"A" * 16).decode()    # same length


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.read(65536).decode("utf-8", "replace")
    except urllib.error.HTTPError as e:
        try:
            return e.code, e.read(65536).decode("utf-8", "replace")
        except Exception:
            return e.code, ""
    except Exception:
        return None, ""


def classify(st, body):
    if st is None:
        return "no-response"
    if st == 500 and "43524" in body:
        return "unpatched"
    if st == 200 and "Malformed Assertion" in body:
        return "patched"
    if "43549" in body:
        return "generic"
    if st == 404:
        return "absent"
    return "unknown:%d" % st


def check(ip, timeout=12):
    op = opener()
    url = "https://%s%s" % (ip, PATH)
    st, body = post(op, url, PROBE, timeout)
    state = classify(st, body)
    if state == "unpatched":
        st2, body2 = post(op, url, CONTROL, timeout)
        if classify(st2, body2) == "unpatched":
            return "%s\tINCONCLUSIVE\tflat-response" % ip
        return "%s\tVULNERABLE\t43524+control-differs" % ip
    if state == "patched":
        return "%s\tPATCHED\tmalformed-assertion" % ip
    if state == "absent":
        return "%s\tUNAFFECTED\tno-saml-endpoint" % ip
    if state == "no-response":
        return "%s\tERROR\tno-response" % ip
    if state == "generic":
        return "%s\tINCONCLUSIVE\t43549" % ip
    return "%s\tINCONCLUSIVE\t%s" % (ip, state)


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


main()
