feat: netOrk's own account through the current login (NetOrk/netork#1817) #67

Merged
christianmanivong merged 3 commits from feature/system-user-1817 into main 2026-11-01 12:39:42 +00:00
3 changed files with 488 additions and 14 deletions

No files matched your search

+10
View File
@@ -14,6 +14,16 @@ recorded here; their history is the git log.
3.12 venv no longer has.
### Added
- `LocalAccountsMixin.add_service_account(name, public_key)`: netOrk's own account,
created through the account the driver logs in with today. It takes a key and no
password, and a rule of its own in `85-service-<name>` lets it run everything as
root without a password (`NOPASSWD: ALL`, checked with `visudo` and `sudo -l`). An
account that is there is opened again and keeps its other keys; root is refused
(NetOrk/netork#1817). With `uid=`, a new account gets that uid once no other account
has it; one that is there keeps its own. A driver supplies
`_account_create_with_uid`. An account that is there and cannot log in (`nologin`,
`false`) is another service's, such as a netOrk satellite's `netork`, and is refused
before anything changes.
- `LocalAccountsMixin` (`napalm_device_types.local_accounts`): personal login accounts
on a host. `get_local_accounts(names)` reads them back (groups, lock, sudo, key
files), `add_local_account(name, public_key, password_hash=, admin=)` creates or
+177 -14
View File
@@ -31,6 +31,12 @@ afterwards shows whether it took effect. A rule elsewhere -- cloud-init's
**The login user's own account and system accounts are never touched**:
locking the first would lock the caller out.
**netOrk's own account** (``add_service_account``) is made the same way,
through the account it logs in with today: a key and no password, and a rule
of its own -- ``<name> ALL=(ALL) NOPASSWD: ALL`` in ``85-service-<name>`` --
so it gains root without a password that could end up anywhere. Once netOrk
logs in with it, the person's account it used before is one like any other.
"""
from __future__ import annotations
@@ -68,9 +74,19 @@ _KEY_BLOB_RE = re.compile(r"[A-Za-z0-9+/]+={0,3}")
#: Before the rule's file name; after cloud-init's ``90-`` it would win, so before it.
SUDOERS_FILE_PREFIX = "80-account-"
#: Before the file name of netOrk's own account's rule; after a person's, before cloud-init's.
SERVICE_SUDOERS_FILE_PREFIX = "85-service-"
#: A line of ``sudo -l`` that lets the account run every command as root.
_RUN_ALL_RE = re.compile(r"^\s*\(ALL(\s*:\s*ALL)?\)\s+([A-Z_]+:\s*)*ALL\s*$", re.MULTILINE)
#: The same, without a password.
_RUN_ALL_NOPASSWD_RE = re.compile(
r"^\s*\(ALL(\s*:\s*ALL)?\)\s+([A-Z_]+:\s*)*NOPASSWD:\s*([A-Z_]+:\s*)*ALL\s*$",
re.MULTILINE,
)
#: Login shells that refuse every login: an account with one belongs to a service.
_NO_LOGIN_SHELLS = frozenset({"nologin", "false"})
#: Stages stdin as a file anyone may read -- the person reads the key file
#: from it -- and prints its path. The content is a public key or a sudo rule.
@@ -114,8 +130,21 @@ def sudoers_rule_path(directory: str, name: str) -> str:
sudo skips a file whose name holds a dot, so a dot becomes ``_2e``, and an
underscore ``__``: no two names share a file.
"""
escaped = name.replace("_", "__").replace(".", "_2e")
return f"{directory}/{SUDOERS_FILE_PREFIX}{escaped}"
return f"{directory}/{SUDOERS_FILE_PREFIX}{_rule_file_name(name)}"
def service_sudoers_rule(name: str) -> str:
"""The rule that lets netOrk's own account *name* run everything as root, no password."""
return f"{name} ALL=(ALL) NOPASSWD: ALL\n"
def service_sudoers_rule_path(directory: str, name: str) -> str:
"""Where the rule of netOrk's own account *name* lives in *directory*."""
return f"{directory}/{SERVICE_SUDOERS_FILE_PREFIX}{_rule_file_name(name)}"
def _rule_file_name(name: str) -> str:
return name.replace("_", "__").replace(".", "_2e")
def authorized_keys_paths(home: str) -> tuple[str, str]:
@@ -228,6 +257,14 @@ class LocalAccountsMixin:
"""The command that takes *name* out of *group*; *groups* are all of its own."""
raise NotImplementedError
def _account_create_with_uid(self, name: str, uid: int) -> list[list[str]]:
"""The commands that create *name* as :meth:`_account_create` does, without a
password, and with the uid *uid*.
Only netOrk's own account asks for one (``add_service_account(uid=)``).
"""
raise NotImplementedError
# -- reading ---------------------------------------------------------------------
def get_local_accounts(self, names: Iterable[str]) -> list[LocalAccountDict]:
@@ -357,6 +394,102 @@ class LocalAccountsMixin:
]
return self._accounts_result(name, parts)
def add_service_account(
self, name: str, public_key: str, *, uid: int | None = None
) -> LocalAccountChangeDict:
"""Make *name* netOrk's own account: it logs in with *public_key*, and gains
root without a password.
Created through the account the driver logs in with now, or opened
again when it is there; its other keys stay. It takes no password. Run
again with the account the driver already logs in with, it only adds
what is missing.
A new account gets *uid* when one is given -- the same on every host --
once no other account has it; an account that is there keeps its own,
as a uid is never changed under files that carry it.
Steps as in :meth:`add_local_account`: ``account``, then ``sudo`` and
``keys``. The new login itself is for the caller to try.
An account that is there and cannot log in (``nologin``, ``false``) is
another service's -- a satellite's ``netork``, say -- and is left alone.
:raises ValueError: for a name or key no host takes, root, a uid of 0 or
less, or another service's account.
:raises RuntimeError: when the login user cannot be told.
"""
check_public_key(public_key)
login, existing = self._accounts_service_target(name, uid)
if name == login:
step: FixStepDict = {
"step": "account",
"ok": True,
"output": f"this driver logs in as {name} already",
}
first: FixResultDict = _joined([step])
else:
first = run_fix_steps(
[("account", lambda: self._accounts_service_account(name, existing, uid))]
)
parts = [first]
if first["success"]:
parts += [
run_fix_steps([("sudo", lambda: self._accounts_grant_service_sudo(name))]),
run_fix_steps([("keys", lambda: self._accounts_add_key(name, public_key))]),
]
return self._accounts_result(name, parts)
def _accounts_service_target(self, name: str, uid: int | None) -> tuple[str, list[str] | None]:
"""The login user and *name*'s passwd line, once *name* may become netOrk's.
:raises ValueError: as :meth:`add_service_account` says.
"""
check_account_name(name)
if uid is not None and uid <= 0:
raise ValueError(f"not a uid for netOrk's own account: {uid}")
login = self._accounts_login()
existing = self._accounts_passwd(name)
if existing is not None and int(existing[2]) == 0:
raise ValueError(f"{name} is root")
if existing is not None and existing[6].rsplit("/", 1)[-1] in _NO_LOGIN_SHELLS:
raise ValueError(
f"{name} is there and cannot log in ({existing[6]}): another service's account"
)
return login, existing
def _accounts_service_account(
self, name: str, passwd: list[str] | None, uid: int | None
) -> FixStepOutcomeDict:
"""netOrk's own account opened or made, a new one with *uid* when given."""
if uid is None:
return self._accounts_open_or_create(name, passwd, None)
if passwd is not None:
outcome = self._accounts_open_or_create(name, passwd, None)
if outcome["ok"] and int(passwd[2]) != uid:
outcome["output"] += f"; it keeps its uid {passwd[2]}, not {uid}"
return outcome
owner = self._accounts_passwd_of_uid(uid)
if owner is not None:
return {"ok": False, "output": f"uid {uid} is the account {owner}'s"}
try:
create = self._account_create_with_uid(name, uid)
except NotImplementedError:
return {"ok": False, "output": f"this driver cannot give an account the uid {uid}"}
failed = self._accounts_run(create)
if failed is not None:
return {"ok": False, "output": _said(failed)}
return {"ok": True, "output": f"account {name} created, uid {uid}"}
def _accounts_passwd_of_uid(self, uid: int) -> str | None:
"""The name of the account with *uid*, or None."""
result = self.run_command(_command(["getent", "passwd", str(uid)]), timeout=30)
if result.exit_code == 2:
return None
if result.exit_code != 0:
raise RuntimeError(f"cannot ask who has uid {uid}: {_said(result)}")
return result.stdout.split(":", 1)[0].strip() or None
def _accounts_check_hash(self, password_hash: str) -> None:
prefixes = PASSWORD_SCHEMES[self.ACCOUNT_PASSWORD_SCHEME]
if not _CRYPT_RE.fullmatch(password_hash) or not password_hash.startswith(prefixes):
@@ -368,16 +501,20 @@ class LocalAccountsMixin:
:raises ValueError: for the login user's own account or a system account.
:raises RuntimeError: when the login user cannot be told.
"""
login = self.run_command("id -un", timeout=30).stdout.strip()
if not login:
raise RuntimeError("cannot tell which account this driver logs in with")
if name == login:
if name == self._accounts_login():
raise ValueError(f"{name} is the account this driver logs in with")
passwd = self._accounts_passwd(name)
if passwd is not None and int(passwd[2]) < self.ACCOUNT_MIN_UID:
raise ValueError(f"{name} is a system account (uid {passwd[2]})")
return passwd
def _accounts_login(self) -> str:
""":raises RuntimeError: when the login user cannot be told."""
login = self.run_command("id -un", timeout=30).stdout.strip()
if not login:
raise RuntimeError("cannot tell which account this driver logs in with")
return login
def _accounts_result(self, name: str, parts: list[FixResultDict]) -> LocalAccountChangeDict:
steps = [s for part in parts for s in part["steps"]]
result = _joined(steps)
@@ -455,7 +592,36 @@ class LocalAccountsMixin:
return {"ok": True, "output": "\n".join(said)}
def _accounts_grant_sudo(self, name: str, path: str) -> FixStepOutcomeDict:
staged = self._accounts_stage(sudoers_rule(name))
failed = self._accounts_install_rule(sudoers_rule(name), path)
if failed is not None:
return failed
if not self._accounts_admin(name):
return {
"ok": False,
"output": f"{path} is written, but sudo does not read it: "
f"does sudoers include {self.SUDOERS_DIR}?",
}
return {"ok": True, "output": f"{name} may use sudo with its password ({path})"}
def _accounts_grant_service_sudo(self, name: str) -> FixStepOutcomeDict:
path = service_sudoers_rule_path(self.SUDOERS_DIR, name)
failed = self._accounts_install_rule(service_sudoers_rule(name), path)
if failed is not None:
return failed
result = self.run_command(_command(["sudo", "-l", "-U", name]), privileged=True, timeout=30)
if result.exit_code != 0:
return {"ok": False, "output": f"cannot ask sudo about {name}: {_said(result)}"}
if not _RUN_ALL_NOPASSWD_RE.search(result.stdout):
return {
"ok": False,
"output": f"{path} is written, but sudo does not read it: "
f"does sudoers include {self.SUDOERS_DIR}?",
}
return {"ok": True, "output": f"{name} may use sudo without a password ({path})"}
def _accounts_install_rule(self, rule: str, path: str) -> FixStepOutcomeDict | None:
"""Check *rule* with visudo and install it at *path*; the failure, or None."""
staged = self._accounts_stage(rule)
try:
checked = self._accounts_root(["visudo", "-cf", staged])
if checked.exit_code != 0:
@@ -467,13 +633,7 @@ class LocalAccountsMixin:
return {"ok": False, "output": f"{path}: {_said(installed)}"}
finally:
self._accounts_unstage(staged)
if not self._accounts_admin(name):
return {
"ok": False,
"output": f"{path} is written, but sudo does not read it: "
f"does sudoers include {self.SUDOERS_DIR}?",
}
return {"ok": True, "output": f"{name} may use sudo with its password ({path})"}
return None
# -- keys --------------------------------------------------------------------------
@@ -576,6 +736,7 @@ def _joined(steps: list[FixStepDict]) -> FixResultDict:
__all__ = [
"ACCOUNT_NAME_RE",
"PASSWORD_SCHEMES",
"SERVICE_SUDOERS_FILE_PREFIX",
"SUDOERS_FILE_PREFIX",
"LocalAccountChangeDict",
"LocalAccountDict",
@@ -583,6 +744,8 @@ __all__ = [
"authorized_keys_paths",
"check_account_name",
"check_public_key",
"service_sudoers_rule",
"service_sudoers_rule_path",
"sudoers_rule",
"sudoers_rule_path",
]
+301
View File
@@ -0,0 +1,301 @@
"""netOrk's own account on a host: created through the account it logs in with today.
The fake host of :mod:`tests.test_local_accounts`, taught the rule that lets
an account run everything as root without a password.
"""
from __future__ import annotations
import shlex
import pytest
from napalm_device_types.channel import CommandResult
from napalm_device_types.local_accounts import (
service_sudoers_rule,
service_sudoers_rule_path,
sudoers_rule_path,
)
from tests.test_local_accounts import (
OWN_KEY,
SHELL_SYNTAX,
_Account,
_Driver,
_Host,
_root_commands,
)
NETORK_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAINetork netork@central"
class _ServiceHost(_Host):
"""The fake host, whose sudo also takes the rule without a password."""
def is_passwordless(self, name: str) -> bool:
rule = self.files.get(service_sudoers_rule_path(_Driver.SUDOERS_DIR, name))
return self.includes_dropins and rule is not None
def _sudo(self, args: list[str], privileged: bool) -> CommandResult:
name = args[2]
if not self.is_passwordless(name):
return super()._sudo(args, privileged)
out = f"User {name} may run the following commands on host:\n (ALL) NOPASSWD: ALL\n"
return CommandResult(out, "", 0)
def _visudo(self, args: list[str], privileged: bool) -> CommandResult:
content = self.files[args[1]]
if content.endswith(" ALL=(ALL) NOPASSWD: ALL\n") and "\n" not in content[:-1]:
return CommandResult("parsed OK", "", 0)
return super()._visudo(args, privileged)
@pytest.fixture
def host() -> _ServiceHost:
return _ServiceHost()
@pytest.fixture
def driver(host: _ServiceHost) -> _Driver:
return _Driver(host)
def test_the_rule_runs_everything_as_root_without_a_password() -> None:
assert service_sudoers_rule("netork") == "netork ALL=(ALL) NOPASSWD: ALL\n"
def test_the_rule_has_a_file_of_its_own_no_personal_rule_shares() -> None:
path = service_sudoers_rule_path("/etc/sudoers.d", "net.ork_1")
assert path == "/etc/sudoers.d/85-service-net_2eork__1"
assert path != sudoers_rule_path("/etc/sudoers.d", "net.ork_1")
def test_a_new_service_account_gets_the_key_and_sudo_without_a_password(
host: _ServiceHost, driver: _Driver
) -> None:
result = driver.add_service_account("netork", NETORK_KEY)
assert result["success"], result["output"]
assert [s["step"] for s in result["steps"]] == ["account", "sudo", "keys"]
assert host.accounts["netork"].password is None
assert host.files["/home/netork/.ssh/authorized_keys"] == NETORK_KEY + "\n"
assert host.is_passwordless("netork")
account = result["account"]
assert account is not None and account["admin"]
def test_every_command_root_runs_is_one_fixed_command(host: _ServiceHost, driver: _Driver) -> None:
driver.add_service_account("netork", NETORK_KEY)
for command in _root_commands(host):
assert not any(s in command for s in SHELL_SYNTAX), command
def test_an_existing_account_keeps_its_keys_and_gets_the_rule(
host: _ServiceHost, driver: _Driver
) -> None:
host.accounts["netork"] = _Account(1001, "/home/netork", groups=["netork"])
host.files["/home/netork/.ssh/authorized_keys"] = OWN_KEY + "\n"
result = driver.add_service_account("netork", NETORK_KEY)
assert result["success"], result["output"]
assert host.files["/home/netork/.ssh/authorized_keys"] == f"{OWN_KEY}\n{NETORK_KEY}\n"
assert host.is_passwordless("netork")
def test_an_existing_system_account_may_become_netorks(host: _ServiceHost, driver: _Driver) -> None:
host.accounts["netork"] = _Account(998, "/var/lib/netork", groups=["netork"])
result = driver.add_service_account("netork", NETORK_KEY)
assert result["success"], result["output"]
def test_a_locked_account_is_opened_again(host: _ServiceHost, driver: _Driver) -> None:
host.accounts["netork"] = _Account(1001, "/home/netork", groups=["netork"], locked=True)
result = driver.add_service_account("netork", NETORK_KEY)
assert result["success"], result["output"]
assert not host.accounts["netork"].locked
def test_the_account_netork_logs_in_with_already_only_gets_what_it_lacks(
host: _ServiceHost, driver: _Driver
) -> None:
host.login = "netork"
host.accounts["netork"] = _Account(1001, "/home/netork", groups=["netork"])
host.files["/home/netork/.ssh/authorized_keys"] = NETORK_KEY + "\n"
result = driver.add_service_account("netork", NETORK_KEY)
assert result["success"], result["output"]
assert not any(c.startswith("openuser") for c in _root_commands(host))
assert "already" in result["output"]
def test_root_is_never_netorks_account(host: _ServiceHost, driver: _Driver) -> None:
host.accounts["toor"] = _Account(0, "/root", groups=["wheel"])
with pytest.raises(ValueError, match="root"):
driver.add_service_account("toor", NETORK_KEY)
assert not _root_commands(host)
@pytest.mark.parametrize("name", ["Netork", "net ork", "-n", ""])
def test_a_name_no_host_takes_is_refused(driver: _Driver, name: str) -> None:
with pytest.raises(ValueError):
driver.add_service_account(name, NETORK_KEY)
def test_a_key_that_is_none_is_refused(driver: _Driver) -> None:
with pytest.raises(ValueError):
driver.add_service_account("netork", "not a key")
def test_a_rule_sudo_does_not_read_fails_the_step(host: _ServiceHost, driver: _Driver) -> None:
host.includes_dropins = False
result = driver.add_service_account("netork", NETORK_KEY)
assert not result["success"]
sudo = next(s for s in result["steps"] if s["step"] == "sudo")
assert not sudo["ok"] and "does not read it" in sudo["output"]
def test_a_rule_with_a_password_is_not_enough(host: _ServiceHost, driver: _Driver) -> None:
host.other_rules.add("netork")
host.includes_dropins = False
result = driver.add_service_account("netork", NETORK_KEY)
assert not result["success"]
def test_a_failed_create_stops_before_sudo_and_keys(host: _ServiceHost, driver: _Driver) -> None:
host.failing.add("mkuser")
result = driver.add_service_account("netork", NETORK_KEY)
assert not result["success"]
assert [s["step"] for s in result["steps"]] == ["account"]
assert result["account"] is None
def test_the_staged_files_are_removed_again(host: _ServiceHost, driver: _Driver) -> None:
driver.add_service_account("netork", NETORK_KEY)
assert not [p for p in host.files if p.startswith("/tmp/")]
def test_a_personal_account_of_the_same_name_keeps_its_own_rule_apart(
host: _ServiceHost, driver: _Driver
) -> None:
driver.add_service_account("netork", NETORK_KEY)
rules = [c for c in _root_commands(host) if c.startswith("install")]
assert [shlex.split(c)[-1] for c in rules] == [
service_sudoers_rule_path(_Driver.SUDOERS_DIR, "netork")
]
# -- a fixed uid (infrastructure BAUSTANDARD A) ------------------------------------------
class _UidDriver(_Driver):
def _account_create_with_uid(self, name: str, uid: int) -> list[list[str]]:
return [["mkuseruid", name, str(uid)]]
def _mkuseruid(host: _ServiceHost):
def handler(args: list[str], privileged: bool) -> CommandResult:
assert privileged
name, uid = args[0], int(args[1])
host.accounts[name] = _Account(uid, f"/home/{name}", groups=[name])
return CommandResult("", "", 0)
return handler
def _getent_uid(host: _ServiceHost, original):
def handler(args: list[str], privileged: bool) -> CommandResult:
if args[1].isdigit():
owner = next((n for n, a in host.accounts.items() if a.uid == int(args[1])), None)
if owner is None:
return CommandResult("", "", 2)
a = host.accounts[owner]
return CommandResult(f"{owner}:*:{a.uid}:{a.uid}::{a.home}:{a.shell}\n", "", 0)
return original(args, privileged)
return handler
@pytest.fixture
def uid_driver(host: _ServiceHost) -> _UidDriver:
host._mkuseruid = _mkuseruid(host) # type: ignore[attr-defined]
host._getent = _getent_uid(host, host._getent) # type: ignore[method-assign]
return _UidDriver(host)
def test_a_new_account_gets_the_uid_asked_for(host: _ServiceHost, uid_driver: _UidDriver) -> None:
result = uid_driver.add_service_account("netork", NETORK_KEY, uid=900)
assert result["success"], result["output"]
assert host.accounts["netork"].uid == 900
account = result["account"]
assert account is not None and account["uid"] == 900
def test_a_uid_another_account_has_stops_before_anything_is_made(
host: _ServiceHost, uid_driver: _UidDriver
) -> None:
host.accounts["fwupd-refresh"] = _Account(900, "/run/fwupd")
result = uid_driver.add_service_account("netork", NETORK_KEY, uid=900)
assert not result["success"]
assert "fwupd-refresh" in result["output"]
assert "netork" not in host.accounts
def test_an_existing_account_keeps_its_uid_and_says_so(
host: _ServiceHost, uid_driver: _UidDriver
) -> None:
host.accounts["netork"] = _Account(1001, "/home/netork", groups=["netork"])
result = uid_driver.add_service_account("netork", NETORK_KEY, uid=900)
assert result["success"], result["output"]
assert host.accounts["netork"].uid == 1001
assert "uid 1001" in result["output"]
def test_a_uid_root_has_is_refused(uid_driver: _UidDriver) -> None:
with pytest.raises(ValueError):
uid_driver.add_service_account("netork", NETORK_KEY, uid=0)
def test_a_driver_that_cannot_set_a_uid_says_so(host: _ServiceHost, driver: _Driver) -> None:
result = driver.add_service_account("netork", NETORK_KEY, uid=900)
assert not result["success"]
assert "uid" in result["output"]
# -- another service's account of the same name (bw-01: the satellite's) ------------------
@pytest.mark.parametrize(
"shell", ["/usr/sbin/nologin", "/sbin/nologin", "/bin/false", "/usr/bin/false"]
)
def test_an_account_that_cannot_log_in_is_another_services_and_left_alone(
host: _ServiceHost, driver: _Driver, shell: str
) -> None:
host.accounts["netork"] = _Account(
999, "/home/netork", shell=shell, groups=["netork", "docker"]
)
with pytest.raises(ValueError, match="cannot log in"):
driver.add_service_account("netork", NETORK_KEY)
assert not _root_commands(host)
assert service_sudoers_rule_path(_Driver.SUDOERS_DIR, "netork") not in host.files