diff --git a/CHANGELOG.md b/CHANGELOG.md index 264818b..2339a6c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Added +- Personal accounts (NetOrk/netork#1793), through napalm-device-types' `LocalAccountsMixin`: + `get_local_accounts()`, `add_local_account()` and `lock_local_account()` with + shadow-utils' commands (`useradd -m -s /bin/bash`, `usermod`, `gpasswd -d`). A locked + account is an expired one (`usermod -L -e 1`): PAM refuses it a key login too, where a + `!` in front of the password stops only the password. Opening it again lifts the expiry + and gives the old password back. Checked on Debian 13 and Rocky Linux 9 with sshd and + sudo. OpenMediaVault (Debian) inherits it; QNAP QTS opts out in napalm-qnap-qts. + Requires the napalm-device-types release with `LocalAccountsMixin`. - `open()` tries the connection again after 1, 3, 7 and 15 s when sshd closes it before its banner -- what OpenSSH 9.8+ does to a source it has just penalised (`PerSourcePenalties`), e.g. after a security scanner's probes. Needs diff --git a/napalm_linux/_local_accounts.py b/napalm_linux/_local_accounts.py new file mode 100644 index 0000000..f612e9f --- /dev/null +++ b/napalm_linux/_local_accounts.py @@ -0,0 +1,64 @@ +"""Personal accounts on a Linux host, with shadow-utils (NetOrk/netork#1793). + +napalm-device-types' ``LocalAccountsMixin`` runs the steps; this names the +commands. A locked account is an expired one (``usermod -L -e 1``): PAM's +account check refuses it every login, a key's too, where a ``!`` in front of +the password -- ``usermod -L`` alone -- stops only the password. Opening it +again lifts the expiry and gives the old password back. +""" + +from __future__ import annotations + +import shlex +import time + +from napalm_device_types import LocalAccountsMixin + +#: What the password field holds when the account never had a password. +_NO_PASSWORD = frozenset({"", "!", "!!", "!*", "*"}) + + +class LinuxLocalAccountsMixin(LocalAccountsMixin): + ACCOUNT_SHELL = "/bin/bash" + #: Debian and Ubuntu grant ``%sudo``, the Red Hat family ``%wheel``, old Ubuntu ``%admin``. + ACCOUNT_ADMIN_GROUPS = ("sudo", "wheel", "admin") + SUDOERS_DIR = "/etc/sudoers.d" + ROOT_GROUP = "root" + + def _account_create(self, name: str, password_hash: str | None) -> list[list[str]]: + password = ["-p", password_hash] if password_hash else [] + return [["useradd", "-m", "-s", self.ACCOUNT_SHELL, *password, name]] + + def _account_open( + self, name: str, password_hash: str | None, *, locked: bool + ) -> list[list[str]]: + if password_hash: + return [["usermod", "-e", "", "-p", password_hash, name]] + # usermod -U refuses to leave an account without any password. + had_one = self._shadow(name)[1].lstrip("!") not in _NO_PASSWORD + return [["usermod", *(["-U"] if had_one else []), "-e", "", name]] + + def _account_lock(self, name: str, *, locked: bool) -> list[list[str]]: + return [] if locked else [["usermod", "-L", "-e", "1", name]] + + def _account_locked(self, name: str, passwd: list[str]) -> bool: + expire = self._shadow(name)[7] + # pam_unix: expired from the day sp_expire names on. + return bool(expire) and int(expire) <= int(time.time() // 86400) + + def _account_leave_group(self, name: str, group: str, groups: list[str]) -> list[str]: + return ["gpasswd", "-d", name, group] + + def _shadow(self, name: str) -> list[str]: + """*name*'s shadow entry, split; only the lock and the expiry are looked at. + + :raises RuntimeError: when it cannot be read. + """ + result = self.run_command( + shlex.join(["getent", "shadow", name]), privileged=True, timeout=30 + ) + fields = result.stdout.strip().split(":") + if result.exit_code != 0 or len(fields) < 9 or fields[0] != name: + reason = (result.stderr or result.stdout).strip() or f"exit {result.exit_code}" + raise RuntimeError(f"cannot read the shadow entry of {name}: {reason}") + return fields diff --git a/napalm_linux/_shell.py b/napalm_linux/_shell.py index a780953..19fc0bd 100644 --- a/napalm_linux/_shell.py +++ b/napalm_linux/_shell.py @@ -3,6 +3,7 @@ from __future__ import annotations import logging +import re from typing import Any logger = logging.getLogger(__name__) @@ -11,6 +12,29 @@ logger = logging.getLogger(__name__) #: like a shell prompt. PROMPT_RE = r"[#$\>]\s*$" +#: A command ending in ``echo __NAME=$?`` reports its exit status on a line of its +#: own: the driver's ``_RC_MARKER``, ``__APT_RC=`` and ``__SVC_RC=`` in +#: napalm-device-types. +STATUS_ECHO_RE = re.compile(r"echo\s+(__[A-Z_]+=)\$\?") + + +def expect_for(command: str) -> str: + """The pattern that ends *command*'s output. + + netmiko stops reading as soon as the pattern matches what it has read so far. + A line the command prints can end in ``#``, ``$`` or ``>`` -- apt's + ```` after a bad signature -- and was taken for the + prompt: half the output came back, and the rest started the next command's + (#615). A command that echoes its exit status is read until that marker, with + a number, and the prompt line after it. The echoed command line carries a + literal ``$?`` and cannot match. + """ + markers: list[str] = STATUS_ECHO_RE.findall(command) + if not markers: + return PROMPT_RE + return re.escape(markers[-1]) + r"\d+\s*\n.*" + PROMPT_RE + + #: Sent before anything else in the interactive session (NetOrk/netork#1039): #: the shell writes no history file and records nothing more. The leading space #: keeps this line itself out of a history under ``HISTCONTROL=ignorespace``; diff --git a/napalm_linux/linux.py b/napalm_linux/linux.py index 800ff01..c8438ec 100644 --- a/napalm_linux/linux.py +++ b/napalm_linux/linux.py @@ -72,8 +72,8 @@ from netmiko import ConnectHandler from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException from napalm_linux._hostname import HostnameMixin -from napalm_linux._shell import PROMPT_RE as _PROMPT_RE -from napalm_linux._shell import prepare_shell +from napalm_linux._local_accounts import LinuxLocalAccountsMixin +from napalm_linux._shell import expect_for, prepare_shell from napalm_linux._sudo_history import LinuxSudoHistoryMixin logger = logging.getLogger("napalm_linux") @@ -88,28 +88,6 @@ _RC_MARKER = "__NETORK_RC=" _RC_MARKER_RE = re.compile(rf"^{_RC_MARKER}(\d+)\s*$", re.MULTILINE) -#: A command ending in ``echo __NAME=$?`` reports its exit status on a line of its -#: own: ``_RC_MARKER`` here, ``__APT_RC=`` and ``__SVC_RC=`` in napalm-device-types. -_STATUS_ECHO_RE = re.compile(r"echo\s+(__[A-Z_]+=)\$\?") - - -def _expect_for(command: str) -> str: - """The pattern that ends *command*'s output. - - netmiko stops reading as soon as the pattern matches what it has read so far. - A line the command prints can end in ``#``, ``$`` or ``>`` -- apt's - ```` after a bad signature -- and was taken for the - prompt: half the output came back, and the rest started the next command's - (#615). A command that echoes its exit status is read until that marker, with - a number, and the prompt line after it. The echoed command line carries a - literal ``$?`` and cannot match. - """ - markers = _STATUS_ECHO_RE.findall(command) - if not markers: - return _PROMPT_RE - return re.escape(markers[-1]) + r"\d+\s*\n.*" + _PROMPT_RE - - def _split_status(raw: str) -> tuple[str, int | None]: """``(output, exit_status)`` of a command followed by ``echo {_RC_MARKER}$?``. @@ -307,6 +285,7 @@ def render_snmpd_conf(settings: SnmpAgentSettingsDict) -> str: class LinuxDriver( LinuxSudoHistoryMixin, + LinuxLocalAccountsMixin, SnmpAgentMixin, EnsurePackageMixin, AptProxyMixin, @@ -442,7 +421,7 @@ class LinuxDriver( command, read_timeout=read_timeout, cmd_verify=False, - expect_string=_expect_for(command), + expect_string=expect_for(command), ) return strip_terminal_codes(output).strip() diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index 88483be..c558b17 100644 --- a/tests/quality_baseline.json +++ b/tests/quality_baseline.json @@ -22,7 +22,7 @@ "napalm_linux.linux" ], "python_file_lines": { - "napalm_linux/linux.py": 2286 + "napalm_linux/linux.py": 2265 }, "untyped_public": [] } diff --git a/tests/test_local_accounts.py b/tests/test_local_accounts.py new file mode 100644 index 0000000..45e69aa --- /dev/null +++ b/tests/test_local_accounts.py @@ -0,0 +1,103 @@ +"""Personal accounts on a Linux host (NetOrk/netork#1793). + +napalm-device-types' ``LocalAccountsMixin`` runs the steps; the driver names +shadow-utils' commands. A locked account is an expired one (``usermod -e 1``): +PAM refuses it a key login too, where a ``!`` in front of the password alone +stops only the password. +""" + +from __future__ import annotations + +import time + +import pytest +from napalm_device_types import CommandResult, LocalAccountsMixin + +from napalm_linux import LinuxDriver + +HASH = "$6$salt$" + "x" * 86 +_TODAY = int(time.time() // 86400) + + +class _Driver(LinuxDriver): + """A Linux driver whose host answers ``getent shadow`` with *shadow*.""" + + def __init__(self, shadow: str = "alice:$6$old:20000:0:99999:7:::") -> None: + super().__init__("host", "netadmin", "pw") + self.shadow = shadow + self.ran: list[tuple[str, bool]] = [] + + def run_command(self, command, *, privileged=False, timeout=60, stdin=None): + self.ran.append((command, privileged)) + if command == "getent shadow alice": + return CommandResult(self.shadow + "\n", "", 0 if self.shadow else 2) + return CommandResult("", "", 0) + + +def _passwd() -> list[str]: + return "alice:x:1001:1001::/home/alice:/bin/bash".split(":") + + +def test_a_linux_host_can_add_and_lock_personal_accounts() -> None: + assert issubclass(LinuxDriver, LocalAccountsMixin) + assert LinuxDriver.ACCOUNT_PASSWORD_SCHEME == "sha512" + assert LinuxDriver.ACCOUNT_SHELL == "/bin/bash" + # Debian and Ubuntu grant %sudo, the Red Hat family %wheel, old Ubuntu %admin. + assert set(LinuxDriver.ACCOUNT_ADMIN_GROUPS) == {"sudo", "wheel", "admin"} + + +def test_a_new_account_gets_a_home_and_bash() -> None: + d = _Driver() + assert d._account_create("alice", HASH) == [ + ["useradd", "-m", "-s", "/bin/bash", "-p", HASH, "alice"] + ] + assert d._account_create("alice", None) == [["useradd", "-m", "-s", "/bin/bash", "alice"]] + + +def test_locking_expires_the_account_and_locks_its_password() -> None: + d = _Driver() + assert d._account_lock("alice", locked=False) == [["usermod", "-L", "-e", "1", "alice"]] + assert d._account_lock("alice", locked=True) == [] + + +def test_opening_lifts_the_expiry_and_sets_the_new_password() -> None: + d = _Driver() + assert d._account_open("alice", HASH, locked=True) == [ + ["usermod", "-e", "", "-p", HASH, "alice"] + ] + + +def test_opening_without_a_new_password_gives_back_the_old_one() -> None: + d = _Driver(shadow="alice:!$6$old:20000:0:99999:7::1:") + assert d._account_open("alice", None, locked=True) == [["usermod", "-U", "-e", "", "alice"]] + + +def test_an_account_that_never_had_a_password_keeps_it_locked() -> None: + # usermod -U refuses to leave an account without a password. + for field in ("!", "!!", "!*", "*"): + d = _Driver(shadow=f"alice:{field}:20000:0:99999:7::1:") + assert d._account_open("alice", None, locked=True) == [["usermod", "-e", "", "alice"]] + + +@pytest.mark.parametrize( + ("expire", "locked"), + [("", False), ("1", True), (str(_TODAY), True), (str(_TODAY + 30), False)], +) +def test_an_expired_account_is_locked(expire: str, locked: bool) -> None: + d = _Driver(shadow=f"alice:$6$old:20000:0:99999:7::{expire}:") + assert d._account_locked("alice", _passwd()) is locked + assert d.ran == [("getent shadow alice", True)] + + +def test_a_shadow_that_cannot_be_read_raises() -> None: + with pytest.raises(RuntimeError, match="alice"): + _Driver(shadow="")._account_locked("alice", _passwd()) + + +def test_leaving_a_group_is_gpasswd() -> None: + assert _Driver()._account_leave_group("alice", "sudo", ["alice", "sudo"]) == [ + "gpasswd", + "-d", + "alice", + "sudo", + ]