feat: netOrk's own account through the current login (NetOrk/netork#1817)
driver / lint (pull_request) Failing after 7s
driver / standard (pull_request) Successful in 21s
driver / types (pull_request) Successful in 1m10s
driver / test (3.12) (pull_request) Successful in 1m9s
driver / test (3.13) (pull_request) Successful in 1m6s
driver / lowest (pull_request) Successful in 50s
driver / build (pull_request) Successful in 38s
driver / security (pull_request) Successful in 1m19s
CI / driver (pull_request) Failing after 2m35s
driver / publish (pull_request) Skipped
driver / lint (pull_request) Failing after 7s
driver / standard (pull_request) Successful in 21s
driver / types (pull_request) Successful in 1m10s
driver / test (3.12) (pull_request) Successful in 1m9s
driver / test (3.13) (pull_request) Successful in 1m6s
driver / lowest (pull_request) Successful in 50s
driver / build (pull_request) Successful in 38s
driver / security (pull_request) Successful in 1m19s
CI / driver (pull_request) Failing after 2m35s
driver / publish (pull_request) Skipped
add_service_account(name, public_key) creates or reopens the account through the login the driver uses today: a key and no password, and a rule of its own in 85-service-<name> that lets it run everything as root without a password, checked with visudo and sudo -l. Root is refused; run again with the account the driver already logs in with, it only adds what is missing.
This commit is contained in:
1 parent
25cc264306
commit
666be091e3
3 files changed
+315
-14
No files matched your search
@@ -14,6 +14,12 @@ 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).
|
||||
- `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
|
||||
|
||||
@@ -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,16 @@ _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,
|
||||
)
|
||||
|
||||
#: 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 +127,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]:
|
||||
@@ -357,6 +383,46 @@ class LocalAccountsMixin:
|
||||
]
|
||||
return self._accounts_result(name, parts)
|
||||
|
||||
def add_service_account(self, name: str, public_key: str) -> 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.
|
||||
|
||||
Steps as in :meth:`add_local_account`: ``account``, then ``sudo`` and
|
||||
``keys``. The new login itself is for the caller to try.
|
||||
|
||||
:raises ValueError: for a name or key no host takes, or root.
|
||||
:raises RuntimeError: when the login user cannot be told.
|
||||
"""
|
||||
check_account_name(name)
|
||||
check_public_key(public_key)
|
||||
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 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_open_or_create(name, existing, None))]
|
||||
)
|
||||
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_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 +434,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 +525,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 +566,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 +669,7 @@ def _joined(steps: list[FixStepDict]) -> FixResultDict:
|
||||
__all__ = [
|
||||
"ACCOUNT_NAME_RE",
|
||||
"PASSWORD_SCHEMES",
|
||||
"SERVICE_SUDOERS_FILE_PREFIX",
|
||||
"SUDOERS_FILE_PREFIX",
|
||||
"LocalAccountChangeDict",
|
||||
"LocalAccountDict",
|
||||
@@ -583,6 +677,8 @@ __all__ = [
|
||||
"authorized_keys_paths",
|
||||
"check_account_name",
|
||||
"check_public_key",
|
||||
"service_sudoers_rule",
|
||||
"service_sudoers_rule_path",
|
||||
"sudoers_rule",
|
||||
"sudoers_rule_path",
|
||||
]
|
||||
@@ -0,0 +1,199 @@
|
||||
"""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")
|
||||
]
|
||||
Reference in new issue
Block a user