driver / standard (pull_request) Successful in 18s
driver / lint (pull_request) Successful in 16s
driver / types (pull_request) Successful in 1m19s
driver / test (3.12) (pull_request) Successful in 1m12s
driver / test (3.13) (pull_request) Successful in 1m9s
driver / lowest (pull_request) Successful in 33s
driver / build (pull_request) Successful in 33s
driver / security (pull_request) Successful in 1m30s
CI / driver (pull_request) Successful in 3m16s
driver / publish (pull_request) Skipped
The RFC 4716 body moves into _rfc4716_body; rfc4716_blob only tells the two key forms apart. main's ratchet job failed on complexity 11.
166 lines
6.7 KiB
Python
166 lines
6.7 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.
|
|
"""
|
|
|
|
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_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"
|