feat: personal accounts the way OMV's web UI makes them (NetOrk/netork#1793) #12
No files matched your search
@@ -7,6 +7,18 @@ All notable changes to this driver. The format follows
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- Personal accounts the way OMV's web UI makes them (NetOrk/netork#1793), on top of
|
||||
napalm-linux's `get_local_accounts()`, `add_local_account()` and `lock_local_account()`.
|
||||
OMV's sshd lets in only `root` and `_ssh`, and OMV keeps a user's keys in its own
|
||||
database, deploying them to `/var/lib/openmediavault/ssh/authorized_keys/<user>`. So a
|
||||
new account is made by `UserMgmt.setUser` in `_ssh`, an account made outside OMV joins
|
||||
`_ssh` when it is opened, and keys are added and removed through `setUser`. Each call
|
||||
applies the modules it made dirty (`postfix`, `ssh`) and nothing else: changes left
|
||||
pending in the web UI stay pending. `setUser` takes a plain password, which netOrk does
|
||||
not have, so the hash is set with `usermod -p`. Like the web UI, `setUser` gives the
|
||||
account OMV's primary group `users`. Checked on a fresh OMV 8 (Debian 13) with the real
|
||||
driver over SSH. Requires the napalm-device-types and napalm-linux releases with
|
||||
personal accounts.
|
||||
- `set_hostname()` the way OMV's web UI renames the NAS: `Network.setGeneralSettings`
|
||||
(an FQDN sets the domain too, a bare name keeps it), then `Config.applyChanges` for the
|
||||
modules the rename made dirty plus the hostname modules already dirty. Changes left
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
"""Personal accounts on OpenMediaVault, the way its web UI makes them (NetOrk/netork#1793).
|
||||
|
||||
napalm-linux adds and locks accounts with shadow-utils and puts keys in
|
||||
``~/.ssh``. OMV needs two things more. Its sshd lets in only ``root`` and the
|
||||
``_ssh`` group (``AllowGroups root _ssh``). And it keeps a user's keys in its
|
||||
own database, from which the ``ssh`` module deploys them to
|
||||
:data:`OMV_KEYS_DIR`, a directory the user cannot write to.
|
||||
|
||||
So an account is made by ``UserMgmt.setUser`` in ``_ssh``, and its keys go
|
||||
through ``setUser`` too. Afterwards only the modules that change made dirty are
|
||||
applied: changes left pending in the web UI stay pending. ``setUser`` takes a
|
||||
plain password, and netOrk holds only the hash, so the hash is set with
|
||||
``usermod -p``; OMV keeps no password of its own. The lock is napalm-linux's,
|
||||
an expiry, which OMV leaves alone. Like the web UI, ``setUser`` gives an
|
||||
account OMV's primary group ``users``, one made outside OMV too.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types import LocalAccountsMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from napalm_device_types.models import FixStepOutcomeDict
|
||||
|
||||
#: Where OMV's ``ssh`` module writes each user's keys, one file per user.
|
||||
OMV_KEYS_DIR = "/var/lib/openmediavault/ssh/authorized_keys"
|
||||
#: The group OMV's sshd lets in.
|
||||
SSH_GROUP = "_ssh"
|
||||
#: ``setUser``'s password for "leave it as it is" (the hash is set apart); not a password.
|
||||
_KEEP_PASSWORD = "" # nosec B105
|
||||
#: What ``setUser`` needs besides the keys, as ``getUser`` returns it.
|
||||
_USER_FIELDS: dict[str, Any] = {
|
||||
"groups": [],
|
||||
"email": "",
|
||||
"disallowusermod": False,
|
||||
"comment": "",
|
||||
"shell": "",
|
||||
}
|
||||
|
||||
|
||||
def rfc4716_blob(text: str) -> str | None:
|
||||
"""The base64 of a public key, in OMV's RFC 4716 form or OpenSSH's one line."""
|
||||
lines = [line.strip() for line in text.strip().splitlines()]
|
||||
if lines and lines[0].startswith("---- BEGIN SSH2 PUBLIC KEY"):
|
||||
body: list[str] = []
|
||||
header = False
|
||||
for line in lines[1:]:
|
||||
if line.startswith("---- END SSH2 PUBLIC KEY"):
|
||||
return "".join(body) or None
|
||||
if header or ":" in line:
|
||||
header = line.endswith("\\") # a header continues on the next line
|
||||
continue
|
||||
body.append(line)
|
||||
return None
|
||||
words = text.split()
|
||||
if len(words) >= 2 and words[0].startswith(("ssh-", "ecdsa-", "sk-")):
|
||||
return words[1]
|
||||
return None
|
||||
|
||||
|
||||
def _holds(keys: list[str] | None, blob: str | None) -> bool:
|
||||
return blob is not None and any(rfc4716_blob(line) == blob for line in keys or [])
|
||||
|
||||
|
||||
class OmvLocalAccountsMixin(LocalAccountsMixin):
|
||||
"""napalm-linux's accounts, made and keyed through OMV's own database."""
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def _omv_rpc(
|
||||
self,
|
||||
service: str,
|
||||
method: str,
|
||||
params: dict[str, Any] | None = None,
|
||||
timeout: float = 60,
|
||||
) -> Any: ...
|
||||
|
||||
def _omv_dirty_modules(self) -> list[str]: ...
|
||||
|
||||
def _account_create(self, name: str, password_hash: str | None) -> list[list[str]]:
|
||||
"""Make *name* through ``setUser`` right away, so what it dirties is applied with it.
|
||||
|
||||
What is left is the password hash, for ``usermod``.
|
||||
|
||||
:raises RuntimeError: when OMV refuses.
|
||||
"""
|
||||
self._omv_save_user(
|
||||
{
|
||||
"name": name,
|
||||
"groups": [SSH_GROUP],
|
||||
"password": _KEEP_PASSWORD,
|
||||
"email": "",
|
||||
"disallowusermod": False,
|
||||
"sshpubkeys": [],
|
||||
"shell": self.ACCOUNT_SHELL,
|
||||
"comment": "",
|
||||
}
|
||||
)
|
||||
return [["usermod", "-p", password_hash, name]] if password_hash else []
|
||||
|
||||
def _account_open(
|
||||
self, name: str, password_hash: str | None, *, locked: bool
|
||||
) -> list[list[str]]:
|
||||
# A user made outside the web UI is not in _ssh: sshd would refuse it.
|
||||
opened = super()._account_open(name, password_hash, locked=locked)
|
||||
return [*opened, ["gpasswd", "-a", name, SSH_GROUP]]
|
||||
|
||||
def _account_key_files(self, name: str, home: str) -> tuple[str, ...]:
|
||||
return (*super()._account_key_files(name, home), f"{OMV_KEYS_DIR}/{name}")
|
||||
|
||||
def _account_add_key(self, name: str, home: str, public_key: str) -> FixStepOutcomeDict:
|
||||
blob = rfc4716_blob(public_key)
|
||||
keys = self._account_read_keys(name, home)
|
||||
if keys is None:
|
||||
return {"ok": False, "output": f"cannot read the key files of {name}"}
|
||||
if _holds(keys, blob):
|
||||
return {"ok": True, "output": f"the key is already one {name} logs in with"}
|
||||
user = self._omv_rpc("UserMgmt", "getUser", {"name": name})
|
||||
stored = list(user.get("sshpubkeys") or [])
|
||||
if not _holds(stored, blob):
|
||||
stored.append(public_key.strip())
|
||||
applied = self._omv_set_keys(user, stored)
|
||||
if not _holds(self._account_read_keys(name, home), blob):
|
||||
where = f"{OMV_KEYS_DIR}/{name}"
|
||||
return {"ok": False, "output": f"the key is in OMV's database, not deployed to {where}"}
|
||||
return {"ok": True, "output": f"key added through OMV ({applied})"}
|
||||
|
||||
def _account_remove_keys(self, name: str, home: str) -> FixStepOutcomeDict:
|
||||
user = self._omv_rpc("UserMgmt", "getUser", {"name": name})
|
||||
said = ""
|
||||
if user.get("sshpubkeys"):
|
||||
said = f"OMV's keys of {name} removed ({self._omv_set_keys(user, [])})\n"
|
||||
outcome = super()._account_remove_keys(name, home)
|
||||
return {"ok": outcome["ok"], "output": said + outcome["output"]}
|
||||
|
||||
def _omv_set_keys(self, user: dict[str, Any], keys: list[str]) -> str:
|
||||
"""Give *user* *keys* in OMV's database and deploy them; what was applied.
|
||||
|
||||
:raises RuntimeError: when OMV refuses.
|
||||
"""
|
||||
params = {field: user.get(field, default) for field, default in _USER_FIELDS.items()}
|
||||
params.update({"name": user["name"], "password": _KEEP_PASSWORD, "sshpubkeys": keys})
|
||||
return self._omv_save_user(params)
|
||||
|
||||
def _omv_save_user(self, params: dict[str, Any]) -> str:
|
||||
"""``setUser`` with *params*, then apply what that made dirty; what was applied.
|
||||
|
||||
Modules dirty before stay pending, ``ssh`` aside: the keys need it.
|
||||
|
||||
:raises RuntimeError: when OMV refuses.
|
||||
"""
|
||||
before = set(self._omv_dirty_modules())
|
||||
self._omv_rpc("UserMgmt", "setUser", params)
|
||||
after = set(self._omv_dirty_modules())
|
||||
modules = sorted((after - before) | (after & {"ssh"}))
|
||||
if modules:
|
||||
self._omv_rpc("Config", "applyChanges", {"modules": modules, "force": False}, 600)
|
||||
return ", ".join(modules) or "nothing to apply"
|
||||
@@ -36,6 +36,8 @@ from napalm_device_types.models import (
|
||||
)
|
||||
from napalm_linux.linux import LinuxDriver
|
||||
|
||||
from napalm_openmediavault._local_accounts import OmvLocalAccountsMixin
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: One label of a hostname (RFC 1123); OMV's own schema asks the same.
|
||||
@@ -48,7 +50,7 @@ _HOSTNAME_MODULES = frozenset(
|
||||
_DIRTY_MODULES = "/var/lib/openmediavault/dirtymodules.json"
|
||||
|
||||
|
||||
class OpenMediaVaultDriver(StorageDriver, LinuxDriver):
|
||||
class OpenMediaVaultDriver(OmvLocalAccountsMixin, StorageDriver, LinuxDriver):
|
||||
"""NAPALM driver for OpenMediaVault NAS systems.
|
||||
|
||||
Declares both roles it fills: a NAS built on Debian. Storage comes first,
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
"""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/<user>``. 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"
|
||||
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)
|
||||
raise AssertionError(command)
|
||||
|
||||
|
||||
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
|
||||
Reference in new issue
Block a user