fix(terminal): log a one-time note when a sudo password goes to a non-local backend
A sudo password (SUDO_PASSWORD, terminal.sudo_password or the interactive prompt cache) is sent to whichever terminal backend runs the command. For container, cloud sandbox, SSH and plugin backends, programs running in that backend can read it there. Hermes sent it without saying so. BaseEnvironment._prepare_command, which every backend goes through (managed Modal included), now passes its result to tools/environments/sudo_password_note.note_sudo_password_sent. The first time a non-empty password is sent to a backend whose is_local is False, it logs one WARNING per process per backend class, naming the backend (derived from the class name, e.g. docker, ssh, vercel_sandbox) and advising a password that is only valid there, or passwordless sudo in that environment's image. The password itself is never logged. A lock guards the once-only state. Which backends receive the password, the command text and the sudo stdin are all unchanged. The sudo docs in tools.md, cli-config.yaml.example and .env.example, and the SUDO_PASSWORD row in the environment variable reference, now give the same advice. Tests (tests/tools/test_sudo_password_backend_note.py) go through real execute / _prepare_command calls with a cached password: a non-local backend logs exactly one warning across two commands, docker and ssh each log their own, LocalEnvironment, a command without sudo, no password and an empty password log none, and the message never contains the password. A control test checks that the command text and stdin match the base output for docker, ssh and local.
This commit is contained in:
committed by
Mark S.
parent
8f442bae8e
commit
2570a16785
@@ -273,6 +273,7 @@ TERMINAL_LIFETIME_SECONDS=300
|
||||
# If set, enables sudo commands by piping password via `sudo -S`.
|
||||
# Works with: local, docker, modal, ssh and plugin backends that run sudo (singularity).
|
||||
# The password is sent to the backend that runs the command: use that backend's sudo password.
|
||||
# Programs running in a non-local backend can read it there, so never reuse this machine's password.
|
||||
#
|
||||
# SECURITY WARNING: Password stored in plaintext. Only use on trusted machines.
|
||||
#
|
||||
|
||||
@@ -562,6 +562,10 @@ terminal:
|
||||
# -----------------------------------------------------------------------------
|
||||
# Add sudo_password to any terminal config above to enable sudo commands.
|
||||
# The password is piped via `sudo -S`. Works with local, ssh, docker, etc.
|
||||
# It is sent to the backend that runs the command, where programs running in
|
||||
# that backend can read it: for ssh, docker, modal, daytona, vercel_sandbox and
|
||||
# plugin backends, use a password that is only valid there (or passwordless sudo
|
||||
# in the image), not this machine's. Hermes logs a one-time warning per backend.
|
||||
#
|
||||
# SECURITY WARNING: Password stored in plaintext!
|
||||
#
|
||||
|
||||
151
tests/tools/test_sudo_password_backend_note.py
Normal file
151
tests/tools/test_sudo_password_backend_note.py
Normal file
@@ -0,0 +1,151 @@
|
||||
"""One-time WARNING when a sudo password is sent to a terminal backend other than the local one.
|
||||
|
||||
Every case goes through a real environment's ``execute`` or ``_prepare_command`` with a cached
|
||||
password; the returned command text and sudo stdin must be the same as without the note.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import sys
|
||||
|
||||
import pytest
|
||||
|
||||
from tools import terminal_tool, terminal_tool_sudo
|
||||
from tools.environments.base import BaseEnvironment
|
||||
from tools.environments.docker import DockerEnvironment
|
||||
from tools.environments.local import LocalEnvironment
|
||||
from tools.environments.ssh import SSHEnvironment
|
||||
|
||||
PW = "synthetic-note-pw-3"
|
||||
NOTE_LOGGER = "tools.environments.sudo_password_note"
|
||||
|
||||
|
||||
class _RecordingSandboxEnv(BaseEnvironment):
|
||||
"""Non-local backend that records ``_run_bash`` calls instead of running them."""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(cwd="/", timeout=10)
|
||||
self.calls = []
|
||||
|
||||
def _run_bash(self, cmd_string, *, login=False, timeout=120, stdin_data=None):
|
||||
self.calls.append((cmd_string, stdin_data))
|
||||
return cmd_string
|
||||
|
||||
def _wait_for_process(self, proc, timeout=120, **_kwargs):
|
||||
return {"output": "", "returncode": 0}
|
||||
|
||||
def cleanup(self):
|
||||
pass
|
||||
|
||||
|
||||
def _bare(env_cls):
|
||||
"""An instance of a real backend class without connecting it; only ``_prepare_command`` runs.
|
||||
The askpass answer is pinned to False so no capability probe reaches a backend."""
|
||||
env = object.__new__(env_cls)
|
||||
env._sudo_askpass_ok = False
|
||||
env.cleanup = lambda: None
|
||||
return env
|
||||
|
||||
|
||||
def _forget_noted_backends():
|
||||
"""Clear the once-only state if the note module is loaded (base.py imports it lazily)."""
|
||||
module = sys.modules.get(NOTE_LOGGER)
|
||||
if module is not None:
|
||||
module._reset_noted_backends()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clean_state(monkeypatch):
|
||||
monkeypatch.delenv("SUDO_PASSWORD", raising=False)
|
||||
monkeypatch.delenv("HERMES_INTERACTIVE", raising=False)
|
||||
terminal_tool.set_sudo_password_callback(None)
|
||||
terminal_tool_sudo._reset_cached_sudo_passwords()
|
||||
_forget_noted_backends()
|
||||
yield
|
||||
terminal_tool_sudo._reset_cached_sudo_passwords()
|
||||
_forget_noted_backends()
|
||||
|
||||
|
||||
def _notes(caplog):
|
||||
return [r for r in caplog.records if r.name == NOTE_LOGGER and r.levelno == logging.WARNING]
|
||||
|
||||
|
||||
def test_non_local_backend_logs_one_warning_across_two_commands(caplog):
|
||||
terminal_tool_sudo._set_cached_sudo_password(PW)
|
||||
env = _RecordingSandboxEnv()
|
||||
env._sudo_askpass_ok = False
|
||||
with caplog.at_level(logging.WARNING, logger=NOTE_LOGGER):
|
||||
env.execute("sudo true")
|
||||
env.execute("sudo id -u")
|
||||
|
||||
notes = _notes(caplog)
|
||||
assert len(notes) == 1
|
||||
message = notes[0].getMessage()
|
||||
assert "_recording_sandbox_env terminal backend" in message
|
||||
assert "only valid there" in message
|
||||
assert PW not in message
|
||||
# The password still reached the backend on stdin for both commands.
|
||||
assert [stdin for _cmd, stdin in env.calls] == [PW + "\n", PW + "\n"]
|
||||
|
||||
|
||||
def test_each_backend_type_logs_its_own_note_once(caplog):
|
||||
terminal_tool_sudo._set_cached_sudo_password(PW)
|
||||
docker, ssh = _bare(DockerEnvironment), _bare(SSHEnvironment)
|
||||
with caplog.at_level(logging.WARNING, logger=NOTE_LOGGER):
|
||||
docker._prepare_command("sudo true")
|
||||
ssh._prepare_command("sudo true")
|
||||
docker._prepare_command("sudo ls")
|
||||
_bare(DockerEnvironment)._prepare_command("sudo ls")
|
||||
ssh._prepare_command("sudo ls")
|
||||
|
||||
messages = [r.getMessage() for r in _notes(caplog)]
|
||||
assert len(messages) == 2
|
||||
assert "docker terminal backend" in messages[0]
|
||||
assert "ssh terminal backend" in messages[1]
|
||||
assert all(PW not in m for m in messages)
|
||||
|
||||
|
||||
def test_local_backend_logs_no_note(caplog):
|
||||
terminal_tool_sudo._set_cached_sudo_password(PW)
|
||||
local = _bare(LocalEnvironment)
|
||||
with caplog.at_level(logging.DEBUG, logger=NOTE_LOGGER):
|
||||
exec_command, sudo_stdin = local._prepare_command("sudo true")
|
||||
assert sudo_stdin == PW + "\n"
|
||||
assert _notes(caplog) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("password", [None, ""])
|
||||
def test_no_password_logs_no_note(caplog, monkeypatch, password):
|
||||
# None: nothing configured or cached; "": SUDO_PASSWORD set to an empty value.
|
||||
if password is not None:
|
||||
monkeypatch.setenv("SUDO_PASSWORD", password)
|
||||
with caplog.at_level(logging.DEBUG, logger=NOTE_LOGGER):
|
||||
_bare(DockerEnvironment)._prepare_command("sudo true")
|
||||
assert _notes(caplog) == []
|
||||
|
||||
|
||||
def test_command_without_sudo_logs_no_note(caplog):
|
||||
terminal_tool_sudo._set_cached_sudo_password(PW)
|
||||
with caplog.at_level(logging.DEBUG, logger=NOTE_LOGGER):
|
||||
result = _bare(DockerEnvironment)._prepare_command("echo sudo-less && ls")
|
||||
assert result == ("echo sudo-less && ls", None)
|
||||
assert _notes(caplog) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("env_cls", [DockerEnvironment, SSHEnvironment, LocalEnvironment])
|
||||
@pytest.mark.parametrize(
|
||||
("command", "cached", "expected"),
|
||||
[
|
||||
("sudo true", True, ("sudo -S -p '' true", PW + "\n")),
|
||||
("sudo a && sudo b", True, ("sudo -S -p '' a && sudo -S -p '' b", (PW + "\n") * 2)),
|
||||
("sudo true", False, ("sudo true", None)),
|
||||
("ls -la", True, ("ls -la", None)),
|
||||
],
|
||||
)
|
||||
def test_prepare_command_output_is_unchanged(env_cls, command, cached, expected):
|
||||
"""Control: passes on base too. The note never alters command text or sudo stdin."""
|
||||
if cached:
|
||||
terminal_tool_sudo._set_cached_sudo_password(PW)
|
||||
env = _bare(env_cls)
|
||||
assert env._prepare_command(command) == expected
|
||||
# Same answer on a second call, after the note has been logged.
|
||||
assert env._prepare_command(command) == expected
|
||||
@@ -822,13 +822,16 @@ class BaseEnvironment(LongLivedProcessMixin, ABC):
|
||||
def _prepare_command(self, command: str) -> tuple[str, str | None]:
|
||||
"""Rewrite sudo for an askpass helper or a piped password (untouched under NOPASSWD) and
|
||||
apply the macOS ``open`` raise-ladder (no-op off Darwin) so opened files come to the front."""
|
||||
from tools.environments.sudo_password_note import note_sudo_password_sent
|
||||
from tools.terminal_tool_macos_open import _transform_macos_open_command
|
||||
from tools.terminal_tool_sudo import _transform_sudo_command
|
||||
return _transform_sudo_command(
|
||||
prepared = _transform_sudo_command(
|
||||
_transform_macos_open_command(command),
|
||||
sudo_nopasswd_check=self._sudo_nopasswd_works,
|
||||
askpass_supported=self._sudo_askpass_supported,
|
||||
)
|
||||
note_sudo_password_sent(self, prepared[1]) # once per non-local backend class
|
||||
return prepared
|
||||
|
||||
_sudo_askpass_supported = sudo_askpass_supported_once
|
||||
_SUDO_PROBE_TIMEOUT_S = 3
|
||||
|
||||
55
tools/environments/sudo_password_note.py
Normal file
55
tools/environments/sudo_password_note.py
Normal file
@@ -0,0 +1,55 @@
|
||||
"""One-time log note when a sudo password is sent to a terminal backend other than the local one.
|
||||
|
||||
Every backend that runs a command with ``sudo`` receives the password (on stdin or through an
|
||||
askpass helper), so programs running in that backend can read it there. For the local backend
|
||||
that is this machine; for container, cloud sandbox, SSH and plugin backends it is another
|
||||
environment, where the password should be one that is only valid in that environment.
|
||||
``note_sudo_password_sent`` logs that advice once per process per backend class.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import threading
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_noted_backend_types: set[type] = set()
|
||||
_noted_lock = threading.Lock()
|
||||
|
||||
_CAMEL_BOUNDARY = re.compile(r"(?<=[a-z0-9])(?=[A-Z])")
|
||||
|
||||
|
||||
def backend_label(env: object) -> str:
|
||||
"""Short backend name from the environment class: ``DockerEnvironment`` -> ``docker``,
|
||||
``VercelSandboxEnvironment`` -> ``vercel_sandbox``, ``SSHEnvironment`` -> ``ssh``."""
|
||||
name = type(env).__name__
|
||||
if name.endswith("Environment") and name != "Environment":
|
||||
name = name[: -len("Environment")]
|
||||
return _CAMEL_BOUNDARY.sub("_", name).lower()
|
||||
|
||||
|
||||
def note_sudo_password_sent(env: object, sudo_stdin: str | None) -> None:
|
||||
"""Log a WARNING the first time this process sends a sudo password to a non-local backend
|
||||
class. No-op for the local backend, when no password is sent (``sudo_stdin`` is None), or
|
||||
when the password is empty. The message never contains the password."""
|
||||
if sudo_stdin is None or not sudo_stdin.strip("\n") or getattr(env, "is_local", False):
|
||||
return
|
||||
backend_type = type(env)
|
||||
with _noted_lock:
|
||||
if backend_type in _noted_backend_types:
|
||||
return
|
||||
_noted_backend_types.add(backend_type)
|
||||
logger.warning(
|
||||
"The sudo password is sent to the %s terminal backend, where programs running in it can "
|
||||
"read it. Use a password that is only valid there, or passwordless sudo in that "
|
||||
"environment's image, rather than the password of the machine running Hermes.",
|
||||
backend_label(env),
|
||||
)
|
||||
|
||||
|
||||
def _reset_noted_backends() -> None:
|
||||
"""Forget which backend types were noted (tests)."""
|
||||
with _noted_lock:
|
||||
_noted_backend_types.clear()
|
||||
@@ -256,7 +256,7 @@ These variables configure the [Tool Gateway](../user-guide/features/tool-gateway
|
||||
| `TERMINAL_TIMEOUT` | Command timeout in seconds |
|
||||
| `TERMINAL_LIFETIME_SECONDS` | Max lifetime for terminal sessions in seconds |
|
||||
| `TERMINAL_CWD` | Deprecated direct override for gateway/cron terminal sessions. Prefer `terminal.cwd` in `config.yaml`; CLI still uses the launch directory. |
|
||||
| `SUDO_PASSWORD` | Enable sudo without interactive prompt |
|
||||
| `SUDO_PASSWORD` | Enable sudo without interactive prompt. Sent to the backend that runs the command; see [Sudo Support](../user-guide/features/tools.md#sudo-support) |
|
||||
|
||||
For cloud sandbox backends, persistence is filesystem-oriented. `TERMINAL_LIFETIME_SECONDS` controls when Hermes cleans up an idle terminal session, and later resumes may recreate the sandbox rather than keep the same live processes running.
|
||||
|
||||
|
||||
@@ -302,7 +302,7 @@ it does not keep unfinished children alive after a timeout or crash.
|
||||
|
||||
## Sudo Support
|
||||
|
||||
On an interactive parent session, supported sudo commands use the masked password prompt (cached for the session). This includes literal absolute or quoted executable paths and `env` prefixes with ordinary options and assignments, such as `env -u UNUSED /usr/bin/sudo id`. Passwordless sudo does not need a prompt. You can also configure `SUDO_PASSWORD` in your profile's `.env` file on the agent machine. It is sent to whichever terminal backend runs the command, so set it to the sudo password of that backend (the remote host for SSH, the container user for Docker), not to a password that belongs to a different machine.
|
||||
On an interactive parent session, supported sudo commands use the masked password prompt (cached for the session). This includes literal absolute or quoted executable paths and `env` prefixes with ordinary options and assignments, such as `env -u UNUSED /usr/bin/sudo id`. Passwordless sudo does not need a prompt. You can also configure `SUDO_PASSWORD` in your profile's `.env` file on the agent machine. It is sent to whichever terminal backend runs the command, so set it to the sudo password of that backend (the remote host for SSH, the container user for Docker), not to a password that belongs to a different machine. Programs running in a container, cloud sandbox or remote backend can read the password there, so use one that is only valid in that environment, or set up passwordless sudo in its image; Hermes logs a one-time warning the first time it sends a sudo password to a backend other than the local one.
|
||||
|
||||
Where the backend's sudo supports an askpass helper (`sudo -A`) and its temp directory allows running a small helper script, the password is handed to each sudo invocation through that helper, so other commands in the same command line never read it from stdin. Otherwise, and for commands that already pass their own `-S` or `-A`, the password goes to sudo through its stdin.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user