diff --git a/CHANGELOG.md b/CHANGELOG.md index ff6b8b1..1b04273 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -30,6 +30,19 @@ recorded here; their history is the git log. - `VmStopRequestMixin.begin_stop_vm(name)`: ask for a VM's clean shutdown and return at once, for callers that wait on a timer instead of in `stop_vm`. No role demands it (NetOrk/netork#1636). +- `SudoHistoryMixin` (`napalm_device_types.sudo_history`): the sudo password an earlier + driver typed into an interactive shell (`echo '' | sudo -S -p "" …`) and + left in the login user's shell history, for a driver to mix in (NetOrk/netork#1090). + The driver says what its lines carry (`SUDO_HISTORY_MARKER`) and which files its + partial sudo left to the login user (`SUDO_ROOT_FILES`), and supplies `run_command`. + - `get_history_sudo_lines()` counts the lines per history file (`~/.bash_history`, + `~/.zsh_history`, `~/.ash_history`, `~/.sh_history`) with `grep -c` as the login + user. No line is read back; a file it cannot read raises. + - `remove_history_sudo_lines()` deletes exactly those lines as the login user (`sed + -i`, its backup overwritten with `shred -u`), and as root gives each of + `SUDO_ROOT_FILES` back to `root:root` where it is a regular file, not a symbolic + link, owned by the login user. It reports every file's lines before and after, + how many were removed and which files are root's again. Nothing goes to stdin. ## [4.22.0] - 2026-10-23 diff --git a/README.md b/README.md index 4705be7..8a4c22e 100644 --- a/README.md +++ b/README.md @@ -252,6 +252,16 @@ A driver mixes it in and supplies `run_command`; a platform that regenerates ssh itself (an appliance with its own database) must not, or opts out with `harden_ssh_server = None`. +`SudoHistoryMixin` (`get_history_sudo_lines`, `remove_history_sudo_lines`) deals with what +a driver left behind when it typed `echo '' | sudo -S -p "" …` into an interactive +shell: that line, password and all, in the login user's shell history, and files its partial +sudo wrote as the login user. The driver names the marker its lines carry +(`SUDO_HISTORY_MARKER`) and those files (`SUDO_ROOT_FILES`). The getter counts the lines per +history file with `grep -c`, as the login user; the fix deletes them with `sed -i` and +overwrites the backup with `shred -u`, then gives the files back to root (regular files the +login user owns, never a symbolic link). The password is never read, sent or written. A +driver mixes it in and supplies `run_command`. + **Update readers raise when they cannot read.** `get_available_updates` returns an empty list only when nothing is pending; netOrk keeps "pending since" per package, and an empty list for "don't know" would reset it. diff --git a/napalm_device_types/__init__.py b/napalm_device_types/__init__.py index 8945a20..b61a8ae 100644 --- a/napalm_device_types/__init__.py +++ b/napalm_device_types/__init__.py @@ -55,6 +55,7 @@ instead of being restated on every role that happens to need it: * :class:`~napalm_device_types.ping_sweep.PingSweepMixin` * :class:`~napalm_device_types.service_clusters.ServiceClustersMixin` * :class:`~napalm_device_types.service_packages.ServicePackagesMixin` +* :class:`~napalm_device_types.sudo_history.SudoHistoryMixin` * :class:`~napalm_device_types.services.ServiceControlMixin` * :class:`~napalm_device_types.systemd.SystemdServicesMixin` * :class:`~napalm_device_types.updates.UpdateMixin` @@ -198,6 +199,12 @@ from napalm_device_types.ssh_server import ( plan_ssh_hardening, ) from napalm_device_types.storage import StorageDriver +from napalm_device_types.sudo_history import ( + HistoryCleanupDict, + HistorySudoLinesDict, + SudoHistoryCleanupDict, + SudoHistoryMixin, +) from napalm_device_types.switch import SwitchDriver from napalm_device_types.system_identity import ( SYSTEM_IDENTITY_COMMAND, @@ -338,6 +345,10 @@ __all__ = [ "SshHardeningPlan", "SshHardeningResult", "plan_ssh_hardening", + "SudoHistoryMixin", + "HistorySudoLinesDict", + "HistoryCleanupDict", + "SudoHistoryCleanupDict", "SSH_HOST_KEYS_ARG", "SSH_HOST_KEY_OBSERVER_ARG", "HostKeyCheck", diff --git a/napalm_device_types/sudo_history.py b/napalm_device_types/sudo_history.py new file mode 100644 index 0000000..865adb6 --- /dev/null +++ b/napalm_device_types/sudo_history.py @@ -0,0 +1,312 @@ +"""The sudo password an earlier driver left in shell histories, and taking it back. + +A driver that typed ``echo '' | sudo -S -p "" `` into an +interactive shell left that line, password and all, in the login user's shell +history, once per command -- and where only the part before the first ``&&`` +ran as root, it left files root should own to the login user. A driver that has +stopped doing so still leaves both behind on every host it ever reached. + +:class:`SudoHistoryMixin` reads the first as a fact and takes both back. The +commands are the same on every POSIX host, so they live here once; a driver +mixes it in, supplies ``run_command`` and says what it once left behind: +:attr:`~SudoHistoryMixin.SUDO_HISTORY_MARKER` and +:attr:`~SudoHistoryMixin.SUDO_ROOT_FILES`. + +**The password never travels.** Lines are counted with ``grep -c`` and deleted +with ``sed``, both matching the marker only, as the login user who owns the +history. Nothing of a line's content is read back, and nothing goes to stdin. + +**What is deleted is gone from the disk too, as far as a file can say.** ``sed +-i`` with a backup suffix renames the old file to the backup and writes a new +one; the backup -- the old file's blocks -- is overwritten with ``shred -u``, +or removed with ``rm`` where there is no ``shred``. Backups, snapshots and an +audit log of the host may still hold the password: only rotating it ends that. + +**A file given back to root** must exist as a regular file, not be a symbolic +link, and be owned by the login user. ``chown -h`` never follows a link that +appears in between. +""" + +from __future__ import annotations + +from collections.abc import Callable +from shlex import quote +from typing import TYPE_CHECKING, ClassVar + +from typing_extensions import TypedDict + +from napalm_device_types.fixes import run_fix_steps +from napalm_device_types.models import FixResultDict, FixStepDict, FixStepOutcomeDict + +if TYPE_CHECKING: # pragma: no cover - for type checkers only + from napalm_device_types.channel import CommandResult + +#: The shell history files looked at, in the login user's home. +HISTORY_FILES = (".bash_history", ".zsh_history", ".ash_history", ".sh_history") + +#: The suffix of the moment's backup ``sed -i`` makes; it carries no application's name. +HISTORY_BACKUP_SUFFIX = ".napalm-bak" + +_COUNT = 'LC_ALL=C grep -c -F -e "$m" -- "$p"' + + +class HistorySudoLinesDict(TypedDict): + """A history file holding lines with the sudo password (``get_history_sudo_lines``).""" + + #: The file, as ``~/``. + file: str + lines: int + + +class HistoryCleanupDict(TypedDict): + """What one history file held before the cleanup and holds after it.""" + + file: str + before: int + after: int + + +class SudoHistoryCleanupDict(FixResultDict): + """The result of ``remove_history_sudo_lines``: the fix, and what it changed.""" + + #: Every history file there is, with its lines before and after. + files: list[HistoryCleanupDict] + #: How many lines were deleted, over all files. + removed: int + #: The files given back to root. + owners_restored: list[str] + + +def _bre(text: str) -> str: + """*text* as a POSIX basic regular expression matching it literally, for ``sed``.""" + return "".join("\\" + c if c in "\\.[]*^$/" else c for c in text) + + +def _history_loop(body: str) -> str: + names = " ".join(HISTORY_FILES) + return f'for f in {names}; do p="$HOME/$f"; [ -f "$p" ] || continue; {body}; done' + + +def count_script(marker: str) -> str: + """Print `` `` per history file there is; exit 2 when one cannot be read.""" + return f"m={quote(marker)}; " + _history_loop( + f'n=$({_COUNT}); [ $? -le 1 ] || exit 2; printf "%s %s\\n" "$n" "$f"' + ) + + +def cleanup_script(marker: str) -> str: + """Delete the lines holding *marker* from every history file there is. + + Prints per file: ``done ``, ``link `` + (left alone), ``unreadable `` or ``failed ``. + """ + backup = f'"$p"{quote(HISTORY_BACKUP_SUFFIX)}' + return f"m={quote(marker)}; r={quote(_bre(marker))}; " + _history_loop( + f"b=$({_COUNT}); " + '[ $? -le 1 ] || { printf "unreadable %s\\n" "$f"; continue; }; ' + 'if [ -L "$p" ]; then printf "link %s %s\\n" "$b" "$f"; continue; fi; ' + 'if [ "$b" -gt 0 ]; then ' + f'LC_ALL=C sed -i{quote(HISTORY_BACKUP_SUFFIX)} -e "/$r/d" "$p"; s=$?; ' + # A sed that renamed the file away and wrote no new one: the backup is the history. + f'[ -e "$p" ] || mv -f {backup} "$p"; ' + f"[ -e {backup} ] && {{ shred -u {backup} 2>/dev/null || rm -f {backup}; }}; " + '[ $s -eq 0 ] || { printf "failed %s %s\\n" "$b" "$f"; continue; }; ' + "fi; " + f'a=$({_COUNT}); printf "done %s %s %s\\n" "$b" "$a" "$f"' + ) + + +def owners_script(user: str, paths: tuple[str, ...]) -> str: + """As root: give each of *paths* back to root:root where *user* owns it. + + Prints ``fixed `` or ``failed `` per file it changed or tried to. + """ + return ( + f"u={quote(user)}; for p in {' '.join(quote(p) for p in paths)}; do " + '[ -f "$p" ] && [ ! -L "$p" ] || continue; ' + '[ -n "$(find "$p" -prune -user "$u" 2>/dev/null)" ] || continue; ' + 'if chown -h 0:0 "$p"; then printf "fixed %s\\n" "$p"; ' + 'else printf "failed %s\\n" "$p"; fi; done' + ) + + +def _home(name: str) -> str: + return f"~/{name}" + + +def _lines(n: int) -> str: + return "1 line" if n == 1 else f"{n} lines" + + +def _done(rest: list[str]) -> tuple[bool, str, HistoryCleanupDict | None]: + before, after, name = int(rest[0]), int(rest[1]), _home(rest[2]) + removed = before - after + text = ( + f"{name}: {_lines(removed)} removed ({before} before, {after} after)" + if before + else f"{name}: no such line" + ) + return after == 0, text, {"file": name, "before": before, "after": after} + + +def _link(rest: list[str]) -> tuple[bool, str, HistoryCleanupDict | None]: + count = int(rest[0]) + return count == 0, f"{_home(rest[1])}: a symbolic link, left alone ({_lines(count)})", None + + +def _unreadable(rest: list[str]) -> tuple[bool, str, HistoryCleanupDict | None]: + return False, f"{_home(rest[0])}: cannot be read", None + + +def _failed(rest: list[str]) -> tuple[bool, str, HistoryCleanupDict | None]: + kept = _lines(int(rest[0])) + return False, f"{_home(rest[1])}: could not be rewritten ({kept} kept)", None + + +#: Per kind of line :func:`cleanup_script` prints: how many words follow, and what it says. +_CLEANUP_LINES: dict[ + str, tuple[int, Callable[[list[str]], tuple[bool, str, HistoryCleanupDict | None]]] +] = { + "done": (3, _done), + "link": (2, _link), + "unreadable": (1, _unreadable), + "failed": (2, _failed), +} + + +class SudoHistoryMixin: + """Reads and removes the sudo password an earlier driver left in shell histories. + + Mixed in by the drivers that once typed it into a shell, not by a base + class, so ``callable(getattr(driver, "get_history_sudo_lines", None))`` + stays a truthful answer. + """ + + #: What every line carries that typed the sudo password into the shell, as a + #: fixed string -- ``"| sudo -S -p "`` for ``echo '' | sudo -S -p "" + #: ``. None for a driver that never did: nothing is looked for. + SUDO_HISTORY_MARKER: ClassVar[str | None] = None + + #: Files an earlier version wrote as the login user where root should have. + SUDO_ROOT_FILES: ClassVar[tuple[str, ...]] = () + + if TYPE_CHECKING: # pragma: no cover - declared for type checkers only + + def run_command( + self, + command: str, + *, + privileged: bool = False, + timeout: float = 60, + stdin: bytes | None = None, + ) -> CommandResult: ... + + def get_history_sudo_lines(self) -> list[HistorySudoLinesDict]: + """The login user's history files that hold lines with the sudo password, and how many. + + A fact: counted with ``grep -c`` as the login user; no line is read. + An empty list when no file holds one, or the driver never typed it. + + :raises RuntimeError: when a history file cannot be read. + """ + marker = self.SUDO_HISTORY_MARKER + if not marker: + return [] + result = self.run_command(count_script(marker), timeout=30) + if result.exit_code != 0: + raise RuntimeError( + f"cannot count the shell history: {(result.stderr or result.stdout).strip()}" + ) + found: list[HistorySudoLinesDict] = [] + for line in result.stdout.splitlines(): + count, _, name = line.strip().partition(" ") + if count.isdigit() and int(count) and name: + found.append({"file": _home(name), "lines": int(count)}) + return found + + def remove_history_sudo_lines(self) -> SudoHistoryCleanupDict: + """Delete those lines, as the login user, and give :attr:`SUDO_ROOT_FILES` back to root. + + Two steps, ``history`` and ``owners``; the second runs when the first + failed, too. Succeeds when no history file holds such a line any more + and every file the login user owned is root's again. + """ + files: list[HistoryCleanupDict] = [] + restored: list[str] = [] + parts = [ + run_fix_steps([("history", lambda: self._clean_histories(files))]), + run_fix_steps([("owners", lambda: self._restore_owners(restored))]), + ] + steps: list[FixStepDict] = [s for part in parts for s in part["steps"]] + return { + "success": all(part["success"] for part in parts), + "steps": steps, + "output": "\n".join(f"[{s['step']}] {s['output']}".rstrip() for s in steps), + "files": files, + "removed": sum(f["before"] - f["after"] for f in files), + "owners_restored": restored, + } + + def _clean_histories(self, files: list[HistoryCleanupDict]) -> FixStepOutcomeDict: + marker = self.SUDO_HISTORY_MARKER + if not marker: + return {"ok": True, "output": "this driver never typed the sudo password"} + result = self.run_command(cleanup_script(marker), timeout=60) + said: list[str] = [] + ok = result.exit_code == 0 + for line in result.stdout.splitlines(): + ok = self._history_line(line.split(), files, said) and ok + if result.exit_code != 0: + said.append((result.stderr or result.stdout).strip()) + return {"ok": ok, "output": "\n".join(said) or "no shell history"} + + @staticmethod + def _history_line(words: list[str], files: list[HistoryCleanupDict], said: list[str]) -> bool: + """Take one line of :func:`cleanup_script` into *files* and *said*; whether it is clean.""" + kind, rest = (words[0], words[1:]) if words else ("", []) + read = _CLEANUP_LINES.get(kind) + if read is None or len(rest) != read[0]: + return True + clean, text, entry = read[1](rest) + said.append(text) + if entry is not None: + files.append(entry) + return clean + + def _restore_owners(self, restored: list[str]) -> FixStepOutcomeDict: + paths = tuple(self.SUDO_ROOT_FILES) + if not paths: + return {"ok": True, "output": "no file to check"} + who = self.run_command("id -u; id -un", timeout=30).stdout.split() + if len(who) < 2: + return {"ok": False, "output": "cannot tell who the login user is"} + uid, user = who[0], who[1] + if uid == "0": + return {"ok": True, "output": "logged in as root: every file it wrote is root's"} + result = self.run_command(owners_script(user, paths), privileged=True, timeout=30) + said: list[str] = [] + ok = result.exit_code == 0 + for line in result.stdout.splitlines(): + kind, _, path = line.strip().partition(" ") + if kind == "fixed": + restored.append(path) + said.append(f"{path}: owned by root again") + elif kind == "failed": + ok = False + said.append(f"{path}: could not be given back to root") + if result.exit_code != 0: + said.append((result.stderr or result.stdout).strip()) + return {"ok": ok, "output": "\n".join(said) or f"no file owned by {user}"} + + +__all__ = [ + "HISTORY_BACKUP_SUFFIX", + "HISTORY_FILES", + "HistoryCleanupDict", + "HistorySudoLinesDict", + "SudoHistoryCleanupDict", + "SudoHistoryMixin", + "cleanup_script", + "count_script", + "owners_script", +] diff --git a/tests/test_sudo_history.py b/tests/test_sudo_history.py new file mode 100644 index 0000000..76d62e6 --- /dev/null +++ b/tests/test_sudo_history.py @@ -0,0 +1,395 @@ +"""The sudo password an earlier driver left in shell histories, and taking it back. + +The scripts are run for real, with ``sh``, against a home directory in a temp +directory: what they count, delete and report is what a host would see. Root's +part -- giving files back to root -- runs with a ``chown`` that only records, +so the test needs no root. +""" + +from __future__ import annotations + +import getpass +import os +import subprocess +from pathlib import Path + +import pytest + +from napalm_device_types.channel import CommandResult +from napalm_device_types.sudo_history import HISTORY_BACKUP_SUFFIX, SudoHistoryMixin + +MARKER = "| sudo -S -p " + +LEAKED = "echo 'hunter2' | sudo -S -p \"\" apt-get update\n" +OTHER = "ls -la\n" + + +class _Host(SudoHistoryMixin): + """A driver whose host is this machine, with *home* as the login user's home.""" + + SUDO_HISTORY_MARKER = MARKER + + def __init__(self, home: Path, bin_dir: Path, *, root: bool = False) -> None: + self.home = home + self.bin_dir = bin_dir + self.root = root + #: Who ``id -un`` says the login user is; None for this machine's user name. + self.user: str | None = None + self.ran: list[tuple[str, bool]] = [] + + def run_command( + self, + command: str, + *, + privileged: bool = False, + timeout: float = 60, + stdin: bytes | None = None, + ) -> CommandResult: + # The password goes ahead of a privileged command's stdin: there must be none. + assert not (privileged and stdin is not None) + self.ran.append((command, privileged)) + env = { + **os.environ, + "HOME": str(self.home), + "PATH": f"{self.bin_dir}:{os.environ['PATH']}", + } + if command.strip() == "id -u; id -un" and self.root: + return CommandResult("0\nroot\n", "", 0) + if command.strip() == "id -u; id -un": + # Never this machine's uid: CI runs as root, which the owner step skips. + return CommandResult(f"4242\n{self.user or getpass.getuser()}\n", "", 0) + done = subprocess.run( # noqa: S603 - the test's own scripts + ["sh", "-c", command], capture_output=True, text=True, env=env, timeout=timeout + ) + return CommandResult(done.stdout, done.stderr, done.returncode) + + +@pytest.fixture +def bin_dir(tmp_path: Path) -> Path: + """A ``chown`` that records its arguments instead of changing anything.""" + d = tmp_path / "bin" + d.mkdir() + chown = d / "chown" + chown.write_text(f'#!/bin/sh\nprintf "%s\\n" "$*" >> {tmp_path / "chowned"}\n') + chown.chmod(0o755) + return d + + +@pytest.fixture +def home(tmp_path: Path) -> Path: + h = tmp_path / "home" + h.mkdir() + return h + + +def _chowned(tmp_path: Path) -> list[str]: + log = tmp_path / "chowned" + return log.read_text().splitlines() if log.exists() else [] + + +class TestCounting: + def test_counts_the_lines_per_history_file_without_reading_them_out(self, home, bin_dir): + (home / ".bash_history").write_text(OTHER + LEAKED * 3) + (home / ".zsh_history").write_text(": 1700000000:0;" + LEAKED) + (home / ".sh_history").write_text(OTHER) + host = _Host(home, bin_dir) + + found = host.get_history_sudo_lines() + + assert found == [ + {"file": "~/.bash_history", "lines": 3}, + {"file": "~/.zsh_history", "lines": 1}, + ] + # Counted as the login user, and nothing of the content came back. + assert all(not privileged for _cmd, privileged in host.ran) + assert "hunter2" not in repr(found) + + def test_no_history_no_lines(self, home, bin_dir): + assert _Host(home, bin_dir).get_history_sudo_lines() == [] + + def test_the_pattern_is_a_fixed_string(self, home, bin_dir): + # "-S" is no regex trouble, but "|" would be an alternation in an ERE. + (home / ".bash_history").write_text("sudo -S -p\n| sudo\n") + assert _Host(home, bin_dir).get_history_sudo_lines() == [] + + def test_a_driver_that_never_typed_the_password_counts_nothing(self, home, bin_dir): + (home / ".bash_history").write_text(LEAKED) + host = _Host(home, bin_dir) + host.SUDO_HISTORY_MARKER = None + + assert host.get_history_sudo_lines() == [] + assert host.ran == [] + + def test_an_unreadable_history_raises_rather_than_reporting_none(self, home, bin_dir): + if os.geteuid() == 0: + pytest.skip("root reads every file") + history = home / ".bash_history" + history.write_text(LEAKED) + history.chmod(0) + try: + with pytest.raises(RuntimeError): + _Host(home, bin_dir).get_history_sudo_lines() + finally: + history.chmod(0o600) + + +class TestRemoving: + def test_deletes_exactly_those_lines_and_says_how_many(self, home, bin_dir): + (home / ".bash_history").write_text(OTHER + LEAKED + "cd /etc\n" + LEAKED) + (home / ".ash_history").write_text(LEAKED) + host = _Host(home, bin_dir) + + result = host.remove_history_sudo_lines() + + assert result["success"] is True + assert (home / ".bash_history").read_text() == OTHER + "cd /etc\n" + assert (home / ".ash_history").read_text() == "" + assert result["removed"] == 3 + assert result["files"] == [ + {"file": "~/.bash_history", "before": 2, "after": 0}, + {"file": "~/.ash_history", "before": 1, "after": 0}, + ] + assert "~/.bash_history: 2 lines removed (2 before, 0 after)" in result["output"] + + def test_no_backup_with_the_password_is_left_behind(self, home, bin_dir): + (home / ".bash_history").write_text(LEAKED) + + _Host(home, bin_dir).remove_history_sudo_lines() + + assert sorted(p.name for p in home.iterdir()) == [".bash_history"] + assert not (home / f".bash_history{HISTORY_BACKUP_SUFFIX}").exists() + + def test_the_history_runs_as_the_login_user(self, home, bin_dir): + (home / ".bash_history").write_text(LEAKED) + host = _Host(home, bin_dir) + + host.remove_history_sudo_lines() + + history_scripts = [(c, p) for c, p in host.ran if ".bash_history" in c] + assert history_scripts and all(not p for _c, p in history_scripts) + + def test_a_clean_history_is_left_as_it_is(self, home, bin_dir): + history = home / ".bash_history" + history.write_text(OTHER) + before = history.stat().st_ino + + result = _Host(home, bin_dir).remove_history_sudo_lines() + + assert result["success"] is True + assert result["removed"] == 0 + assert result["files"] == [{"file": "~/.bash_history", "before": 0, "after": 0}] + assert history.stat().st_ino == before # not rewritten + + def test_a_history_that_is_a_link_is_left_alone_and_the_fix_fails( + self, home, bin_dir, tmp_path + ): + target = tmp_path / "elsewhere" + target.write_text(LEAKED) + (home / ".bash_history").symlink_to(target) + + result = _Host(home, bin_dir).remove_history_sudo_lines() + + assert result["success"] is False + assert target.read_text() == LEAKED + assert (home / ".bash_history").is_symlink() + assert "~/.bash_history: a symbolic link, left alone (1 line)" in result["output"] + + def test_the_lines_of_a_driver_that_never_typed_the_password_are_not_looked_for( + self, home, bin_dir + ): + host = _Host(home, bin_dir) + host.SUDO_HISTORY_MARKER = None + + result = host.remove_history_sudo_lines() + + assert result["success"] is True + assert result["removed"] == 0 + + def test_an_unreadable_history_fails_the_step(self, home, bin_dir): + if os.geteuid() == 0: + pytest.skip("root reads every file") + history = home / ".bash_history" + history.write_text(LEAKED) + history.chmod(0) + try: + result = _Host(home, bin_dir).remove_history_sudo_lines() + finally: + history.chmod(0o600) + + assert result["success"] is False + assert "~/.bash_history: cannot be read" in result["output"] + + def test_a_sed_that_fails_keeps_the_lines_and_leaves_no_backup(self, home, bin_dir): + (bin_dir / "sed").write_text( + '#!/bin/sh\nfor a; do f="$a"; done\ncp "$f" "$f.napalm-bak"\nexit 4\n' + ) + (bin_dir / "sed").chmod(0o755) + (home / ".bash_history").write_text(LEAKED * 2) + + result = _Host(home, bin_dir).remove_history_sudo_lines() + + assert result["success"] is False + assert "~/.bash_history: could not be rewritten (2 lines kept)" in result["output"] + assert sorted(p.name for p in home.iterdir()) == [".bash_history"] + + def test_a_sed_that_lost_the_file_gets_it_back(self, home, bin_dir): + (bin_dir / "sed").write_text( + '#!/bin/sh\nfor a; do f="$a"; done\nmv "$f" "$f.napalm-bak"\nexit 4\n' + ) + (bin_dir / "sed").chmod(0o755) + (home / ".bash_history").write_text(OTHER + LEAKED) + + result = _Host(home, bin_dir).remove_history_sudo_lines() + + assert result["success"] is False + assert (home / ".bash_history").read_text() == OTHER + LEAKED + assert sorted(p.name for p in home.iterdir()) == [".bash_history"] + + def test_a_script_that_dies_says_why(self, home, bin_dir): + host = _Host(home, bin_dir) + host.run_command = lambda command, **kw: CommandResult("", "sh: killed", 137) # type: ignore[method-assign] + + result = host.remove_history_sudo_lines() + + assert result["success"] is False + assert "sh: killed" in result["output"] + + def test_a_line_it_does_not_know_is_ignored(self): + files: list = [] + said: list[str] = [] + + assert SudoHistoryMixin._history_line(["what", "ever"], files, said) is True + assert SudoHistoryMixin._history_line([], files, said) is True + assert files == [] and said == [] + + +class TestOwners: + def _host(self, home, bin_dir, files): + host = _Host(home, bin_dir) + host.SUDO_ROOT_FILES = tuple(str(f) for f in files) + return host + + def test_a_file_the_login_user_owns_goes_back_to_root(self, home, bin_dir, tmp_path): + conf = tmp_path / "snmpd.conf" + conf.write_text("x") + + result = self._host(home, bin_dir, [conf]).remove_history_sudo_lines() + + assert _chowned(tmp_path) == [f"-h 0:0 {conf}"] + assert result["owners_restored"] == [str(conf)] + assert result["success"] is True + + def test_only_as_root_and_without_stdin(self, home, bin_dir, tmp_path): + conf = tmp_path / "snmpd.conf" + conf.write_text("x") + host = self._host(home, bin_dir, [conf]) + + host.remove_history_sudo_lines() + + privileged = [c for c, p in host.ran if p] + assert len(privileged) == 1 and "chown" in privileged[0] + # The login user's name is quoted into root's script, never taken from stdin. + assert getpass.getuser() in privileged[0] + + def test_a_link_or_a_missing_file_is_not_touched(self, home, bin_dir, tmp_path): + real = tmp_path / "real" + real.write_text("x") + link = tmp_path / "00proxy" + link.symlink_to(real) + + result = self._host(home, bin_dir, [link, tmp_path / "missing"]).remove_history_sudo_lines() + + assert _chowned(tmp_path) == [] + assert result["owners_restored"] == [] + assert result["success"] is True + + def test_a_file_someone_else_owns_is_not_touched(self, home, bin_dir, tmp_path): + conf = tmp_path / "snmpd.conf" + conf.write_text("x") + host = self._host(home, bin_dir, [conf]) + host.user = "nobody-here-4242" + + result = host.remove_history_sudo_lines() + + assert _chowned(tmp_path) == [] + assert result["owners_restored"] == [] + + def test_a_root_login_has_nothing_to_give_back(self, home, bin_dir, tmp_path): + conf = tmp_path / "snmpd.conf" + conf.write_text("x") + host = self._host(home, bin_dir, [conf]) + host.root = True + + result = host.remove_history_sudo_lines() + + assert _chowned(tmp_path) == [] + assert result["success"] is True + + def test_the_owners_are_set_even_when_the_history_could_not_be_cleaned( + self, home, bin_dir, tmp_path + ): + target = tmp_path / "elsewhere" + target.write_text(LEAKED) + (home / ".bash_history").symlink_to(target) + conf = tmp_path / "snmpd.conf" + conf.write_text("x") + + result = self._host(home, bin_dir, [conf]).remove_history_sudo_lines() + + assert result["success"] is False + assert [s["step"] for s in result["steps"]] == ["history", "owners"] + assert result["owners_restored"] == [str(conf)] + + def test_without_knowing_the_login_user_nothing_changes_owner(self, home, bin_dir, tmp_path): + conf = tmp_path / "snmpd.conf" + conf.write_text("x") + host = self._host(home, bin_dir, [conf]) + real = host.run_command + + def run(command, **kw): + if command.startswith("id "): + return CommandResult("", "id: not found", 127) + return real(command, **kw) + + host.run_command = run # type: ignore[method-assign] + + result = host.remove_history_sudo_lines() + + assert result["success"] is False + assert "cannot tell who the login user is" in result["output"] + assert _chowned(tmp_path) == [] + + def test_a_sudo_that_refuses_fails_the_step(self, home, bin_dir, tmp_path): + conf = tmp_path / "snmpd.conf" + conf.write_text("x") + host = self._host(home, bin_dir, [conf]) + real = host.run_command + + def run(command, *, privileged=False, **kw): + if privileged: + return CommandResult("", "sudo: a password is required", 1) + return real(command, privileged=privileged, **kw) + + host.run_command = run # type: ignore[method-assign] + + result = host.remove_history_sudo_lines() + + assert result["success"] is False + assert "sudo: a password is required" in result["output"] + + def test_a_refused_chown_fails_the_step(self, home, bin_dir, tmp_path): + (bin_dir / "chown").write_text("#!/bin/sh\necho 'Operation not permitted' >&2\nexit 1\n") + conf = tmp_path / "snmpd.conf" + conf.write_text("x") + + result = self._host(home, bin_dir, [conf]).remove_history_sudo_lines() + + assert result["success"] is False + assert result["owners_restored"] == [] + assert f"{conf}: could not be given back to root" in result["output"] + + +def test_exported_from_the_package(): + import napalm_device_types + + assert napalm_device_types.SudoHistoryMixin is SudoHistoryMixin