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
@@ -0,0 +1,641 @@
|
||||
"""Personal accounts on a host: reading them, adding one, locking one again.
|
||||
|
||||
The host is a fake that keeps accounts, groups, sudo rules and key files in
|
||||
memory and answers the fixed commands the mixin and a driver send. A driver's
|
||||
own commands (create, open, lock, leave a group) are stand-ins here; the real
|
||||
ones are tested in the drivers.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shlex
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types.channel import CommandResult
|
||||
from napalm_device_types.local_accounts import (
|
||||
LocalAccountsMixin,
|
||||
authorized_keys_paths,
|
||||
sudoers_rule,
|
||||
sudoers_rule_path,
|
||||
)
|
||||
|
||||
ALICE_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAlice alice@laptop"
|
||||
OWN_KEY = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQOwn own@desktop"
|
||||
HASH = "$6$salt$" + "x" * 86
|
||||
#: Shell syntax a command for root must not hold: each is one fixed command.
|
||||
SHELL_SYNTAX = (";", "&&", "||", "|", ">", "<", "$(", "`")
|
||||
|
||||
|
||||
@dataclass
|
||||
class _Account:
|
||||
uid: int
|
||||
home: str
|
||||
shell: str = "/bin/sh"
|
||||
groups: list[str] = field(default_factory=list)
|
||||
locked: bool = False
|
||||
password: str | None = None
|
||||
|
||||
|
||||
class _Host:
|
||||
"""What the fake host holds, and the commands it ran."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.login = "netadmin"
|
||||
self.accounts: dict[str, _Account] = {
|
||||
"netadmin": _Account(1000, "/home/netadmin", groups=["netadmin", "wheel"]),
|
||||
"daemon": _Account(1, "/usr/sbin"),
|
||||
}
|
||||
#: Path -> content, for the sudoers drop-ins and the key files.
|
||||
self.files: dict[str, str] = {}
|
||||
#: Users a rule outside the drop-in directory lets run everything.
|
||||
self.other_rules: set[str] = set()
|
||||
#: Whether sudo reads the drop-in directory at all.
|
||||
self.includes_dropins = True
|
||||
#: Commands that fail, by their first words ("as <command>" for one run as
|
||||
#: the person); and commands that succeed without doing anything.
|
||||
self.failing: set[str] = set()
|
||||
self.ignored: set[str] = set()
|
||||
self.ran: list[tuple[str, bool]] = []
|
||||
self.staged = 0
|
||||
|
||||
def is_admin(self, name: str) -> bool:
|
||||
rule = self.files.get(sudoers_rule_path(_Driver.SUDOERS_DIR, name))
|
||||
return name in self.other_rules or (self.includes_dropins and rule is not None)
|
||||
|
||||
def run(self, command: str, privileged: bool, stdin: bytes | None) -> CommandResult:
|
||||
self.ran.append((command, privileged))
|
||||
if stdin is not None:
|
||||
assert not privileged, "a privileged command takes no stdin"
|
||||
return self._stage(command, stdin)
|
||||
words = shlex.split(command)
|
||||
if " ".join(words[:2]) in self.failing or words[0] in self.failing:
|
||||
return CommandResult("", f"{words[0]}: failed", 1)
|
||||
if words[:3] == ["sudo", "-n", "-u"]:
|
||||
assert privileged, "only root changes to another user"
|
||||
return self._as_user(words[3], words[4:])
|
||||
handler = getattr(self, "_" + words[0].replace("-", "_"), None)
|
||||
assert handler is not None, f"unexpected command: {command}"
|
||||
return handler(words[1:], privileged)
|
||||
|
||||
# -- staging, as the login user ---------------------------------------------
|
||||
|
||||
def _stage(self, command: str, stdin: bytes) -> CommandResult:
|
||||
assert "mktemp" in command
|
||||
if "mktemp" in self.failing:
|
||||
return CommandResult("", "mktemp: No space left on device", 1)
|
||||
self.staged += 1
|
||||
path = f"/tmp/tmp.{self.staged}"
|
||||
self.files[path] = stdin.decode()
|
||||
return CommandResult(path, "", 0)
|
||||
|
||||
def _rm(self, args: list[str], privileged: bool) -> CommandResult:
|
||||
for path in args[args.index("--") + 1 :]:
|
||||
if path.startswith("/tmp/"):
|
||||
assert not privileged, "the staged file is the login user's"
|
||||
self.files.pop(path, None)
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
# -- the account database -------------------------------------------------------
|
||||
|
||||
def _getent(self, args: list[str], privileged: bool) -> CommandResult:
|
||||
assert args[0] == "passwd" and not privileged
|
||||
a = self.accounts.get(args[1])
|
||||
if a is None:
|
||||
return CommandResult("", "", 2)
|
||||
return CommandResult(f"{args[1]}:*:{a.uid}:{a.uid}::{a.home}:{a.shell}\n", "", 0)
|
||||
|
||||
def _id(self, args: list[str], privileged: bool) -> CommandResult:
|
||||
if args == ["-un"]:
|
||||
return CommandResult(f"{self.login}\n", "", 0)
|
||||
assert args[0] == "-Gn" and not privileged
|
||||
a = self.accounts.get(args[1])
|
||||
if a is None:
|
||||
return CommandResult("", f"id: {args[1]}: no such user", 1)
|
||||
return CommandResult(" ".join(a.groups) + "\n", "", 0)
|
||||
|
||||
def _sudo(self, args: list[str], privileged: bool) -> CommandResult:
|
||||
assert args[:2] == ["-l", "-U"] and privileged
|
||||
name = args[2]
|
||||
if self.is_admin(name):
|
||||
out = f"User {name} may run the following commands on host:\n (ALL) ALL\n"
|
||||
else:
|
||||
out = f"User {name} is not allowed to run sudo on host.\n"
|
||||
return CommandResult(out, "", 0)
|
||||
|
||||
def _visudo(self, args: list[str], privileged: bool) -> CommandResult:
|
||||
assert args[0] == "-cf" and privileged
|
||||
content = self.files[args[1]]
|
||||
ok = content.endswith(" ALL=(ALL) ALL\n") and "\n" not in content[:-1]
|
||||
return CommandResult("parsed OK" if ok else "syntax error", "", 0 if ok else 1)
|
||||
|
||||
def _install(self, args: list[str], privileged: bool) -> CommandResult:
|
||||
assert privileged
|
||||
source, target = args[args.index("--") + 1 :]
|
||||
assert target.startswith(_Driver.SUDOERS_DIR + "/"), "root installs only sudo rules"
|
||||
assert args[:6] == ["-m", "440", "-o", "root", "-g", _Driver.ROOT_GROUP]
|
||||
self.files[target] = self.files[source]
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
def _test(self, args: list[str], privileged: bool) -> CommandResult:
|
||||
assert args[0] == "-e"
|
||||
return CommandResult("", "", 0 if args[1] in self.files else 1)
|
||||
|
||||
# -- the person's own files, as that person ------------------------------------
|
||||
|
||||
def _as_user(self, name: str, words: list[str]) -> CommandResult:
|
||||
a = self.accounts[name]
|
||||
if a.locked:
|
||||
return CommandResult("", "sudo: account expired", 1)
|
||||
rest = words[words.index("--") + 1 :] if "--" in words else words[1:]
|
||||
if f"as {words[0]}" in self.failing:
|
||||
return CommandResult("", f"{words[0]}: Permission denied", 1)
|
||||
if f"as {words[0]}" in self.ignored:
|
||||
return CommandResult("", "", 0)
|
||||
assert all(p.startswith(a.home + "/") or p.startswith("/tmp/") for p in rest)
|
||||
if words[0] == "cat":
|
||||
return CommandResult(self.files.get(rest[0], ""), "", 0)
|
||||
if words[0] == "mkdir":
|
||||
return CommandResult("", "", 0)
|
||||
if words[0] == "install":
|
||||
assert words[1:3] == ["-m", "600"]
|
||||
self.files[rest[1]] = self.files[rest[0]]
|
||||
return CommandResult("", "", 0)
|
||||
if words[0] == "rm":
|
||||
for path in rest:
|
||||
self.files.pop(path, None)
|
||||
return CommandResult("", "", 0)
|
||||
raise AssertionError(f"unexpected command as {name}: {words}")
|
||||
|
||||
# -- the driver's own commands (stand-ins) -------------------------------------
|
||||
|
||||
def _mkuser(self, args: list[str], privileged: bool) -> CommandResult:
|
||||
assert privileged
|
||||
name, password = args[0], (args[1] if len(args) > 1 else None)
|
||||
uid = 1001 + len(self.accounts)
|
||||
self.accounts[name] = _Account(uid, f"/home/{name}", groups=[name], password=password)
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
def _openuser(self, args: list[str], privileged: bool) -> CommandResult:
|
||||
assert privileged
|
||||
a = self.accounts[args[0]]
|
||||
a.locked = False
|
||||
if len(args) > 1:
|
||||
a.password = args[1]
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
def _lockuser(self, args: list[str], privileged: bool) -> CommandResult:
|
||||
assert privileged
|
||||
self.accounts[args[0]].locked = "lockuser" not in self.ignored
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
def _islocked(self, args: list[str], privileged: bool) -> CommandResult:
|
||||
assert privileged
|
||||
return CommandResult("yes\n" if self.accounts[args[0]].locked else "no\n", "", 0)
|
||||
|
||||
def _leavegroup(self, args: list[str], privileged: bool) -> CommandResult:
|
||||
assert privileged
|
||||
self.accounts[args[0]].groups.remove(args[1])
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
|
||||
class _Driver(LocalAccountsMixin):
|
||||
ACCOUNT_SHELL = "/bin/sh"
|
||||
ACCOUNT_ADMIN_GROUPS = ("wheel", "sudo")
|
||||
SUDOERS_DIR = "/etc/sudoers.d"
|
||||
ROOT_GROUP = "wheel"
|
||||
|
||||
def __init__(self, host: _Host) -> None:
|
||||
self.host = host
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult:
|
||||
return self.host.run(command, privileged, stdin)
|
||||
|
||||
def _account_create(self, name: str, password_hash: str | None) -> list[list[str]]:
|
||||
return [["mkuser", name, *([password_hash] if password_hash else [])]]
|
||||
|
||||
def _account_open(
|
||||
self, name: str, password_hash: str | None, *, locked: bool
|
||||
) -> list[list[str]]:
|
||||
return [["openuser", name, *([password_hash] if password_hash else [])]]
|
||||
|
||||
def _account_lock(self, name: str, *, locked: bool) -> list[list[str]]:
|
||||
return [] if locked else [["lockuser", name]]
|
||||
|
||||
def _account_locked(self, name: str, passwd: list[str]) -> bool:
|
||||
result = self.run_command(shlex.join(["islocked", name]), privileged=True)
|
||||
return result.stdout.strip() == "yes"
|
||||
|
||||
def _account_leave_group(self, name: str, group: str, groups: list[str]) -> list[str]:
|
||||
return ["leavegroup", name, group]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def host() -> _Host:
|
||||
return _Host()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def driver(host: _Host) -> _Driver:
|
||||
return _Driver(host)
|
||||
|
||||
|
||||
def _root_commands(host: _Host) -> list[str]:
|
||||
return [c for c, privileged in host.ran if privileged]
|
||||
|
||||
|
||||
def _add_alice(host: _Host, *, locked: bool = False, keys: str = "") -> None:
|
||||
host.accounts["alice"] = _Account(
|
||||
1001, "/home/alice", groups=["alice", "wheel"], locked=locked, password=HASH
|
||||
)
|
||||
if keys:
|
||||
host.files["/home/alice/.ssh/authorized_keys"] = keys
|
||||
|
||||
|
||||
# -- the helpers ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_sudo_rule_names_the_account_and_asks_for_its_password() -> None:
|
||||
assert sudoers_rule("alice") == "alice ALL=(ALL) ALL\n"
|
||||
|
||||
|
||||
def test_the_rule_file_has_no_dot_sudo_would_skip() -> None:
|
||||
# sudo ignores a file in an included directory whose name holds a dot.
|
||||
path = sudoers_rule_path("/etc/sudoers.d", "a.lice")
|
||||
assert path.startswith("/etc/sudoers.d/")
|
||||
assert "." not in path.rsplit("/", 1)[1]
|
||||
assert sudoers_rule_path("/etc/sudoers.d", "a.lice") != sudoers_rule_path(
|
||||
"/etc/sudoers.d", "a_lice"
|
||||
)
|
||||
|
||||
|
||||
def test_both_key_files_sshd_reads_by_default() -> None:
|
||||
assert authorized_keys_paths("/home/alice") == (
|
||||
"/home/alice/.ssh/authorized_keys",
|
||||
"/home/alice/.ssh/authorized_keys2",
|
||||
)
|
||||
|
||||
|
||||
# -- reading --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_an_account_is_read_with_its_groups_lock_sudo_and_keys(
|
||||
host: _Host, driver: _Driver
|
||||
) -> None:
|
||||
_add_alice(host, keys=ALICE_KEY + "\n" + OWN_KEY + "\n")
|
||||
host.other_rules.add("alice")
|
||||
|
||||
[account] = driver.get_local_accounts(["alice"])
|
||||
|
||||
assert account == {
|
||||
"name": "alice",
|
||||
"uid": 1001,
|
||||
"home": "/home/alice",
|
||||
"shell": "/bin/sh",
|
||||
"groups": ["alice", "wheel"],
|
||||
"locked": False,
|
||||
"admin": True,
|
||||
"authorized_keys": [ALICE_KEY, OWN_KEY],
|
||||
}
|
||||
|
||||
|
||||
def test_an_account_that_is_not_there_is_left_out(driver: _Driver) -> None:
|
||||
assert driver.get_local_accounts(["bob"]) == []
|
||||
|
||||
|
||||
def test_a_locked_accounts_keys_that_cannot_be_read_are_unknown(
|
||||
host: _Host, driver: _Driver
|
||||
) -> None:
|
||||
_add_alice(host, locked=True, keys=ALICE_KEY + "\n")
|
||||
|
||||
[account] = driver.get_local_accounts(["alice"])
|
||||
|
||||
assert account["locked"] is True
|
||||
assert account["authorized_keys"] is None
|
||||
|
||||
|
||||
def test_an_account_without_a_key_file_has_no_keys(host: _Host, driver: _Driver) -> None:
|
||||
_add_alice(host)
|
||||
|
||||
[account] = driver.get_local_accounts(["alice"])
|
||||
|
||||
assert account["authorized_keys"] == []
|
||||
|
||||
|
||||
def test_a_failing_read_raises_rather_than_report_nothing(host: _Host, driver: _Driver) -> None:
|
||||
_add_alice(host)
|
||||
host.failing.add("sudo -l")
|
||||
|
||||
with pytest.raises(RuntimeError, match="alice"):
|
||||
driver.get_local_accounts(["alice"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["", "Alice", "1alice", "al ice", "a;b", "-alice", "a" * 33])
|
||||
def test_a_name_no_guest_takes_is_refused(driver: _Driver, name: str) -> None:
|
||||
with pytest.raises(ValueError, match="account name"):
|
||||
driver.get_local_accounts([name])
|
||||
|
||||
|
||||
# -- adding ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_new_account_gets_the_key_and_the_sudo_rule(host: _Host, driver: _Driver) -> None:
|
||||
result = driver.add_local_account("alice", ALICE_KEY, password_hash=HASH, admin=True)
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert [s["step"] for s in result["steps"]] == ["account", "sudo", "keys"]
|
||||
assert host.accounts["alice"].password == HASH
|
||||
assert host.files["/home/alice/.ssh/authorized_keys"] == ALICE_KEY + "\n"
|
||||
assert host.files["/etc/sudoers.d/80-account-alice"] == "alice ALL=(ALL) ALL\n"
|
||||
account = result["account"]
|
||||
assert account is not None
|
||||
assert account["admin"] is True and account["authorized_keys"] == [ALICE_KEY]
|
||||
|
||||
|
||||
def test_every_command_root_runs_is_one_fixed_command(host: _Host, driver: _Driver) -> None:
|
||||
driver.add_local_account("alice", ALICE_KEY, password_hash=HASH, admin=True)
|
||||
driver.lock_local_account("alice")
|
||||
|
||||
for command in _root_commands(host):
|
||||
assert not any(s in command for s in SHELL_SYNTAX), command
|
||||
|
||||
|
||||
def test_the_staged_files_are_removed_again(host: _Host, driver: _Driver) -> None:
|
||||
driver.add_local_account("alice", ALICE_KEY, password_hash=HASH, admin=True)
|
||||
|
||||
assert host.staged == 2
|
||||
assert not [p for p in host.files if p.startswith("/tmp/")]
|
||||
|
||||
|
||||
def test_an_existing_account_keeps_its_own_keys(host: _Host, driver: _Driver) -> None:
|
||||
_add_alice(host, keys=OWN_KEY + "\n")
|
||||
|
||||
result = driver.add_local_account("alice", ALICE_KEY)
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert host.files["/home/alice/.ssh/authorized_keys"] == f"{OWN_KEY}\n{ALICE_KEY}\n"
|
||||
|
||||
|
||||
def test_a_line_without_a_key_is_kept_and_not_taken_for_one(host: _Host, driver: _Driver) -> None:
|
||||
_add_alice(host, keys="# the laptop\n")
|
||||
|
||||
result = driver.add_local_account("alice", ALICE_KEY)
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert host.files["/home/alice/.ssh/authorized_keys"] == f"# the laptop\n{ALICE_KEY}\n"
|
||||
|
||||
|
||||
def test_a_key_already_there_is_not_written_again(host: _Host, driver: _Driver) -> None:
|
||||
# The same key with options in front and another comment is the same key.
|
||||
_add_alice(host, keys=f'from="10.0.0.0/8" {ALICE_KEY.rsplit(" ", 1)[0]} old\n')
|
||||
|
||||
result = driver.add_local_account("alice", ALICE_KEY)
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert host.staged == 0
|
||||
assert "already" in result["steps"][-1]["output"]
|
||||
|
||||
|
||||
def test_a_locked_account_is_opened_again(host: _Host, driver: _Driver) -> None:
|
||||
_add_alice(host, locked=True)
|
||||
|
||||
result = driver.add_local_account("alice", ALICE_KEY, password_hash=HASH)
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert host.accounts["alice"].locked is False
|
||||
assert result["account"] is not None and result["account"]["locked"] is False
|
||||
|
||||
|
||||
def test_without_sudo_the_rule_and_the_admin_groups_go(host: _Host, driver: _Driver) -> None:
|
||||
_add_alice(host)
|
||||
host.files["/etc/sudoers.d/80-account-alice"] = sudoers_rule("alice")
|
||||
|
||||
result = driver.add_local_account("alice", ALICE_KEY, admin=False)
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert "/etc/sudoers.d/80-account-alice" not in host.files
|
||||
assert host.accounts["alice"].groups == ["alice"]
|
||||
|
||||
|
||||
def test_sudo_another_rule_still_grants_fails_the_step(host: _Host, driver: _Driver) -> None:
|
||||
_add_alice(host)
|
||||
host.other_rules.add("alice")
|
||||
|
||||
result = driver.add_local_account("alice", ALICE_KEY, admin=False)
|
||||
|
||||
assert not result["success"]
|
||||
sudo = next(s for s in result["steps"] if s["step"] == "sudo")
|
||||
assert not sudo["ok"] and "another rule" in sudo["output"]
|
||||
# The key still went in: the steps after the account are independent.
|
||||
assert host.files["/home/alice/.ssh/authorized_keys"] == ALICE_KEY + "\n"
|
||||
|
||||
|
||||
def test_a_rule_sudo_does_not_read_fails_the_step(host: _Host, driver: _Driver) -> None:
|
||||
host.includes_dropins = False
|
||||
|
||||
result = driver.add_local_account("alice", ALICE_KEY, password_hash=HASH, admin=True)
|
||||
|
||||
sudo = next(s for s in result["steps"] if s["step"] == "sudo")
|
||||
assert not sudo["ok"] and "/etc/sudoers.d" in sudo["output"]
|
||||
|
||||
|
||||
def test_a_rule_visudo_rejects_is_not_installed(host: _Host, driver: _Driver) -> None:
|
||||
host.failing.add("visudo")
|
||||
|
||||
result = driver.add_local_account("alice", ALICE_KEY, password_hash=HASH, admin=True)
|
||||
|
||||
assert not result["success"]
|
||||
assert "/etc/sudoers.d/80-account-alice" not in host.files
|
||||
assert not [p for p in host.files if p.startswith("/tmp/")]
|
||||
|
||||
|
||||
def test_a_failed_create_stops_before_sudo_and_keys(host: _Host, driver: _Driver) -> None:
|
||||
host.failing.add("mkuser")
|
||||
|
||||
result = driver.add_local_account("alice", ALICE_KEY, admin=True)
|
||||
|
||||
assert not result["success"]
|
||||
assert [s["step"] for s in result["steps"]] == ["account"]
|
||||
assert result["account"] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"key",
|
||||
["", "not a key", ALICE_KEY + "\n" + OWN_KEY, "ssh-ed25519", "ssh-ed25519 AAAA;rm"],
|
||||
)
|
||||
def test_a_public_key_that_is_none_is_refused(driver: _Driver, key: str) -> None:
|
||||
with pytest.raises(ValueError, match="public key"):
|
||||
driver.add_local_account("alice", key)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("password_hash", ["secret", "$6$salt$ab cd", "$2b$10$" + "x" * 53])
|
||||
def test_a_password_hash_the_guest_does_not_take_is_refused(
|
||||
driver: _Driver, password_hash: str
|
||||
) -> None:
|
||||
# This driver takes SHA-512 crypt: neither plain text nor bcrypt.
|
||||
with pytest.raises(ValueError, match="password hash"):
|
||||
driver.add_local_account("alice", ALICE_KEY, password_hash=password_hash)
|
||||
|
||||
|
||||
def test_the_login_users_own_account_is_never_touched(host: _Host, driver: _Driver) -> None:
|
||||
for change in (
|
||||
lambda: driver.add_local_account("netadmin", ALICE_KEY),
|
||||
lambda: driver.lock_local_account("netadmin"),
|
||||
):
|
||||
with pytest.raises(ValueError, match="logs in"):
|
||||
change()
|
||||
assert _root_commands(host) == []
|
||||
|
||||
|
||||
def test_nothing_changes_when_the_login_user_cannot_be_told(host: _Host, driver: _Driver) -> None:
|
||||
_add_alice(host)
|
||||
host.login = ""
|
||||
|
||||
with pytest.raises(RuntimeError, match="logs in"):
|
||||
driver.lock_local_account("alice")
|
||||
assert _root_commands(host) == []
|
||||
|
||||
|
||||
def test_a_system_account_is_never_touched(host: _Host, driver: _Driver) -> None:
|
||||
with pytest.raises(ValueError, match="system account"):
|
||||
driver.lock_local_account("daemon")
|
||||
assert _root_commands(host) == []
|
||||
|
||||
|
||||
# -- locking --------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_locking_takes_keys_sudo_and_login_away(host: _Host, driver: _Driver) -> None:
|
||||
_add_alice(host, keys=ALICE_KEY + "\n" + OWN_KEY + "\n")
|
||||
host.files["/home/alice/.ssh/authorized_keys2"] = OWN_KEY + "\n"
|
||||
host.files["/etc/sudoers.d/80-account-alice"] = sudoers_rule("alice")
|
||||
|
||||
result = driver.lock_local_account("alice")
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert [s["step"] for s in result["steps"]] == ["keys", "lock", "sudo"]
|
||||
a = host.accounts["alice"]
|
||||
assert a.locked and a.groups == ["alice"] and a.password == HASH
|
||||
assert not [p for p in host.files if p.startswith("/home/alice/")]
|
||||
assert "/etc/sudoers.d/80-account-alice" not in host.files
|
||||
account = result["account"]
|
||||
assert account is not None and account["locked"] and not account["admin"]
|
||||
|
||||
|
||||
def test_a_rule_left_elsewhere_is_named_but_harmless_once_locked(
|
||||
host: _Host, driver: _Driver
|
||||
) -> None:
|
||||
_add_alice(host)
|
||||
host.other_rules.add("alice")
|
||||
|
||||
result = driver.lock_local_account("alice")
|
||||
|
||||
assert result["success"], result["output"]
|
||||
sudo = next(s for s in result["steps"] if s["step"] == "sudo")
|
||||
assert "another rule" in sudo["output"] and "locked" in sudo["output"]
|
||||
|
||||
|
||||
def test_the_lock_comes_even_when_the_keys_could_not_go(host: _Host, driver: _Driver) -> None:
|
||||
_add_alice(host, locked=True, keys=ALICE_KEY + "\n")
|
||||
|
||||
result = driver.lock_local_account("alice")
|
||||
|
||||
assert not result["success"]
|
||||
keys = next(s for s in result["steps"] if s["step"] == "keys")
|
||||
assert not keys["ok"]
|
||||
assert next(s for s in result["steps"] if s["step"] == "lock")["ok"]
|
||||
assert host.accounts["alice"].locked
|
||||
|
||||
|
||||
def test_locking_an_account_that_is_not_there_fails(driver: _Driver) -> None:
|
||||
result = driver.lock_local_account("bob")
|
||||
|
||||
assert not result["success"]
|
||||
assert "no account" in result["output"]
|
||||
assert result["account"] is None
|
||||
|
||||
|
||||
# -- what fails is said ---------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failing", ["getent", "id -Gn"])
|
||||
def test_an_account_that_cannot_be_read_raises(host: _Host, driver: _Driver, failing: str) -> None:
|
||||
_add_alice(host)
|
||||
host.failing.add(failing)
|
||||
|
||||
with pytest.raises(RuntimeError, match="alice"):
|
||||
driver.get_local_accounts(["alice"])
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("failing", "step", "said"),
|
||||
[
|
||||
("rm -f", "sudo", "80-account-alice"),
|
||||
("leavegroup", "sudo", "out of wheel"),
|
||||
("as cat", "keys", "cannot read"),
|
||||
("as install", "keys", "authorized_keys"),
|
||||
("mktemp", "keys", "cannot stage"),
|
||||
],
|
||||
)
|
||||
def test_a_step_that_fails_says_why(
|
||||
host: _Host, driver: _Driver, failing: str, step: str, said: str
|
||||
) -> None:
|
||||
_add_alice(host, keys=OWN_KEY + "\n")
|
||||
host.failing.add(failing)
|
||||
|
||||
result = driver.add_local_account("alice", ALICE_KEY)
|
||||
|
||||
failed = next(s for s in result["steps"] if s["step"] == step)
|
||||
assert not failed["ok"] and said in failed["output"]
|
||||
assert not result["success"]
|
||||
|
||||
|
||||
def test_a_rule_that_cannot_be_installed_fails_the_step(host: _Host, driver: _Driver) -> None:
|
||||
host.failing.add("install -m")
|
||||
|
||||
result = driver.add_local_account("alice", ALICE_KEY, password_hash=HASH, admin=True)
|
||||
|
||||
sudo = next(s for s in result["steps"] if s["step"] == "sudo")
|
||||
assert not sudo["ok"] and "80-account-alice" in sudo["output"]
|
||||
assert not [p for p in host.files if p.startswith("/tmp/")]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("failing", "ignored", "step", "said"),
|
||||
[
|
||||
({"lockuser"}, set(), "lock", "lockuser: failed"),
|
||||
(set(), {"lockuser"}, "lock", "still not locked"),
|
||||
({"as rm"}, set(), "keys", "cannot remove"),
|
||||
(set(), {"as rm"}, "keys", "still has keys"),
|
||||
],
|
||||
)
|
||||
def test_a_lock_that_did_not_take_says_so(
|
||||
host: _Host, driver: _Driver, failing: set[str], ignored: set[str], step: str, said: str
|
||||
) -> None:
|
||||
_add_alice(host, keys=ALICE_KEY + "\n")
|
||||
host.failing |= failing
|
||||
host.ignored |= ignored
|
||||
|
||||
result = driver.lock_local_account("alice")
|
||||
|
||||
failed = next(s for s in result["steps"] if s["step"] == step)
|
||||
assert not failed["ok"] and said in failed["output"]
|
||||
assert not result["success"]
|
||||
|
||||
|
||||
def test_an_account_that_cannot_be_read_back_is_said(host: _Host, driver: _Driver) -> None:
|
||||
_add_alice(host)
|
||||
host.failing.add("sudo -l")
|
||||
|
||||
result = driver.lock_local_account("alice")
|
||||
|
||||
assert result["account"] is None
|
||||
assert "[read back] cannot ask sudo about alice" in result["output"]
|
||||
Reference in new issue
Block a user