#!/usr/bin/env python3
"""CVE-2026-119977 detector: flag WordPress upgrade-window staged-installer
probes in a web access log and correlate them with core-upgrade activity.
Detection / forensic-triage practice only — no exploit code.

Signals (see ../hunt-checklist-cve-2026-119977.md):
  UPGRADE      wp-admin update-core.php / update.php core-upgrade activity
  STAGE_PROBE  request under /wp-content/upgrade/ for setup-config.php,
               install.php, or other staged installer/admin PHP
Verdicts per IP (upgrade events themselves are not attributed to an attacker):
  INCIDENT     accepted (2xx) STAGE_PROBE that overlaps an upgrade window
               (±5 minutes of any UPGRADE event in the log)
  SUSPICIOUS   accepted STAGE_PROBE with no upgrade window in the log
  RECON        STAGE_PROBE only, all non-2xx
Benign by design: normal front-end, /wp-admin/edit.php, wp-json, and wp-cron
traffic never match STAGE_PROBE. Lines that are not valid combined-log requests
are skipped and counted.

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

LOG = re.compile(r'^(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+)[^"]*" (\d{3}) ')
UPGRADE = re.compile(
    r"/wp-admin/(?:update-core\.php|update\.php(?:\?[^/\s]*)?(?:action=)?(?:do-core-upgrade|update-selected-core))",
    re.I,
)
STAGE = re.compile(
    r"/wp-content/upgrade/(?:[^/\s]+/)*(?:setup-config|install)\.php",
    re.I,
)
# Also catch other staged PHP under upgrade/ (not just the installer entrypoints)
STAGE_PHP = re.compile(r"/wp-content/upgrade/[^?\s]*\.php", re.I)
TIME_FMT = "%d/%b/%Y:%H:%M:%S %z"
WINDOW = timedelta(minutes=5)


def _parse_ts(ts: str):
    try:
        return datetime.strptime(ts, TIME_FMT)
    except ValueError:
        # some logs omit the zone; treat as +0000
        try:
            return datetime.strptime(ts + " +0000", TIME_FMT)
        except ValueError:
            return None


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

    If *stats* is a dict it receives counters: lines, skipped_malformed.
    """
    hits = {}
    upgrades = []  # list of parsed datetimes
    stats = stats if stats is not None else {}
    stats.update(lines=0, skipped_malformed=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 = LOG.match(line)
            if not m:
                stats["skipped_malformed"] += 1
                continue
            ip, ts, _method, uri, status = m.groups()
            kind = None
            if UPGRADE.search(uri):
                kind = "UPGRADE"
                t = _parse_ts(ts)
                if t is not None:
                    upgrades.append(t)
            elif STAGE.search(uri) or (
                STAGE_PHP.search(uri)
                and re.search(r"(setup-config|install|wp-admin)", uri, re.I)
            ):
                kind = "STAGE_PROBE"
            if kind == "STAGE_PROBE":
                hits.setdefault(ip, []).append((n, ts, kind, status, uri))
            # UPGRADE events are recorded for correlation only; not attacker hits
    result = {}
    for ip, hs in hits.items():
        ok = lambda h: h[3].startswith("2")
        probe_ok = [h for h in hs if h[2] == "STAGE_PROBE" and ok(h)]
        probe_bad = [h for h in hs if h[2] == "STAGE_PROBE" and not ok(h)]
        if probe_ok:
            near_upgrade = False
            for h in probe_ok:
                t = _parse_ts(h[1])
                if t is None:
                    continue
                if any(abs(t - u) <= WINDOW for u in upgrades):
                    near_upgrade = True
                    break
            verdict = "INCIDENT" if near_upgrade or not upgrades else "SUSPICIOUS"
            # If the log has upgrade events but none near this IP → still SUSPICIOUS
            if upgrades and not near_upgrade:
                verdict = "SUSPICIOUS"
            elif near_upgrade:
                verdict = "INCIDENT"
            elif not upgrades:
                verdict = "SUSPICIOUS"
        else:
            verdict = "RECON" if probe_bad else "RECON"
        result[ip] = {"verdict": verdict, "hits": hs}
    return result


def main(path):
    stats = {}
    res = analyze(path, stats)
    if not res:
        print("no findings")
    for ip, r in sorted(res.items()):
        print(f"[{r['verdict']}] {ip} ({len(r['hits'])} hits):")
        for n, ts, kind, status, uri in r["hits"]:
            print(f"  L{n} {ts} {kind:<12} {status} {uri[:100]}")
    if stats["skipped_malformed"]:
        print(f"note: {stats['skipped_malformed']} malformed line(s) skipped")


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