import asyncio, os, re, ssl, sys

SRC = '/root/recon/scan_uid.list'
OUT = '/root/recon/uid_hits.tsv'
CONC = 300
TIMEOUT = 6
PATHS = ['/php/uidrc.php', '/php/uidlogin.php']

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

done = set()
if os.path.exists(OUT):
    for l in open(OUT):
        done.add(l.split('\t')[0])

targets = []
seen = set()
for line in open(SRC):
    p = line.split()
    if len(p) < 5 or p[0] != 'open':
        continue
    port, ip = p[2], p[3]
    if ip in seen or ip in done:
        continue
    seen.add(ip)
    targets.append((ip, port))

out = open(OUT, 'a', buffering=1)
stat = {'n': 0, 'hit': 0}


def srcport(proto):
    return 6080 if proto == 'http' else 6081


async def fetch(ip, port, path, tls):
    if tls:
        r, w = await asyncio.wait_for(asyncio.open_connection(ip, port, ssl=in_ctx, server_hostname=ip), TIMEOUT)
    else:
        r, w = await asyncio.wait_for(asyncio.open_connection(ip, port), TIMEOUT)
    host = '%s:%s' % (ip, port)
    req = ('GET %s HTTP/1.1\r\nHost: %s\r\nUser-Agent: Mozilla/5.0\r\nAccept: */*\r\nConnection: close\r\n\r\n' % (path, host)).encode()
    w.write(req)
    await w.drain()
    data = await asyncio.wait_for(r.read(8192), TIMEOUT)
    try:
        w.close()
    except Exception:
        pass
    return data


async def probe(ip, port, sem):
    async with sem:
        stat['n'] += 1
        for tls in (False, True):
            p = 6080 if not tls else 6081
            if port != str(p):
                continue
            for path in PATHS:
                try:
                    data = await fetch(ip, p, path, tls)
                except Exception:
                    continue
                if not data:
                    continue
                head, _, body = data.partition(b'\r\n\r\n')
                first = head.split(b'\r\n')[0].decode('latin1', 'replace')
                low = data.lower()
                if b'200' not in first.split()[1:2]:
                    continue
                title = ''
                m = re.search(rb'<title>([^<]{0,80})', body, re.I)
                if m:
                    title = m.group(1).decode('latin1', 'replace')
                mark = ''
                for k in (b'user-id', b'authentication portal', b'palo alto', b'uidlogin', b'uidrc'):
                    if k in low:
                        mark += k.decode() + ','
                if not mark and not title:
                    continue
                out.write('%s\t%s\t%s\t%s\t%s\t%s\t%d\n' % (ip, p, 'tls' if tls else 'http', path, first, (mark or title)[:80], len(body)))
                stat['hit'] += 1


async def main():
    print('targets', len(targets), flush=True)
    sem = asyncio.Semaphore(CONC)
    batch = []
    for ip, port in targets:
        batch.append(asyncio.create_task(probe(ip, port, sem)))
        if len(batch) >= 500:
            await asyncio.gather(*batch)
            batch = []
            print('done', stat, flush=True)
    if batch:
        await asyncio.gather(*batch)
    print('finished', stat, flush=True)


asyncio.run(main())
