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

UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36"


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 https(ip):
    try:
        conn = http.client.HTTPSConnection(ip, 443, timeout=10, context=CTX)
        conn.request("GET", "/", headers={"Host": ip, "User-Agent": UA})
        r = conn.getresponse()
        b = r.read(20000).decode("utf-8", "replace")
        loc = r.getheader("Location") or ""
        srv = r.getheader("Server") or ""
        conn.close()
        m = re.search(r"<title[^>]*>(.*?)</title>", b, re.S | re.I)
        title = " ".join(m.group(1).split())[:70] if m else ""
        return "%d\t%s\t%s\t%s\t%d" % (r.status, loc[:50], srv[:20], title, len(b))
    except Exception as e:
        return "ERR\t%s" % type(e).__name__


def chain(ip):
    try:
        p = subprocess.run(["openssl", "s_client", "-connect", "%s:443" % ip, "-showcerts", "-servername", ip],
                           input="", capture_output=True, text=True, timeout=15)
        txt = p.stdout
        certs = txt.count("-----BEGIN CERTIFICATE-----")
        subs = re.findall(r"s:\s*(.+)", txt)
        iss = re.findall(r"i:\s*(.+)", txt)
        s0 = subs[0][:70] if subs else ""
        i0 = iss[0][:70] if iss else ""
        s1 = subs[1][:60] if len(subs) > 1 else ""
        return "%d\t%s\t%s\t%s" % (certs, s0, i0, s1)
    except Exception as e:
        return "0\tERR\t%s\t" % type(e).__name__


ips = [l.strip() for l in open(sys.argv[1]) if l.strip()]
print("targets", len(ips), flush=True)
with concurrent.futures.ThreadPoolExecutor(max_workers=12) as pool:
    ch = list(pool.map(chain, ips))
    ht = list(pool.map(https, ips))
for ip, c, h in zip(ips, ch, ht):
    print("%s\t%s\t%s" % (ip, c, h))
