#!/usr/bin/env python3
"""CVE-2026-21589 log hunt: flag Atlassian DC '::' path traversal in a web
access log and correlate per source IP. Detection only.

Complements the soc-skills self-test (cve-2026-21589-detect.py, inline corpus)
by running against a log file (../samples/confluence-access.log).

Signals (see ../hunt-checklist-cve-2026-21589.md):
  TRAVERSAL_PROBE   literal '::' in the URL PATH (not host, not query string)
  SENSITIVE_READ    200 on WEB-INF/ META-INF/ conf/server.xml, with or without '::'
Verdicts per IP:
  INCIDENT   '::' probe + 200 on a sensitive file
  RECON      '::' probes, no successful sensitive read
Allowlist: approved scanner IPs (document in report §3.2).
The path is percent-decoded once before matching, so '%3A%3A' counts as '::'.
Lines that are not valid combined-log requests ('-' requests, truncated
lines) are skipped and counted. See ../../NOISY_DATA.md for TP/FP on
samples/noisy/confluence-access-noisy.log and tuning hints.

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

ALLOWLIST_IPS = {"10.0.5.8"}  # approved weekly vuln scanner
LOG = re.compile(r'^(\S+) \S+ \S+ \[([^\]]+)\] "(\S+) (\S+)[^"]*" (\d{3}) ')
ATLASSIAN = re.compile(r"^/(confluence|jira|bitbucket|bamboo|crowd|plugins|rest|download)/", re.I)
SENSITIVE = re.compile(r"(WEB-INF/|META-INF/|conf/server\.xml)", 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, traversal = {}, set()
    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()
            if ip in ALLOWLIST_IPS:
                continue
            req_path = unquote(uri.split("?", 1)[0].split("#", 1)[0])
            if not ATLASSIAN.search(req_path):
                continue
            kind = None
            if status == "200" and SENSITIVE.search(req_path):
                kind = "SENSITIVE_READ"
            elif "::" in req_path:
                kind = "TRAVERSAL_PROBE"
            if kind:
                hits.setdefault(ip, []).append((n, ts, kind, status, uri))
                if "::" in req_path:
                    traversal.add(ip)
    result = {}
    for ip, hs in hits.items():
        kinds = {h[2] for h in hs}
        verdict = "INCIDENT" if "SENSITIVE_READ" in kinds and ip in traversal else \
                  "SUSPICIOUS" if "SENSITIVE_READ" in kinds 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:<15} {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")
