Exploit database

GH-7bb6db2dcaefafa9ad105ede8f7e2591

avi99999/sshhole-scanner

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-123158

29 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files6
avi99999/sshhole-scannerRevision 3b0e902876f0

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

sshhole_scan.py

Python · 27,654 bytes
#!/usr/bin/env python3
"""
sshhole_scan.py - detector for CVE-2026-123158 ("sshhole")

OpenSSH < 10.6p2, sshd on Linux built against musl libc WITHOUT PAM:
password authentication bypass.

Root cause (summary):
  * For an account whose stored password field is too short to hold a salt
    (e.g. "*"), sshd borrows the salt of another local account ($5$/$6$ hash).
  * musl's crypt() returns the constant string "*" on failure, and its
    SHA-256/SHA-512 crypt fails for keys longer than 256 bytes.
  * So crypt(<257..1024-byte password>, "$6$...") == "*" == stored field,
    and the login is accepted with ANY long password.

Exploitable when ALL of these hold:
  1. sshd is linked against musl (Alpine, OpenWrt, Buildroot, Yocto, ...)
  2. sshd does not use PAM (UsePAM no / not built with PAM)
  3. PasswordAuthentication is enabled (default: yes)
  4. sshd is unpatched (upstream < 10.6p2, or Alpine package below the
     fixed backport release for its branch)
  5. an SSH-reachable account has a shadow field of exactly "*"
  6. at least one local account has a $5$ / $6$ hash (the borrowed salt)

This tool only READS local state (or banner/auth-method info remotely).
It never attempts the bypass.

Modes:
  local   (default)  audit this host. Run as root for full results.
  --root DIR         audit an offline filesystem (mounted disk, extracted
                     container image: `docker export c | tar -x -C DIR`).
  --remote HOST      non-intrusive network check (banner + offered auth
                     methods via a "none" auth request; needs paramiko for
                     the auth-method part).

Exit codes: 0 not vulnerable, 1 vulnerable, 2 potentially vulnerable /
undetermined, 3 error.
"""

from __future__ import annotations

import argparse
import glob
import json
import os
import re
import shutil
import socket
import subprocess
import sys
from dataclasses import dataclass, field, asdict

CVE = "CVE-2026-123158"

# Alpine fixed openssh package versions per branch (from Alpine advisory
# 2026-11-05). Key: "major.minor" of /etc/alpine-release, or "edge".
ALPINE_FIXED = {
    "edge": "10.6_p2-r0",
    "3.24": "10.3_p1-r2",
    "3.23": "10.2_p1-r1",
    "3.22": "10.0_p1-r11",
    "3.21": "9.9_p2-r1",
    "3.20": "9.7_p1-r6",
    "3.19": "9.6_p1-r3",
    "3.18": "9.3_p2-r4",
    "3.17": "9.1_p1-r7",
    "3.16": "9.0_p1-r6",
}
UPSTREAM_FIXED = (10, 6, 2)  # 10.6p2

VULNERABLE, POTENTIAL, NOT_VULNERABLE = "VULNERABLE", "POTENTIALLY VULNERABLE", "NOT VULNERABLE"


# --------------------------------------------------------------------------
# Result model
# --------------------------------------------------------------------------

@dataclass
class Check:
    name: str
    status: str          # "affected" | "safe" | "unknown" | "info"
    detail: str


@dataclass
class Report:
    target: str
    checks: list[Check] = field(default_factory=list)
    exposed_accounts: list[dict] = field(default_factory=list)
    ioc_log_hits: list[str] = field(default_factory=list)
    verdict: str = ""
    summary: str = ""
    remediation: list[str] = field(default_factory=list)

    def add(self, name, status, detail):
        self.checks.append(Check(name, status, detail))
        return status


# --------------------------------------------------------------------------
# Version helpers
# --------------------------------------------------------------------------

def parse_upstream(ver: str):
    """'OpenSSH_10.0p1' / '9.9p2' -> (10, 0, 1). Returns None if unparsable."""
    m = re.search(r"(\d+)\.(\d+)(?:p(\d+))?", ver)
    if not m:
        return None
    return int(m.group(1)), int(m.group(2)), int(m.group(3) or 0)


def parse_apk(ver: str):
    """Alpine '10.0_p1-r11' -> ((10, 0), 1, 11). Simplified apk ordering that
    is sufficient for openssh package versions."""
    m = re.match(r"^(\d+(?:\.\d+)*)(?:_p(\d+))?(?:-r(\d+))?", ver.strip())
    if not m:
        return None
    nums = tuple(int(x) for x in m.group(1).split("."))
    return nums, int(m.group(2) or 0), int(m.group(3) or 0)


def apk_lt(a: str, b: str):
    pa, pb = parse_apk(a), parse_apk(b)
    if pa is None or pb is None:
        return None
    return pa < pb


# --------------------------------------------------------------------------
# Filesystem access (live host or offline root)
# --------------------------------------------------------------------------

class FS:
    def __init__(self, root: str | None):
        self.root = root
        self.live = root is None

    def p(self, path: str) -> str:
        if self.root is None:
            return path
        return os.path.join(self.root, path.lstrip("/"))

    def read(self, path: str) -> str | None:
        try:
            with open(self.p(path), "r", encoding="utf-8", errors="replace") as f:
                return f.read()
        except (OSError, UnicodeError):
            return None

    def readb(self, path: str, limit: int = 64 * 1024 * 1024) -> bytes | None:
        try:
            with open(self.p(path), "rb") as f:
                return f.read(limit)
        except OSError:
            return None

    def exists(self, path: str) -> bool:
        return os.path.lexists(self.p(path))

    def glob(self, pattern: str) -> list[str]:
        hits = sorted(glob.glob(self.p(pattern)))
        if self.root is None:
            return hits
        return ["/" + os.path.relpath(h, self.root).replace(os.sep, "/") for h in hits]


def run(cmd: list[str], timeout=15) -> tuple[int, str]:
    try:
        r = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout)
        return r.returncode, (r.stdout or "") + (r.stderr or "")
    except (OSError, subprocess.SubprocessError) as e:
        return 127, str(e)


# --------------------------------------------------------------------------
# Local checks
# --------------------------------------------------------------------------

def find_sshd(fs: FS) -> str | None:
    for cand in ("/usr/sbin/sshd", "/usr/local/sbin/sshd", "/sbin/sshd",
                 "/usr/bin/sshd", "/usr/sbin/sshd.pam"):
        if fs.exists(cand):
            return cand
    if fs.live:
        w = shutil.which("sshd")
        if w:
            return w
    return None


def elf_interp_and_needed(data: bytes) -> tuple[str | None, list[str]]:
    """Cheap ELF inspection: PT_INTERP string and DT_NEEDED-ish library names
    found in the binary's string table."""
    interp = None
    m = re.search(rb"/lib(?:64)?/ld-[\w.\-]+\.so[\w.\-]*", data[:8192])
    if m:
        interp = m.group(0).decode(errors="replace")
    needed = sorted({x.decode() for x in re.findall(rb"lib[\w\-+]+\.so(?:\.[\d.]+)?", data)})
    return interp, needed


def detect_libc(fs: FS, sshd: str, rep: Report) -> str:
    data = fs.readb(sshd)
    interp, needed = elf_interp_and_needed(data or b"")
    rep._sshd_needed = needed  # stash for PAM detection
    if interp and "musl" in interp:
        rep.add("libc", "affected", f"sshd uses musl loader {interp}")
        return "musl"
    if interp and ("ld-linux" in interp or "ld64" in interp):
        rep.add("libc", "safe", f"sshd uses glibc loader {interp} (bug is musl-specific)")
        return "glibc"
    if any("libc.musl" in n for n in needed) or fs.glob("/lib/ld-musl-*.so.1"):
        rep.add("libc", "affected", "musl libc detected on system")
        return "musl"
    rep.add("libc", "unknown", "could not determine libc of sshd")
    return "unknown"


def sshd_version(fs: FS, sshd: str) -> str | None:
    if fs.live:
        for cmd in ([sshd, "-V"], ["ssh", "-V"]):
            _, out = run(cmd)
            m = re.search(r"OpenSSH_[\w.]+", out)
            if m:
                return m.group(0)
    data = fs.readb(sshd) or b""
    m = re.search(rb"OpenSSH_\d+\.\d+(?:p\d+)?", data)
    return m.group(0).decode() if m else None


def alpine_info(fs: FS):
    rel = (fs.read("/etc/alpine-release") or "").strip()
    if not rel:
        return None, None, {}
    branch = "edge" if ("_alpha" in rel or "_git" in rel) else ".".join(rel.split(".")[:2])
    pkgs = {}
    db = fs.read("/lib/apk/db/installed") or ""
    for block in db.split("\n\n"):
        name = ver = None
        for line in block.splitlines():
            if line.startswith("P:"):
                name = line[2:]
            elif line.startswith("V:"):
                ver = line[2:]
        if name and ver and name.startswith("openssh"):
            pkgs[name] = ver
    # repositories pointing at edge => edge
    repos = fs.read("/etc/apk/repositories") or ""
    if re.search(r"^[^#].*/edge/main", repos, re.M):
        branch = "edge"
    return rel, branch, pkgs


# ---- sshd_config parsing (fallback when `sshd -T` is unavailable) ---------

def parse_sshd_config(fs: FS, path="/etc/ssh/sshd_config", seen=None) -> dict:
    """First-value-wins, honours Include (glob, relative to /etc/ssh).
    Match blocks are skipped (we report global settings)."""
    seen = seen if seen is not None else set()
    cfg: dict[str, str] = {}
    if path in seen:
        return cfg
    seen.add(path)
    text = fs.read(path)
    if text is None:
        return cfg
    in_match = False
    for raw in text.splitlines():
        line = raw.split("#", 1)[0].strip()
        if not line:
            continue
        parts = re.split(r"[\s=]+", line, maxsplit=1)
        key = parts[0].lower()
        val = parts[1].strip() if len(parts) > 1 else ""
        if key == "match":
            in_match = True
            continue
        if in_match:
            continue
        if key == "include":
            for pat in val.split():
                if not pat.startswith("/"):
                    pat = "/etc/ssh/" + pat
                for inc in fs.glob(pat):
                    for k, v in parse_sshd_config(fs, inc, seen).items():
                        cfg.setdefault(k, v)
            continue
        cfg.setdefault(key, val)
    return cfg


def effective_config(fs: FS, sshd: str, rep: Report) -> dict:
    is_root = hasattr(os, "geteuid") and os.geteuid() == 0
    if fs.live and is_root:
        rc, out = run([sshd, "-T"])
        if rc == 0 and out:
            cfg = {}
            for line in out.splitlines():
                k, _, v = line.partition(" ")
                cfg.setdefault(k.lower(), v.strip())
            rep.add("config source", "info", "effective config from `sshd -T`")
            return cfg
    cfg = parse_sshd_config(fs)
    rep.add("config source", "info",
            "parsed /etc/ssh/sshd_config (+Includes); Match blocks ignored"
            + ("" if fs.read("/etc/ssh/sshd_config") is not None
               else " - file not readable, assuming defaults"))
    return cfg


def detect_pam(fs: FS, sshd: str, cfg: dict, alpine_pkgs: dict, rep: Report) -> bool | None:
    needed = getattr(rep, "_sshd_needed", [])
    linked = any(n.startswith("libpam") for n in needed)
    usepam = cfg.get("usepam", "no").lower() == "yes"
    if "openssh-server-pam" in alpine_pkgs:
        linked = True
    if linked and usepam:
        rep.add("PAM", "safe", "sshd built with PAM and UsePAM yes (crypt() not called directly)")
        return True
    if linked and not usepam:
        rep.add("PAM", "affected", "sshd supports PAM but UsePAM is not 'yes' -> uses crypt() directly")
        return False
    rep.add("PAM", "affected", "sshd not linked against libpam -> uses crypt() directly")
    return False


def check_version(fs: FS, sshd: str, rep: Report, alpine_branch, alpine_pkgs) -> bool | None:
    """Returns True if unpatched, False if patched, None if unknown."""
    upstream = sshd_version(fs, sshd)
    pkg = alpine_pkgs.get("openssh-server-pam") or alpine_pkgs.get("openssh-server") \
        or alpine_pkgs.get("openssh")
    if alpine_branch and pkg:
        fixed = ALPINE_FIXED.get(alpine_branch)
        if fixed is None:
            # branch older than 3.16 has no fix at all
            try:
                older = tuple(map(int, alpine_branch.split("."))) < (3, 16)
            except ValueError:
                older = False
            if older:
                rep.add("version", "affected",
                        f"Alpine {alpine_branch} is EOL and has no fixed package (openssh {pkg})")
                return True
            rep.add("version", "unknown", f"Alpine branch {alpine_branch} not in fix table (openssh {pkg})")
            return None
        lt = apk_lt(pkg, fixed)
        if lt is None:
            rep.add("version", "unknown", f"cannot compare apk version {pkg}")
            return None
        if lt:
            rep.add("version", "affected", f"openssh {pkg} < fixed {fixed} for Alpine {alpine_branch}")
            return True
        rep.add("version", "safe", f"openssh {pkg} >= fixed {fixed} for Alpine {alpine_branch}")
        return False
    if upstream:
        v = parse_upstream(upstream)
        if v and v < UPSTREAM_FIXED:
            rep.add("version", "affected",
                    f"{upstream} < OpenSSH_10.6p2 (distro backports not detectable on non-Alpine)")
            return True
        if v:
            rep.add("version", "safe", f"{upstream} >= OpenSSH_10.6p2")
            return False
    rep.add("version", "unknown", "could not determine OpenSSH version")
    return None


def login_shell_ok(fs: FS, shell: str) -> bool:
    if not shell:
        return True  # empty shell = /bin/sh
    if shell.endswith(("nologin", "/false")):
        return False
    return True


def check_accounts(fs: FS, cfg: dict, rep: Report):
    """Returns (exposed accounts, salt_source_present, shadow_readable)."""
    passwd = fs.read("/etc/passwd") or ""
    shadow = fs.read("/etc/shadow")
    shadow_map = {}
    if shadow is not None:
        for line in shadow.splitlines():
            f = line.split(":")
            if len(f) >= 2:
                shadow_map[f[0]] = f[1]

    permit_root = cfg.get("permitrootlogin", "prohibit-password").lower()
    allow_users = cfg.get("allowusers", "").split()
    deny_users = cfg.get("denyusers", "").split()

    salt_sources, exposed = [], []
    for line in passwd.splitlines():
        f = line.split(":")
        if len(f) < 7:
            continue
        user, pw, uid, shell = f[0], f[1], f[2], f[6]
        stored = shadow_map.get(user, pw if pw != "x" else None)
        if stored is None:
            continue
        if stored.startswith(("$5$", "$6$")):
            salt_sources.append(user)
        if stored != "*":
            continue
        reasons = []
        reachable = True
        if user == "root" and permit_root not in ("yes",):
            reachable, reasons = False, [f"PermitRootLogin {permit_root} blocks password login for root"]
        if allow_users and not any(re.fullmatch(a.split("@")[0].replace("*", ".*").replace("?", "."), user)
                                   for a in allow_users):
            reachable, reasons = False, reasons + ["not in AllowUsers"]
        if any(re.fullmatch(d.split("@")[0].replace("*", ".*").replace("?", "."), user) for d in deny_users):
            reachable, reasons = False, reasons + ["in DenyUsers"]
        shell_ok = login_shell_ok(fs, shell)
        if not shell_ok:
            reasons.append(f"shell {shell} gives no interactive session (auth still succeeds; "
                           "port-forwarding may still be possible)")
        exposed.append({"user": user, "uid": uid, "shell": shell,
                        "ssh_reachable": reachable, "interactive_shell": shell_ok,
                        "notes": reasons})

    if shadow is None:
        rep.add("accounts", "unknown", "/etc/shadow not readable (run as root) - cannot list '*' accounts")
    elif not exposed:
        rep.add("accounts", "safe", "no account has a shadow password field of exactly '*'")
    else:
        names = ", ".join(a["user"] + ("" if a["ssh_reachable"] else " (blocked)") for a in exposed)
        rep.add("accounts", "affected" if any(a["ssh_reachable"] for a in exposed) else "safe",
                f"accounts with '*' password field: {names}")

    if salt_sources:
        rep.add("salt source", "affected",
                f"$5$/$6$ hashes present (borrowed salt): {', '.join(salt_sources)}")
    elif shadow is not None:
        rep.add("salt source", "safe", "no $5$/$6$ hash on the system - no salt to borrow")
    else:
        rep.add("salt source", "unknown", "cannot read /etc/shadow")

    nss = fs.read("/etc/nsswitch.conf") or ""
    if re.search(r"^\s*(passwd|shadow):.*\b(ldap|sss|winbind)\b", nss, re.M):
        rep.add("directory users", "affected",
                "nsswitch uses ldap/sss/winbind - directory users without a shadow entry can also "
                "be affected and are not enumerated here")

    rep.exposed_accounts = exposed
    return exposed, bool(salt_sources), shadow is not None


def scan_logs(fs: FS, users: list[str], rep: Report):
    if not users:
        return
    pat = re.compile(r"Accepted password for (\S+) from (\S+)")
    files = []
    for g in ("/var/log/messages*", "/var/log/auth.log*", "/var/log/secure*", "/var/log/sshd*"):
        files += fs.glob(g)
    hits = []
    for path in files:
        if path.endswith(".gz"):
            import gzip
            try:
                with gzip.open(fs.p(path), "rt", errors="replace") as f:
                    text = f.read()
            except OSError:
                continue
        else:
            text = fs.read(path) or ""
        for line in text.splitlines():
            m = pat.search(line)
            if m and m.group(1) in users:
                hits.append(f"{path}: {line.strip()}")
    rep.ioc_log_hits = hits
    if hits:
        rep.add("logs (IoC)", "affected",
                f"{len(hits)} 'Accepted password' event(s) for '*' accounts - LIKELY COMPROMISE")
    elif files:
        rep.add("logs (IoC)", "safe", f"no password logins for '*' accounts in {len(files)} log file(s)")
    else:
        rep.add("logs (IoC)", "unknown", "no syslog files found (check journal/remote syslog)")


def local_scan(root: str | None) -> Report:
    fs = FS(root)
    rep = Report(target=root or socket.gethostname())

    sshd = find_sshd(fs)
    if not sshd:
        rep.add("sshd", "safe", "no sshd binary found")
        rep.verdict, rep.summary = NOT_VULNERABLE, "OpenSSH server not installed."
        return rep
    rep.add("sshd", "info", f"found {sshd}")

    rel, branch, pkgs = alpine_info(fs)
    if rel:
        rep.add("distro", "info", f"Alpine {rel} (branch {branch}); packages: "
                + ", ".join(f"{k}={v}" for k, v in pkgs.items()))

    libc = detect_libc(fs, sshd, rep)
    cfg = effective_config(fs, sshd, rep)
    uses_pam = detect_pam(fs, sshd, cfg, pkgs, rep)
    unpatched = check_version(fs, sshd, rep, branch, pkgs)

    pwauth = cfg.get("passwordauthentication", "yes").lower()
    pw_on = pwauth != "no"
    rep.add("PasswordAuthentication", "affected" if pw_on else "safe", f"PasswordAuthentication {pwauth}")

    exposed, salt, shadow_ok = check_accounts(fs, cfg, rep)
    scan_logs(fs, [a["user"] for a in exposed], rep)

    reachable = [a for a in exposed if a["ssh_reachable"]]

    # ---- verdict ----
    if libc == "glibc":
        rep.verdict, rep.summary = NOT_VULNERABLE, "sshd uses glibc; the bug requires musl libc."
    elif uses_pam:
        rep.verdict, rep.summary = NOT_VULNERABLE, "sshd authenticates through PAM."
    elif unpatched is False:
        rep.verdict, rep.summary = NOT_VULNERABLE, "OpenSSH package contains the fix."
    elif not pw_on:
        rep.verdict, rep.summary = NOT_VULNERABLE, (
            "PasswordAuthentication is disabled (mitigated). Still upgrade openssh.")
    elif shadow_ok and not salt:
        rep.verdict, rep.summary = NOT_VULNERABLE, (
            "Unpatched, but no $5$/$6$ hash exists to borrow a salt from. Upgrade anyway: "
            "creating any password user would make it exploitable.")
    elif shadow_ok and not reachable:
        rep.verdict, rep.summary = POTENTIAL, (
            "Unpatched musl/no-PAM sshd with password auth on, but no SSH-reachable '*' account "
            "right now. Directory users or future accounts could make it exploitable.")
    elif libc == "musl" and unpatched and shadow_ok and reachable and salt:
        rep.verdict, rep.summary = VULNERABLE, (
            "Any password of 257-1024 bytes logs in as: " + ", ".join(a["user"] for a in reachable))
    else:
        rep.verdict, rep.summary = POTENTIAL, "Some conditions could not be verified (see 'unknown' checks)."

    if rep.ioc_log_hits:
        rep.summary += " Log evidence of password logins to '*' accounts found: investigate as compromised."

    if rep.verdict != NOT_VULNERABLE or unpatched:
        rep.remediation = [
            "apk upgrade -U -a   (or upgrade to OpenSSH >= 10.6p2 / your distro's fixed build)",
            "rc-service sshd restart   (upgrading does NOT restart the running daemon)",
            "Interim: echo 'PasswordAuthentication no' > /etc/ssh/sshd_config.d/00-no-passwords.conf "
            "&& rc-service sshd restart   (verify key login first; keep a session open)",
            "Verify: sshd -T | grep -i passwordauthentication  -> passwordauthentication no",
        ]
    if rep.ioc_log_hits:
        rep.remediation.append("Review doas/sudo use, new users, authorized_keys, cron and persistence on this host.")
    return rep


# --------------------------------------------------------------------------
# Remote (non-intrusive) check
# --------------------------------------------------------------------------

def remote_scan(host: str, port: int, user: str, timeout: float) -> Report:
    rep = Report(target=f"{host}:{port}")
    try:
        with socket.create_connection((host, port), timeout=timeout) as s:
            s.settimeout(timeout)
            banner = s.recv(256).decode(errors="replace").strip().splitlines()[0]
    except OSError as e:
        rep.add("connect", "unknown", f"connection failed: {e}")
        rep.verdict, rep.summary = POTENTIAL, "Could not connect."
        return rep
    rep.add("banner", "info", banner)

    if "OpenSSH" not in banner:
        rep.add("implementation", "safe", "not OpenSSH (e.g. dropbear) - not affected")
        rep.verdict, rep.summary = NOT_VULNERABLE, "Server is not OpenSSH."
        return rep

    v = parse_upstream(banner.split("OpenSSH_", 1)[1])
    comment = banner.split(" ", 1)[1] if " " in banner else ""
    glibc_distro = re.search(r"Debian|Ubuntu|Raspbian|FreeBSD|NetBSD", comment, re.I)
    if glibc_distro:
        rep.add("platform", "safe", f"banner comment '{comment}' indicates a non-musl distro")
    elif comment:
        rep.add("platform", "unknown", f"banner comment '{comment}'")
    else:
        rep.add("platform", "unknown",
                "no distro comment in banner (consistent with Alpine/musl builds, not conclusive)")

    if v and v >= UPSTREAM_FIXED:
        rep.add("version", "safe", f"OpenSSH {v[0]}.{v[1]}p{v[2]} >= 10.6p2")
    else:
        rep.add("version", "unknown" if v else "unknown",
                f"OpenSSH {v[0]}.{v[1]}p{v[2]} < 10.6p2 upstream; Alpine backports keep the old "
                "version string, so the banner cannot prove it is unpatched" if v else "unparsable version")

    pw_offered = None
    try:
        import paramiko  # type: ignore
        t = paramiko.Transport((host, port))
        t.banner_timeout = timeout
        t.start_client(timeout=timeout)
        try:
            t.auth_none(user)
            methods = []
        except paramiko.BadAuthenticationType as e:
            methods = list(e.allowed_types)
        except paramiko.SSHException:
            methods = []
        finally:
            t.close()
        pw_offered = "password" in methods
        rep.add("auth methods", "affected" if pw_offered else "safe",
                f"server offers {methods or 'nothing'} for user '{user}'")
    except ImportError:
        rep.add("auth methods", "unknown", "install paramiko to check whether password auth is offered")
    except Exception as e:  # noqa: BLE001
        rep.add("auth methods", "unknown", f"auth-method probe failed: {e}")

    if glibc_distro:
        rep.verdict, rep.summary = NOT_VULNERABLE, "Banner indicates a glibc distribution."
    elif v and v >= UPSTREAM_FIXED:
        rep.verdict, rep.summary = NOT_VULNERABLE, "OpenSSH 10.6p2 or later."
    elif pw_offered is False:
        rep.verdict, rep.summary = NOT_VULNERABLE, "Password authentication is not offered (mitigated)."
    else:
        rep.verdict, rep.summary = POTENTIAL, (
            "OpenSSH < 10.6p2 with no distro marker" + (" and password auth offered" if pw_offered else "")
            + ". A remote check cannot see libc, PAM or '*' accounts - run this tool locally on the host.")
    return rep


# --------------------------------------------------------------------------
# Output
# --------------------------------------------------------------------------

COLORS = {"affected": "\033[31m", "safe": "\033[32m", "unknown": "\033[33m", "info": "\033[36m"}
VCOLORS = {VULNERABLE: "\033[1;41;97m", POTENTIAL: "\033[1;43;30m", NOT_VULNERABLE: "\033[1;42;30m"}


def print_report(rep: Report, color: bool):
    c = (lambda k, s: f"{COLORS.get(k, '')}{s}\033[0m") if color else (lambda k, s: s)
    print(f"\n{CVE} (sshhole) scan - target: {rep.target}\n" + "-" * 72)
    for ch in rep.checks:
        tag = {"affected": "[!]", "safe": "[ok]", "unknown": "[?]", "info": "[i]"}[ch.status]
        print(f"{c(ch.status, f'{tag:5}')} {ch.name:24} {ch.detail}")
    if rep.exposed_accounts:
        print("\n'*' accounts:")
        for a in rep.exposed_accounts:
            flag = "REACHABLE" if a["ssh_reachable"] else "blocked"
            print(f"   - {a['user']:16} uid={a['uid']:6} shell={a['shell']:18} {flag}"
                  + (f"  ({'; '.join(a['notes'])})" if a["notes"] else ""))
    if rep.ioc_log_hits:
        print("\nSuspicious log entries:")
        for h in rep.ioc_log_hits[:50]:
            print("   " + h)
    v = f" {rep.verdict} " if not color else f"{VCOLORS[rep.verdict]} {rep.verdict} \033[0m"
    print("\nVerdict:", v)
    print("        ", rep.summary)
    if rep.remediation:
        print("\nRemediation:")
        for r in rep.remediation:
            print("   *", r)
    print()


def main():
    ap = argparse.ArgumentParser(description=f"Detect {CVE} (OpenSSH musl/no-PAM password auth bypass)")
    g = ap.add_mutually_exclusive_group()
    g.add_argument("--root", help="scan an offline filesystem / extracted container image")
    g.add_argument("--remote", metavar="HOST", help="non-intrusive remote check")
    ap.add_argument("--port", type=int, default=22)
    ap.add_argument("--user", default="root", help="username for the remote auth-method probe")
    ap.add_argument("--timeout", type=float, default=8.0)
    ap.add_argument("--json", action="store_true", help="JSON output")
    ap.add_argument("--no-color", action="store_true")
    a = ap.parse_args()

    try:
        rep = remote_scan(a.remote, a.port, a.user, a.timeout) if a.remote else local_scan(a.root)
    except Exception as e:  # noqa: BLE001
        print(f"error: {e}", file=sys.stderr)
        return 3

    if a.json:
        d = asdict(rep)
        print(json.dumps(d, indent=2))
    else:
        print_report(rep, color=sys.stdout.isatty() and not a.no_color and os.name != "nt" or
                     (os.name == "nt" and not a.no_color and "WT_SESSION" in os.environ))
    return {VULNERABLE: 1, POTENTIAL: 2, NOT_VULNERABLE: 0}[rep.verdict]


if __name__ == "__main__":
    sys.exit(main())