diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 7530c79..c1a016c 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -11,5 +11,7 @@ jobs: uses: NAPALM/driver-standard/.gitea/workflows/driver.yml@main with: standard-ref: main + # Until the napalm-device-types release with LocalAccountsMixin is on PyPI. + pre-install: "git+https://git.netork.io/NAPALM/napalm-device-types.git" secrets: PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e56a37..8893d23 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added +- Personal accounts on FreeBSD (NetOrk/netork#1793), through napalm-device-types' + `LocalAccountsMixin`: `get_local_accounts()`, `add_local_account()` and + `lock_local_account()` with `pw useradd -m -w no`, `chpass -p` for the password hash, + `pw lock`/`pw unlock` and `pw groupmod -d`. A locked account carries `*LOCKED*`, which + sshd refuses a key login too; the sudo rule goes to `/usr/local/etc/sudoers.d`. + Checked on FreeBSD 15.1 over SSH with sudo -S (sshd with `UsePAM no`, as nuageinit + sets it). OpenBSD does not offer it yet. Requires the napalm-device-types release with + `LocalAccountsMixin`. + ### Changed - Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6). diff --git a/napalm_bsd/accounts.py b/napalm_bsd/accounts.py new file mode 100644 index 0000000..4520145 --- /dev/null +++ b/napalm_bsd/accounts.py @@ -0,0 +1,58 @@ +"""Personal accounts on a FreeBSD host, with pw(8) and chpass(1) (NetOrk/netork#1793). + +napalm-device-types' ``LocalAccountsMixin`` runs the steps; this names the +commands. A locked account is ``pw lock``'s: ``*LOCKED*`` in front of the +password, which sshd refuses a key login too. getpwnam(3) shows the password +field to root only, so the lock is read as root; nothing but its prefix is +looked at. +""" + +from __future__ import annotations + +import shlex + +from napalm_device_types import LocalAccountsMixin + +#: What ``pw lock`` puts in front of the password. +_LOCKED_PREFIX = "*LOCKED*" + + +class FreeBSDLocalAccountsMixin(LocalAccountsMixin): + ACCOUNT_SHELL = "/bin/sh" + ACCOUNT_ADMIN_GROUPS = ("wheel",) + #: The sudo package's, which its default sudoers includes. + SUDOERS_DIR = "/usr/local/etc/sudoers.d" + ROOT_GROUP = "wheel" + + def _account_create(self, name: str, password_hash: str | None) -> list[list[str]]: + # -w no: the password field is "*", no password login until one is set. + create = ["pw", "useradd", "-n", name, "-m", "-s", self.ACCOUNT_SHELL, "-w", "no"] + return [create, *self._set_password(name, password_hash)] + + def _account_open( + self, name: str, password_hash: str | None, *, locked: bool + ) -> list[list[str]]: + unlock = [["pw", "unlock", name]] if locked else [] + return [*unlock, *self._set_password(name, password_hash)] + + def _account_lock(self, name: str, *, locked: bool) -> list[list[str]]: + # pw refuses to lock a locked account again. + return [] if locked else [["pw", "lock", name]] + + def _account_locked(self, name: str, passwd: list[str]) -> bool: + result = self.run_command( + shlex.join(["getent", "passwd", name]), privileged=True, timeout=30 + ) + fields = result.stdout.strip().split(":") + if result.exit_code != 0 or len(fields) < 7 or fields[0] != name: + reason = (result.stderr or result.stdout).strip() or f"exit {result.exit_code}" + raise RuntimeError(f"cannot read whether {name} is locked: {reason}") + return fields[1].startswith(_LOCKED_PREFIX) + + def _account_leave_group(self, name: str, group: str, groups: list[str]) -> list[str]: + return ["pw", "groupmod", group, "-d", name] + + @staticmethod + def _set_password(name: str, password_hash: str | None) -> list[list[str]]: + """chpass takes the crypt(3) string itself from root.""" + return [["chpass", "-p", password_hash, name]] if password_hash else [] diff --git a/napalm_bsd/freebsd.py b/napalm_bsd/freebsd.py index 17ad9d3..edad020 100644 --- a/napalm_bsd/freebsd.py +++ b/napalm_bsd/freebsd.py @@ -5,10 +5,11 @@ from __future__ import annotations from napalm_device_types import FingerprintRule from napalm_bsd import parse +from napalm_bsd.accounts import FreeBSDLocalAccountsMixin from napalm_bsd.base import BASE_SYSTEM, BsdDriver -class FreeBSDDriver(BsdDriver): +class FreeBSDDriver(FreeBSDLocalAccountsMixin, BsdDriver): """NAPALM driver for FreeBSD hosts, over SSH.""" TYPE_LABEL = "FreeBSD" diff --git a/tests/test_local_accounts.py b/tests/test_local_accounts.py new file mode 100644 index 0000000..780adee --- /dev/null +++ b/tests/test_local_accounts.py @@ -0,0 +1,99 @@ +"""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 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", + ]