fix(sudo): run the whole command as root without a sudo password
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
This commit is contained in:
1 parent
c2d7c4d1b4
commit
d3134c83b8
5 files changed
+232
-7
No files matched your search
@@ -45,6 +45,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
||||
on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6).
|
||||
|
||||
### Fixed
|
||||
- `get_available_updates()` works on dnf and yum hosts whose login user has
|
||||
passwordless sudo (NOPASSWD), as netOrk's own account does, and marks the security
|
||||
fixes there (#56). The security-advisory query did not parse under `sudo -n`, so no
|
||||
answer came back and the read ran into its 120 s timeout. Without a sudo password a
|
||||
privileged command now runs as root as a whole, in one `sh -c`, as it already did
|
||||
with a password; before, only its first command did. A refused sudo still reports
|
||||
its exit status at once.
|
||||
- `ping()` passes `destination` and `source` to the host's shell as one quoted word
|
||||
each (#55). A destination such as `192.0.2.1; id` ran the command after the `;` as
|
||||
the login user. `count`, `timeout`, `size` and `ttl` must be numbers; anything else
|
||||
|
||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from shlex import quote
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -17,6 +18,10 @@ PROMPT_RE = r"[#$\>]\s*$"
|
||||
#: napalm-device-types.
|
||||
STATUS_ECHO_RE = re.compile(r"echo\s+(__[A-Z_]+=)\$\?")
|
||||
|
||||
#: The same echo as the last command of a line: ``sudo_without_password`` keeps it
|
||||
#: outside sudo.
|
||||
_TRAILING_STATUS_ECHO_RE = re.compile(r";\s*echo\s+__[A-Z_]+=\$\?\s*$")
|
||||
|
||||
|
||||
def expect_for(command: str) -> str:
|
||||
"""The pattern that ends *command*'s output.
|
||||
@@ -35,6 +40,20 @@ def expect_for(command: str) -> str:
|
||||
return re.escape(markers[-1]) + r"\d+\s*\n.*" + PROMPT_RE
|
||||
|
||||
|
||||
def sudo_without_password(command: str) -> str:
|
||||
"""The line that runs all of *command* as root through ``sudo -n`` (#56).
|
||||
|
||||
The command goes to ``sh -c`` as one argument: ``sudo -n <command>`` covered only
|
||||
its first simple command, and one that starts with a brace group did not parse.
|
||||
A status echo at its end stays outside and reports sh's status, the command's:
|
||||
it arrives when sudo refuses as well, where netmiko would otherwise wait for it
|
||||
until the read timeout.
|
||||
"""
|
||||
echo = _TRAILING_STATUS_ECHO_RE.search(command)
|
||||
body, tail = (command[: echo.start()], echo.group()) if echo else (command, "")
|
||||
return f"sudo -n sh -c {quote(body)}{tail}"
|
||||
|
||||
|
||||
#: Sent before anything else in the interactive session (NetOrk/netork#1039):
|
||||
#: the shell writes no history file and records nothing more. The leading space
|
||||
#: keeps this line itself out of a history under ``HISTCONTROL=ignorespace``;
|
||||
|
||||
@@ -76,7 +76,7 @@ from napalm_linux._hostname import HostnameMixin
|
||||
from napalm_linux._local_accounts import LinuxLocalAccountsMixin
|
||||
from napalm_linux._ping import parse_ping, ping_command
|
||||
from napalm_linux._routes import IP_ROUTE_COMMANDS, parse_ip_route
|
||||
from napalm_linux._shell import expect_for, prepare_shell
|
||||
from napalm_linux._shell import expect_for, prepare_shell, sudo_without_password
|
||||
from napalm_linux._sudo_history import LinuxSudoHistoryMixin
|
||||
|
||||
logger = logging.getLogger("napalm_linux")
|
||||
@@ -510,14 +510,14 @@ class LinuxDriver(
|
||||
return self._run_privileged(command, timeout)
|
||||
|
||||
def _run_privileged(self, command: str, timeout: float = 100) -> str:
|
||||
"""Run *command* as root: directly for a root login, through ``_sudo``
|
||||
with a sudo password, and through ``sudo -n`` without one -- which fails at
|
||||
once where a password prompt would hang the session until the timeout."""
|
||||
"""Run all of *command* as root: directly for a root login, through ``_sudo``
|
||||
with a sudo password, and through ``sudo -n sh -c`` without one -- which fails
|
||||
at once where a password prompt would hang the session until the timeout."""
|
||||
if self._is_root():
|
||||
return self._send(command, read_timeout=timeout)
|
||||
if self._sudo_password:
|
||||
return self._sudo(command, read_timeout=timeout) # never typed into the shell
|
||||
return self._send(f"sudo -n {command}", read_timeout=timeout)
|
||||
return self._send(sudo_without_password(command), read_timeout=timeout)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Command channel (napalm-device-types CommandChannelMixin)
|
||||
|
||||
+2
-2
@@ -1601,7 +1601,7 @@ class TestManageService:
|
||||
|
||||
driver.manage_service("cron", "enable")
|
||||
|
||||
assert self._sent(driver)[1].startswith("sudo -n timeout 45 systemctl")
|
||||
assert self._sent(driver)[1].startswith("sudo -n sh -c 'timeout 45 systemctl")
|
||||
|
||||
def test_a_missing_sudo_password_is_explained(self, driver):
|
||||
driver._device.send_command.side_effect = [
|
||||
@@ -1832,7 +1832,7 @@ class TestRefreshAvailableUpdates:
|
||||
result = driver.refresh_available_updates()
|
||||
|
||||
assert result["success"] is False
|
||||
assert self._sent(driver)[1].startswith("sudo -n apt-get update")
|
||||
assert self._sent(driver)[1].startswith("sudo -n sh -c 'apt-get update")
|
||||
|
||||
def test_dnf_refreshes_its_metadata(self, driver):
|
||||
driver._pkg_manager = "dnf"
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
"""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
|
||||
Reference in new issue
Block a user