import asyncio, ssl, sys
from cryptography import x509
from cryptography.hazmat.backends import default_backend

BASE = "/var/www/html/ARTEX-main/data/tasks/1/i90"
SNIS = ["logs.fansky.net", "ledger-hub.fansky.net"]
CONC = 500
TIMEOUT = 3.0

ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

def parse(der):
    try:
        c = x509.load_der_x509_certificate(der, default_backend())
        sans=[]
        try:
            sans = c.extensions.get_extension_for_class(x509.SubjectAlternativeName).value.get_values_for_type(x509.DNSName)
        except Exception: pass
        return c.subject.rfc4514_string(), sans
    except Exception:
        return None, []

ips = [l.split('\t')[0].strip() for l in open(f"{BASE}/live_hosts.txt") if l.strip()]
ips = list(dict.fromkeys(ips))
print(f"second-pass: {len(ips)} live hosts x {len(SNIS)} SNIs", flush=True)

out = open(f"{BASE}/fansky_sni2.txt", "a")
sem = asyncio.Semaphore(CONC)

async def probe(ip, sni):
    async with sem:
        try:
            r,w = await asyncio.wait_for(asyncio.open_connection(ip,443,ssl=ctx,server_hostname=sni), TIMEOUT)
            try:
                so = w.get_extra_info('ssl_object')
                der = so.getpeercert(binary_form=True) if so else None
                if der:
                    cn, sans = parse(der)
                    if any('fansky' in (s or '') for s in sans) or 'fansky' in (cn or ''):
                        line = f"{ip}\tSNI={sni}\tcn={cn}\tsans={sans}\n"
                        out.write(line); out.flush()
                        print("HIT", line.strip(), flush=True)
                w.close()
                try: await w.wait_closed()
                except Exception: pass
            except Exception:
                try: w.close()
                except Exception: pass
        except Exception:
            pass

async def main():
    tasks=[]
    for ip in ips:
        for sni in SNIS:
            tasks.append(asyncio.create_task(probe(ip,sni)))
    done=0
    for t in asyncio.as_completed(tasks):
        await t
        done+=1
        if done % 4000 == 0:
            print(f"done {done}/{len(tasks)}", flush=True)
    print("SECOND-PASS DONE", flush=True)

asyncio.run(main())
