#!/usr/bin/env python3
"""CVE-2026-123158 detector: flag sshd "Accepted password" logins for accounts
whose password field is not a hash.

Detection / forensic-triage practice only — no exploit code. sshd does not log
the password or the shadow field, and the OpenSSH 10.6p2 notes do not name a
distinct log line. The Alpine Linux advisory (cited by the CISA KEV notes)
says to look for `Accepted password for` an account that has no password.

This script joins that message with an account census you record in the log
as comment lines (the stand-in for reading field 2 of /etc/shadow):

  # INVENTORY password_field=* : alpine root
  # INVENTORY password_field=hash : admin
  # INVENTORY password_field=! : nobody

Signals:
  ACCEPTED_STAR      Accepted password for a password_field=* account
  ACCEPTED_UNKNOWN   Accepted password for an account missing from the census
Verdicts per source address:
  INCIDENT    any ACCEPTED_STAR (Alpine: if you cannot rule out the login,
              treat the machine as compromised)
  SUSPICIOUS  ACCEPTED_UNKNOWN only — finish the census before calling it
              this CVE
Not this signal, and never flagged: Accepted publickey, Failed password,
Accepted password for a hash account, Accepted password for a locked (`!`)
account. Password length is not a key: the logs do not contain it, and NVD
and the Alpine advisory do not state the same lower bound.

The census is file-wide. On a multi-host log, split by host first.

Usage: python3 cve-2026-123158-detect.py <auth.log>
"""
import re
import sys

INV = re.compile(r"^#\s*INVENTORY\s+password_field=(\*|hash|!)\s*:\s*(.*?)\s*$")
# syslog or ISO-8601 timestamp, optional hostname, sshd or sshd-session.
ACCEPTED = re.compile(
    r"^(?:[A-Z][a-z]{2}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}"
    r"|\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?)"
    r"\s+(?:\S+\s+)?sshd(?:-session)?\[\d+\]:\s+"
    r"Accepted password for (\S+) from (\S+) port \d+\b"
)
SYSLOGISH = re.compile(
    r"^(?:[A-Z][a-z]{2}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}"
    r"|\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})"
)


def _census(lines):
    star, known = set(), set()
    for line in lines:
        m = INV.match(line.rstrip("\n"))
        if not m:
            continue
        field, users = m.group(1), m.group(2).split()
        if field == "*":
            star.update(users)
        else:
            known.update(users)
    return star, known


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

    If *stats* is a dict it receives counters: lines, skipped_malformed.
    """
    with open(path, errors="replace") as fh:
        lines = fh.readlines()
    star, known = _census(lines)
    hits = {}
    stats = stats if stats is not None else {}
    stats.update(lines=0, skipped_malformed=0)
    for n, line in enumerate(lines, 1):
        if not line.strip() or line.lstrip().startswith("#"):
            continue
        stats["lines"] += 1
        m = ACCEPTED.search(line)
        if not m:
            if not SYSLOGISH.match(line):
                stats["skipped_malformed"] += 1
            continue
        user, ip = m.group(1), m.group(2)
        if user in star:
            kind = "ACCEPTED_STAR"
        elif user in known:
            continue
        else:
            kind = "ACCEPTED_UNKNOWN"
        ts = line.split(" ssh", 1)[0].strip()
        hits.setdefault(ip, []).append((n, ts, kind, user, ip))
    result = {}
    for ip, hs in hits.items():
        verdict = "INCIDENT" if any(h[2] == "ACCEPTED_STAR" for h in hs) else "SUSPICIOUS"
        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, user, src in r["hits"]:
            print(f"  L{n} {ts} {kind:<18} {user} from {src}")
    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")
