feat: SudoHistoryMixin, the sudo password left in shell histories (NetOrk/netork#1090)
driver / standard (pull_request) Failing after 7s
driver / lint (pull_request) Successful in 20s
driver / types (pull_request) Successful in 1m8s
driver / test (3.12) (pull_request) Failing after 1m9s
driver / test (3.13) (pull_request) Failing after 1m3s
driver / lowest (pull_request) Failing after 33s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 1m8s
CI / driver (pull_request) Failing after 2m24s
driver / publish (pull_request) Skipped

A driver that typed `echo '<password>' | sudo -S -p "" <command>` 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, files root should own were left to the login user.

get_history_sudo_lines() counts the lines per history file with grep -c,
as the login user, without reading any back. remove_history_sudo_lines()
deletes exactly those lines with sed -i, overwrites the backup with
shred -u, and as root gives the driver's SUDO_ROOT_FILES back to root:root
where each is a regular file, not a link, owned by the login user. It
reports each file's lines before and after. Nothing goes to stdin.

The driver names the marker and the files and supplies run_command.
This commit is contained in:
christianmanivong committed 2026-10-30 21:09:24 +01:00
1 parent 551ed0a29d
commit cb90fa9835
5 files changed
+740

No files matched your search

+11
View File
@@ -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",
+312
View File
@@ -0,0 +1,312 @@
"""The sudo password an earlier driver left in shell histories, and taking it back.
A driver that typed ``echo '<password>' | sudo -S -p "" <command>`` 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 ``~/<name>``.
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 ``<count> <name>`` 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 <before> <after> <name>``, ``link <count> <name>``
(left alone), ``unreadable <name>`` or ``failed <before> <name>``.
"""
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 <path>`` or ``failed <path>`` 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 '<password>' | sudo -S -p ""
#: <command>``. 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",
]