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
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:
1 parent
551ed0a29d
commit
cb90fa9835
5 files changed
+740
No files matched your search
@@ -0,0 +1,394 @@
|
||||
"""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 answer.
|
||||
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" and self.user:
|
||||
return CommandResult(f"4242\n{self.user}\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
|
||||
Reference in new issue
Block a user