From fbaded5913f6a60541e1431ce867bb683d891c57 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Fri, 30 Oct 2026 21:09:33 +0100 Subject: [PATCH] feat: count and remove the sudo password the old _sudo left in histories (NetOrk/netork#1090) Until NetOrk/netork#1039, _sudo typed `echo '' | sudo -S -p "" ` into netmiko's interactive shell, so the login user's history kept the password once per command, and the part after the first `&&` ran without root, leaving snmpd.conf and apt's 00proxy to the login user. LinuxDriver mixes in napalm-device-types' SudoHistoryMixin and names what to look for: the marker "| sudo -S -p " and those two files. get_history_sudo_lines() and remove_history_sudo_lines() run on the exec channel; OpenMediaVault and QNAP inherit both. The _privileged docstring points at _as_root instead of restating it, so linux.py does not grow. Requires the napalm-device-types release with SudoHistoryMixin. --- CHANGELOG.md | 9 +++ README.md | 8 ++ napalm_linux/_sudo_history.py | 19 +++++ napalm_linux/linux.py | 10 +-- tests/test_sudo_history.py | 140 ++++++++++++++++++++++++++++++++++ 5 files changed, 181 insertions(+), 5 deletions(-) create mode 100644 napalm_linux/_sudo_history.py create mode 100644 tests/test_sudo_history.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 5a63868..407db2e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] ### Added +- 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 + was typed into the interactive shell as `echo '' | sudo -S -p "" …`, so the + login user's history kept the password once per command. `get_history_sudo_lines()` + counts those lines with `grep -c`, without reading them; `remove_history_sudo_lines()` + deletes exactly them and gives `/etc/snmp/snmpd.conf` and `/etc/apt/apt.conf.d/00proxy` + back to `root:root` where the old partial sudo left them to the login user (a regular + file, never a symbolic link). OpenMediaVault and QNAP inherit both. Requires the + napalm-device-types release with `SudoHistoryMixin`. - `set_hostname()` (#45): netOrk could save a Linux host's new name but not apply it ("The driver linux does not support set_hostname()"). The host now takes the short name through `hostnamectl`, or `/etc/hostname` and `hostname(1)` without systemd; diff --git a/README.md b/README.md index 7a93686..955a195 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,14 @@ shell: the password reaches `sudo -S` on stdin, never a command line, so it show the process list nor in a shell history. The interactive session switches its history off before its first command. +Versions before that typed `echo '' | sudo -S -p "" ` into the interactive +shell, so the login user's history kept the password once per command. +`get_history_sudo_lines()` counts those lines per history file without reading them, and +`remove_history_sudo_lines()` deletes exactly them and gives `/etc/snmp/snmpd.conf` and +`/etc/apt/apt.conf.d/00proxy` back to root where they were left to the login user +(napalm-device-types' `SudoHistoryMixin`). Rotate the sudo password afterwards: backups, +snapshots and audit logs may still hold it. + `get_services()` and `manage_service()` come from napalm-device-types' `SystemdServicesMixin`; this driver supplies only the transport. An action runs as `timeout 45 systemctl --no-ask-password -- .service`, so a unit that hangs diff --git a/napalm_linux/_sudo_history.py b/napalm_linux/_sudo_history.py new file mode 100644 index 0000000..24eb149 --- /dev/null +++ b/napalm_linux/_sudo_history.py @@ -0,0 +1,19 @@ +"""What the old ``_sudo`` left on every host it reached (NetOrk/netork#1090). + +Until NetOrk/netork#1039, ``_sudo`` typed ``echo '' | sudo -S -p "" +`` into netmiko's interactive shell, and only the part before the first +``&&`` ran as root. napalm-device-types' ``SudoHistoryMixin`` counts and deletes +those lines and gives the files back to root; this says what to look for. +""" + +from __future__ import annotations + +from napalm_device_types import AptProxyMixin, SudoHistoryMixin + + +class LinuxSudoHistoryMixin(SudoHistoryMixin): + #: Every line the old ``_sudo`` typed carries it, with the sudo password before it. + SUDO_HISTORY_MARKER = "| sudo -S -p " + #: Written as the login user where the part that should have been root's came + #: after the first ``&&``: snmpd.conf (``configure_snmp_agent``) and apt's proxy. + SUDO_ROOT_FILES = ("/etc/snmp/snmpd.conf", AptProxyMixin.APT_PROXY_FILE) diff --git a/napalm_linux/linux.py b/napalm_linux/linux.py index c01f49b..6bc555d 100644 --- a/napalm_linux/linux.py +++ b/napalm_linux/linux.py @@ -74,6 +74,7 @@ from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutExc from napalm_linux._hostname import HostnameMixin from napalm_linux._shell import PROMPT_RE as _PROMPT_RE from napalm_linux._shell import prepare_shell +from napalm_linux._sudo_history import LinuxSudoHistoryMixin logger = logging.getLogger("napalm_linux") @@ -305,6 +306,7 @@ def render_snmpd_conf(settings: SnmpAgentSettingsDict) -> str: class LinuxDriver( + LinuxSudoHistoryMixin, SnmpAgentMixin, EnsurePackageMixin, AptProxyMixin, @@ -547,12 +549,10 @@ class LinuxDriver( def _privileged(self, command: str, privileged: bool) -> tuple[str, bytes | None]: """The command line that runs *command* with the privileges asked for, - and what has to reach its stdin first. + and what has to reach its stdin first: root's as ``_as_root`` says. - Root runs it directly. With a sudo password, ``sudo -S`` reads it from - stdin, so it never appears in a process list. Without one, ``sudo -n`` - fails at once where a prompt would hang. The command goes to ``sh -c`` - as one argument, so the privilege covers every part of it. + The command goes to ``sh -c`` as one argument, so the privilege covers + every part of it. """ if not privileged or self._is_root(): return command, None diff --git a/tests/test_sudo_history.py b/tests/test_sudo_history.py new file mode 100644 index 0000000..580fbad --- /dev/null +++ b/tests/test_sudo_history.py @@ -0,0 +1,140 @@ +"""What the old ``_sudo`` left on every host, and taking it back (NetOrk/netork#1090). + +Until NetOrk/netork#1039, ``_sudo`` typed ``echo '' | sudo -S -p "" +`` into netmiko's interactive shell: the login user's history kept the +password once per command. Where only the part before the first ``&&`` ran as +root, snmpd.conf and apt's proxy file were left to the login user. The driver +says so through napalm-device-types' ``SudoHistoryMixin``, which counts and +deletes the lines and gives the files back to root. +""" + +from __future__ import annotations + +import shlex +from types import SimpleNamespace +from unittest.mock import MagicMock + +from napalm_device_types import SudoHistoryMixin + +from napalm_linux import LinuxDriver +from napalm_linux.linux import _SNMPD_CONF + +_PW = "s3cr3t" + + +class _Channel: + def __init__(self, transport: _Transport): + self.transport = transport + self.command = "" + self.stdin = b"" + self._out = b"" + + def exec_command(self, command): + self.command = command + self.transport.commands.append(command) + self._out = self.transport.answer(command).encode() + + def settimeout(self, timeout): + pass + + def sendall(self, data): + self.stdin += data + + def shutdown_write(self): + pass + + def close(self): + pass + + def recv_ready(self): + return bool(self._out) + + def recv(self, size): + chunk, self._out = self._out[:size], self._out[size:] + return chunk + + def recv_stderr_ready(self): + return False + + def recv_stderr(self, size): + return b"" + + def exit_status_ready(self): + return not self._out + + def recv_exit_status(self): + return 0 + + +class _Transport: + def __init__(self, answers: dict[str, str]): + self.answers = answers + self.commands: list[str] = [] + self.channels: list[_Channel] = [] + + def answer(self, command: str) -> str: + return next((out for key, out in self.answers.items() if key in command), "") + + def open_session(self): + self.channels.append(_Channel(self)) + return self.channels[-1] + + +def _driver(answers: dict[str, str]) -> tuple[LinuxDriver, _Transport]: + driver = LinuxDriver("h", "admin", "p", optional_args={"sudo_password": _PW}) + transport = _Transport(answers) + driver._device = MagicMock() + driver._device.remote_conn_pre = SimpleNamespace(get_transport=lambda: transport) + driver._root = False + return driver, transport + + +def test_the_marker_is_what_the_old_sudo_typed(): + typed = f'echo {shlex.quote(_PW)} | sudo -S -p "" apt-get update' + assert isinstance(LinuxDriver.SUDO_HISTORY_MARKER, str) + assert LinuxDriver.SUDO_HISTORY_MARKER in typed + + +def test_the_files_the_partial_sudo_left_to_the_login_user(): + assert LinuxDriver.SUDO_ROOT_FILES == ( + _SNMPD_CONF, + LinuxDriver.APT_PROXY_FILE, + ) + assert LinuxDriver.APT_PROXY_FILE == "/etc/apt/apt.conf.d/00proxy" + + +def test_it_is_the_device_types_mixin(): + assert issubclass(LinuxDriver, SudoHistoryMixin) + + +def test_counting_runs_as_the_login_user_on_the_exec_channel(): + driver, transport = _driver({"grep -c": "121 .bash_history\n0 .zsh_history\n"}) + + assert driver.get_history_sudo_lines() == [{"file": "~/.bash_history", "lines": 121}] + + # No sudo, no password on stdin, nothing typed into the interactive shell + # (whose history is where the lines came from). + assert not transport.channels[-1].command.startswith("sudo") + assert transport.channels[-1].stdin == b"" + driver._device.send_command.assert_not_called() + + +def test_the_owner_fix_runs_as_root_without_stdin_but_the_password(): + driver, transport = _driver( + { + "sed -i": "done 3 0 .bash_history\n", + "id -u": "1000\nadmin\n", + "chown": "fixed /etc/snmp/snmpd.conf\n", + } + ) + + result = driver.remove_history_sudo_lines() + + assert result["success"] is True + assert result["removed"] == 3 + assert result["owners_restored"] == ["/etc/snmp/snmpd.conf"] + root = [c for c in transport.channels if c.command.startswith("sudo -S")] + assert len(root) == 1 and "chown -h 0:0" in root[0].command + # sudo -S reads the password, and the command itself reads nothing. + assert root[0].stdin == f"{_PW}\n".encode() + assert all(c.stdin == b"" for c in transport.channels if c is not root[0]) -- 2.54.0