"""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