#!/usr/bin/env bash
# =============================================================================
# ONCyber ARTEX log hunt · v1.0 · November 2026
#
# Searches Apache and Nginx access logs on this server for published ARTEX
# indicators of compromise and for the behaviour patterns of AI-driven attack
# tooling (account recovery abuse, identifier enumeration, wordlist scanning,
# source map harvesting, rotating proxy pools). Every hit gets a confidence
# rating.
#
# Read-only. Nothing leaves this server. The only network call downloads the
# indicator list from ONCyber.
#
# One shot:
#   curl -fsSL https://kevsys.oncyber.ca/support/artex_hunt.sh | sudo bash
#   curl -fsSL https://kevsys.oncyber.ca/support/artex_hunt.sh | sudo bash -s -- /var/log/nginx --since 2026-10-01
#
# Saved copy:
#   sudo bash artex_hunt.sh [log paths...] [options]
#
# Options:
#   --since YYYY-MM-DD[ HH:MM]   only requests at or after this log time
#   --until YYYY-MM-DD[ HH:MM]   only requests before this log time
#   --ioc-file FILE              use a local indicator file (repeatable), skip download
#   --ioc-base URL               indicator location (default below)
#   --out DIR                    where to write the CSV results (default: current dir)
#   --allow IP[,IP...]           your own addresses, never reported
#   --quiet                      summary only
#
# Exit codes: 0 no hits · 1 Low or Medium hits · 2 High hits · 3 error
#
# Supported: Ubuntu 18.04+, Amazon Linux 2 and 2023. Needs python3 (3.6+),
# curl or wget. Reads plain and .gz logs. Log formats detected per line:
# Apache common, combined and vhost_combined, Nginx combined, either with an
# X-Forwarded-For field, and JSON access logs.
#
# Questions or hits: ONCyber · info@oncyber.ca · +1-289-203-8707
# =============================================================================
set -euo pipefail

IOC_BASE="${IOC_BASE:-https://kevsys.oncyber.ca/support}"
DEFAULT_IOC_FILES="artex_iocs.csv artex_iocs_2026-11.csv artex_ips_2026-11.txt"

err() { echo "artex_hunt: $*" >&2; }

# ---- python3 -----------------------------------------------------------------
if ! command -v python3 >/dev/null 2>&1; then
  err "python3 is required."
  if [ -f /etc/os-release ] && grep -qi 'amazon' /etc/os-release; then
    err "Install it with: sudo yum install -y python3   (or: sudo dnf install -y python3)"
  else
    err "Install it with: sudo apt-get install -y python3"
  fi
  exit 3
fi

# ---- arguments: pick out the ones the wrapper needs, pass the rest through -----
PASS=()
LOCAL_IOCS=()
while [ $# -gt 0 ]; do
  case "$1" in
    --ioc-base) IOC_BASE="$2"; shift 2 ;;
    --ioc-file) LOCAL_IOCS+=("$2"); shift 2 ;;
    -h|--help) sed -n '2,40p' "$0" 2>/dev/null || true; exit 0 ;;
    *) PASS+=("$1"); shift ;;
  esac
done

WORK="$(mktemp -d /tmp/artex_hunt.XXXXXX)"
trap 'rm -rf "$WORK"' EXIT
mkdir -p "$WORK/iocs"

fetch() {  # fetch URL DEST
  if command -v curl >/dev/null 2>&1; then
    curl -fsSL --max-time 60 "$1" -o "$2"
  elif command -v wget >/dev/null 2>&1; then
    wget -q -T 60 -O "$2" "$1"
  else
    err "curl or wget is required to download indicators (or use --ioc-file)."
    return 1
  fi
}

looks_like_html() { head -c 512 "$1" | grep -qiE '<!doctype|<html'; }

# ---- indicators ----------------------------------------------------------------
if [ ${#LOCAL_IOCS[@]} -gt 0 ]; then
  for f in "${LOCAL_IOCS[@]}"; do
    [ -r "$f" ] || { err "cannot read $f"; exit 3; }
    cp "$f" "$WORK/iocs/"
  done
else
  FILES=""
  if fetch "$IOC_BASE/artex_manifest.txt" "$WORK/manifest.txt" 2>/dev/null && ! looks_like_html "$WORK/manifest.txt"; then
    FILES="$(grep -E '^artex_[A-Za-z0-9_.-]+$' "$WORK/manifest.txt" || true)"
  fi
  [ -n "$FILES" ] || FILES="$DEFAULT_IOC_FILES"
  GOT=0
  for f in $FILES; do
    if fetch "$IOC_BASE/$f" "$WORK/iocs/$f" 2>/dev/null && [ -s "$WORK/iocs/$f" ] && ! looks_like_html "$WORK/iocs/$f"; then
      GOT=$((GOT + 1))
    else
      rm -f "$WORK/iocs/$f"
    fi
  done
  if [ "$GOT" -eq 0 ]; then
    err "could not download indicators from $IOC_BASE."
    err "Behaviour checks will still run. Use --ioc-file to supply a local list."
  fi
fi

# ---- analyzer --------------------------------------------------------------------
cat > "$WORK/hunt.py" <<'PYEOF'
import argparse, csv, glob, gzip, hashlib, ipaddress, json, os, re, socket, sys
from collections import Counter, defaultdict, deque
from datetime import datetime, timedelta

RANK = {"High": 3, "Medium": 2, "Low": 1}

# ---------------------------------------------------------------- built-in patterns
SELF_NAMED_UA = re.compile(r"artex|reconprobe|norma/\d", re.I)
FAKE_UA_FAMILIES = [
    (re.compile(r"^Mozilla/5\.0 Chrome/\d+(\.0)?$"), "Truncated Chrome UA (Mozilla/5.0 Chrome/N)"),
    (re.compile(r"^Mozilla/5\.0 \(Windows NT 10\.0; Win64; x64\) Chrome/\d+(\.0)*( Safari/537\.36)?$"),
     "Chrome UA with no AppleWebKit"),
    (re.compile(r"^Mozilla/5\.0 \([^)]*\) AppleWebKit/537\.36 Chrome/\d+(\.0)* Safari/537\.36$"),
     "Chrome UA with no KHTML, like Gecko"),
    (re.compile(r"^Mozilla/5\.0 \(Windows NT 10\.0; Win64; x64\)( AppleWebKit/537\.36)?$"),
     "Unfinished Windows browser UA"),
]
BARE_MOZILLA = "Mozilla/5.0"
SCRIPT_UA = re.compile(r"^(curl/|python-requests/|Python-urllib/|Go-http-client/|azure-toolkit/|aiohttp/|httpx/|okhttp/|Wget/|libwww-perl/)", re.I)
HEADLESS_UA = re.compile(r"HeadlessChrome|PhantomJS|puppeteer|playwright", re.I)

SENSITIVE_PATH = re.compile(r"login|signin|sign-in|logon|auth|oauth|token|password|passwd|reset|recover|forgot|"
                            r"admin|wp-login|xmlrpc|account|session|register|signup|mfa|2fa|otp|/api/", re.I)
RESET_PATH = re.compile(r"(forgot|reset|recover|lost)[-_]?pass(word)?|pass(word)?[-_/]?(reset|recover|forgot)|"
                        r"account[-_/]?recover|recover_password|forgot_password", re.I)
LOGIN_PATH = re.compile(r"login|signin|sign-in|logon|/auth(enticate)?\b|/session", re.I)
PROBE_PATH = re.compile(r"zzz[-_.]?nonexist|nonexist(ent)?[-_]|notexist[-_]?xyz|/[a-z]{3,}-nonexistent-", re.I)
SECRET_IN_QUERY = re.compile(r"[?&](password|passwd|pwd|pass|new_password)=[^&]{3,}", re.I)
MAP_FILE = re.compile(r"\.(js|css)\.map(\?|$)", re.I)
ASSET = re.compile(r"\.(css|js|png|jpe?g|gif|svg|webp|woff2?|ttf|ico|map)(\?|$)", re.I)
ID_PARAM = re.compile(r"(?:^|[?&])(id|uid|user|user_id|userid|token|account|acct|dealer|tenant|org|customer|cid|u_id|d_id)=([^&]+)", re.I)

CLOUDFLARE_NETS = [ipaddress.ip_network(n) for n in (
    "173.245.48.0/20", "103.21.244.0/22", "103.22.200.0/22", "103.31.4.0/22", "141.101.64.0/18",
    "108.162.192.0/18", "190.93.240.0/20", "188.114.96.0/20", "197.234.240.0/22", "198.41.128.0/17",
    "162.158.0.0/15", "104.16.0.0/13", "104.24.0.0/14", "172.64.0.0/13", "131.0.72.0/22",
    "2400:cb00::/32", "2606:4700::/32", "2803:f800::/32", "2405:b500::/32", "2405:8100::/32",
    "2a06:98c0::/29", "2c0f:f248::/32")]

# ---------------------------------------------------------------- helpers
def ip_obj(s):
    try:
        return ipaddress.ip_address(s.strip().strip("[]"))
    except ValueError:
        return None

def is_cf(ip):
    return any(ip.version == n.version and ip in n for n in CLOUDFLARE_NETS)

def b64_int(v):
    import base64, binascii
    try:
        s = v.replace("%3D", "=").replace("%3d", "=")
        d = base64.b64decode(s + "=" * (-len(s) % 4), validate=True).decode("ascii")
        return int(d) if d.isdigit() and len(d) < 12 else None
    except (binascii.Error, ValueError, UnicodeDecodeError):
        return None

def as_int(v):
    if v.isdigit() and len(v) < 12:
        return int(v)
    return b64_int(v)

QUOTED = re.compile(r'"((?:[^"\\]|\\.)*)"')
CLF = re.compile(r'^(?P<pre>.*?)\[(?P<time>[^\]]+)\]\s+"(?P<req>(?:[^"\\]|\\.)*)"\s+(?P<status>\d{3}|-)\s+(?P<bytes>\S+)(?P<rest>.*)$')

def parse_time(s):
    s = s.strip()
    for fmt in ("%d/%b/%Y:%H:%M:%S", "%Y-%m-%dT%H:%M:%S", "%Y-%m-%d %H:%M:%S"):
        try:
            return datetime.strptime(s[:19] if fmt != "%d/%b/%Y:%H:%M:%S" else s[:20], fmt)
        except ValueError:
            continue
    return None

def pick_client(lead_ips, xff_ips):
    """Real client: leading address, unless it is private or Cloudflare and a forwarded address exists."""
    lead = lead_ips[0] if lead_ips else None
    fwd = [i for i in xff_ips if not i.is_private and not is_cf(i)]
    if lead is None:
        return (fwd[0] if fwd else None), False
    if (lead.is_private or is_cf(lead)) and fwd:
        return fwd[0], False
    if len(lead_ips) > 1 and (lead.is_private or is_cf(lead)):
        for i in lead_ips[1:]:
            if not i.is_private and not is_cf(i):
                return i, False
    return lead, is_cf(lead)

def parse_line(line):
    line = line.rstrip("\n")
    if line.startswith("{"):
        try:
            j = json.loads(line)
        except ValueError:
            return None
        g = lambda *ks: next((str(j[k]) for k in ks if k in j and j[k] not in (None, "")), "")
        req = g("request")
        if not req:
            req = "%s %s HTTP/1.1" % (g("request_method", "method"), g("request_uri", "uri", "path"))
        lead = [x for x in (ip_obj(g("remote_addr", "client_ip", "clientip", "ip")),) if x]
        xff = [x for x in (ip_obj(p) for p in re.split(r"[,\s]+", g("http_x_forwarded_for", "x_forwarded_for", "xff"))) if x]
        t = parse_time(g("time_local", "time_iso8601", "@timestamp", "time", "timestamp"))
        return dict(lead=lead, xff=xff, time=t, req=req, status=g("status"),
                    ua=g("http_user_agent", "user_agent", "ua"), ref=g("http_referer", "referer"),
                    host=g("host", "server_name", "vhost"))
    m = CLF.match(line)
    if not m:
        return None
    pre = m.group("pre").split()
    host = ""
    if pre and ":" in pre[0] and not ip_obj(pre[0]) and re.match(r"^[A-Za-z0-9.-]+:\d+$", pre[0]):
        host = pre[0]
    lead = [x for x in (ip_obj(t) for t in re.split(r"[,\s]+", m.group("pre"))) if x]
    q = QUOTED.findall(m.group("rest"))
    ref = q[0] if len(q) > 0 else ""
    ua = q[1] if len(q) > 1 else ""
    xff = []
    for extra in q[2:]:
        cand = [ip_obj(p) for p in re.split(r"[,\s]+", extra) if p]
        if cand and all(cand):
            xff = cand
            break
    return dict(lead=lead, xff=xff, time=parse_time(m.group("time")), req=m.group("req"),
                status=m.group("status"), ua=ua.replace('\\"', '"'), ref=ref, host=host)

# ---------------------------------------------------------------- indicators
def load_iocs(paths):
    ips, nets, uas, ua_res, url_paths, url_res, domains = {}, [], {}, [], {}, [], {}
    meta = Counter()
    sha = hashlib.sha256()
    for p in paths:
        data = open(p, "rb").read()
        sha.update(data)
        text = data.decode("utf-8", "replace")
        rows = []
        first = text.lstrip().splitlines()[0] if text.strip() else ""
        if "indicator" in first.lower() and "," in first:
            rows = list(csv.DictReader(text.splitlines()))
        else:
            for ln in text.splitlines():
                ln = ln.strip()
                if ln and not ln.startswith("#") and (ip_obj(ln) or "/" in ln):
                    rows.append({"indicator": ln, "type": "cidr" if "/" in ln else "ip",
                                 "source": os.path.basename(p), "notes": ""})
        for r in rows:
            ind = (r.get("indicator") or "").strip()
            typ = (r.get("type") or "").strip().lower()
            if not ind:
                continue
            src = (r.get("source") or os.path.basename(p)).strip()
            conf = (r.get("confidence") or "").strip().title()
            note = (r.get("notes") or "").strip()
            rec = {"indicator": ind, "source": src, "notes": note, "confidence": conf if conf in RANK else ""}
            meta[typ] += 1
            if typ == "ip" and ip_obj(ind):
                ips[str(ip_obj(ind))] = rec
            elif typ == "cidr":
                try:
                    nets.append((ipaddress.ip_network(ind, strict=False), rec))
                except ValueError:
                    pass
            elif typ == "user_agent":
                uas[ind] = rec
            elif typ == "user_agent_regex":
                try:
                    ua_res.append((re.compile(ind), rec))
                except re.error:
                    pass
            elif typ == "url_path":
                url_paths[ind.lower()] = rec
            elif typ == "url_regex":
                try:
                    url_res.append((re.compile(ind, re.I), rec))
                except re.error:
                    pass
            elif typ == "domain":
                domains[ind.lower()] = rec
    return dict(ips=ips, nets=nets, uas=uas, ua_res=ua_res, url_paths=url_paths, url_res=url_res,
                domains=domains, meta=meta, sha=sha.hexdigest()[:16] if paths else "none")

def ua_conf(ua, rec):
    if rec.get("confidence"):
        return rec["confidence"]
    if SELF_NAMED_UA.search(ua):
        return "High"
    if any(r.match(ua) for r, _ in FAKE_UA_FAMILIES):
        return "Medium"
    return "Low"   # generic strings like curl/7.88.1 are noisy alone

# ---------------------------------------------------------------- log discovery
DEFAULT_DIRS = ["/var/log/apache2", "/var/log/httpd", "/var/log/nginx"]

def find_logs(paths):
    out = []
    for p in paths or DEFAULT_DIRS:
        if os.path.isfile(p):
            out.append(p)
        elif os.path.isdir(p):
            for d, _, files in os.walk(p, followlinks=True):
                for f in sorted(files):
                    lf = f.lower()
                    if "access" in lf and "error" not in lf:
                        out.append(os.path.join(d, f))
    return sorted(set(out))

def open_log(p):
    return gzip.open(p, "rt", errors="replace") if p.endswith(".gz") else open(p, "r", errors="replace")

# ---------------------------------------------------------------- findings
class Findings:
    def __init__(self):
        self.ind = {}                       # (kind, indicator) -> record
        self.ip = defaultdict(lambda: {"conf": 0, "reasons": Counter(), "rrank": {}, "n": 0, "first": None, "last": None})

    def add(self, kind, indicator, conf, ip, t, sample, source="", t_last=None):
        k = (kind, indicator)
        r = self.ind.get(k)
        if r is None:
            r = self.ind[k] = {"kind": kind, "indicator": indicator, "conf": conf, "hits": 0,
                               "ips": Counter(), "first": t, "last": t, "sample": sample, "source": source}
        if RANK[conf] > RANK[r["conf"]]:
            r["conf"] = conf
        r["hits"] += 1
        if ip:
            r["ips"][ip] += 1
        tl = t_last or t
        if t:
            r["first"] = t if r["first"] is None or t < r["first"] else r["first"]
        if tl:
            r["last"] = tl if r["last"] is None or tl > r["last"] else r["last"]
        if ip:
            pr = self.ip[ip]
            pr["conf"] = max(pr["conf"], RANK[conf])
            key = kind if indicator == kind else kind + ": " + indicator[:60]
            pr["reasons"][key] += 1
            pr["rrank"][key] = max(pr["rrank"].get(key, 0), RANK[conf])

def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("paths", nargs="*")
    ap.add_argument("--ioc-dir")
    ap.add_argument("--since")
    ap.add_argument("--until")
    ap.add_argument("--out", default=".")
    ap.add_argument("--allow", default="")
    ap.add_argument("--quiet", action="store_true")
    a = ap.parse_args()

    def when(s):
        if not s:
            return None
        for f in ("%Y-%m-%d %H:%M", "%Y-%m-%d"):
            try:
                return datetime.strptime(s, f)
            except ValueError:
                pass
        sys.exit("bad date %r, use YYYY-MM-DD or 'YYYY-MM-DD HH:MM'" % s)
    since, until = when(a.since), when(a.until)
    allow = {x.strip() for x in a.allow.split(",") if x.strip()}

    ioc_files = sorted(glob.glob(os.path.join(a.ioc_dir, "*"))) if a.ioc_dir else []
    I = load_iocs(ioc_files)
    logs = find_logs(a.paths)
    if not logs:
        print("No access logs found. Pass log files or folders, e.g. /var/log/nginx", file=sys.stderr)
        return 3

    F = Findings()
    per_ip = defaultdict(lambda: {"n": 0, "assets": 0, "first": None, "last": None, "uas": Counter()})
    err404 = defaultdict(deque)          # ip -> recent 404 times
    max404 = Counter()
    login_posts = defaultdict(deque)
    max_login = Counter()
    maps = defaultdict(set)
    enum = defaultdict(set)              # (ip, template) -> ids
    reset_ids = defaultdict(set)
    odd_ua_hits = defaultdict(list)      # ua -> [(t, ip)]
    stats = Counter()

    for path in logs:
        try:
            fh = open_log(path)
        except OSError as e:
            print("Cannot read %s: %s (run with sudo?)" % (path, e), file=sys.stderr)
            stats["unreadable"] += 1
            continue
        stats["files"] += 1
        with fh:
            for line in fh:
                stats["lines"] += 1
                rec = parse_line(line)
                if not rec or not rec["req"]:
                    stats["unparsed"] += 1
                    continue
                t = rec["time"]
                if t and ((since and t < since) or (until and t >= until)):
                    continue
                stats["in_window"] += 1
                ipo, cf_only = pick_client(rec["lead"], rec["xff"])
                if cf_only:
                    stats["cloudflare_without_real_ip"] += 1
                ip = str(ipo) if ipo else ""
                if ip in allow:
                    continue
                parts = rec["req"].split(" ")
                method = parts[0] if parts else ""
                url = parts[1] if len(parts) > 1 else rec["req"]
                pth = url.split("?")[0]
                ua, status = rec["ua"], rec["status"]
                sample = "%s %s %s %s" % (t.strftime("%Y-%m-%d %H:%M:%S") if t else "?", method, url[:100], status)

                p = per_ip[ip]
                p["n"] += 1
                p["first"] = t if t and (p["first"] is None or t < p["first"]) else p["first"]
                p["last"] = t if t and (p["last"] is None or t > p["last"]) else p["last"]
                p["uas"][ua] += 1
                if ASSET.search(pth):
                    p["assets"] += 1
                sensitive = bool(SENSITIVE_PATH.search(url))

                # ---- feed indicators
                if ip and ip in I["ips"]:
                    r = I["ips"][ip]
                    F.add("IOC IP", ip, r["confidence"] or "Medium", ip, t, sample, r["source"])
                elif ipo and I["nets"]:
                    for net, r in I["nets"]:
                        if ipo.version == net.version and ipo in net:
                            F.add("IOC network", str(net), r["confidence"] or "Medium", ip, t, sample, r["source"])
                            break
                if ua in I["uas"]:
                    r = I["uas"][ua]
                    c = ua_conf(ua, r)
                    if c == "Low" and sensitive:
                        c = "Medium"
                    F.add("IOC user agent", ua, c, ip, t, sample, r["source"])
                for rx, r in I["ua_res"]:
                    if rx.search(ua):
                        F.add("IOC user agent", rx.pattern, r["confidence"] or "Medium", ip, t, sample, r["source"])
                        break
                low = url.lower()
                for frag, r in I["url_paths"].items():
                    if frag in low:
                        F.add("IOC URL", frag, r["confidence"] or "High", ip, t, sample, r["source"])
                for rx, r in I["url_res"]:
                    if rx.search(url):
                        F.add("IOC URL", rx.pattern, r["confidence"] or "High", ip, t, sample, r["source"])
                if I["domains"]:
                    for dom, r in I["domains"].items():
                        if dom in rec["ref"].lower() or dom in rec["host"].lower():
                            F.add("IOC domain", dom, r["confidence"] or "Medium", ip, t, sample, r["source"])

                # ---- behaviour
                if SELF_NAMED_UA.search(ua):
                    F.add("Tool names itself in UA", ua[:120], "High", ip, t, sample)
                if PROBE_PATH.search(url):
                    F.add("Baseline not-found probe", pth[:80], "High", ip, t, sample)
                fake = next((label for rx, label in FAKE_UA_FAMILIES if rx.match(ua)), None)
                if fake:
                    F.add("Fabricated browser UA", fake, "Medium" if sensitive else "Low", ip, t, sample)
                    if sensitive and t:
                        odd_ua_hits[ua].append((t, ip))
                if ua == BARE_MOZILLA and sensitive:
                    F.add("Bare Mozilla/5.0 UA on sensitive path", BARE_MOZILLA, "Low", ip, t, sample)
                if SCRIPT_UA.match(ua) and sensitive:
                    F.add("Scripting client on sensitive path", ua.split("/")[0] + "/", "Medium", ip, t, sample)
                    if t:
                        odd_ua_hits[ua].append((t, ip))
                if HEADLESS_UA.search(ua) and sensitive:
                    F.add("Headless browser on sensitive path", ua[:60], "Medium", ip, t, sample)
                if SECRET_IN_QUERY.search(url):
                    F.add("Password in URL query string", pth[:80], "Medium", ip, t, sample)
                if RESET_PATH.search(url):
                    for name, val in ID_PARAM.findall(url):
                        n = as_int(val)
                        if n is not None:
                            reset_ids[ip].add(n)
                            F.add("Password reset with an identifier parameter", pth[:80], "Medium", ip, t, sample)
                if MAP_FILE.search(pth) and (SCRIPT_UA.match(ua) or fake or ua in ("", "-", BARE_MOZILLA)):
                    maps[ip].add(pth)
                for name, val in ID_PARAM.findall(url):
                    n = as_int(val)
                    if n is not None:
                        enum[(ip, pth + "?" + name.lower())].add(n)
                if status == "404" and t:
                    dq = err404[ip]
                    dq.append(t)
                    while dq and (t - dq[0]) > timedelta(minutes=5):
                        dq.popleft()
                    if len(dq) > max404[ip]:
                        max404[ip] = len(dq)
                if method == "POST" and LOGIN_PATH.search(pth) and not RESET_PATH.search(pth) and t:
                    dq = login_posts[ip]
                    dq.append(t)
                    while dq and (t - dq[0]) > timedelta(minutes=10):
                        dq.popleft()
                    if len(dq) > max_login[ip]:
                        max_login[ip] = len(dq)

    # ---- end-of-run behaviour rules (one row per check, detail per IP in the sample)
    def rule(kind, conf, ip, detail):
        p = per_ip[ip]
        F.add(kind, kind, conf, ip, p["first"], "%s: %s" % (ip, detail), t_last=p["last"])
    for ip, n in max404.items():
        if n >= 50:
            rule("404 burst (wordlist scanning)", "Medium" if n < 200 else "High", ip, "%d not-found in 5 min" % n)
    for ip, n in max_login.items():
        if n >= 20:
            rule("Login brute force", "Medium" if n < 100 else "High", ip, "%d login POSTs in 10 min" % n)
    for ip, st in maps.items():
        if len(st) >= 5:
            rule("Source map harvesting by a non-browser client", "Medium", ip, "%d distinct .map files" % len(st))
    for ip, st in reset_ids.items():
        if len(st) >= 10:
            rule("Password reset across many identifiers", "High", ip, "%d distinct IDs" % len(st))
    for (ip, tmpl), st in enum.items():
        ids = sorted(st)
        run = best = 1
        for x, y in zip(ids, ids[1:]):
            run = run + 1 if y == x + 1 else 1
            best = max(best, run)
        if len(ids) >= 25 and best >= 10:
            rule("Sequential identifier enumeration", "High" if best >= 25 else "Medium", ip,
                 "%s, %d IDs, run of %d" % (tmpl[:60], len(ids), best))
    for ua, hits in odd_ua_hits.items():
        hits.sort()
        j = 0
        window_ips = Counter()
        best = 0
        best_set = set()
        for (t, ip) in hits:
            window_ips[ip] += 1
            while hits[j][0] < t - timedelta(minutes=60):
                window_ips[hits[j][1]] -= 1
                if window_ips[hits[j][1]] == 0:
                    del window_ips[hits[j][1]]
                j += 1
            if len(window_ips) > best:
                best, best_set = len(window_ips), set(window_ips)
        if best >= 10:
            for ip in best_set:
                rule("Rotating address pool (one odd UA, 10+ IPs in an hour)", "High", ip,
                     "%s from %d IPs" % (ua[:60], best))
    for ip, p in per_ip.items():
        if ip in F.ip and p["assets"] == 0 and p["n"] >= 20:
            F.ip[ip]["reasons"]["no page assets loaded (scripted)"] += 1

    # ---- report
    host = socket.gethostname()
    stamp = datetime.now().strftime("%Y%m%d_%H%M")
    os.makedirs(a.out, exist_ok=True)
    f_ind = os.path.join(a.out, "oncyber_artex_hunt_%s_%s_indicators.csv" % (host, stamp))
    f_ip = os.path.join(a.out, "oncyber_artex_hunt_%s_%s_ips.csv" % (host, stamp))
    tty = sys.stdout.isatty()
    C = {"High": "\033[31;1m", "Medium": "\033[33;1m", "Low": "\033[36m"} if tty else {"High": "", "Medium": "", "Low": ""}
    R = "\033[0m" if tty else ""
    fmt = lambda d: d.strftime("%Y-%m-%d %H:%M") if d else "?"

    ind = sorted(F.ind.values(), key=lambda r: (-RANK[r["conf"]], -r["hits"]))
    levels = Counter(r["conf"] for r in ind)
    print("ONCyber ARTEX log hunt · %s · %s" % (host, datetime.now().strftime("%Y-%m-%d %H:%M")))
    print("Indicators: %s (feed %s)" % (", ".join("%s %d" % kv for kv in sorted(I["meta"].items())) or "none, behaviour checks only", I["sha"]))
    print("Logs: %d files, %d lines, %d in window, %d unparsed%s" % (
        stats["files"], stats["lines"], stats["in_window"], stats["unparsed"],
        ", %d unreadable" % stats["unreadable"] if stats["unreadable"] else ""))
    if stats["cloudflare_without_real_ip"]:
        print("Note: %d requests show a Cloudflare address as the client. Log the real visitor IP "
              "(mod_remoteip / real_ip_header CF-Connecting-IP) or IP matching will be incomplete."
              % stats["cloudflare_without_real_ip"])
    print("Result: %d High, %d Medium, %d Low\n" % (levels["High"], levels["Medium"], levels["Low"]))

    if ind:
        print("%-7s %-46s %-42s %7s %5s  %-16s  %-16s" % ("CONF", "CHECK", "INDICATOR", "HITS", "IPS", "FIRST", "LAST"))
        shown = ind if not a.quiet else [r for r in ind if r["conf"] != "Low"]
        for r in shown[:80]:
            print("%s%-7s%s %-46s %-42s %7d %5d  %-16s  %-16s" % (
                C[r["conf"]], r["conf"], R, r["kind"][:46], r["indicator"][:42], r["hits"], len(r["ips"]),
                fmt(r["first"]), fmt(r["last"])))
        if len(shown) > 80:
            print("... %d more in %s" % (len(shown) - 80, f_ind))
        print("\nAddresses by confidence:")
        inv = {3: "High", 2: "Medium", 1: "Low"}
        rows = sorted(F.ip.items(), key=lambda kv: (-kv[1]["conf"], -per_ip[kv[0]]["n"]))
        for ip, r in rows[:40]:
            c = inv[r["conf"]]
            if a.quiet and c == "Low":
                continue
            p = per_ip[ip]
            print("  %s%-7s%s %-40s %6d req  %s -> %s  %s" % (C[c], c, R, ip or "(no IP)", p["n"], fmt(p["first"]), fmt(p["last"]),
                                                       "; ".join(k for k, _ in sorted(r["reasons"].items(), key=lambda kv: (-r["rrank"].get(kv[0], 0), -kv[1]))[:3])[:110]))
        if len(rows) > 40:
            print("  ... %d more in %s" % (len(rows) - 40, f_ip))
    else:
        print("No indicator or behaviour hits in the scanned window.")

    with open(f_ind, "w", newline="") as fh:
        w = csv.writer(fh)
        w.writerow(["confidence", "check", "indicator", "hits", "distinct_ips", "top_ips", "first", "last", "sample", "source"])
        for r in ind:
            w.writerow([r["conf"], r["kind"], r["indicator"], r["hits"], len(r["ips"]),
                        " ".join(i for i, _ in r["ips"].most_common(10)), fmt(r["first"]), fmt(r["last"]),
                        r["sample"], r["source"]])
    with open(f_ip, "w", newline="") as fh:
        w = csv.writer(fh)
        w.writerow(["ip", "confidence", "requests", "asset_requests", "first", "last", "reasons", "top_user_agent"])
        for ip, r in sorted(F.ip.items(), key=lambda kv: -kv[1]["conf"]):
            p = per_ip[ip]
            w.writerow([ip, {3: "High", 2: "Medium", 1: "Low"}[r["conf"]], p["n"], p["assets"], fmt(p["first"]), fmt(p["last"]),
                        "; ".join("%s x%d" % kv for kv in sorted(r["reasons"].items(), key=lambda kv: (-r["rrank"].get(kv[0], 0), -kv[1]))),
                        (p["uas"].most_common(1)[0][0] if p["uas"] else "")[:200]])
    print("\nResults: %s\n         %s" % (f_ind, f_ip))
    print("High = act now and send both CSVs to ONCyber (info@oncyber.ca). "
          "Medium = review the sample requests. Low = context only.")
    return 2 if levels["High"] else (1 if ind else 0)

if __name__ == "__main__":
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        sys.exit(3)
PYEOF

set +e
python3 "$WORK/hunt.py" --ioc-dir "$WORK/iocs" "${PASS[@]+"${PASS[@]}"}" </dev/null
RC=$?
set -e
exit $RC
