Files
napalm-linux/napalm_linux/_local_accounts.py
T
Christian Manivong d03fe2a2ba
driver / lint (pull_request) Successful in 17s
driver / standard (pull_request) Successful in 19s
driver / types (pull_request) Successful in 1m9s
driver / test (3.13) (pull_request) Successful in 1m2s
driver / test (3.12) (pull_request) Successful in 1m11s
driver / lowest (pull_request) Successful in 32s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m6s
CI / driver (pull_request) Successful in 2m27s
driver / publish (pull_request) Skipped
feat(accounts): clear a password, replace and remove keys
napalm-device-types 4.28.0 lets add_local_account remove the old keys
(replaces) and the password (clear_password), and adds
remove_local_account_keys. The key changes run through the mixin's own
key files as the person; the password goes with usermod -p '*', which
leaves the expiry (the lock) alone and keeps the key login working with
and without PAM, where an empty password or a '!' would not.

See NetOrk/netork#2013
2026-11-04 11:46:13 +01:00

83 lines
3.8 KiB
Python

"""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.
An account whose password is removed (NetOrk/netork#2013) gets ``*`` as its
password field, which no hash matches: it logs in with a key only. Not an
empty field (``passwd -d``), which pam_unix's ``nullok`` -- on by default on
Debian and Ubuntu -- takes as "no password needed" for ``su`` and the console.
Not ``!``, which sshd takes for a locked account and refuses a key too where
PAM is off (``UsePAM no``). And not the expiry, which is the lock.
"""
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({"", "!", "!!", "!*", "*"})
#: The password field of an account that logs in with a key only: no hash matches it.
_KEY_ONLY = "*"
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_create_with_uid(self, name: str, uid: int) -> list[list[str]]:
# Below UID_MIN useradd warns and goes on: netOrk's own account is a system's.
return [["useradd", "-m", "-u", str(uid), "-s", self.ACCOUNT_SHELL, 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 _account_clear_password(self, name: str) -> list[list[str]]:
# usermod -p leaves the expiry -- the lock -- alone, and dates the change today,
# so pam_unix asks for no new password at the next key login.
return [["usermod", "-p", _KEY_ONLY, name]]
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