From 1d71ff8f915afc7dea2048af36fb0db0f6903834 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Sat, 7 Nov 2026 15:05:50 +0100 Subject: [PATCH 1/2] feat(ssh-server): read how sshd lets people log in SshServerAuthMixin.get_ssh_server_auth() reads the authentication settings from sshd -T as root (password, keyboard-interactive, public key, host-based, GSSAPI, AuthenticationMethods, PermitRootLogin, UsePAM) and, with PAM on, the modules of sshd's PAM auth stack from /etc/pam.d with its includes followed. It reports the facts; whether a module is a second factor is the consumer's call. OpenSshServerMixin carries it and both read sshd -T by the same fixed command, so every driver that can harden sshd can say this too. Refs NetOrk/netork#662 --- CHANGELOG.md | 9 + README.md | 10 + napalm_device_types/__init__.py | 15 ++ napalm_device_types/ssh_server.py | 9 +- napalm_device_types/ssh_server_auth.py | 281 ++++++++++++++++++++ tests/test_ssh_server_auth.py | 353 +++++++++++++++++++++++++ 6 files changed, 675 insertions(+), 2 deletions(-) create mode 100644 napalm_device_types/ssh_server_auth.py create mode 100644 tests/test_ssh_server_auth.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ca67b0e..aaf2ede 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ recorded here; their history is the git log. ## [Unreleased] +### Added +- `SshServerAuthMixin.get_ssh_server_auth()`: how an OpenSSH server lets people log in -- + password, keyboard-interactive, public key, host-based and GSSAPI authentication, + `AuthenticationMethods` as lists of methods, `PermitRootLogin` and `UsePAM`, from `sshd -T` + as root, and sshd's PAM `auth` stack (each module with its control and arguments, includes + followed), from `/etc/pam.d` as the login user. `OpenSshServerMixin` carries it, so every + driver that can harden sshd has it. `parse_sshd_auth`, `parse_pam_auth`, `parse_pam_files`, + `pam_auth_stack` and `SSHD_EFFECTIVE_COMMAND` are public (NetOrk/netork#662). + ## [4.31.1] - 2026-11-06 ### Fixed diff --git a/README.md b/README.md index 09a1bee..2289e26 100644 --- a/README.md +++ b/README.md @@ -295,6 +295,16 @@ A driver mixes it in and supplies `run_command`; a platform that regenerates ssh itself (an appliance with its own database) must not, or opts out with `harden_ssh_server = None`. +`SshServerAuthMixin` (`get_ssh_server_auth`) says how an OpenSSH server lets people log in: +password, keyboard-interactive, public key, host-based and GSSAPI authentication on or off, +`AuthenticationMethods` as lists of methods (empty for `any`), `PermitRootLogin` and +`UsePAM` (None where sshd has no PAM), from `sshd -T` as root -- the same fixed command the +hardening reads. With PAM on, it also names the modules of sshd's PAM `auth` stack +with each control and its arguments, read from `/etc/pam.d` in one listing as the +login user and followed through `@include`, `include` and `substack`. Which of them is a +second factor is the consumer's call. `Match` blocks are not read. `OpenSshServerMixin` +carries it; a driver can also mix it in alone and supply `run_command`. + `SudoHistoryMixin` (`get_history_sudo_lines`, `remove_history_sudo_lines`) deals with what a driver left behind when it typed `echo '' | sudo -S -p "" …` into an interactive shell: that line, password and all, in the login user's shell history, and files its partial diff --git a/napalm_device_types/__init__.py b/napalm_device_types/__init__.py index d7fe728..54c27b5 100644 --- a/napalm_device_types/__init__.py +++ b/napalm_device_types/__init__.py @@ -58,6 +58,7 @@ instead of being restated on every role that happens to need it: * :class:`~napalm_device_types.ping_sweep.PingSweepMixin` * :class:`~napalm_device_types.service_clusters.ServiceClustersMixin` * :class:`~napalm_device_types.service_packages.ServicePackagesMixin` +* :class:`~napalm_device_types.ssh_server_auth.SshServerAuthMixin` * :class:`~napalm_device_types.sudo_history.SudoHistoryMixin` * :class:`~napalm_device_types.scheduled_jobs.ScheduledJobsMixin` * :class:`~napalm_device_types.scheduled_jobs_posix.PosixScheduledJobsMixin` @@ -271,6 +272,14 @@ from napalm_device_types.ssh_server import ( SshHardeningResult, plan_ssh_hardening, ) +from napalm_device_types.ssh_server_auth import ( + SSHD_EFFECTIVE_COMMAND, + PamAuthEntryDict, + SshServerAuthDict, + SshServerAuthMixin, + pam_auth_stack, + parse_sshd_auth, +) from napalm_device_types.storage import StorageDriver from napalm_device_types.sudo_history import ( HistoryCleanupDict, @@ -469,6 +478,12 @@ __all__ = [ "is_placeholder_identity", "parse_system_identity", "OpenSshServerMixin", + "PamAuthEntryDict", + "SshServerAuthDict", + "SshServerAuthMixin", + "SSHD_EFFECTIVE_COMMAND", + "pam_auth_stack", + "parse_sshd_auth", "SSH_ALGORITHM_CLASSES", "SshHardeningPlan", "SshHardeningResult", diff --git a/napalm_device_types/ssh_server.py b/napalm_device_types/ssh_server.py index a7e10b4..db2586c 100644 --- a/napalm_device_types/ssh_server.py +++ b/napalm_device_types/ssh_server.py @@ -53,6 +53,8 @@ from typing import ( TYPE_CHECKING, ) +from napalm_device_types.ssh_server_auth import SSHD_EFFECTIVE_COMMAND, SshServerAuthMixin + if TYPE_CHECKING: # pragma: no cover - for type checkers only from napalm_device_types.channel import CommandResult @@ -420,7 +422,7 @@ def _unchanged( return result -class OpenSshServerMixin: +class OpenSshServerMixin(SshServerAuthMixin): """Adds :meth:`harden_ssh_server` to a driver that can run commands as root on an OpenSSH host. Mixed in by the drivers whose host runs a stock OpenSSH, not by a base class, @@ -430,6 +432,9 @@ class OpenSshServerMixin: ``harden_ssh_server = None``: its file would be overwritten on the next apply. Where that generated file still includes the drop-in directory, the driver sets :attr:`SSHD_CONFIG_GENERATED` instead and keeps the hardening. + + It carries :class:`~napalm_device_types.ssh_server_auth.SshServerAuthMixin`: + a host whose sshd can be hardened can also say how it lets people log in. """ #: True where the platform writes sshd_config from its own database @@ -513,7 +518,7 @@ class OpenSshServerMixin: return parse_sshd_effective(self._sshd_effective_text()) def _sshd_effective_text(self) -> str: - result = self._ssh_run("PATH=$PATH:/usr/sbin:/sbin sshd -T") + result = self._ssh_run(SSHD_EFFECTIVE_COMMAND) if result.exit_code != 0: raise RuntimeError(f"sshd -T failed: {(result.stderr or result.stdout).strip()}") return result.stdout diff --git a/napalm_device_types/ssh_server_auth.py b/napalm_device_types/ssh_server_auth.py new file mode 100644 index 0000000..302b469 --- /dev/null +++ b/napalm_device_types/ssh_server_auth.py @@ -0,0 +1,281 @@ +"""How an OpenSSH server lets people log in: the effective settings and sshd's PAM stack. + +Whether a host takes a password, only a key, or a key *and* a second factor is +the same question on every host that runs OpenSSH, so the reading lives here, +and a driver only mixes in :class:`SshServerAuthMixin` and supplies +``run_command``. + +**What sshd uses, not what a file says.** ``sshd -T`` prints the settings after +sshd's defaults, ``sshd_config``, every ``Include`` and first-match-wins -- the +same reading :class:`~napalm_device_types.ssh_server.OpenSshServerMixin` plans +its hardening on, by the same fixed command (:data:`SSHD_EFFECTIVE_COMMAND`). It +needs root: without it sshd cannot load its host keys and exits. + +**PAM, as far as it can be read.** With ``UsePAM yes``, keyboard-interactive +asks whatever PAM's ``auth`` stack for sshd asks: a password from +``pam_unix.so``, a one-time code from an OTP module, or both. The stack is read +from ``/etc/pam.d`` in one listing as the login user (the files are +world-readable), and followed through ``@include``, ``include`` and +``substack``. Each module is reported with its control and arguments as +written; which of them is a second factor, and whether ``nullok`` lets a user +without one through, is the consumer's call. + +Not read: ``Match`` blocks (``sshd -T`` without ``-C`` prints the global +settings), and what a PAM module's own configuration asks for. +""" + +from __future__ import annotations + +import re +from collections.abc import Mapping +from typing import TYPE_CHECKING, TypedDict + +if TYPE_CHECKING: # pragma: no cover - for type checkers only + from napalm_device_types.channel import CommandResult + +#: sshd's effective configuration. ``sshd`` lives in ``/usr/sbin``, outside a login +#: user's ``PATH``. One fixed command, run as root. +SSHD_EFFECTIVE_COMMAND = "PATH=$PATH:/usr/sbin:/sbin sshd -T" + +PAM_DIR = "/etc/pam.d" +#: Every file in ``/etc/pam.d``, each after a ``==> path <==`` header (GNU, BSD and +#: busybox ``tail`` alike). One fixed command, as the login user. +PAM_FILES_COMMAND = f"tail -n +1 -- {PAM_DIR}/*" +#: The PAM service sshd runs as. +PAM_SERVICE = "sshd" + +_TIMEOUT = 30 +_HEADER_RE = re.compile(rf"^==> {re.escape(PAM_DIR)}/(?P[^/]+) <==$") +#: A service name an include may name: a file in ``/etc/pam.d``, never a path out of it. +_SERVICE_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$") +_INCLUDE_CONTROLS = ("include", "substack") + + +class PamAuthEntryDict(TypedDict): + """One line of a PAM ``auth`` stack: ``auth required pam_unix.so nullok``.""" + + #: The module's file name, without its directory: ``pam_unix.so``. + module: str + #: ``required``, ``requisite``, ``sufficient``, ``optional``, or a bracketed + #: ``[value=action ...]`` as written. + control: str + args: list[str] + + +class SshServerAuthDict(TypedDict): + """How an OpenSSH server lets people log in, as ``get_ssh_server_auth`` read it. + + The global settings ``sshd -T`` prints. A ``Match`` block can change them for + some users or addresses; ``sshd -T`` without ``-C`` does not show that. + + ``authentication_methods`` is ``AuthenticationMethods``: each inner list is one + way in, every method of it required in turn (``publickey,keyboard-interactive`` + -> ``["publickey", "keyboard-interactive"]``); empty for ``any``, where any one + enabled method is enough. A method keeps its submethod + (``keyboard-interactive:pam``). + + ``use_pam`` is None where sshd has no PAM (OpenBSD). ``pam_auth_stack`` is the + ``auth`` stack PAM runs for sshd, includes and substacks followed; None when + PAM is off or its files gave nothing for sshd. + """ + + password_authentication: bool + #: ``KbdInteractiveAuthentication``; before OpenSSH 8.7, either it or + #: ``ChallengeResponseAuthentication``. + kbd_interactive_authentication: bool + pubkey_authentication: bool + hostbased_authentication: bool + #: False also where sshd was built without GSSAPI. + gssapi_authentication: bool + authentication_methods: list[list[str]] + #: ``yes``, ``prohibit-password`` (``without-password``), ``forced-commands-only`` or ``no``. + permit_root_login: str + use_pam: bool | None + pam_auth_stack: list[PamAuthEntryDict] | None + + +def _flag(settings: Mapping[str, str], keyword: str) -> bool: + return settings.get(keyword, "no") == "yes" + + +def _settings(text: str) -> dict[str, str]: + """``keyword value`` per line, the first one of each keyword.""" + found: dict[str, str] = {} + for raw in text.splitlines(): + parts = raw.strip().split(None, 1) + if len(parts) == 2: + found.setdefault(parts[0].lower(), parts[1].strip()) + return found + + +def _methods(value: str) -> list[list[str]]: + if value == "any": + return [] + return [[m for m in alternative.split(",") if m] for alternative in value.split()] + + +def parse_sshd_auth(text: str) -> SshServerAuthDict: + """The authentication settings from ``sshd -T`` output; ``pam_auth_stack`` left None. + + :raises ValueError: if a setting every OpenSSH prints is missing -- not sshd -T + output, or cut short. + """ + settings = _settings(text) + missing = [ + k + for k in ("passwordauthentication", "pubkeyauthentication", "permitrootlogin") + if k not in settings + ] + if missing: + raise ValueError(f"sshd -T printed no {', '.join(missing)}") + use_pam = settings.get("usepam") + return { + "password_authentication": _flag(settings, "passwordauthentication"), + "kbd_interactive_authentication": _flag(settings, "kbdinteractiveauthentication") + or _flag(settings, "challengeresponseauthentication"), + "pubkey_authentication": _flag(settings, "pubkeyauthentication"), + "hostbased_authentication": _flag(settings, "hostbasedauthentication"), + "gssapi_authentication": _flag(settings, "gssapiauthentication"), + "authentication_methods": _methods(settings.get("authenticationmethods", "any")), + "permit_root_login": settings["permitrootlogin"], + "use_pam": None if use_pam is None else use_pam == "yes", + "pam_auth_stack": None, + } + + +def _pam_tokens(line: str) -> list[str]: + """A PAM line's tokens, a bracketed control (``[success=1 default=ignore]``) as one.""" + tokens: list[str] = [] + for part in line.split(): + if tokens and tokens[-1].startswith("[") and not tokens[-1].endswith("]"): + tokens[-1] += " " + part + else: + tokens.append(part) + return tokens + + +def _pam_entry(line: str) -> PamAuthEntryDict | None: + tokens = _pam_tokens(line.split("#", 1)[0]) + if len(tokens) >= 2 and tokens[0] == "@include": + tokens = ["auth", "include", tokens[1]] + if len(tokens) < 3 or tokens[0].lstrip("-") != "auth": + return None + control, target, args = tokens[1], tokens[2], tokens[3:] + if control in _INCLUDE_CONTROLS: + if not _SERVICE_RE.match(target): + return None + return {"module": target, "control": control, "args": []} + return {"module": target.rsplit("/", 1)[-1], "control": control, "args": args} + + +def parse_pam_auth(text: str) -> list[PamAuthEntryDict]: + """One PAM file's ``auth`` stack, in order. + + A module by its file name (``pam_unix.so``), with its control and arguments. + An include is an entry whose control is ``include`` or ``substack`` and whose + module is the service it names: ``@include common-auth`` brings in a whole + file, ``auth include`` and ``auth substack`` its ``auth`` lines; both are + followed by :func:`pam_auth_stack`. An include that names a path rather than + a service is left out. + """ + return [entry for line in text.splitlines() if (entry := _pam_entry(line.strip()))] + + +def parse_pam_files(text: str) -> dict[str, str]: + """:data:`PAM_FILES_COMMAND`'s output, by file name.""" + files: dict[str, list[str]] = {} + current: list[str] | None = None + for line in text.splitlines(): + header = _HEADER_RE.match(line.strip()) + if header: + current = files.setdefault(header["name"], []) + elif current is not None: + current.append(line) + return {name: "\n".join(lines).strip("\n") + "\n" for name, lines in files.items()} + + +def pam_auth_stack( + files: Mapping[str, str], service: str = PAM_SERVICE +) -> list[PamAuthEntryDict] | None: + """*service*'s ``auth`` modules, includes and substacks followed, in stack order. + + A file included twice -- or in a loop -- counts once; an include of a file + that is not there adds nothing, as with PAM. None without a file for *service*. + """ + if service not in files: + return None + stack: list[PamAuthEntryDict] = [] + seen: set[str] = set() + + def walk(name: str) -> None: + if name in seen or name not in files: + return + seen.add(name) + for entry in parse_pam_auth(files[name]): + if entry["control"] in _INCLUDE_CONTROLS: + walk(entry["module"]) + else: + stack.append(entry) + + walk(service) + return stack + + +class SshServerAuthMixin: + """Adds :meth:`get_ssh_server_auth` to a driver that can run commands on an OpenSSH host. + + Mixed in by the drivers whose host runs a stock OpenSSH -- + :class:`~napalm_device_types.ssh_server.OpenSshServerMixin` carries it -- so + ``hasattr(driver, "get_ssh_server_auth")`` stays a truthful answer. Reading, + not writing: a platform that generates sshd_config itself can carry it too. + """ + + if TYPE_CHECKING: # pragma: no cover - declared for type checkers only + + def run_command( + self, + command: str, + *, + privileged: bool = False, + timeout: float = 60, + stdin: bytes | None = None, + ) -> CommandResult: ... + + def get_ssh_server_auth(self) -> SshServerAuthDict: + """ + Returns how sshd lets people log in, from ``sshd -T`` and PAM's sshd stack. + + Example:: + + { + "password_authentication": False, + "kbd_interactive_authentication": True, + "pubkey_authentication": True, + "hostbased_authentication": False, + "gssapi_authentication": False, + "authentication_methods": [["publickey", "keyboard-interactive"]], + "permit_root_login": "no", + "use_pam": True, + "pam_auth_stack": [ + {"module": "pam_google_authenticator.so", "control": "required", "args": []} + ], + } + + :raises RuntimeError: if ``sshd -T`` fails -- no OpenSSH, or no root. + """ + result = self.run_command(SSHD_EFFECTIVE_COMMAND, privileged=True, timeout=_TIMEOUT) + if result.exit_code != 0: + raise RuntimeError(f"sshd -T failed: {(result.stderr or result.stdout).strip()}") + auth = parse_sshd_auth(result.stdout) + if auth["use_pam"]: + auth["pam_auth_stack"] = self._pam_auth_stack() + return auth + + def _pam_auth_stack(self) -> list[PamAuthEntryDict] | None: + """sshd's PAM auth stack; None when ``/etc/pam.d`` gave nothing for sshd. + + ``tail`` goes on past a file it cannot open and exits 1, so what it did + print is used whatever the exit status. + """ + result = self.run_command(PAM_FILES_COMMAND, privileged=False, timeout=_TIMEOUT) + return pam_auth_stack(parse_pam_files(result.stdout)) diff --git a/tests/test_ssh_server_auth.py b/tests/test_ssh_server_auth.py new file mode 100644 index 0000000..d11fd7a --- /dev/null +++ b/tests/test_ssh_server_auth.py @@ -0,0 +1,353 @@ +"""How an OpenSSH server lets people in: the effective settings and sshd's PAM auth stack. + +The parsers are pure. The getter runs against a fake host that answers ``sshd -T`` +and the dump of ``/etc/pam.d`` from a dict, so the root read, the PAM includes +and a failed read are covered without a machine. + +The ``sshd -T`` texts are abridged from what OpenSSH 9.2p1 on Debian 12 prints +(the keywords and their order as sshd writes them; the lines that say nothing +about authentication are left out). OpenSSH before 8.7 also prints +``challengeresponseauthentication``; OpenBSD's sshd has no ``usepam``. +""" + +from __future__ import annotations + +import pytest + +from napalm_device_types.channel import CommandResult +from napalm_device_types.ssh_server import OpenSshServerMixin +from napalm_device_types.ssh_server_auth import ( + PAM_FILES_COMMAND, + SSHD_EFFECTIVE_COMMAND, + SshServerAuthMixin, + pam_auth_stack, + parse_pam_auth, + parse_pam_files, + parse_sshd_auth, +) + +#: Debian 12 as installed: password login on, PAM on, no AuthenticationMethods. +SSHD_T_DEBIAN = """\ +port 22 +addressfamily any +listenaddress [::]:22 +listenaddress 0.0.0.0:22 +usepam yes +logingracetime 120 +x11displayoffset 10 +maxauthtries 6 +maxsessions 10 +clientaliveinterval 0 +clientalivecountmax 3 +permitrootlogin without-password +ignorerhosts yes +ignoreuserknownhosts no +hostbasedauthentication no +hostbasedusesnamefrompacketonly no +pubkeyauthentication yes +kerberosauthentication no +kerberosorlocalpasswd yes +kerberosticketcleanup yes +gssapiauthentication no +gssapicleanupcredentials yes +gssapikeyexchange no +gssapistrictacceptorcheck yes +gssapistorecredentialsonrotate no +passwordauthentication yes +kbdinteractiveauthentication no +printmotd no +x11forwarding yes +authenticationmethods any +kexalgorithms sntrup761x25519-sha512@openssh.com,curve25519-sha256 +""" + +#: Key only: password and keyboard-interactive off. +SSHD_T_KEY_ONLY = SSHD_T_DEBIAN.replace( + "passwordauthentication yes", "passwordauthentication no" +).replace("permitrootlogin without-password", "permitrootlogin no") + +#: A key and then an OTP through PAM, for everyone. +SSHD_T_KEY_AND_OTP = SSHD_T_KEY_ONLY.replace( + "kbdinteractiveauthentication no", "kbdinteractiveauthentication yes" +).replace("authenticationmethods any", "authenticationmethods publickey,keyboard-interactive") + +#: OpenSSH 8.4p1 (Debian 11): the old keyword beside the new one. +SSHD_T_OLD = SSHD_T_KEY_ONLY.replace( + "kbdinteractiveauthentication no", + "kbdinteractiveauthentication yes\nchallengeresponseauthentication no", +) + +#: OpenBSD 7.6: no usepam line. +SSHD_T_OPENBSD = SSHD_T_KEY_ONLY.replace("usepam yes\n", "") + +#: Debian 12's /etc/pam.d/sshd, abridged: the auth stack comes from common-auth. +PAM_SSHD_DEBIAN = """\ +# PAM configuration for the Secure Shell service + +# Standard Un*x authentication. +@include common-auth + +# Disallow non-root logins when /etc/nologin exists. +account required pam_nologin.so + +# Standard Un*x authorization. +@include common-account +session [success=ok ignore=ignore module_unknown=ignore default=bad] pam_selinux.so close +@include common-session +@include common-password +""" + +PAM_COMMON_AUTH = """\ +auth\t[success=1 default=ignore]\tpam_unix.so nullok +auth\trequisite\t\t\tpam_deny.so +auth\trequired\t\t\tpam_permit.so +""" + +PAM_COMMON_ACCOUNT = "account [success=1 new_authtok_reqd=done default=ignore] pam_unix.so\n" + +#: The usual way to add a TOTP: a line of its own in sshd's stack. +PAM_SSHD_OTP = PAM_SSHD_DEBIAN.replace( + "@include common-auth", + "#@include common-auth\nauth required pam_google_authenticator.so nullok", +) + +#: Red Hat's form: ``auth substack password-auth``, a module by its full path. +PAM_SSHD_RHEL = """\ +#%PAM-1.0 +auth substack password-auth +auth include postlogin +-auth optional /usr/lib64/security/pam_reauthorize.so prepare +account required pam_sepermit.so +""" +PAM_PASSWORD_AUTH = "auth required pam_env.so\nauth sufficient pam_unix.so try_first_pass nullok\n" +PAM_POSTLOGIN = "session optional pam_umask.so silent\n" + + +# ── parse_sshd_auth ────────────────────────────────────────────────────── + + +def test_parse_reads_the_settings_that_decide_how_people_log_in(): + auth = parse_sshd_auth(SSHD_T_DEBIAN) + assert auth == { + "password_authentication": True, + "kbd_interactive_authentication": False, + "pubkey_authentication": True, + "hostbased_authentication": False, + "gssapi_authentication": False, + "authentication_methods": [], + "permit_root_login": "without-password", + "use_pam": True, + "pam_auth_stack": None, + } + + +def test_parse_splits_authentication_methods_into_lists_of_methods(): + auth = parse_sshd_auth( + SSHD_T_KEY_ONLY.replace( + "authenticationmethods any", + "authenticationmethods publickey,keyboard-interactive:pam publickey,password", + ) + ) + assert auth["authentication_methods"] == [ + ["publickey", "keyboard-interactive:pam"], + ["publickey", "password"], + ] + + +def test_parse_counts_the_old_challenge_response_keyword_as_keyboard_interactive(): + """Before 8.7 either keyword could switch PAM's prompts on: either one is enough.""" + assert parse_sshd_auth(SSHD_T_OLD)["kbd_interactive_authentication"] is True + old_only = SSHD_T_KEY_ONLY.replace( + "kbdinteractiveauthentication no", + "kbdinteractiveauthentication no\nchallengeresponseauthentication yes", + ) + assert parse_sshd_auth(old_only)["kbd_interactive_authentication"] is True + + +def test_parse_says_none_for_usepam_where_sshd_has_no_pam(): + assert parse_sshd_auth(SSHD_T_OPENBSD)["use_pam"] is None + + +def test_parse_takes_a_method_sshd_was_built_without_as_off(): + """sshd built without GSSAPI prints no gssapiauthentication line: that method cannot be used.""" + text = SSHD_T_DEBIAN.replace("gssapiauthentication no\n", "") + assert parse_sshd_auth(text)["gssapi_authentication"] is False + + +def test_parse_refuses_output_that_is_not_sshd_t(): + with pytest.raises(ValueError, match="passwordauthentication"): + parse_sshd_auth("sshd: no hostkeys available -- exiting.\n") + + +# ── PAM ────────────────────────────────────────────────────────────────── + + +def _pairs(entries) -> list[tuple[str, str]]: + return [(e["control"], e["module"]) for e in entries] + + +def _modules(stack) -> list[str]: + return [e["module"] for e in stack] + + +def test_pam_auth_lists_modules_and_includes_in_stack_order(): + # Every @include: which of them hold auth lines is for the included file to say. + assert _pairs(parse_pam_auth(PAM_SSHD_DEBIAN)) == [ + ("include", "common-auth"), + ("include", "common-account"), + ("include", "common-session"), + ("include", "common-password"), + ] + + +def test_pam_auth_reads_bracketed_controls_paths_and_optional_lines(): + assert _pairs(parse_pam_auth(PAM_SSHD_RHEL)) == [ + ("substack", "password-auth"), + ("include", "postlogin"), + ("optional", "pam_reauthorize.so"), + ] + assert parse_pam_auth(PAM_COMMON_AUTH) == [ + {"module": "pam_unix.so", "control": "[success=1 default=ignore]", "args": ["nullok"]}, + {"module": "pam_deny.so", "control": "requisite", "args": []}, + {"module": "pam_permit.so", "control": "required", "args": []}, + ] + + +def test_pam_auth_keeps_a_modules_arguments(): + """``nullok`` lets a user without an OTP secret through: the consumer has to see it.""" + assert parse_pam_auth(PAM_SSHD_OTP)[0] == { + "module": "pam_google_authenticator.so", + "control": "required", + "args": ["nullok"], + } + + +def test_pam_auth_skips_comments_and_other_types(): + assert _pairs(parse_pam_auth(PAM_SSHD_OTP)) == [ + ("required", "pam_google_authenticator.so"), + ("include", "common-account"), + ("include", "common-session"), + ("include", "common-password"), + ] + + +def test_pam_auth_ignores_an_include_that_is_not_a_service_name(): + assert parse_pam_auth("auth include ../../etc/shadow\n@include\nauth required\n") == [] + + +def _dump(files: dict[str, str]) -> str: + """What ``tail -n +1`` prints for several files: a header before each.""" + return "\n".join(f"==> /etc/pam.d/{name} <==\n{text}" for name, text in files.items()) + + +def test_pam_files_splits_the_dump_by_file(): + files = {"sshd": PAM_SSHD_DEBIAN, "common-auth": PAM_COMMON_AUTH} + assert parse_pam_files(_dump(files)) == files + + +def test_auth_stack_follows_includes_and_substacks_in_stack_order(): + files = { + "sshd": PAM_SSHD_RHEL + "auth include password-auth\n", + "password-auth": PAM_PASSWORD_AUTH, + "postlogin": PAM_POSTLOGIN, + } + assert _modules(pam_auth_stack(files)) == ["pam_env.so", "pam_unix.so", "pam_reauthorize.so"] + + +def test_auth_stack_stops_at_an_include_loop_and_skips_a_missing_file(): + files = { + "sshd": "@include a\n@include gone\n", + "a": "@include sshd\nauth required pam_unix.so\n", + } + assert _modules(pam_auth_stack(files)) == ["pam_unix.so"] + + +def test_auth_stack_is_none_without_a_file_for_the_service(): + assert pam_auth_stack({"login": PAM_COMMON_AUTH}) is None + + +# ── the getter ─────────────────────────────────────────────────────────── + + +class _Host(SshServerAuthMixin): + """Answers ``sshd -T`` (root only) and the dump of /etc/pam.d.""" + + def __init__(self, sshd_t: str | None, pam: dict[str, str] | None = None) -> None: + self.sshd_t = sshd_t + self.pam = pam + self.calls: list[tuple[str, bool]] = [] + + def run_command( + self, + command: str, + *, + privileged: bool = False, + timeout: float = 60, + stdin: bytes | None = None, + ) -> CommandResult: + self.calls.append((command, privileged)) + if command == SSHD_EFFECTIVE_COMMAND: + if self.sshd_t is None or not privileged: + return CommandResult("", "sshd: no hostkeys available -- exiting.", 1) + return CommandResult(self.sshd_t, "", 0) + assert command == PAM_FILES_COMMAND, command + if self.pam is None: + return CommandResult("", "tail: cannot open '/etc/pam.d/*' for reading", 1) + return CommandResult(_dump(self.pam), "", 0) + + +def test_getter_reads_sshd_t_as_root_and_pam_without(): + host = _Host( + SSHD_T_DEBIAN, + { + "sshd": PAM_SSHD_DEBIAN, + "common-auth": PAM_COMMON_AUTH, + "common-account": PAM_COMMON_ACCOUNT, + }, + ) + auth = host.get_ssh_server_auth() + assert auth["password_authentication"] is True + assert _modules(auth["pam_auth_stack"]) == ["pam_unix.so", "pam_deny.so", "pam_permit.so"] + # sshd -T once, as root; PAM's files once, as the login user. + assert host.calls == [(SSHD_EFFECTIVE_COMMAND, True), (PAM_FILES_COMMAND, False)] + + +def test_getter_names_an_otp_module_in_sshds_own_stack(): + host = _Host(SSHD_T_KEY_AND_OTP, {"sshd": PAM_SSHD_OTP}) + stack = host.get_ssh_server_auth()["pam_auth_stack"] + assert _modules(stack) == ["pam_google_authenticator.so"] + + +def test_getter_keeps_what_it_read_when_one_pam_file_is_unreadable(): + """tail goes on past a file it cannot open and exits 1: the rest is still read.""" + + class _Partial(_Host): + def run_command(self, command: str, **kwargs) -> CommandResult: # type: ignore[override] + result = super().run_command(command, **kwargs) + if command == PAM_FILES_COMMAND: + return CommandResult(result.stdout, "tail: cannot open 'x'", 1) + return result + + host = _Partial(SSHD_T_DEBIAN, {"sshd": "auth required pam_unix.so\n"}) + assert _modules(host.get_ssh_server_auth()["pam_auth_stack"]) == ["pam_unix.so"] + + +def test_getter_leaves_pam_unread_without_usepam(): + host = _Host(SSHD_T_OPENBSD) + auth = host.get_ssh_server_auth() + assert auth["pam_auth_stack"] is None + assert host.calls == [(SSHD_EFFECTIVE_COMMAND, True)] + + +def test_getter_says_none_when_pam_cannot_be_read(): + assert _Host(SSHD_T_DEBIAN).get_ssh_server_auth()["pam_auth_stack"] is None + + +def test_getter_raises_when_sshd_t_fails(): + with pytest.raises(RuntimeError, match="no hostkeys"): + _Host(None).get_ssh_server_auth() + + +def test_the_hardening_mixin_carries_the_reader(): + """Every driver that can harden sshd can also say how it lets people in.""" + assert issubclass(OpenSshServerMixin, SshServerAuthMixin) From 58c7616401c7ea05a4c93caf02e378f871a79e9f Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Sat, 7 Nov 2026 19:44:49 +0100 Subject: [PATCH 2/2] chore(release): 4.32.0 --- CHANGELOG.md | 2 ++ pyproject.toml | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aaf2ede..e4a2f33 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ recorded here; their history is the git log. ## [Unreleased] +## [4.32.0] - 2026-11-07 + ### Added - `SshServerAuthMixin.get_ssh_server_auth()`: how an OpenSSH server lets people log in -- password, keyboard-interactive, public key, host-based and GSSAPI authentication, diff --git a/pyproject.toml b/pyproject.toml index 7421863..692e982 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "napalm-device-types" -version = "4.31.1" +version = "4.32.0" description = "Abstract device-type base classes for NAPALM drivers" readme = "README.md" requires-python = ">=3.12"