feat: LocalAccountsMixin, personal accounts added and locked again (NetOrk/netork#1793)
driver / standard (pull_request) Successful in 25s
driver / lint (pull_request) Successful in 30s
driver / types (pull_request) Successful in 1m36s
driver / test (3.13) (pull_request) Successful in 1m15s
driver / test (3.12) (pull_request) Successful in 1m41s
driver / lowest (pull_request) Successful in 46s
driver / build (pull_request) Successful in 36s
driver / security (pull_request) Successful in 1m21s
CI / driver (pull_request) Successful in 3m6s
driver / publish (pull_request) Skipped
driver / standard (pull_request) Successful in 25s
driver / lint (pull_request) Successful in 30s
driver / types (pull_request) Successful in 1m36s
driver / test (3.13) (pull_request) Successful in 1m15s
driver / test (3.12) (pull_request) Successful in 1m41s
driver / lowest (pull_request) Successful in 46s
driver / build (pull_request) Successful in 36s
driver / security (pull_request) Successful in 1m21s
CI / driver (pull_request) Successful in 3m6s
driver / publish (pull_request) Skipped
get_local_accounts(names) reads a person's account back: groups, lock, sudo, key files. add_local_account() creates or reopens one with the person's key, optional password hash and optional sudo rule; lock_local_account() takes the keys and sudo away and refuses every login, keeping the home. Every command root runs is one fixed command, so a sudoers allowlist can name it. The key files are read and written as the person (sudo -n -u), never as root, since a link in a home the person owns may point anywhere. The sudo rule is a drop-in of its own, checked with visudo before and sudo -l after; a rule elsewhere (cloud-init's) is reported, not edited. The login user's own account and system accounts are refused. A driver supplies creating, opening, locking, reading the lock and leaving a group.
This commit is contained in:
1 parent
888a7229dc
commit
49c65cbd5d
4 files changed
+1224
No files matched your search
@@ -48,6 +48,7 @@ instead of being restated on every role that happens to need it:
|
||||
* :class:`~napalm_device_types.interface_filter.InterfaceFilterMixin`
|
||||
* :class:`~napalm_device_types.kernel.KernelFactsMixin`
|
||||
* :class:`~napalm_device_types.listening.ListeningSocketsMixin`
|
||||
* :class:`~napalm_device_types.local_accounts.LocalAccountsMixin`
|
||||
* :class:`~napalm_device_types.host_firewall.HostFirewallMixin`
|
||||
* :class:`~napalm_device_types.mac_acl.MacAclMixin`
|
||||
* :class:`~napalm_device_types.nat_vpn.NatVpnMixin`
|
||||
@@ -123,6 +124,11 @@ from napalm_device_types.listening import (
|
||||
ListeningSocketsUnavailable,
|
||||
parse_listening_sockets,
|
||||
)
|
||||
from napalm_device_types.local_accounts import (
|
||||
LocalAccountChangeDict,
|
||||
LocalAccountDict,
|
||||
LocalAccountsMixin,
|
||||
)
|
||||
from napalm_device_types.mac_acl import MacAclMixin
|
||||
from napalm_device_types.management_controller import ManagementControllerDriver
|
||||
from napalm_device_types.media import MediaDriver
|
||||
@@ -317,6 +323,9 @@ __all__ = [
|
||||
"ListeningSocketsMixin",
|
||||
"ListeningSocketsUnavailable",
|
||||
"parse_listening_sockets",
|
||||
"LocalAccountsMixin",
|
||||
"LocalAccountDict",
|
||||
"LocalAccountChangeDict",
|
||||
"PhoneDriver",
|
||||
"PingSweepMixin",
|
||||
"PortSpec",
|
||||
|
||||
@@ -0,0 +1,565 @@
|
||||
"""Personal login accounts on a host: reading them, adding one, locking one again.
|
||||
|
||||
A person who is to work on a host gets an account of their own: they log in
|
||||
with their public key and, where they are to administer the host, may use
|
||||
sudo with their own password. When they leave, the account is locked, not
|
||||
deleted: their key goes, sudo goes, the login is refused, and the home stays.
|
||||
|
||||
:class:`LocalAccountsMixin` holds what is the same on every POSIX host -- the
|
||||
checks, reading an account back, the order of the steps, the key file and the
|
||||
sudo rule. A driver supplies the commands that differ between operating
|
||||
systems: creating, opening and locking an account, reading its lock, and
|
||||
taking it out of a group.
|
||||
|
||||
**Every command root runs is one fixed command**, with no shell syntax of its
|
||||
own -- ``useradd ...``, ``install -m 440 ...``, ``rm -f -- <path>`` -- so a
|
||||
sudoers allowlist of commands can name each one. What goes into a file is
|
||||
staged first, without privilege; root never reads stdin, where a sudo that
|
||||
does not prompt would leave the password.
|
||||
|
||||
**Nothing root runs follows the person's files.** The key files live in a home
|
||||
the person owns, where a symbolic link may point anywhere, so they are read and
|
||||
written as that person (``sudo -n -u <name>``). Only the existence of a key
|
||||
file is asked as root.
|
||||
|
||||
**The sudo rule is a file of its own** in the drop-in directory sudo includes,
|
||||
``<name> ALL=(ALL) ALL``: the person's own password, as on a new VM. A group
|
||||
alone is not enough, as some distributions grant ``%wheel`` and others
|
||||
``%sudo``. ``visudo`` checks the rule before it is installed, and ``sudo -l``
|
||||
afterwards shows whether it took effect. A rule elsewhere -- cloud-init's
|
||||
``90-cloud-init-users`` -- is not edited; it is reported.
|
||||
|
||||
**The login user's own account and system accounts are never touched**:
|
||||
locking the first would lock the caller out.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shlex
|
||||
from collections.abc import Iterable, Sequence
|
||||
from typing import TYPE_CHECKING, ClassVar
|
||||
|
||||
from typing_extensions import TypedDict
|
||||
|
||||
from napalm_device_types.fixes import run_fix_steps
|
||||
from napalm_device_types.models import FixResultDict, FixStepDict, FixStepOutcomeDict
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - for type checkers only
|
||||
from napalm_device_types.channel import CommandResult
|
||||
|
||||
#: A login name every POSIX host takes as it is: lowercase, a letter or an
|
||||
#: underscore first, at most 32 characters. It is also safe in a root command.
|
||||
ACCOUNT_NAME_RE = re.compile(r"[a-z_][a-z0-9_.-]{0,31}")
|
||||
|
||||
#: The crypt(3) prefixes of each password scheme a driver may take.
|
||||
PASSWORD_SCHEMES: dict[str, tuple[str, ...]] = {
|
||||
"sha512": ("$6$",),
|
||||
"bcrypt": ("$2b$", "$2a$", "$2y$"),
|
||||
}
|
||||
_CRYPT_RE = re.compile(r"\$[0-9a-z]+\$[./0-9A-Za-z$]+")
|
||||
|
||||
#: The public key types OpenSSH takes in a key file.
|
||||
_KEY_TYPE_RE = re.compile(
|
||||
r"(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(256|384|521)"
|
||||
r"|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com)"
|
||||
)
|
||||
_KEY_BLOB_RE = re.compile(r"[A-Za-z0-9+/]+={0,3}")
|
||||
|
||||
#: Before the rule's file name; after cloud-init's ``90-`` it would win, so before it.
|
||||
SUDOERS_FILE_PREFIX = "80-account-"
|
||||
|
||||
#: A line of ``sudo -l`` that lets the account run every command as root.
|
||||
_RUN_ALL_RE = re.compile(r"^\s*\(ALL(\s*:\s*ALL)?\)\s+([A-Z_]+:\s*)*ALL\s*$", re.MULTILINE)
|
||||
|
||||
#: Stages stdin as a file anyone may read -- the person reads the key file
|
||||
#: from it -- and prints its path. The content is a public key or a sudo rule.
|
||||
_STAGE = 't=$(mktemp) && chmod 644 "$t" && cat > "$t" && printf %s "$t"'
|
||||
|
||||
|
||||
class LocalAccountDict(TypedDict):
|
||||
"""A person's account as the host has it (``get_local_accounts``)."""
|
||||
|
||||
name: str
|
||||
uid: int
|
||||
home: str
|
||||
shell: str
|
||||
#: Primary group first.
|
||||
groups: list[str]
|
||||
#: No login, with a key or a password.
|
||||
locked: bool
|
||||
#: ``sudo -l`` lets it run every command as root.
|
||||
admin: bool
|
||||
#: The lines of its key files; None when they could not be read (a locked
|
||||
#: account cannot run a command any more).
|
||||
authorized_keys: list[str] | None
|
||||
|
||||
|
||||
class LocalAccountChangeDict(FixResultDict):
|
||||
"""The result of ``add_local_account`` and ``lock_local_account``."""
|
||||
|
||||
#: The account read back after the change; None when it is not there or
|
||||
#: could not be read.
|
||||
account: LocalAccountDict | None
|
||||
|
||||
|
||||
def sudoers_rule(name: str) -> str:
|
||||
"""The rule that lets *name* run everything as root, with its own password."""
|
||||
return f"{name} ALL=(ALL) ALL\n"
|
||||
|
||||
|
||||
def sudoers_rule_path(directory: str, name: str) -> str:
|
||||
"""Where *name*'s rule lives in *directory*.
|
||||
|
||||
sudo skips a file whose name holds a dot, so a dot becomes ``_2e``, and an
|
||||
underscore ``__``: no two names share a file.
|
||||
"""
|
||||
escaped = name.replace("_", "__").replace(".", "_2e")
|
||||
return f"{directory}/{SUDOERS_FILE_PREFIX}{escaped}"
|
||||
|
||||
|
||||
def authorized_keys_paths(home: str) -> tuple[str, str]:
|
||||
"""The key files sshd reads in *home* unless configured otherwise."""
|
||||
return f"{home}/.ssh/authorized_keys", f"{home}/.ssh/authorized_keys2"
|
||||
|
||||
|
||||
def check_account_name(name: str) -> None:
|
||||
""":raises ValueError: when *name* is no login name every host takes."""
|
||||
if not ACCOUNT_NAME_RE.fullmatch(name):
|
||||
raise ValueError(f"not an account name: {name!r}")
|
||||
|
||||
|
||||
def _key_blob(line: str) -> str | None:
|
||||
"""The base64 part of a key file line, options and comment aside."""
|
||||
words = line.split()
|
||||
for i, word in enumerate(words[:-1]):
|
||||
if _KEY_TYPE_RE.fullmatch(word):
|
||||
return words[i + 1]
|
||||
return None
|
||||
|
||||
|
||||
def check_public_key(key: str) -> None:
|
||||
""":raises ValueError: when *key* is not one OpenSSH public key on one line."""
|
||||
words = key.split()
|
||||
if (
|
||||
"\n" in key.strip()
|
||||
or len(words) < 2
|
||||
or not _KEY_TYPE_RE.fullmatch(words[0])
|
||||
or not _KEY_BLOB_RE.fullmatch(words[1])
|
||||
):
|
||||
raise ValueError("not a public key: expected '<type> <base64> [comment]' on one line")
|
||||
|
||||
|
||||
def _command(argv: Sequence[str]) -> str:
|
||||
return shlex.join(argv)
|
||||
|
||||
|
||||
def _as(name: str, *argv: str) -> str:
|
||||
"""*argv* run as *name*, from root: nothing it does reaches beyond that account."""
|
||||
return _command(["sudo", "-n", "-u", name, *argv])
|
||||
|
||||
|
||||
def _said(result: CommandResult) -> str:
|
||||
return (result.stderr or result.stdout).strip() or f"exit {result.exit_code}"
|
||||
|
||||
|
||||
class LocalAccountsMixin:
|
||||
"""Reads, adds and locks personal accounts; a driver supplies the OS's commands.
|
||||
|
||||
Mixed in by the drivers that can, so ``callable(getattr(driver,
|
||||
"add_local_account", None))`` says whether a driver can.
|
||||
"""
|
||||
|
||||
#: The login shell of a new account.
|
||||
ACCOUNT_SHELL: ClassVar[str] = "/bin/sh"
|
||||
#: The password scheme the host's accounts take, a key of :data:`PASSWORD_SCHEMES`.
|
||||
ACCOUNT_PASSWORD_SCHEME: ClassVar[str] = "sha512"
|
||||
#: Groups that make an account an administrator; a person without sudo leaves them.
|
||||
ACCOUNT_ADMIN_GROUPS: ClassVar[tuple[str, ...]] = ("wheel",)
|
||||
#: The lowest uid of a person's account; below are the system's.
|
||||
ACCOUNT_MIN_UID: ClassVar[int] = 1000
|
||||
#: The drop-in directory sudo includes.
|
||||
SUDOERS_DIR: ClassVar[str] = "/etc/sudoers.d"
|
||||
#: The group of root's files.
|
||||
ROOT_GROUP: ClassVar[str] = "root"
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult: ...
|
||||
|
||||
# -- what a driver supplies ------------------------------------------------------
|
||||
|
||||
def _account_create(self, name: str, password_hash: str | None) -> list[list[str]]:
|
||||
"""The commands that create *name* with a home and :attr:`ACCOUNT_SHELL`.
|
||||
|
||||
Without *password_hash* the account takes no password, only a key.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def _account_open(
|
||||
self, name: str, password_hash: str | None, *, locked: bool
|
||||
) -> list[list[str]]:
|
||||
"""The commands that let *name* log in again, with *password_hash* if given."""
|
||||
raise NotImplementedError
|
||||
|
||||
def _account_lock(self, name: str, *, locked: bool) -> list[list[str]]:
|
||||
"""The commands that refuse *name* every login, a key's too; none when *locked*."""
|
||||
raise NotImplementedError
|
||||
|
||||
def _account_locked(self, name: str, passwd: list[str]) -> bool:
|
||||
"""Whether *name* is locked; *passwd* is its ``getent passwd`` line, split.
|
||||
|
||||
:raises RuntimeError: when that cannot be read.
|
||||
"""
|
||||
raise NotImplementedError
|
||||
|
||||
def _account_leave_group(self, name: str, group: str, groups: list[str]) -> list[str]:
|
||||
"""The command that takes *name* out of *group*; *groups* are all of its own."""
|
||||
raise NotImplementedError
|
||||
|
||||
# -- reading ---------------------------------------------------------------------
|
||||
|
||||
def get_local_accounts(self, names: Iterable[str]) -> list[LocalAccountDict]:
|
||||
"""The accounts of *names* the host has, in that order; a missing one is left out.
|
||||
|
||||
:raises ValueError: for a name that is no account name.
|
||||
:raises RuntimeError: when an account cannot be read.
|
||||
"""
|
||||
wanted = list(names)
|
||||
for name in wanted:
|
||||
check_account_name(name)
|
||||
found = (self._accounts_read(name) for name in wanted)
|
||||
return [account for account in found if account is not None]
|
||||
|
||||
def _accounts_passwd(self, name: str) -> list[str] | None:
|
||||
result = self.run_command(_command(["getent", "passwd", name]), timeout=30)
|
||||
if result.exit_code == 2:
|
||||
return None
|
||||
fields = result.stdout.strip().split(":")
|
||||
if result.exit_code != 0 or len(fields) < 7 or fields[0] != name:
|
||||
raise RuntimeError(f"cannot read the account {name}: {_said(result)}")
|
||||
return fields
|
||||
|
||||
def _accounts_read(self, name: str) -> LocalAccountDict | None:
|
||||
passwd = self._accounts_passwd(name)
|
||||
if passwd is None:
|
||||
return None
|
||||
groups = self.run_command(_command(["id", "-Gn", name]), timeout=30)
|
||||
if groups.exit_code != 0:
|
||||
raise RuntimeError(f"cannot read the groups of {name}: {_said(groups)}")
|
||||
home = passwd[5]
|
||||
return {
|
||||
"name": name,
|
||||
"uid": int(passwd[2]),
|
||||
"home": home,
|
||||
"shell": passwd[6],
|
||||
"groups": groups.stdout.split(),
|
||||
"locked": self._account_locked(name, passwd),
|
||||
"admin": self._accounts_admin(name),
|
||||
"authorized_keys": self._accounts_keys(name, home),
|
||||
}
|
||||
|
||||
def _accounts_admin(self, name: str) -> bool:
|
||||
result = self.run_command(_command(["sudo", "-l", "-U", name]), privileged=True, timeout=30)
|
||||
if result.exit_code != 0:
|
||||
raise RuntimeError(f"cannot ask sudo about {name}: {_said(result)}")
|
||||
return bool(_RUN_ALL_RE.search(result.stdout))
|
||||
|
||||
def _accounts_keys(self, name: str, home: str) -> list[str] | None:
|
||||
"""The lines of *name*'s key files, read as *name*; None when it cannot."""
|
||||
lines: list[str] = []
|
||||
for path in authorized_keys_paths(home):
|
||||
there = self.run_command(_command(["test", "-e", path]), privileged=True, timeout=30)
|
||||
if there.exit_code != 0:
|
||||
continue
|
||||
result = self.run_command(_as(name, "cat", "--", path), privileged=True, timeout=30)
|
||||
if result.exit_code != 0:
|
||||
return None
|
||||
lines += [ln for ln in result.stdout.splitlines() if ln.strip()]
|
||||
return lines
|
||||
|
||||
# -- changing ----------------------------------------------------------------------
|
||||
|
||||
def add_local_account(
|
||||
self,
|
||||
name: str,
|
||||
public_key: str,
|
||||
*,
|
||||
password_hash: str | None = None,
|
||||
admin: bool = False,
|
||||
) -> LocalAccountChangeDict:
|
||||
"""Give *name* an account that logs in with *public_key*, or open it again.
|
||||
|
||||
An account that is there is opened again and keeps its other keys; a
|
||||
new one gets a home. *password_hash* (crypt(3), in
|
||||
:attr:`ACCOUNT_PASSWORD_SCHEME`) becomes its password; *admin* gives it
|
||||
the sudo rule, which asks for that password -- so an administrator
|
||||
needs one. Without *admin*, the rule and :attr:`ACCOUNT_ADMIN_GROUPS`
|
||||
are taken away.
|
||||
|
||||
Steps: ``account``, then ``sudo`` and ``keys``, each of which runs when
|
||||
the other failed.
|
||||
|
||||
:raises ValueError: for a name, key or hash no host takes, the login
|
||||
user's own account, or a system account.
|
||||
"""
|
||||
check_account_name(name)
|
||||
check_public_key(public_key)
|
||||
if password_hash is not None:
|
||||
self._accounts_check_hash(password_hash)
|
||||
existing = self._accounts_changeable(name)
|
||||
first = run_fix_steps(
|
||||
[("account", lambda: self._accounts_open_or_create(name, existing, password_hash))]
|
||||
)
|
||||
parts = [first]
|
||||
if first["success"]:
|
||||
parts += [
|
||||
run_fix_steps([("sudo", lambda: self._accounts_set_sudo(name, admin=admin))]),
|
||||
run_fix_steps([("keys", lambda: self._accounts_add_key(name, public_key))]),
|
||||
]
|
||||
return self._accounts_result(name, parts)
|
||||
|
||||
def lock_local_account(self, name: str) -> LocalAccountChangeDict:
|
||||
"""Lock *name*: its keys go, every login is refused, sudo goes; its home stays.
|
||||
|
||||
Steps ``keys``, ``lock`` and ``sudo``, each run when one before failed:
|
||||
the lock matters most. A sudo rule outside the drop-in directory is
|
||||
reported, not edited -- with the account locked it can no longer be used.
|
||||
|
||||
:raises ValueError: for a name no host takes, the login user's own
|
||||
account, or a system account.
|
||||
"""
|
||||
check_account_name(name)
|
||||
if self._accounts_changeable(name) is None:
|
||||
step: FixStepDict = {"step": "account", "ok": False, "output": f"no account {name}"}
|
||||
return {**_joined([step]), "account": None}
|
||||
parts = [
|
||||
run_fix_steps([("keys", lambda: self._accounts_remove_keys(name))]),
|
||||
run_fix_steps([("lock", lambda: self._accounts_lock(name))]),
|
||||
run_fix_steps(
|
||||
[("sudo", lambda: self._accounts_set_sudo(name, admin=False, locked=True))]
|
||||
),
|
||||
]
|
||||
return self._accounts_result(name, parts)
|
||||
|
||||
def _accounts_check_hash(self, password_hash: str) -> None:
|
||||
prefixes = PASSWORD_SCHEMES[self.ACCOUNT_PASSWORD_SCHEME]
|
||||
if not _CRYPT_RE.fullmatch(password_hash) or not password_hash.startswith(prefixes):
|
||||
raise ValueError(f"not a {self.ACCOUNT_PASSWORD_SCHEME} password hash")
|
||||
|
||||
def _accounts_changeable(self, name: str) -> list[str] | None:
|
||||
"""*name*'s passwd line, None when there is none.
|
||||
|
||||
:raises ValueError: for the login user's own account or a system account.
|
||||
:raises RuntimeError: when the login user cannot be told.
|
||||
"""
|
||||
login = self.run_command("id -un", timeout=30).stdout.strip()
|
||||
if not login:
|
||||
raise RuntimeError("cannot tell which account this driver logs in with")
|
||||
if name == login:
|
||||
raise ValueError(f"{name} is the account this driver logs in with")
|
||||
passwd = self._accounts_passwd(name)
|
||||
if passwd is not None and int(passwd[2]) < self.ACCOUNT_MIN_UID:
|
||||
raise ValueError(f"{name} is a system account (uid {passwd[2]})")
|
||||
return passwd
|
||||
|
||||
def _accounts_result(self, name: str, parts: list[FixResultDict]) -> LocalAccountChangeDict:
|
||||
steps = [s for part in parts for s in part["steps"]]
|
||||
result = _joined(steps)
|
||||
account: LocalAccountDict | None = None
|
||||
try:
|
||||
account = self._accounts_read(name)
|
||||
except RuntimeError as exc:
|
||||
result["output"] += f"\n[read back] {exc}"
|
||||
return {**result, "account": account}
|
||||
|
||||
def _accounts_root(self, argv: Sequence[str]) -> CommandResult:
|
||||
return self.run_command(_command(argv), privileged=True, timeout=60)
|
||||
|
||||
def _accounts_run(self, commands: list[list[str]]) -> CommandResult | None:
|
||||
"""Run *commands* as root in order; the first that failed, or None."""
|
||||
for argv in commands:
|
||||
result = self._accounts_root(argv)
|
||||
if result.exit_code != 0:
|
||||
return result
|
||||
return None
|
||||
|
||||
def _accounts_open_or_create(
|
||||
self, name: str, passwd: list[str] | None, password_hash: str | None
|
||||
) -> FixStepOutcomeDict:
|
||||
if passwd is None:
|
||||
failed = self._accounts_run(self._account_create(name, password_hash))
|
||||
done = f"account {name} created"
|
||||
else:
|
||||
locked = self._account_locked(name, passwd)
|
||||
failed = self._accounts_run(self._account_open(name, password_hash, locked=locked))
|
||||
done = f"account {name} opened again" if locked else f"account {name} is there"
|
||||
if failed is not None:
|
||||
return {"ok": False, "output": _said(failed)}
|
||||
return {"ok": True, "output": done + (", password set" if password_hash else "")}
|
||||
|
||||
def _accounts_lock(self, name: str) -> FixStepOutcomeDict:
|
||||
passwd = self._accounts_passwd(name)
|
||||
if passwd is None:
|
||||
return {"ok": False, "output": f"no account {name}"}
|
||||
locked = self._account_locked(name, passwd)
|
||||
failed = self._accounts_run(self._account_lock(name, locked=locked))
|
||||
if failed is not None:
|
||||
return {"ok": False, "output": _said(failed)}
|
||||
if not self._account_locked(name, passwd):
|
||||
return {"ok": False, "output": f"{name} is still not locked"}
|
||||
return {"ok": True, "output": f"{name} was locked already" if locked else f"{name} locked"}
|
||||
|
||||
# -- sudo --------------------------------------------------------------------------
|
||||
|
||||
def _accounts_set_sudo(
|
||||
self, name: str, *, admin: bool, locked: bool = False
|
||||
) -> FixStepOutcomeDict:
|
||||
path = sudoers_rule_path(self.SUDOERS_DIR, name)
|
||||
if admin:
|
||||
return self._accounts_grant_sudo(name, path)
|
||||
said: list[str] = []
|
||||
removed = self._accounts_root(["rm", "-f", "--", path])
|
||||
if removed.exit_code != 0:
|
||||
return {"ok": False, "output": f"{path}: {_said(removed)}"}
|
||||
groups = self.run_command(_command(["id", "-Gn", name]), timeout=30).stdout.split()
|
||||
for group in self.ACCOUNT_ADMIN_GROUPS:
|
||||
if group not in groups[1:]:
|
||||
continue
|
||||
left = self._accounts_root(self._account_leave_group(name, group, groups))
|
||||
if left.exit_code != 0:
|
||||
return {"ok": False, "output": f"cannot take {name} out of {group}: {_said(left)}"}
|
||||
groups.remove(group)
|
||||
said.append(f"{name} left {group}")
|
||||
if self._accounts_admin(name):
|
||||
rest = f"another rule than {path} still lets {name} run everything as root"
|
||||
if locked:
|
||||
return {"ok": True, "output": f"{rest}; the account is locked, so it cannot use it"}
|
||||
return {"ok": False, "output": rest}
|
||||
said.append(f"{name} has no sudo")
|
||||
return {"ok": True, "output": "\n".join(said)}
|
||||
|
||||
def _accounts_grant_sudo(self, name: str, path: str) -> FixStepOutcomeDict:
|
||||
staged = self._accounts_stage(sudoers_rule(name))
|
||||
try:
|
||||
checked = self._accounts_root(["visudo", "-cf", staged])
|
||||
if checked.exit_code != 0:
|
||||
return {"ok": False, "output": f"visudo refuses the rule: {_said(checked)}"}
|
||||
installed = self._accounts_root(
|
||||
["install", "-m", "440", "-o", "root", "-g", self.ROOT_GROUP, "--", staged, path]
|
||||
)
|
||||
if installed.exit_code != 0:
|
||||
return {"ok": False, "output": f"{path}: {_said(installed)}"}
|
||||
finally:
|
||||
self._accounts_unstage(staged)
|
||||
if not self._accounts_admin(name):
|
||||
return {
|
||||
"ok": False,
|
||||
"output": f"{path} is written, but sudo does not read it: "
|
||||
f"does sudoers include {self.SUDOERS_DIR}?",
|
||||
}
|
||||
return {"ok": True, "output": f"{name} may use sudo with its password ({path})"}
|
||||
|
||||
# -- keys --------------------------------------------------------------------------
|
||||
|
||||
def _accounts_stage(self, content: str) -> str:
|
||||
"""*content* in a fresh file of the login user's; its path.
|
||||
|
||||
:raises RuntimeError: when it cannot be staged.
|
||||
"""
|
||||
result = self.run_command(_STAGE, timeout=30, stdin=content.encode())
|
||||
path = result.stdout.strip().splitlines()[-1:] or [""]
|
||||
if result.exit_code != 0 or not path[0].startswith("/"):
|
||||
raise RuntimeError(f"cannot stage a file: {_said(result)}")
|
||||
return path[0]
|
||||
|
||||
def _accounts_unstage(self, path: str) -> None:
|
||||
self.run_command(_command(["rm", "-f", "--", path]), timeout=30)
|
||||
|
||||
def _accounts_add_key(self, name: str, public_key: str) -> FixStepOutcomeDict:
|
||||
passwd = self._accounts_passwd(name)
|
||||
if passwd is None:
|
||||
return {"ok": False, "output": f"no account {name}"}
|
||||
home = passwd[5]
|
||||
path = authorized_keys_paths(home)[0]
|
||||
current = self._accounts_keys(name, home)
|
||||
if current is None:
|
||||
return {"ok": False, "output": f"cannot read the key files of {name}"}
|
||||
blob = _key_blob(public_key)
|
||||
if any(_key_blob(line) == blob for line in current):
|
||||
return {"ok": True, "output": f"the key is already in {path}"}
|
||||
mine = self._accounts_key_file(name, path)
|
||||
if mine is None:
|
||||
return {"ok": False, "output": f"cannot read {path}"}
|
||||
staged = self._accounts_stage("".join(f"{line}\n" for line in [*mine, public_key.strip()]))
|
||||
try:
|
||||
failed = self._accounts_run_as(
|
||||
name,
|
||||
[
|
||||
["mkdir", "-p", "-m", "700", "--", f"{home}/.ssh"],
|
||||
["install", "-m", "600", "--", staged, path],
|
||||
],
|
||||
)
|
||||
finally:
|
||||
self._accounts_unstage(staged)
|
||||
if failed is not None:
|
||||
return {"ok": False, "output": f"{path}: {_said(failed)}"}
|
||||
return {"ok": True, "output": f"key added to {path}"}
|
||||
|
||||
def _accounts_key_file(self, name: str, path: str) -> list[str] | None:
|
||||
there = self.run_command(_command(["test", "-e", path]), privileged=True, timeout=30)
|
||||
if there.exit_code != 0:
|
||||
return []
|
||||
result = self.run_command(_as(name, "cat", "--", path), privileged=True, timeout=30)
|
||||
if result.exit_code != 0:
|
||||
return None
|
||||
return [line for line in result.stdout.splitlines() if line.strip()]
|
||||
|
||||
def _accounts_run_as(self, name: str, commands: list[list[str]]) -> CommandResult | None:
|
||||
for argv in commands:
|
||||
result = self.run_command(_as(name, *argv), privileged=True, timeout=60)
|
||||
if result.exit_code != 0:
|
||||
return result
|
||||
return None
|
||||
|
||||
def _accounts_remove_keys(self, name: str) -> FixStepOutcomeDict:
|
||||
passwd = self._accounts_passwd(name)
|
||||
if passwd is None:
|
||||
return {"ok": False, "output": f"no account {name}"}
|
||||
paths = authorized_keys_paths(passwd[5])
|
||||
failed = self._accounts_run_as(name, [["rm", "-f", "--", *paths]])
|
||||
if failed is not None:
|
||||
return {"ok": False, "output": f"cannot remove the keys of {name}: {_said(failed)}"}
|
||||
if self._accounts_keys(name, passwd[5]):
|
||||
return {"ok": False, "output": f"{name} still has keys"}
|
||||
return {"ok": True, "output": f"keys of {name} removed"}
|
||||
|
||||
|
||||
def _joined(steps: list[FixStepDict]) -> FixResultDict:
|
||||
return {
|
||||
"success": bool(steps) and all(s["ok"] for s in steps),
|
||||
"steps": steps,
|
||||
"output": "\n".join(f"[{s['step']}] {s['output']}".rstrip() for s in steps),
|
||||
}
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ACCOUNT_NAME_RE",
|
||||
"PASSWORD_SCHEMES",
|
||||
"SUDOERS_FILE_PREFIX",
|
||||
"LocalAccountChangeDict",
|
||||
"LocalAccountDict",
|
||||
"LocalAccountsMixin",
|
||||
"authorized_keys_paths",
|
||||
"check_account_name",
|
||||
"check_public_key",
|
||||
"sudoers_rule",
|
||||
"sudoers_rule_path",
|
||||
]
|
||||
Reference in new issue
Block a user