"""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 shlex 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", ] def test_netorks_own_account_is_made_with_its_uid() -> None: """A fixed uid on every host, below UID_MIN (NetOrk/netork#1817).""" assert _Driver()._account_create_with_uid("netork", 900) == [ ["useradd", "-m", "-u", "900", "-s", "/bin/bash", "netork"] ] # -- what a person changes follows them (NetOrk/netork#2013) ---------------------------- ALICE_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAlice alice@laptop" OLD_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOld alice@lost-laptop" OWN_KEY = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQOwn own@desktop" _KEYS = "/home/alice/.ssh/authorized_keys" class _Host(LinuxDriver): """A Linux host with Alice's account, her key files and what ran as whom.""" def __init__(self, shadow: str, keys: str) -> None: super().__init__("host", "netadmin", "pw") self.shadow = shadow self.files = {_KEYS: keys} self.ran: list[tuple[str, bool]] = [] def run_command(self, command, *, privileged=False, timeout=60, stdin=None): self.ran.append((command, privileged)) if stdin is not None: self.files["/tmp/staged"] = stdin.decode() return CommandResult("/tmp/staged", "", 0) argv = shlex.split(command) answers = { "id -un": "netadmin\n", "getent passwd alice": "alice:x:1001:1001::/home/alice:/bin/bash\n", "getent shadow alice": self.shadow + "\n", "id -Gn alice": "alice sudo\n", "sudo -l -U alice": "User alice is not allowed to run sudo on host.\n", } if command in answers: return CommandResult(answers[command], "", 0) if argv[:2] == ["test", "-e"]: return CommandResult("", "", 0 if argv[2] in self.files else 1) if argv[:4] == ["sudo", "-n", "-u", "alice"]: return self._as_alice(argv[4:]) return CommandResult("", "", 0) def _as_alice(self, argv: list[str]) -> CommandResult: if argv[0] == "cat": return CommandResult(self.files.get(argv[-1], ""), "", 0) if argv[0] == "install": self.files[argv[-1]] = self.files[argv[-2]] return CommandResult("", "", 0) def as_root(self) -> list[list[str]]: """What root ran that changes something: no reads, nothing as Alice.""" reads = ("getent", "id", "test") words = [shlex.split(c) for c, privileged in self.ran if privileged] return [ w for w in words if w[0] not in reads and w[:2] not in (["sudo", "-n"], ["sudo", "-l"]) ] _OPEN = "alice:$6$old:20000:0:99999:7:::" def test_clearing_the_password_is_a_star_no_hash_matches() -> None: # Not passwd -d: an empty password and pam_unix's nullok let anyone su to it. # Not "!": sshd without PAM takes it for a lock and refuses the key too. # Not an expiry: that is the lock, and PAM refuses a key of an expired account. assert _Driver()._account_clear_password("alice") == [["usermod", "-p", "*", "alice"]] def test_a_key_only_account_opens_again_without_its_password_coming_back() -> None: d = _Driver(shadow="alice:!*:20000:0:99999:7::1:") assert d._account_open("alice", None, locked=True) == [["usermod", "-e", "", "alice"]] def test_removing_the_password_runs_usermod_and_takes_sudo_away() -> None: host = _Host(_OPEN, keys=ALICE_KEY + "\n") result = host.add_local_account("alice", ALICE_KEY, clear_password=True) assert result["success"], result["output"] assert host.as_root() == [ ["usermod", "-U", "-e", "", "alice"], ["rm", "-f", "--", "/etc/sudoers.d/80-account-alice"], ["gpasswd", "-d", "alice", "sudo"], ["usermod", "-p", "*", "alice"], ] def test_a_replaced_key_is_written_out_of_the_key_file_as_the_person() -> None: host = _Host(_OPEN, keys=f"{OLD_KEY}\n{OWN_KEY}\n") result = host.add_local_account("alice", ALICE_KEY, replaces=[OLD_KEY]) assert result["success"], result["output"] assert host.files[_KEYS] == f"{OWN_KEY}\n{ALICE_KEY}\n" installs = [c for c, _ in host.ran if "install -m 600" in c] assert installs and all(c.startswith("sudo -n -u alice install") for c in installs) def test_a_deleted_key_takes_the_password_and_sudo_with_it_when_asked() -> None: """NetOrk/netork#2033: the password went with the person's key, so it goes from the host too, with sudo; the account stays open.""" host = _Host(_OPEN, keys=f"{ALICE_KEY}\n{OWN_KEY}\n") result = host.remove_local_account_keys("alice", [ALICE_KEY], clear_password=True) assert result["success"], result["output"] assert [s["step"] for s in result["steps"]] == ["keys", "password", "sudo"] assert host.files[_KEYS] == f"{OWN_KEY}\n" assert host.as_root() == [ ["usermod", "-p", "*", "alice"], ["rm", "-f", "--", "/etc/sudoers.d/80-account-alice"], ["gpasswd", "-d", "alice", "sudo"], ] def test_a_deleted_key_goes_and_the_account_stays_open() -> None: host = _Host(_OPEN, keys=f"{ALICE_KEY}\n{OWN_KEY}\n") result = host.remove_local_account_keys("alice", [ALICE_KEY]) assert result["success"], result["output"] assert host.files[_KEYS] == f"{OWN_KEY}\n" assert host.as_root() == []