Files
napalm-bsd/tests/test_local_accounts.py
T
Christian Manivong 4ac854482a
driver / lint (pull_request) Successful in 15s
driver / standard (pull_request) Successful in 18s
driver / types (pull_request) Successful in 1m6s
driver / test (3.13) (pull_request) Successful in 1m8s
driver / test (3.12) (pull_request) Successful in 1m12s
driver / lowest (pull_request) Successful in 30s
driver / build (pull_request) Successful in 32s
driver / security (pull_request) Successful in 1m12s
CI / driver (pull_request) Successful in 2m38s
driver / publish (pull_request) Skipped
feat(local-accounts): a deleted key can take the password with it
napalm-device-types 4.29.0 lets remove_local_account_keys clear the password and sudo too (NetOrk/netork#2033). This driver's _account_clear_password already does the work; a test pins the commands, and the floor rises to 4.29.0.
2026-11-04 15:22:50 +01:00

208 lines
8.0 KiB
Python

"""Personal accounts on a FreeBSD host (NetOrk/netork#1793).
napalm-device-types' ``LocalAccountsMixin`` runs the steps; the driver names
FreeBSD's commands. A locked account is ``pw lock``'s ``*LOCKED*``, which sshd
refuses a key login too. OpenBSD offers none of it yet.
"""
from __future__ import annotations
import shlex
import pytest
from napalm_device_types import CommandResult, LocalAccountsMixin
from napalm_bsd import FreeBSDDriver, OpenBSDDriver
HASH = "$6$salt$" + "x" * 86
class _Driver(FreeBSDDriver):
"""A FreeBSD driver whose host answers ``getent passwd alice`` with *entry*."""
def __init__(self, entry: str = "alice:$6$old:1001:1001::0:0:Alice:/home/alice:/bin/sh"):
super().__init__("host", "netadmin", "pw")
self.entry = entry
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 passwd alice":
return CommandResult(self.entry + "\n", "", 0 if self.entry else 2)
return CommandResult("", "", 0)
def _passwd() -> list[str]:
return "alice:*:1001:1001:Alice:/home/alice:/bin/sh".split(":")
def test_freebsd_can_add_and_lock_personal_accounts() -> None:
assert issubclass(FreeBSDDriver, LocalAccountsMixin)
assert FreeBSDDriver.ACCOUNT_SHELL == "/bin/sh"
assert FreeBSDDriver.ACCOUNT_PASSWORD_SCHEME == "sha512"
assert FreeBSDDriver.ACCOUNT_ADMIN_GROUPS == ("wheel",)
# The sudo package lives under /usr/local and includes its sudoers.d.
assert FreeBSDDriver.SUDOERS_DIR == "/usr/local/etc/sudoers.d"
assert FreeBSDDriver.ROOT_GROUP == "wheel"
def test_openbsd_offers_none_of_it_yet() -> None:
assert not issubclass(OpenBSDDriver, LocalAccountsMixin)
assert not hasattr(OpenBSDDriver, "add_local_account")
def test_a_new_account_gets_a_home_and_its_password_through_chpass() -> None:
d = _Driver()
create = ["pw", "useradd", "-n", "alice", "-m", "-s", "/bin/sh", "-w", "no"]
assert d._account_create("alice", None) == [create]
assert d._account_create("alice", HASH) == [create, ["chpass", "-p", HASH, "alice"]]
def test_opening_unlocks_only_a_locked_account() -> None:
d = _Driver()
assert d._account_open("alice", None, locked=True) == [["pw", "unlock", "alice"]]
assert d._account_open("alice", None, locked=False) == []
assert d._account_open("alice", HASH, locked=True) == [
["pw", "unlock", "alice"],
["chpass", "-p", HASH, "alice"],
]
def test_locking_is_pw_lock_once() -> None:
d = _Driver()
# pw refuses to lock a locked account again.
assert d._account_lock("alice", locked=False) == [["pw", "lock", "alice"]]
assert d._account_lock("alice", locked=True) == []
@pytest.mark.parametrize(
("password", "locked"),
[("$6$old", False), ("*", False), ("*LOCKED*$6$old", True), ("*LOCKED**", True)],
)
def test_the_lock_is_read_from_the_password_field_as_root(password: str, locked: bool) -> None:
# getpwnam(3) returns the encrypted password only to root, "*" to anyone else.
d = _Driver(entry=f"alice:{password}:1001:1001:Alice:/home/alice:/bin/sh")
assert d._account_locked("alice", _passwd()) is locked
assert d.ran == [("getent passwd alice", True)]
def test_an_entry_that_cannot_be_read_raises() -> None:
with pytest.raises(RuntimeError, match="alice"):
_Driver(entry="")._account_locked("alice", _passwd())
def test_leaving_a_group_is_pw_groupmod() -> None:
assert _Driver()._account_leave_group("alice", "wheel", ["alice", "wheel"]) == [
"pw",
"groupmod",
"wheel",
"-d",
"alice",
]
def test_netorks_own_account_is_made_with_its_uid() -> None:
"""NetOrk/netork#1817: a fixed uid on every host, no password."""
assert _Driver()._account_create_with_uid("netork", 900) == [
["pw", "useradd", "-n", "netork", "-u", "900", "-m", "-s", "/bin/sh", "-w", "no"]
]
# -- 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(_Driver):
"""A FreeBSD host with Alice's account and her key files."""
def __init__(self, keys: str) -> None:
# getent passwd: the seven fields, the hash shown to root only.
super().__init__(entry="alice:$6$old:1001:1001:Alice:/home/alice:/bin/sh")
self.files = {_KEYS: keys}
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": self.entry + "\n",
"id -Gn alice": "alice wheel\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"] and argv[4] == "cat":
return CommandResult(self.files.get(argv[-1], ""), "", 0)
if argv[:4] == ["sudo", "-n", "-u", "alice"] and argv[4] == "install":
self.files[argv[-1]] = self.files[argv[-2]]
return CommandResult("", "", 0)
def changed_as_root(self) -> list[list[str]]:
reads = (["getent"], ["id"], ["test"], ["sudo", "-n"], ["sudo", "-l"])
words = [shlex.split(c) for c, privileged in self.ran if privileged]
return [w for w in words if not any(w[: len(r)] == r for r in reads)]
def test_clearing_the_password_leaves_the_star_pw_gives_a_key_only_account() -> None:
# "*" is what pw useradd -w no writes: sshd lets the key in, no password matches.
# Not "*LOCKED*", which is the lock and refuses the key too.
assert _Driver()._account_clear_password("alice") == [["chpass", "-p", "*", "alice"]]
def test_removing_the_password_runs_chpass_and_takes_sudo_away() -> None:
host = _Host(keys=ALICE_KEY + "\n")
result = host.add_local_account("alice", ALICE_KEY, clear_password=True)
assert result["success"], result["output"]
assert host.changed_as_root() == [
["rm", "-f", "--", "/usr/local/etc/sudoers.d/80-account-alice"],
["pw", "groupmod", "wheel", "-d", "alice"],
["chpass", "-p", "*", "alice"],
]
def test_a_replaced_key_is_written_out_of_the_key_file_as_the_person() -> None:
host = _Host(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"
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 chpass clears it
and sudo goes; the account stays open."""
host = _Host(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.changed_as_root() == [
["chpass", "-p", "*", "alice"],
["rm", "-f", "--", "/usr/local/etc/sudoers.d/80-account-alice"],
["pw", "groupmod", "wheel", "-d", "alice"],
]
def test_a_deleted_key_goes_and_the_account_stays_open() -> None:
host = _Host(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.changed_as_root() == []