feat: personal accounts with shadow-utils, locked by expiry (NetOrk/netork#1793)
driver / standard (pull_request) Failing after 17s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Failing after 1m17s
driver / test (3.12) (pull_request) Failing after 1m19s
driver / test (3.13) (pull_request) Failing after 1m7s
driver / lowest (pull_request) Failing after 41s
driver / build (pull_request) Successful in 42s
driver / security (pull_request) Successful in 1m29s
CI / driver (pull_request) Failing after 3m19s
driver / publish (pull_request) Skipped
driver / standard (pull_request) Failing after 17s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Failing after 1m17s
driver / test (3.12) (pull_request) Failing after 1m19s
driver / test (3.13) (pull_request) Failing after 1m7s
driver / lowest (pull_request) Failing after 41s
driver / build (pull_request) Successful in 42s
driver / security (pull_request) Successful in 1m29s
CI / driver (pull_request) Failing after 3m19s
driver / publish (pull_request) Skipped
LinuxDriver mixes in napalm-device-types' LocalAccountsMixin with useradd -m -s /bin/bash, usermod and gpasswd -d. A locked account is an expired one (usermod -L -e 1): PAM refuses it a key login too, where a "!" in front of the password stops only the password. Opening it again lifts the expiry and gives the old password back. Checked on Debian 13 and Rocky Linux 9 containers with sshd and sudo: key login works after adding, is refused after locking and works again after reopening; the sudo rule takes effect with the person's password; membership of sudo/wheel goes when sudo is not wanted.
This commit is contained in:
1 parent
7550b884b0
commit
c5be71adac
4 files changed
+177
No files matched your search
@@ -8,6 +8,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
- Personal accounts (NetOrk/netork#1793), through napalm-device-types' `LocalAccountsMixin`:
|
||||||
|
`get_local_accounts()`, `add_local_account()` and `lock_local_account()` with
|
||||||
|
shadow-utils' commands (`useradd -m -s /bin/bash`, `usermod`, `gpasswd -d`). A locked
|
||||||
|
account is an expired one (`usermod -L -e 1`): PAM refuses it a key login too, where a
|
||||||
|
`!` in front of the password stops only the password. Opening it again lifts the expiry
|
||||||
|
and gives the old password back. Checked on Debian 13 and Rocky Linux 9 with sshd and
|
||||||
|
sudo. OpenMediaVault (Debian) inherits it; QNAP QTS opts out in napalm-qnap-qts.
|
||||||
|
Requires the napalm-device-types release with `LocalAccountsMixin`.
|
||||||
- The sudo password the old `_sudo` left in shell histories (NetOrk/netork#1090), through
|
- The sudo password the old `_sudo` left in shell histories (NetOrk/netork#1090), through
|
||||||
napalm-device-types' `SudoHistoryMixin`. Until NetOrk/netork#1039 every privileged command
|
napalm-device-types' `SudoHistoryMixin`. Until NetOrk/netork#1039 every privileged command
|
||||||
was typed into the interactive shell as `echo '<password>' | sudo -S -p "" …`, so the
|
was typed into the interactive shell as `echo '<password>' | sudo -S -p "" …`, so the
|
||||||
|
|||||||
@@ -0,0 +1,64 @@
|
|||||||
|
"""Personal accounts on a Linux host, with shadow-utils (NetOrk/netork#1793).
|
||||||
|
|
||||||
|
napalm-device-types' ``LocalAccountsMixin`` runs the steps; this names the
|
||||||
|
commands. A locked account is an expired one (``usermod -L -e 1``): PAM's
|
||||||
|
account check refuses it every login, a key's too, where a ``!`` in front of
|
||||||
|
the password -- ``usermod -L`` alone -- stops only the password. Opening it
|
||||||
|
again lifts the expiry and gives the old password back.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import shlex
|
||||||
|
import time
|
||||||
|
|
||||||
|
from napalm_device_types import LocalAccountsMixin
|
||||||
|
|
||||||
|
#: What the password field holds when the account never had a password.
|
||||||
|
_NO_PASSWORD = frozenset({"", "!", "!!", "!*", "*"})
|
||||||
|
|
||||||
|
|
||||||
|
class LinuxLocalAccountsMixin(LocalAccountsMixin):
|
||||||
|
ACCOUNT_SHELL = "/bin/bash"
|
||||||
|
#: Debian and Ubuntu grant ``%sudo``, the Red Hat family ``%wheel``, old Ubuntu ``%admin``.
|
||||||
|
ACCOUNT_ADMIN_GROUPS = ("sudo", "wheel", "admin")
|
||||||
|
SUDOERS_DIR = "/etc/sudoers.d"
|
||||||
|
ROOT_GROUP = "root"
|
||||||
|
|
||||||
|
def _account_create(self, name: str, password_hash: str | None) -> list[list[str]]:
|
||||||
|
password = ["-p", password_hash] if password_hash else []
|
||||||
|
return [["useradd", "-m", "-s", self.ACCOUNT_SHELL, *password, name]]
|
||||||
|
|
||||||
|
def _account_open(
|
||||||
|
self, name: str, password_hash: str | None, *, locked: bool
|
||||||
|
) -> list[list[str]]:
|
||||||
|
if password_hash:
|
||||||
|
return [["usermod", "-e", "", "-p", password_hash, name]]
|
||||||
|
# usermod -U refuses to leave an account without any password.
|
||||||
|
had_one = self._shadow(name)[1].lstrip("!") not in _NO_PASSWORD
|
||||||
|
return [["usermod", *(["-U"] if had_one else []), "-e", "", name]]
|
||||||
|
|
||||||
|
def _account_lock(self, name: str, *, locked: bool) -> list[list[str]]:
|
||||||
|
return [] if locked else [["usermod", "-L", "-e", "1", name]]
|
||||||
|
|
||||||
|
def _account_locked(self, name: str, passwd: list[str]) -> bool:
|
||||||
|
expire = self._shadow(name)[7]
|
||||||
|
# pam_unix: expired from the day sp_expire names on.
|
||||||
|
return bool(expire) and int(expire) <= int(time.time() // 86400)
|
||||||
|
|
||||||
|
def _account_leave_group(self, name: str, group: str, groups: list[str]) -> list[str]:
|
||||||
|
return ["gpasswd", "-d", name, group]
|
||||||
|
|
||||||
|
def _shadow(self, name: str) -> list[str]:
|
||||||
|
"""*name*'s shadow entry, split; only the lock and the expiry are looked at.
|
||||||
|
|
||||||
|
:raises RuntimeError: when it cannot be read.
|
||||||
|
"""
|
||||||
|
result = self.run_command(
|
||||||
|
shlex.join(["getent", "shadow", name]), privileged=True, timeout=30
|
||||||
|
)
|
||||||
|
fields = result.stdout.strip().split(":")
|
||||||
|
if result.exit_code != 0 or len(fields) < 9 or fields[0] != name:
|
||||||
|
reason = (result.stderr or result.stdout).strip() or f"exit {result.exit_code}"
|
||||||
|
raise RuntimeError(f"cannot read the shadow entry of {name}: {reason}")
|
||||||
|
return fields
|
||||||
@@ -72,6 +72,7 @@ from netmiko import ConnectHandler
|
|||||||
from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException
|
from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException
|
||||||
|
|
||||||
from napalm_linux._hostname import HostnameMixin
|
from napalm_linux._hostname import HostnameMixin
|
||||||
|
from napalm_linux._local_accounts import LinuxLocalAccountsMixin
|
||||||
from napalm_linux._shell import PROMPT_RE as _PROMPT_RE
|
from napalm_linux._shell import PROMPT_RE as _PROMPT_RE
|
||||||
from napalm_linux._shell import prepare_shell
|
from napalm_linux._shell import prepare_shell
|
||||||
from napalm_linux._sudo_history import LinuxSudoHistoryMixin
|
from napalm_linux._sudo_history import LinuxSudoHistoryMixin
|
||||||
@@ -307,6 +308,7 @@ def render_snmpd_conf(settings: SnmpAgentSettingsDict) -> str:
|
|||||||
|
|
||||||
class LinuxDriver(
|
class LinuxDriver(
|
||||||
LinuxSudoHistoryMixin,
|
LinuxSudoHistoryMixin,
|
||||||
|
LinuxLocalAccountsMixin,
|
||||||
SnmpAgentMixin,
|
SnmpAgentMixin,
|
||||||
EnsurePackageMixin,
|
EnsurePackageMixin,
|
||||||
AptProxyMixin,
|
AptProxyMixin,
|
||||||
|
|||||||
@@ -0,0 +1,103 @@
|
|||||||
|
"""Personal accounts on a Linux host (NetOrk/netork#1793).
|
||||||
|
|
||||||
|
napalm-device-types' ``LocalAccountsMixin`` runs the steps; the driver names
|
||||||
|
shadow-utils' commands. A locked account is an expired one (``usermod -e 1``):
|
||||||
|
PAM refuses it a key login too, where a ``!`` in front of the password alone
|
||||||
|
stops only the password.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import time
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from napalm_device_types import CommandResult, LocalAccountsMixin
|
||||||
|
|
||||||
|
from napalm_linux import LinuxDriver
|
||||||
|
|
||||||
|
HASH = "$6$salt$" + "x" * 86
|
||||||
|
_TODAY = int(time.time() // 86400)
|
||||||
|
|
||||||
|
|
||||||
|
class _Driver(LinuxDriver):
|
||||||
|
"""A Linux driver whose host answers ``getent shadow`` with *shadow*."""
|
||||||
|
|
||||||
|
def __init__(self, shadow: str = "alice:$6$old:20000:0:99999:7:::") -> None:
|
||||||
|
super().__init__("host", "netadmin", "pw")
|
||||||
|
self.shadow = shadow
|
||||||
|
self.ran: list[tuple[str, bool]] = []
|
||||||
|
|
||||||
|
def run_command(self, command, *, privileged=False, timeout=60, stdin=None):
|
||||||
|
self.ran.append((command, privileged))
|
||||||
|
if command == "getent shadow alice":
|
||||||
|
return CommandResult(self.shadow + "\n", "", 0 if self.shadow else 2)
|
||||||
|
return CommandResult("", "", 0)
|
||||||
|
|
||||||
|
|
||||||
|
def _passwd() -> list[str]:
|
||||||
|
return "alice:x:1001:1001::/home/alice:/bin/bash".split(":")
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_linux_host_can_add_and_lock_personal_accounts() -> None:
|
||||||
|
assert issubclass(LinuxDriver, LocalAccountsMixin)
|
||||||
|
assert LinuxDriver.ACCOUNT_PASSWORD_SCHEME == "sha512"
|
||||||
|
assert LinuxDriver.ACCOUNT_SHELL == "/bin/bash"
|
||||||
|
# Debian and Ubuntu grant %sudo, the Red Hat family %wheel, old Ubuntu %admin.
|
||||||
|
assert set(LinuxDriver.ACCOUNT_ADMIN_GROUPS) == {"sudo", "wheel", "admin"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_new_account_gets_a_home_and_bash() -> None:
|
||||||
|
d = _Driver()
|
||||||
|
assert d._account_create("alice", HASH) == [
|
||||||
|
["useradd", "-m", "-s", "/bin/bash", "-p", HASH, "alice"]
|
||||||
|
]
|
||||||
|
assert d._account_create("alice", None) == [["useradd", "-m", "-s", "/bin/bash", "alice"]]
|
||||||
|
|
||||||
|
|
||||||
|
def test_locking_expires_the_account_and_locks_its_password() -> None:
|
||||||
|
d = _Driver()
|
||||||
|
assert d._account_lock("alice", locked=False) == [["usermod", "-L", "-e", "1", "alice"]]
|
||||||
|
assert d._account_lock("alice", locked=True) == []
|
||||||
|
|
||||||
|
|
||||||
|
def test_opening_lifts_the_expiry_and_sets_the_new_password() -> None:
|
||||||
|
d = _Driver()
|
||||||
|
assert d._account_open("alice", HASH, locked=True) == [
|
||||||
|
["usermod", "-e", "", "-p", HASH, "alice"]
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def test_opening_without_a_new_password_gives_back_the_old_one() -> None:
|
||||||
|
d = _Driver(shadow="alice:!$6$old:20000:0:99999:7::1:")
|
||||||
|
assert d._account_open("alice", None, locked=True) == [["usermod", "-U", "-e", "", "alice"]]
|
||||||
|
|
||||||
|
|
||||||
|
def test_an_account_that_never_had_a_password_keeps_it_locked() -> None:
|
||||||
|
# usermod -U refuses to leave an account without a password.
|
||||||
|
for field in ("!", "!!", "!*", "*"):
|
||||||
|
d = _Driver(shadow=f"alice:{field}:20000:0:99999:7::1:")
|
||||||
|
assert d._account_open("alice", None, locked=True) == [["usermod", "-e", "", "alice"]]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("expire", "locked"),
|
||||||
|
[("", False), ("1", True), (str(_TODAY), True), (str(_TODAY + 30), False)],
|
||||||
|
)
|
||||||
|
def test_an_expired_account_is_locked(expire: str, locked: bool) -> None:
|
||||||
|
d = _Driver(shadow=f"alice:$6$old:20000:0:99999:7::{expire}:")
|
||||||
|
assert d._account_locked("alice", _passwd()) is locked
|
||||||
|
assert d.ran == [("getent shadow alice", True)]
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_shadow_that_cannot_be_read_raises() -> None:
|
||||||
|
with pytest.raises(RuntimeError, match="alice"):
|
||||||
|
_Driver(shadow="")._account_locked("alice", _passwd())
|
||||||
|
|
||||||
|
|
||||||
|
def test_leaving_a_group_is_gpasswd() -> None:
|
||||||
|
assert _Driver()._account_leave_group("alice", "sudo", ["alice", "sudo"]) == [
|
||||||
|
"gpasswd",
|
||||||
|
"-d",
|
||||||
|
"alice",
|
||||||
|
"sudo",
|
||||||
|
]
|
||||||
Reference in new issue
Block a user