"""Personal accounts on OpenMediaVault, the way its web UI makes them (NetOrk/netork#1793). napalm-linux adds and locks accounts with shadow-utils and keys in ``~/.ssh``. On OMV that is not enough: sshd lets in only ``root`` and the ``_ssh`` group, and a user's keys live in OMV's database, which the ``ssh`` module deploys to ``/var/lib/openmediavault/ssh/authorized_keys/``. So the account is made through ``UserMgmt.setUser``, the keys go through it as well, and only the modules that change made dirty are applied. """ from __future__ import annotations import json import shlex import pytest from napalm_device_types import CommandResult from napalm_openmediavault._local_accounts import OMV_KEYS_DIR, rfc4716_blob from napalm_openmediavault.openmediavault import OpenMediaVaultDriver ALICE_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAlice alice@laptop" #: The key Alice had before, on the laptop she lost. OLD_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOld alice@lost-laptop" OWN_KEY = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQOwn own@desktop" HASH = "$6$salt$" + "x" * 86 def _rfc4716(key: str) -> str: """*key* as OMV stores it.""" kind, blob, comment = key.split(" ", 2) lines = [blob[i : i + 70] for i in range(0, len(blob), 70)] return "\n".join( [ "---- BEGIN SSH2 PUBLIC KEY ----", f'Comment: "{comment}"', *lines, "---- END SSH2 PUBLIC KEY ----", ] ) class Omv: """omv-rpc and the dirty-modules file, as ``_sudo_status`` sees them.""" def __init__(self, *, dirty=("apt",), deploys=True): self.users: dict[str, dict] = { "alice": { "name": "alice", "groups": ["users", "_ssh"], "email": "alice@example.net", "disallowusermod": False, "comment": "Alice", "shell": "/bin/bash", "sshpubkeys": [_rfc4716(OWN_KEY)], } } #: What the ssh module last wrote, per user: OpenSSH lines. self.deployed: dict[str, list[str]] = {"alice": [OWN_KEY]} self.dirty = list(dirty) self.deploys = deploys self.calls: list[tuple[str, object]] = [] def __call__(self, command: str, read_timeout: float = 100) -> tuple[str, int | None]: if command.startswith("cat /var/lib/openmediavault/dirtymodules.json"): return json.dumps(self.dirty), 0 argv = shlex.split(command) assert argv[:3] == ["omv-rpc", "-u", "admin"], command method = f"{argv[3]}.{argv[4]}" params = json.loads(argv[5]) if len(argv) > 5 else None self.calls.append((method, params)) if method == "UserMgmt.getUser": return json.dumps(self.users[params["name"]]), 0 if method == "UserMgmt.setUser": assert params["password"] == "", "OMV takes the plain password: none is sent" self.users[params["name"]] = { **params, "sshpubkeys": [ k if k.startswith("----") else _rfc4716(k) for k in params["sshpubkeys"] ], } # As OMV 8 does: the user's mail alias and keys are to be deployed. self.dirty += [m for m in ("postfix", "ssh") if m not in self.dirty] return json.dumps(params), 0 if method == "Config.applyChanges": if "ssh" in params["modules"] and self.deploys: for name, user in self.users.items(): self.deployed[name] = [_openssh(k) for k in user["sshpubkeys"]] self.dirty = [m for m in self.dirty if m not in params["modules"]] return "null", 0 raise AssertionError(command) def params(self, method: str) -> list: return [p for m, p in self.calls if m == method] def _openssh(rfc: str) -> str: blob = rfc4716_blob(rfc) kind = "ssh-ed25519" if "ZDI1NTE5" in (blob or "") else "ssh-rsa" return f"{kind} {blob}" class _Driver(OpenMediaVaultDriver): """OMV's own calls go to *omv*; the key files sshd reads come from it too.""" def __init__(self, omv: Omv, home_keys: list[str] | None = None) -> None: super().__init__("nas", "netadmin", "p") self.omv = omv self.home_keys = home_keys if home_keys is not None else [] self.ran: list[tuple[str, bool]] = [] def _sudo_status(self, command: str, read_timeout: float = 100) -> tuple[str, int | None]: return self.omv(command, read_timeout) def run_command(self, command, *, privileged=False, timeout=60, stdin=None): self.ran.append((command, privileged)) argv = shlex.split(command) if argv[:2] == ["test", "-e"]: path = argv[2] there = path.startswith(OMV_KEYS_DIR) and path.rsplit("/", 1)[1] in self.omv.deployed there = there or (path.endswith("/.ssh/authorized_keys") and bool(self.home_keys)) return CommandResult("", "", 0 if there else 1) if argv[:3] == ["sudo", "-n", "-u"] and argv[4] == "cat": path = argv[-1] if path.startswith(OMV_KEYS_DIR): lines = self.omv.deployed[path.rsplit("/", 1)[1]] else: lines = self.home_keys return CommandResult("".join(f"{line}\n" for line in lines), "", 0) if argv[:3] == ["sudo", "-n", "-u"] and argv[4] == "rm": self.home_keys = [] return CommandResult("", "", 0) return self._write_home_keys(argv, stdin) def _write_home_keys(self, argv: list[str], stdin: bytes | None) -> CommandResult: """Staging a key file as the login user, and installing it as the person.""" if stdin is not None: self.staged = stdin.decode() return CommandResult("/tmp/tmp.1", "", 0) if argv[:3] == ["sudo", "-n", "-u"] and argv[4] == "mkdir": return CommandResult("", "", 0) if argv[:3] == ["sudo", "-n", "-u"] and argv[4] == "install": assert argv[-1] == "/home/alice/.ssh/authorized_keys", "only ~/.ssh is written" self.home_keys = self.staged.splitlines() return CommandResult("", "", 0) if argv[:3] == ["rm", "-f", "--"] and argv[3].startswith("/tmp/"): return CommandResult("", "", 0) raise AssertionError(shlex.join(argv)) def test_omv_offers_personal_accounts_of_its_own() -> None: assert callable(getattr(OpenMediaVaultDriver, "add_local_account", None)) assert callable(getattr(OpenMediaVaultDriver, "lock_local_account", None)) assert callable(getattr(OpenMediaVaultDriver, "get_local_accounts", None)) def test_the_key_file_omv_deploys_is_read_too() -> None: files = _Driver(Omv())._account_key_files("alice", "/home/alice") assert files[-1] == f"{OMV_KEYS_DIR}/alice" assert "/home/alice/.ssh/authorized_keys" in files def test_a_new_account_is_made_by_omv_in_its_ssh_group() -> None: omv = Omv() commands = _Driver(omv)._account_create("bob", HASH) [params] = omv.params("UserMgmt.setUser") assert params["name"] == "bob" and params["groups"] == ["_ssh"] # OMV hashes a plain password itself; netOrk has the hash only. assert params["password"] == "" and params["sshpubkeys"] == [] assert commands == [["usermod", "-p", HASH, "bob"]] def test_making_an_account_applies_what_it_made_dirty_and_nothing_else() -> None: omv = Omv() _Driver(omv)._account_create("bob", None) assert omv.params("Config.applyChanges") == [{"modules": ["postfix", "ssh"], "force": False}] assert omv.dirty == ["apt"] def test_without_a_hash_no_password_is_set() -> None: assert _Driver(Omv())._account_create("bob", None) == [] def test_opening_again_puts_the_account_back_into_ssh() -> None: commands = _Driver(Omv())._account_open("alice", HASH, locked=True) assert commands[-1] == ["gpasswd", "-a", "alice", "_ssh"] assert ["usermod", "-e", "", "-p", HASH, "alice"] in commands def test_a_key_goes_into_omvs_database_and_is_deployed() -> None: omv = Omv() outcome = _Driver(omv)._account_add_key("alice", "/home/alice", ALICE_KEY) assert outcome["ok"], outcome["output"] [params] = omv.params("UserMgmt.setUser") assert params["sshpubkeys"] == [_rfc4716(OWN_KEY), ALICE_KEY] # Everything else the user had stays as it was. assert params["email"] == "alice@example.net" and params["groups"] == ["users", "_ssh"] assert params["comment"] == "Alice" and params["shell"] == "/bin/bash" # Only what the change made dirty is applied: the pending apt change stays. assert omv.params("Config.applyChanges") == [{"modules": ["postfix", "ssh"], "force": False}] assert omv.dirty == ["apt"] assert any("AAAAC3NzaC1lZDI1NTE5AAAAIAlice" in k for k in omv.deployed["alice"]) def test_a_key_already_there_is_not_added_again() -> None: omv = Omv() outcome = _Driver(omv)._account_add_key("alice", "/home/alice", OWN_KEY) assert outcome["ok"] and "already" in outcome["output"] assert omv.params("UserMgmt.setUser") == [] def test_a_key_omv_does_not_deploy_fails_the_step() -> None: outcome = _Driver(Omv(deploys=False))._account_add_key("alice", "/home/alice", ALICE_KEY) assert not outcome["ok"] assert "not deployed" in outcome["output"] def test_locking_empties_omvs_keys_and_the_home_ones() -> None: omv = Omv() driver = _Driver(omv, home_keys=[ALICE_KEY]) outcome = driver._account_remove_keys("alice", "/home/alice") assert outcome["ok"], outcome["output"] [params] = omv.params("UserMgmt.setUser") assert params["sshpubkeys"] == [] assert omv.deployed["alice"] == [] and driver.home_keys == [] def test_an_account_omv_holds_no_key_for_is_not_written() -> None: omv = Omv() omv.users["alice"]["sshpubkeys"] = [] omv.deployed["alice"] = [] outcome = _Driver(omv, home_keys=[ALICE_KEY])._account_remove_keys("alice", "/home/alice") assert outcome["ok"], outcome["output"] assert omv.params("UserMgmt.setUser") == [] @pytest.mark.parametrize( ("text", "blob"), [ (_rfc4716(ALICE_KEY), "AAAAC3NzaC1lZDI1NTE5AAAAIAlice"), ( '---- BEGIN SSH2 PUBLIC KEY ----\nComment: "a long \\\ncomment"\nAAAA\nBBBB\n' "---- END SSH2 PUBLIC KEY ----", "AAAABBBB", ), (ALICE_KEY, "AAAAC3NzaC1lZDI1NTE5AAAAIAlice"), ("nonsense", None), ], ) def test_the_key_omv_stores_is_read_back_as_its_base64(text: str, blob: str | None) -> None: assert rfc4716_blob(text) == blob def test_netorks_own_account_with_a_fixed_uid_is_not_made_on_omv_yet() -> None: """Its keys go through UserMgmt, which knows only the users it made (NetOrk/netork#1817).""" import pytest with pytest.raises(NotImplementedError): _Driver(Omv())._account_create_with_uid("netork", 900) # -- what a person changes follows them (NetOrk/netork#2013) ---------------------------- def test_a_replaced_key_goes_from_omvs_database_and_the_others_stay() -> None: omv = Omv() omv.users["alice"]["sshpubkeys"] = [_rfc4716(OLD_KEY), _rfc4716(OWN_KEY)] omv.deployed["alice"] = [OLD_KEY, OWN_KEY] outcome = _Driver(omv)._account_drop_keys("alice", "/home/alice", [OLD_KEY]) assert outcome["ok"], outcome["output"] [params] = omv.params("UserMgmt.setUser") assert params["sshpubkeys"] == [_rfc4716(OWN_KEY)] # Everything else the user had stays as it was, and only what it dirtied is applied. assert params["email"] == "alice@example.net" and params["groups"] == ["users", "_ssh"] assert omv.params("Config.applyChanges") == [{"modules": ["postfix", "ssh"], "force": False}] assert [rfc4716_blob(k) for k in omv.deployed["alice"]] == [rfc4716_blob(OWN_KEY)] assert "removed from OMV's keys" in outcome["output"] def test_a_replaced_key_in_the_home_goes_too_as_the_person() -> None: omv = Omv() driver = _Driver(omv, home_keys=[OLD_KEY, ALICE_KEY]) outcome = driver._account_drop_keys("alice", "/home/alice", [OLD_KEY]) assert outcome["ok"], outcome["output"] assert driver.home_keys == [ALICE_KEY] # The key was not in OMV's database: nothing is saved or applied there. assert omv.params("UserMgmt.setUser") == [] assert omv.params("Config.applyChanges") == [] def test_a_removed_key_omv_does_not_deploy_away_fails_the_step() -> None: omv = Omv(deploys=False) outcome = _Driver(omv)._account_drop_keys("alice", "/home/alice", [OWN_KEY]) assert not outcome["ok"] assert "still has" in outcome["output"] def test_clearing_the_password_is_napalm_linuxs_and_omv_sends_none() -> None: # OMV keeps no password of its own: setUser is never given one (Omv asserts it). assert _Driver(Omv())._account_clear_password("alice") == [["usermod", "-p", "*", "alice"]] class _Account(_Driver): """The account's reads too, for a whole run through the mixin.""" def run_command(self, command, *, privileged=False, timeout=60, stdin=None): answers = { "id -un": "netadmin\n", "getent passwd alice": "alice:x:1001:100::/home/alice:/bin/bash\n", "getent shadow alice": "alice:$6$old:20000:0:99999:7:::\n", "id -Gn alice": "users _ssh\n", "sudo -l -U alice": "User alice is not allowed to run sudo on nas.\n", } if command in answers: self.ran.append((command, privileged)) return CommandResult(answers[command], "", 0) if shlex.split(command)[0] in {"usermod", "gpasswd", "rm"} and privileged: self.ran.append((command, privileged)) return CommandResult("", "", 0) return super().run_command(command, privileged=privileged, timeout=timeout, stdin=stdin) def test_a_person_who_replaced_a_key_and_removed_the_password_gets_both_on_omv() -> None: omv = Omv() omv.users["alice"]["sshpubkeys"] = [_rfc4716(OLD_KEY), _rfc4716(OWN_KEY)] omv.deployed["alice"] = [OLD_KEY, OWN_KEY] driver = _Account(omv) result = driver.add_local_account("alice", ALICE_KEY, replaces=[OLD_KEY], clear_password=True) assert result["success"], result["output"] assert ("usermod -p '*' alice", True) in driver.ran assert omv.users["alice"]["sshpubkeys"] == [_rfc4716(OWN_KEY), _rfc4716(ALICE_KEY)] account = result["account"] assert account is not None assert [rfc4716_blob(k) for k in account["authorized_keys"] or []] == [ rfc4716_blob(OWN_KEY), rfc4716_blob(ALICE_KEY), ] def test_a_deleted_key_goes_through_omv_and_the_account_stays_open() -> None: omv = Omv() driver = _Account(omv) result = driver.remove_local_account_keys("alice", [OWN_KEY]) assert result["success"], result["output"] assert omv.users["alice"]["sshpubkeys"] == [] assert not [c for c, _ in driver.ran if c.startswith(("usermod", "gpasswd"))] def test_a_deleted_key_takes_the_password_and_sudo_with_it_on_omv() -> None: """NetOrk/netork#2033: the key goes through OMV, the password with usermod as on napalm-linux, and sudo; the account stays open and in _ssh.""" omv = Omv() driver = _Account(omv) result = driver.remove_local_account_keys("alice", [OWN_KEY], clear_password=True) assert result["success"], result["output"] assert [s["step"] for s in result["steps"]] == ["keys", "password", "sudo"] assert omv.users["alice"]["sshpubkeys"] == [] assert ("usermod -p '*' alice", True) in driver.ran assert ("rm -f -- /etc/sudoers.d/80-account-alice", True) in driver.ran assert not [c for c, _ in driver.ran if c.startswith("gpasswd -d alice _ssh")]