#!/usr/bin/env python3
"""CVE-2026-102764 hunt (reference): flag the 7 ARMORY CASTLE artifact types in
a BeyondTrust appliance log and correlate per host. Detection only.

Exercise 2: write your own hunt FIRST, then compare with this.

Artifact types (see ../hunt-checklist.md):
  WEBSHELL       new/modified .php under the web root, no change ticket
  SUID_ROOT      setuid-root file outside package-managed bin dirs
  VAULT_ACCESS   vault read/export by anyone except the sync service account
  BOOT_PERSIST   rc.local / init.d / sudoers changed, no ticket
  TUNNEL         haproxy.cfg changed without ticket, or new websocket/socks listener
  PRIV_ESC       role raised to Administrator, no ticket
  LOG_GAP        per-host sequence number jumps (records deleted)

Correlation: >=2 distinct artifact types on one host within 24h -> INCIDENT;
exactly 1 -> SUSPICIOUS (hunt deeper).
Allowlist (document why in report §3.2): cron haproxy reloads, logrotate,
vault reads by svc_vault_sync, any change carrying a ticket=CHG-* reference.

Robustness (noisy logs): lines with an unparseable timestamp are skipped and
counted; a missing or non-numeric seq= field skips the LOG_GAP check for that
line instead of inventing a gap. See ../../NOISY_DATA.md for the TP/FP this
reference rule produces on samples/noisy/appliance-noisy.log, and tuning hints.

Usage: python3 cve-2026-102764-detect.py <appliance.log>
"""
import re
import sys
from datetime import datetime, timedelta

VAULT_SERVICE_ACCOUNTS = {"svc_vault_sync"}
PKG_BIN_DIRS = ("/usr/bin/", "/bin/", "/usr/sbin/", "/sbin/")
BOOT_PATHS = re.compile(r"^/etc/(rc\.local|init\.d/|sudoers(\.d/|$))")
WEBROOT_PHP = re.compile(r"^/var/www/.*\.php\d?$", re.IGNORECASE)
LINE = re.compile(r"^(\S+)\s+(.*)$")
KV = re.compile(r"(\w+)=(\S+)")
WINDOW = timedelta(hours=24)


def has_ticket(f):
    return f.get("ticket", "-").startswith("CHG-")


def classify(f):
    src, ev, path = f.get("src"), f.get("event"), f.get("path", "")
    if src == "fim" and ev in ("create", "modify") and not has_ticket(f):
        if WEBROOT_PHP.match(path):
            return "WEBSHELL"
        if BOOT_PATHS.match(path):
            return "BOOT_PERSIST"
        if path == "/etc/haproxy/haproxy.cfg":
            return "TUNNEL"
    if src == "auditd" and ev == "setuid_set" and f.get("owner") == "root" \
            and not path.startswith(PKG_BIN_DIRS):
        return "SUID_ROOT"
    if src == "appliance" and ev.startswith("vault_") \
            and f.get("account") not in VAULT_SERVICE_ACCOUNTS:
        return "VAULT_ACCESS"
    if src == "net" and ev == "listen" and f.get("new") == "yes" \
            and f.get("proto") in ("websocket", "socks5", "socks"):
        return "TUNNEL"
    if src == "appliance" and ev == "role_change" \
            and f.get("new_role") == "Administrator" and not has_ticket(f):
        return "PRIV_ESC"
    return None


def analyze(path, stats=None):
    """Return {host: {"verdict": str, "hits": [(lineno, ts, kind, detail)]}}.

    If *stats* is a dict it receives counters: lines, skipped_malformed, no_seq.
    """
    hits, last_seq = {}, {}
    stats = stats if stats is not None else {}
    stats.update(lines=0, skipped_malformed=0, no_seq=0)
    with open(path, errors="replace") as fh:
        for n, line in enumerate(fh, 1):
            if not line.strip() or line.lstrip().startswith("#"):
                continue
            stats["lines"] += 1
            m = LINE.match(line.strip())
            if not m:
                stats["skipped_malformed"] += 1
                continue
            try:
                ts = datetime.strptime(m.group(1), "%Y-%m-%dT%H:%M:%SZ")
            except ValueError:
                stats["skipped_malformed"] += 1
                continue
            f = dict(KV.findall(m.group(2)))
            host = f.get("host", "?")
            raw_seq = f.get("seq", "")
            if raw_seq.isdigit():
                seq = int(raw_seq)
                prev = last_seq.get(host)
                if prev is not None and seq != prev + 1:
                    hits.setdefault(host, []).append(
                        (n, ts, "LOG_GAP", f"seq {prev} -> {seq} ({seq - prev - 1} missing)"))
                last_seq[host] = seq
            else:
                stats["no_seq"] += 1
            kind = classify(f)
            if kind:
                detail = f.get("path") or f.get("account") or f.get("proto", "")
                hits.setdefault(host, []).append((n, ts, kind, f"{f.get('event')} {detail}"))
    result = {}
    for host, hs in hits.items():
        hs.sort(key=lambda h: h[1])
        # any 24h window holding >=2 distinct kinds -> incident
        incident = any(
            len({k for _, t, k, _ in hs if hs[i][1] <= t <= hs[i][1] + WINDOW}) >= 2
            for i in range(len(hs)))
        result[host] = {"verdict": "INCIDENT" if incident else "SUSPICIOUS", "hits": hs}
    return result


def main(path):
    stats = {}
    res = analyze(path, stats)
    if not res:
        print("no artifacts found")
    for host, r in sorted(res.items()):
        kinds = sorted({h[2] for h in r["hits"]})
        print(f"[{r['verdict']}] {host} ({len(r['hits'])} hits, {len(kinds)} types: {', '.join(kinds)})")
        for n, ts, kind, detail in r["hits"]:
            print(f"  L{n} {ts:%Y-%m-%dT%H:%M:%SZ} {kind:<13} {detail}")
    if stats["skipped_malformed"] or stats["no_seq"]:
        print(f"note: {stats['skipped_malformed']} malformed line(s) skipped, "
              f"{stats['no_seq']} line(s) without seq= (gap check skipped)")


if __name__ == "__main__":
    main(sys.argv[1] if len(sys.argv) > 1 else "/dev/stdin")
