import asyncio, ssl, ipaddress, sys
from cryptography import x509

ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

async def probe(ip, sni, timeout=3.0):
    try:
        r, w = await asyncio.wait_for(asyncio.open_connection(ip, 443, ssl=ctx, server_hostname=sni), timeout=timeout)
        so = w.get_extra_info('ssl_object')
        cert = so.getpeercert(binary_form=True) if so else None
        w.close()
        try: await w.wait_closed()
        except Exception: pass
        return cert
    except Exception:
        return None

def parse(cert):
    c = x509.load_der_x509_certificate(cert)
    cn = c.subject.rfc4514_string()
    try:
        san = c.extensions.get_extension_for_class(x509.SubjectAlternativeName).value.get_values_for_type(x509.DNSName)
    except Exception:
        san = []
    return cn, san

async def main(net, sni):
    ips = [str(ip) for ip in ipaddress.ip_network(net).hosts()]
    sem = asyncio.Semaphore(400)
    async def work(ip):
        async with sem:
            return ip, await probe(ip, sni)
    results = await asyncio.gather(*(work(ip) for ip in ips))
    live = 0; fansky = []
    for ip, cert in results:
        if cert:
            live += 1
            cn, san = parse(cert)
            blob = (cn + " " + ",".join(san)).lower()
            if 'fansky' in blob:
                fansky.append(f"{ip}\tCN={cn}\tSAN={','.join(san[:10])}")
    print(f"[net {net}] live_with_tls={live} fansky_matches={len(fansky)}", flush=True)
    for f in fansky: print(f, flush=True)

if __name__ == "__main__":
    asyncio.run(main(sys.argv[1], sys.argv[2]))
