feat(ssh-server): read how sshd lets people log in
driver / lint (pull_request) Successful in 15s
driver / standard (pull_request) Successful in 17s
driver / types (pull_request) Successful in 1m10s
driver / test (3.13) (pull_request) Successful in 1m25s
driver / test (3.12) (pull_request) Successful in 1m32s
driver / lowest (pull_request) Successful in 44s
driver / build (pull_request) Successful in 32s
driver / security (pull_request) Successful in 1m5s
CI / driver (pull_request) Successful in 2m48s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Successful in 15s
driver / standard (pull_request) Successful in 17s
driver / types (pull_request) Successful in 1m10s
driver / test (3.13) (pull_request) Successful in 1m25s
driver / test (3.12) (pull_request) Successful in 1m32s
driver / lowest (pull_request) Successful in 44s
driver / build (pull_request) Successful in 32s
driver / security (pull_request) Successful in 1m5s
CI / driver (pull_request) Successful in 2m48s
driver / publish (pull_request) Skipped
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
This commit is contained in:
1 parent
c1a05d6dba
commit
1d71ff8f91
6 files changed
+675
-2
No files matched your search
@@ -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)
|
||||
Reference in new issue
Block a user