#!/usr/bin/env python3
"""CVE-2026-110447 detector: flag Nextcloud richdocumentscode proxy.php
injection probes, dropped shx*.php shells, and shell command requests in a web
access log; correlate per source IP. Detection only.

Signals (see ../hunt-checklist-cve-2026-110447.md):
  PROBE        proxy.php request containing %2e%2e, $( / %24%28, or ${IFS} / %24%7BIFS%7D
  SHELL_DROP   request for shx*.php (or any .php under apps/richdocumentscode/ other than proxy.php)
  SHELL_CMD    request to such a shell carrying ?c=
Verdicts per IP:
  INCIDENT     accepted probe (2xx) AND a 2xx shell request
  SUSPICIOUS   2xx shell request without a probe seen (log gap? other vector?)
  RECON        probes / shell guesses, all 4xx
Benign by design: plain proxy.php?status health checks and editor loads carry
no indicator strings, so no allowlist is needed for them.
Lines that are not valid combined-log requests are skipped and counted. See
../../NOISY_DATA.md for TP/FP on samples/noisy/nextcloud-access-noisy.log.

Usage: python3 cve-2026-110447-detect.py <access.log>
"""
import re
import sys
from urllib.parse import unquote

LOG = re.compile(r'^(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+)[^"]*" (\d{3}) ')
PROXY = re.compile(r"/apps/richdocumentscode/proxy\.php", re.I)
INJECT = re.compile(r"(\.\./|\$\(|\$\{IFS\})", re.I)
SHELL = re.compile(r"/apps/richdocumentscode/(?!proxy\.php)[^/?\s]*\.php\d?|/shx[^/?\s]*\.php", re.I)
CMD = re.compile(r"[?&]c=", re.I)


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 = {}
    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()
            decoded = unquote(unquote(uri))  # catch single and double encoding
            kind = None
            if PROXY.search(uri) and INJECT.search(decoded):
                kind = "PROBE"
            elif SHELL.search(uri):
                kind = "SHELL_CMD" if CMD.search(uri) else "SHELL_DROP"
            if kind:
                hits.setdefault(ip, []).append((n, ts, kind, status, uri))
    result = {}
    for ip, hs in hits.items():
        ok = lambda h: h[3].startswith("2")
        probe_ok = any(h[2] == "PROBE" and ok(h) for h in hs)
        shell_ok = any(h[2] != "PROBE" and ok(h) for h in hs)
        verdict = "INCIDENT" if probe_ok and shell_ok else \
                  "SUSPICIOUS" if shell_ok or probe_ok 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:<10} {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")
