#!/usr/bin/env python3
"""Dedicated BeyondTrust RS/PRA hunter (CVE-2026-1731).
Probes https://IP/ and, for thin-200 or login-redirect responses, /login too.
Output: bt_full.tsv (hits only). Stats -> bt_stats.log
Usage: bt_probe.py ips.txt bt_full.tsv
"""
import asyncio
import re
import sys
import time

import aiohttp

BT = re.compile(r"(?i)beyondtrust|bomgar")
LOGIN_RED = re.compile(r"(?i)/login")
TITLE = re.compile(r"(?is)<title[^>]*>\s*(.*?)</title>")

stats = {"done": 0, "hits": 0, "extra": 0, "start": time.time()}
SEM = asyncio.Semaphore(900)


async def fetch(sess, url):
    async with sess.get(url, allow_redirects=False) as r:
        raw = await r.content.read(65536)
        return r.status, r.headers, raw.decode("utf-8", "replace")


async def probe(sess, ip, out, lock):
    try:
        status, hdr, txt = await fetch(sess, f"https://{ip}/")
        server = hdr.get("Server", "")[:60]
        loc = hdr.get("Location", "")[:80]
        blob1 = server + "\n" + txt
        hit = bool(BT.search(blob1))
        used = "/"
        if not hit:
            thin = status == 200 and len(txt) < 3000
            redir = status in (301, 302, 303, 307, 308) and LOGIN_RED.search(loc)
            if thin or redir:
                stats["extra"] += 1
                try:
                    st2, hdr2, txt2 = await fetch(sess, f"https://{ip}/login")
                    blob2 = hdr2.get("Server", "") + "\n" + txt2
                    if BT.search(blob2):
                        hit = True
                        used = "/login"
                        txt = txt2
                        status = st2
                except Exception:
                    pass
        if hit:
            t = TITLE.search(txt)
            title = re.sub(r"\s+", " ", t.group(1)).strip()[:120] if t else ""
            stats["hits"] += 1
            async with lock:
                out.write("\t".join([ip, str(status), server, title, used, loc]) + "\n")
                out.flush()
    except Exception:
        pass
    finally:
        stats["done"] += 1


async def stats_log():
    with open("/root/recon/bt_stats.log", "a") as f:
        while True:
            el = time.time() - stats["start"]
            hps = stats["done"] / el if el else 0
            f.write(f"{time.strftime('%H:%M:%S')} done={stats['done']} "
                    f"hps={hps:.0f} hits={stats['hits']} extra={stats['extra']}\n")
            f.flush()
            await asyncio.sleep(60)


async def main():
    infile, outfile = sys.argv[1], sys.argv[2]
    hosts = iter(l.strip() for l in open(infile, errors="replace") if l.strip())
    conn = aiohttp.TCPConnector(limit=0, ssl=False)
    tout = aiohttp.ClientTimeout(total=9, connect=5, sock_read=6)
    hdr = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"}
    lock = asyncio.Lock()
    stag = asyncio.create_task(stats_log())
    with open(outfile, "a") as out:
        async with aiohttp.ClientSession(connector=conn, timeout=tout,
                                         headers=hdr) as sess:
            pend = set()

            async def task(h):
                async with SEM:
                    await probe(sess, h, out, lock)

            for h in hosts:
                pend.add(asyncio.ensure_future(task(h)))
                if len(pend) >= 900:
                    _, pend = await asyncio.wait(
                        pend, return_when=asyncio.FIRST_COMPLETED)
            if pend:
                await asyncio.wait(pend)
    stag.cancel()
    with open("/root/recon/bt_stats.log", "a") as f:
        f.write(f"PASS COMPLETE done={stats['done']} hits={stats['hits']}\n")


if __name__ == "__main__":
    asyncio.run(main())
