Files
napalm-openmediavault/napalm_openmediavault/_local_accounts.py
T
Christian Manivong ed083df018
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 1m40s
driver / test (3.12) (pull_request) Successful in 1m44s
driver / lowest (pull_request) Successful in 38s
driver / test (3.13) (pull_request) Successful in 1m50s
driver / build (pull_request) Successful in 35s
driver / security (pull_request) Successful in 1m15s
CI / driver (pull_request) Successful in 3m29s
driver / publish (pull_request) Skipped
feat(accounts): take replaced and deleted keys out of OMV's database
napalm-device-types 4.28.0 lets add_local_account remove the old keys
(replaces) and adds remove_local_account_keys. OMV keeps a user's keys
in its own database and deploys them where the person cannot write, so
the mixin's key files alone would leave the old key deployed. The keys
go through UserMgmt.setUser, applying only what that made dirty, and
then out of ~/.ssh. Clearing the password is napalm-linux 0.17.0's.

See NetOrk/netork#2013
2026-11-04 11:48:52 +01:00

188 lines
8.0 KiB
Python

"""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.
A key the person replaced or deleted (NetOrk/netork#2013) goes from OMV's
database the same way, and from ``~/.ssh`` as napalm-linux takes it out; the
other keys stay. A password removed is napalm-linux's ``usermod -p '*'``.
"""
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"):
return _rfc4716_body(lines[1:])
words = text.split()
if len(words) >= 2 and words[0].startswith(("ssh-", "ecdsa-", "sk-")):
return words[1]
return None
def _rfc4716_body(lines: list[str]) -> str | None:
"""The base64 between the headers and the END line; None without an END line."""
body: list[str] = []
header = False
for line in lines:
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
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_create_with_uid(self, name: str, uid: int) -> list[list[str]]:
"""Not on OMV yet (NetOrk/netork#1817): its keys go through ``UserMgmt``, which
knows only the users it made, and whether ``setUser`` takes a uid is untested."""
raise NotImplementedError
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 _account_drop_keys(self, name: str, home: str, keys: list[str]) -> FixStepOutcomeDict:
"""*keys* out of OMV's database, deployed, then out of ``~/.ssh``; the others stay."""
blobs = {rfc4716_blob(key) for key in keys}
user = self._omv_rpc("UserMgmt", "getUser", {"name": name})
stored = list(user.get("sshpubkeys") or [])
kept = [key for key in stored if rfc4716_blob(key) not in blobs]
said = ""
if len(kept) != len(stored):
applied = self._omv_set_keys(user, kept)
said = f"{len(stored) - len(kept)} removed from OMV's keys of {name} ({applied})\n"
outcome = super()._account_drop_keys(name, home, keys)
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"