Without a root login and without a sudo password, _run_privileged typed "sudo -n <command>" into the interactive shell. sudo covered only the first simple command of the line, and dnf's and yum's advisory query, which starts with a brace group, did not parse at all: no status marker ever arrived, so netmiko waited out the 120 s read timeout and get_available_updates() failed. This is the default path for netOrk's own NOPASSWD account. The command now goes to "sudo -n sh -c" as one argument, as _as_root already does with a password. A status echo at its end stays outside sh -c: it reports sh's status, which is the command's, and still arrives when sudo refuses. Closes #56
200 lines
6.8 KiB
Python
200 lines
6.8 KiB
Python
"""Without a sudo password the whole command runs as root, in one ``sh -c`` (#56).
|
|
|
|
A login that is not root and has no sudo password (NOPASSWD sudo, e.g. netOrk's
|
|
own account from NetOrk/netork#1817) types its privileged commands into the
|
|
interactive shell. ``sudo -n <command>`` covered only the first simple command of
|
|
the line, and a command that starts with a brace group did not even parse:
|
|
``sudo -n { LC_ALL=C dnf …; echo __DNF_RC=$?; } | cat`` is a syntax error, so dnf's
|
|
and yum's security advisories were always unknown.
|
|
|
|
The command now goes to ``sudo -n sh -c`` as one argument, as ``_as_root`` does.
|
|
A status echo at its end (``; echo __NETORK_RC=$?``) stays outside: it reports
|
|
sh's status, which is the command's, and still arrives when sudo refuses.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
from pathlib import Path
|
|
from shlex import quote
|
|
from unittest.mock import MagicMock
|
|
|
|
import pytest
|
|
from napalm_device_types import DNF_SECURITY_COMMAND
|
|
|
|
from napalm_linux import LinuxDriver
|
|
from napalm_linux.linux import _YUM_SECURITY_COMMAND
|
|
|
|
BASH = shutil.which("bash")
|
|
needs_bash = pytest.mark.skipif(BASH is None, reason="needs bash")
|
|
|
|
#: dnf's answer on a Fedora 40 host with one pending security advisory.
|
|
_ADVISORY = "FEDORA-2024-1a2b3c4d5e Important/Sec. openssl-libs-1:3.1.4-2.fc40.x86_64"
|
|
|
|
|
|
def _driver(pkg_manager: str = "dnf", answers: list[str] | None = None) -> LinuxDriver:
|
|
"""A driver logged in as a user that is not root, without a sudo password."""
|
|
d = LinuxDriver.__new__(LinuxDriver)
|
|
d.hostname = "testhost"
|
|
d._sudo_password = None
|
|
d._pkg_manager = pkg_manager
|
|
d._root = False
|
|
d._device = MagicMock()
|
|
d._device.send_command.side_effect = answers or []
|
|
return d
|
|
|
|
|
|
def _sent(driver: LinuxDriver) -> list[str]:
|
|
return [c[0][0] for c in driver._device.send_command.call_args_list]
|
|
|
|
|
|
def _bash_parses(line: str) -> str:
|
|
"""bash's complaint about *line*, empty when it parses."""
|
|
assert BASH is not None
|
|
checked = subprocess.run( # noqa: S603 - a fixed interpreter, the line only parsed
|
|
[BASH, "-n", "-c", line], capture_output=True, text=True, check=False
|
|
)
|
|
return checked.stderr
|
|
|
|
|
|
class TestTheSecurityAdvisories:
|
|
@needs_bash
|
|
@pytest.mark.parametrize("manager", ["dnf", "yum"])
|
|
def test_the_line_parses(self, manager):
|
|
driver = _driver(manager, [f"{_ADVISORY}\n__DNF_RC=0\n__NETORK_RC=0"])
|
|
|
|
driver._rpm_security_names()
|
|
|
|
assert _bash_parses(_sent(driver)[0]) == ""
|
|
|
|
@pytest.mark.parametrize(
|
|
("manager", "command"), [("dnf", DNF_SECURITY_COMMAND), ("yum", _YUM_SECURITY_COMMAND)]
|
|
)
|
|
def test_all_of_it_runs_as_root_and_the_status_stays_outside(self, manager, command):
|
|
driver = _driver(manager, [f"{_ADVISORY}\n__DNF_RC=0\n__NETORK_RC=0"])
|
|
|
|
driver._rpm_security_names()
|
|
|
|
assert _sent(driver) == [f"sudo -n sh -c {quote(command)}; echo __NETORK_RC=$?"]
|
|
|
|
def test_the_advisories_are_read(self):
|
|
driver = _driver("dnf", [f"{_ADVISORY}\n__DNF_RC=0\n__NETORK_RC=0"])
|
|
|
|
assert driver._rpm_security_names() == {"openssl-libs"}
|
|
|
|
|
|
#: Every caller of ``_run_privileged``, with an answer that satisfies it.
|
|
_CALLERS = {
|
|
"reboot_host": (lambda d: d.reboot_host(), ["__NETORK_RC=0"]),
|
|
"refresh apt": (lambda d: d.refresh_available_updates(), ["__NETORK_RC=0"]),
|
|
"check-update": (
|
|
lambda d: d.get_available_updates(),
|
|
["__NETORK_RC=0", "__DNF_RC=0\n__NETORK_RC=0"],
|
|
),
|
|
"manage_service": (lambda d: d.manage_service("wg-quick@wg0", "restart"), ["__SVC_RC=0"]),
|
|
"listening sockets": (
|
|
lambda d: d._run_listening_sockets_command("sh -c 'ss -H -ltn'", privileged=True),
|
|
[""],
|
|
),
|
|
}
|
|
|
|
|
|
@needs_bash
|
|
@pytest.mark.parametrize("caller", sorted(_CALLERS))
|
|
def test_every_privileged_line_parses_and_runs_whole_as_root(caller):
|
|
call, answers = _CALLERS[caller]
|
|
driver = _driver("apt" if caller == "refresh apt" else "dnf", answers)
|
|
|
|
call(driver)
|
|
|
|
for line in _sent(driver):
|
|
assert line.startswith("sudo -n sh -c '")
|
|
assert _bash_parses(line) == ""
|
|
|
|
|
|
def test_the_service_status_stays_outside():
|
|
driver = _driver(answers=["__SVC_RC=0"])
|
|
|
|
driver.manage_service("cron", "restart")
|
|
|
|
assert _sent(driver) == [
|
|
"sudo -n sh -c 'timeout 45 systemctl --no-ask-password restart -- cron.service 2>&1';"
|
|
" echo __SVC_RC=$?"
|
|
]
|
|
|
|
|
|
def test_a_command_without_a_status_echo_is_wrapped_whole():
|
|
driver = _driver(answers=[""])
|
|
|
|
driver._run_privileged("ss -H -ltnp | sort")
|
|
|
|
assert _sent(driver) == ["sudo -n sh -c 'ss -H -ltnp | sort'"]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# The lines run in a real bash, with a stand-in sudo and package manager
|
|
# ---------------------------------------------------------------------------
|
|
|
|
_SUDO_OK = '#!/bin/sh\n[ "$1" = -n ] && shift\nexec "$@"\n'
|
|
_SUDO_REFUSES = "#!/bin/sh\necho 'sudo: a password is required' >&2\nexit 1\n"
|
|
_DNF = f"#!/bin/sh\necho '{_ADVISORY}'\n"
|
|
|
|
|
|
def _shell_host(tmp_path: Path, sudo: str) -> LinuxDriver:
|
|
"""A driver whose interactive shell is a real bash with stand-ins on its PATH.
|
|
|
|
Like netmiko, it reads until the command's expect pattern matches and fails
|
|
when it never does.
|
|
"""
|
|
for name, script in (("sudo", sudo), ("dnf", _DNF)):
|
|
stub = tmp_path / name
|
|
stub.write_text(script)
|
|
stub.chmod(0o755)
|
|
env = {"PATH": f"{tmp_path}:/usr/bin:/bin", "LC_ALL": "C"}
|
|
|
|
def send_command(command, *, expect_string, **_kwargs):
|
|
assert BASH is not None
|
|
ran = subprocess.run( # noqa: S603 - a fixed interpreter and stand-ins
|
|
[BASH, "-c", command],
|
|
stdout=subprocess.PIPE,
|
|
stderr=subprocess.STDOUT, # one stream, in order, as on the PTY
|
|
text=True,
|
|
env=env,
|
|
check=False,
|
|
)
|
|
output = f"{ran.stdout}user@host:~$ "
|
|
if not re.search(expect_string, output):
|
|
raise TimeoutError(f"pattern not detected: {expect_string!r} in {output!r}")
|
|
return output
|
|
|
|
driver = _driver("dnf")
|
|
driver._device.send_command.side_effect = send_command
|
|
return driver
|
|
|
|
|
|
@needs_bash
|
|
def test_a_real_shell_reads_the_advisories(tmp_path):
|
|
driver = _shell_host(tmp_path, _SUDO_OK)
|
|
|
|
assert driver._rpm_security_names() == {"openssl-libs"}
|
|
|
|
|
|
@needs_bash
|
|
def test_a_refused_sudo_still_reports_its_status(tmp_path):
|
|
driver = _shell_host(tmp_path, _SUDO_REFUSES)
|
|
|
|
result = driver.refresh_available_updates()
|
|
|
|
assert result["success"] is False
|
|
assert "a password is required" in result["output"]
|
|
assert "NOPASSWD" in result["output"] # the hint
|
|
|
|
|
|
@needs_bash
|
|
def test_a_refused_sudo_leaves_the_advisories_unknown(tmp_path):
|
|
driver = _shell_host(tmp_path, _SUDO_REFUSES)
|
|
|
|
assert driver._rpm_security_names() is None
|