#!/usr/bin/env python3
"""Dedicated Barracuda Email Security Gateway hunter (CVE-2026-116606).
Probes /cgi-mod/index.cgi first, then / ; matches Barracuda ESG markers,
extracts firmware version. Output: bdui_full.tsv. Stats: bdui_stats.log
Usage: bdui_probe.py ips.txt bdui_full.tsv
"""
import asyncio
import re
import sys
import time

import aiohttp

MARK = re.compile(r"(?i)barracuda|email security gateway|barracuda networks")
TITLE = re.compile(r"(?is)<title[^>]*>\s*(.*?)\s*</title>")
VER = re.compile(r"(?i)(?:version|firmware)[^0-9]{0,30}(\d+\.\d+\.\d+\.\d+)")
VER2 = re.compile(r"\b(9|1[0-9])\.\d+\.\d+\.\d+\b")

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


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")


def pick_version(txt):
    m = VER.search(txt)
    if m:
        return m.group(1)
    m = VER2.search(txt)
    return m.group(0) if m else ""


async def probe(sess, ip, out, lock):
    try:
        hit = False
        used = ""
        txt = ""
        status = ""
        server = ""
        try:
            status, hdr, txt = await fetch(sess, f"https://{ip}/cgi-mod/index.cgi")
            server = hdr.get("Server", "")[:50]
            if MARK.search(server + "\n" + txt):
                hit = True
                used = "/cgi-mod/index.cgi"
        except Exception:
            pass
        if not hit:
            stats["second"] += 1
            try:
                status, hdr, txt = await fetch(sess, f"https://{ip}/")
                server = hdr.get("Server", "")[:50]
                if MARK.search(server + "\n" + txt):
                    hit = True
                    used = "/"
            except Exception:
                pass
        if hit:
            ver = pick_version(txt)
            t = TITLE.search(txt)
            title = re.sub(r"\s+", " ", t.group(1)).strip()[:100] if t else ""
            async with lock:
                out.write("\t".join([ip, str(status), ver, title, used, server]) + "\n")
                out.flush()
            stats["hits"] += 1
    except Exception:
        pass
    finally:
        stats["done"] += 1


async def stats_log():
    with open("/root/recon/bdui_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']} hps={hps:.0f} "
                    f"hits={stats['hits']} second={stats['second']}\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) >= 1200:
                    _, pend = await asyncio.wait(pend, return_when=asyncio.FIRST_COMPLETED)
            if pend:
                await asyncio.wait(pend)
    stag.cancel()
    with open("/root/recon/bdui_stats.log", "a") as f:
        f.write(f"PASS COMPLETE done={stats['done']} hits={stats['hits']}\n")


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