import asyncio, ssl, ipaddress, sys, json, re, socket

CIDR = sys.argv[1]
SNI = sys.argv[2] if len(sys.argv) > 2 else "connect.fansky.net"
HOST = SNI
SEM = 800
CONN_TIMEOUT = 3.0
found = []

def cert_info(der):
    try:
        from cryptography import x509
        from cryptography.hazmat.backends import default_backend
        c = x509.load_der_x509_certificate(der, default_backend())
        sans = []
        try:
            ext = c.extensions.get_extension_for_class(x509.SubjectAlternativeName)
            sans = list(ext.value.get_values_for_type(x509.DNSName))
        except Exception:
            pass
        cn = c.subject.rfc4514_string()
        return cn, sans
    except Exception:
        return None, []

def tls_ctx():
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    return ctx

async def try_tls(ip, ctx):
    try:
        r, w = await asyncio.wait_for(asyncio.open_connection(ip, 443, ssl=ctx, server_hostname=SNI), CONN_TIMEOUT)
    except Exception:
        return None
    try:
        sslobj = w.get_extra_info('ssl_object')
        der = sslobj.getpeercert(binary_form=True)
        return cert_info(der)
    except Exception:
        return None
    finally:
        try: w.close()
        except Exception: pass

async def try_http(ip):
    try:
        r, w = await asyncio.wait_for(asyncio.open_connection(ip, 80), CONN_TIMEOUT)
    except Exception:
        return None
    try:
        req = f"GET / HTTP/1.1\r\nHost: {HOST}\r\nUser-Agent: Mozilla/5.0\r\nAccept: */*\r\nConnection: close\r\n\r\n"
        w.write(req.encode())
        await w.drain()
        data = await asyncio.wait_for(r.read(6000), CONN_TIMEOUT)
        return data
    except Exception:
        return None
    finally:
        try: w.close()
        except Exception: pass

async def worker(ip, sem, ctx):
    async with sem:
        tl = await try_tls(ip, ctx)
        if tl:
            cn, sans = tl
            blob = (cn + " " + " ".join(sans)).lower()
            if "fansky" in blob:
                found.append({"ip": ip, "port": 443, "cn": cn, "sans": sans})
                print(f"[TLS MATCH] {ip}:443 cn={cn} sans={sans}", flush=True)
        h = await try_http(ip)
        if h:
            txt = h.decode("utf-8", "ignore").lower()
            if ("fansky connect" in txt) or ("connect the world" in txt):
                m = re.search(r"<title>([^<]*)</title>", txt, re.I)
                title = m.group(1).strip() if m else ""
                found.append({"ip": ip, "port": 80, "title": title, "len": len(h)})
                print(f"[HTTP MATCH] {ip}:80 title={title!r} len={len(h)}", flush=True)

async def main():
    net = ipaddress.ip_network(CIDR)
    sem = asyncio.Semaphore(SEM)
    ctx = tls_ctx()
    ips = [str(x) for x in net.hosts()]
    print(f"scanning {CIDR} ({len(ips)} hosts) SNI={SNI}", flush=True)
    batch = 4000
    for i in range(0, len(ips), batch):
        chunk = ips[i:i+batch]
        await asyncio.gather(*(worker(ip, sem, ctx) for ip in chunk))
        print(f"progress {min(i+batch,len(ips))}/{len(ips)} found={len(found)}", flush=True)
    print("DONE", flush=True)
    with open("scan_result.json", "w") as f:
        json.dump(found, f, indent=2)

asyncio.run(main())
