"""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_create_with_uid(self, name: str, uid: int) -> list[list[str]]: return [ [ "pw", "useradd", "-n", name, "-u", str(uid), "-m", "-s", self.ACCOUNT_SHELL, "-w", "no", ] ] 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 []