import concurrent.futures, http.client, re, ssl, sys

UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36"
PATHS = ("/", "/sslvpn/Login/Login", "/clients/", "/Login/Login")
MARK = ("check point", "checkpoint", "/sslvpn/", "cpvpn", "mobile access", "remote access vpn", "endpoint security")


def ctx():
    c = ssl.create_default_context()
    c.check_hostname = False
    c.verify_mode = ssl.CERT_NONE
    c.set_ciphers("DEFAULT@SECLEVEL=1")
    return c


CTX = ctx()


def get(ip, path, timeout=8):
    try:
        conn = http.client.HTTPSConnection(ip, 443, timeout=timeout, context=CTX)
        conn.request("GET", path, headers={"Host": ip, "User-Agent": UA, "Accept": "*/*"})
        r = conn.getresponse()
        b = r.read(30000).decode("utf-8", "replace")
        st, loc, srv = r.status, (r.getheader("Location") or ""), (r.getheader("Server") or "")
        conn.close()
        return st, loc, srv, b
    except Exception:
        return None, "", "", ""


def chain_len(ip, timeout=8):
    import socket as so
    try:
        raw = so.create_connection((ip, 443), timeout=timeout)
        s = CTX.wrap_socket(raw, server_hostname=ip)
        try:
            ch = s._sslobj.get_unverified_chain()
            n = len(ch)
            subj = ""
            if n:
                subj = str(ch[0].subject)
            return n, subj[:60]
        except Exception:
            return -1, ""
        finally:
            s.close()
    except Exception:
        return 0, ""


def one(ip):
    marks = []
    first = ""
    for path in PATHS:
        st, loc, srv, b = get(ip, path)
        if st is None:
            if not first:
                first = "ERR"
            continue
        if not first:
            first = "%s %s %s" % (st, loc[:45], srv[:15])
        low = b.lower()
        hit = [m for m in MARK if m in low]
        if hit:
            marks.append("%s:%s:%s" % (path, st, ",".join(sorted(set(hit)))))
            if len(marks) >= 2:
                break
    if marks:
        n, subj = chain_len(ip)
        return "%s\t%s\t%s\t%d\t%s" % (ip, ";".join(marks), first, n, subj)
    return "%s\t-\t%s\t0\t" % (ip, first)


def main():
    ips = [l.split()[-1] for l in open(sys.argv[1]) if l.strip()][:int(sys.argv[3])]
    print("targets", len(ips), flush=True)
    with open(sys.argv[2], "w") as f:
        with concurrent.futures.ThreadPoolExecutor(max_workers=32) as pool:
            for i, r in enumerate(pool.map(one, ips), 1):
                f.write(r + "\n")
                f.flush()
                if i % 500 == 0:
                    print("done", i, flush=True)
    print("finished", flush=True)


main()
