The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(code-execution): lock down remote kernel/RPC dirs, keep RPC token out of argv
beardthelion5b8fd7fc32d4
diff --git a/tests/tools/test_code_execution.py b/tests/tools/test_code_execution.pyindex d7c6a6516c2..9bf1572cd4d 100644--- a/tests/tools/test_code_execution.py+++ b/tests/tools/test_code_execution.py@@ -132,17 +132,17 @@ class TestExecuteCodeRemoteTempDir(unittest.TestCase):def execute(self, command, cwd=None, timeout=None):self.commands.append((command, cwd, timeout))if "command -v python3" in command:- return {"output": "OK\n"}+ return {"output": "OK\n", "returncode": 0}if "python3 script.py" in command:return {"output": "hello\n", "returncode": 0}- return {"output": ""}+ return {"output": "", "returncode": 0}env = FakeEnv()fake_thread = MagicMock()with patch("tools.code_execution_tool._load_config", return_value={"timeout": 30, "max_tool_calls": 5}), \patch("tools.code_execution_tool._get_or_create_env", return_value=(env, "ssh")), \- patch("tools.code_execution_tool._ship_file_to_remote"), \+ patch("tools.code_execution_tool._ship_file_to_remote") as ship_mock, \patch("tools.code_execution_tool.threading.Thread", return_value=fake_thread):result = json.loads(_execute_remote("print('hello')", "task-1", ["terminal"]))@@ -159,12 +159,19 @@ class TestExecuteCodeRemoteTempDir(unittest.TestCase):cleanup_cmd = next(cmd for cmd, _, _ in env.commandsif "rm -rf" in cmd and "hermes_exec_" in cmd)self.assertIn("mkdir -p /data/data/com.termux/files/usr/tmp/hermes_exec_", mkdir_cmd)- self.assertIn("HERMES_RPC_DIR=/data/data/com.termux/files/usr/tmp/hermes_exec_", run_cmd)self.assertIn("rm -rf /data/data/com.termux/files/usr/tmp/hermes_exec_", cleanup_cmd)self.assertNotIn("mkdir -p /tmp/hermes_exec_", mkdir_cmd)+ # Env vars travel in the shipped sandbox.env (sourced by the remote+ # shell), not on the command line.+ self.assertIn(". ./sandbox.env", run_cmd)+ env_ship = next(c for c in ship_mock.call_args_list+ if c.args[1].endswith("sandbox.env"))+ self.assertIn("HERMES_RPC_DIR=/data/data/com.termux/files/usr/tmp/hermes_exec_",+ env_ship.args[2])def test_timezone_shell_quoted_in_remote_execution(self):- """HERMES_TIMEZONE must be shell-quoted in remote env_prefix to prevent injection."""+ """HERMES_TIMEZONE must be shell-quoted in the sourced sandbox.env file+ to prevent injection at source time."""class FakeEnv:def __init__(self):self.commands = []@@ -175,10 +182,10 @@ class TestExecuteCodeRemoteTempDir(unittest.TestCase):def execute(self, command, cwd=None, timeout=None):self.commands.append((command, cwd, timeout))if "command -v python3" in command:- return {"output": "OK\n"}+ return {"output": "OK\n", "returncode": 0}if "python3 script.py" in command:return {"output": "hello\n", "returncode": 0}- return {"output": ""}+ return {"output": "", "returncode": 0}env = FakeEnv()fake_thread = MagicMock()@@ -189,7 +196,7 @@ class TestExecuteCodeRemoteTempDir(unittest.TestCase):return_value={"timeout": 30, "max_tool_calls": 5}), \patch("tools.code_execution_tool._get_or_create_env",return_value=(env, "ssh")), \- patch("tools.code_execution_tool._ship_file_to_remote"), \+ patch("tools.code_execution_tool._ship_file_to_remote") as ship_mock, \patch("tools.code_execution_tool.threading.Thread",return_value=fake_thread), \patch.dict(os.environ, {"HERMES_TIMEZONE": malicious_tz}):@@ -197,14 +204,171 @@ class TestExecuteCodeRemoteTempDir(unittest.TestCase):self.assertEqual(result["status"], "success")run_cmd = next(cmd for cmd, _, _ in env.commands if "python3 script.py" in cmd)- # The TZ value must be shell-quoted — it should NOT contain unescaped semicolons- self.assertNotIn("TZ=US/Eastern; echo PWNED", run_cmd,+ # TZ travels in the shipped sandbox.env (sourced by the remote shell),+ # never on the command line.+ self.assertNotIn("TZ=", run_cmd)+ env_ship = next(c for c in ship_mock.call_args_list+ if c.args[1].endswith("sandbox.env"))+ env_content = env_ship.args[2]+ # The TZ value must be shell-quoted in the sourced env file — an+ # unescaped semicolon would inject a command at source time.+ self.assertNotIn("TZ=US/Eastern; echo PWNED", env_content,"TZ value with shell metacharacters must not appear unquoted")- # shlex.quote wraps values containing special characters in single quotes- self.assertIn("TZ='US/Eastern; echo PWNED'", run_cmd,+ self.assertIn("TZ='US/Eastern; echo PWNED'", env_content,"TZ value must be wrapped in single quotes by shlex.quote()")+class TestRemoteSharedHostLockdown(unittest.TestCase):+ """Shared-host hardening for remote backends: sandbox dirs must be+ owner-only, remote writes owner-only, and the RPC token must never ride a+ command line (the remote shell's argv is world-readable via ps)."""++ def test_per_call_sandbox_locks_down_dirs_and_hides_token(self):+ class FakeEnv:+ def __init__(self):+ self.commands = []++ def get_temp_dir(self):+ return "/tmp"++ def execute(self, command, cwd=None, timeout=None):+ self.commands.append((command, cwd, timeout))+ if "command -v python3" in command:+ return {"output": "OK\n", "returncode": 0}+ if "python3 script.py" in command:+ return {"output": "hello\n", "returncode": 0}+ return {"output": "", "returncode": 0}++ env = FakeEnv()+ with patch("tools.code_execution_tool._load_config",+ return_value={"timeout": 30, "max_tool_calls": 5}), \+ patch("tools.code_execution_tool._get_or_create_env",+ return_value=(env, "ssh")), \+ patch("tools.code_execution_tool._ship_file_to_remote") as ship_mock, \+ patch("tools.code_execution_tool.threading.Thread",+ return_value=MagicMock()):+ result = json.loads(_execute_remote("print('hello')", "task-1", ["terminal"]))++ self.assertEqual(result["status"], "success")+ commands = [c for c, _, _ in env.commands]+ # The kernel path runs first and fails open here (no PID), so both the+ # kernel.env and sandbox.env ships are recorded. Neither token may+ # appear in any executed command.+ for env_name in ("kernel.env", "sandbox.env"):+ env_ship = next((c for c in ship_mock.call_args_list+ if c.args[1].endswith(env_name)), None)+ self.assertIsNotNone(env_ship, f"{env_name} was not shipped")+ token_line = next(l for l in env_ship.args[2].splitlines()+ if l.startswith("HERMES_RPC_TOKEN="))+ token = token_line.split("=", 1)[1].strip("'\"")+ self.assertTrue(token)+ self.assertFalse(any(token in c for c in commands),+ f"{env_name} token appeared in a remote command line")+ run_cmd = next(c for c in commands if "python3 script.py" in c)+ # The env file is sourced inside a subshell so set -a's exports never+ # reach the backend's session-snapshot dump (issue #71296 class); exec+ # keeps the script's exit code as the command's.+ self.assertIn("( set -a", run_cmd)+ self.assertIn(". ./sandbox.env", run_cmd)+ self.assertIn("exec python3 script.py", run_cmd)+ self.assertNotIn("HERMES_RPC_TOKEN=", run_cmd)+ mkdir_cmd = next(c for c in commands+ if "mkdir -p" in c and "hermes_exec_" in c)+ self.assertIn("umask 077", mkdir_cmd)+ self.assertIn("chmod 700", mkdir_cmd)++ def test_rpc_response_write_is_owner_only(self):+ """_rpc_poll_loop's res file write must be owner-only and must not put+ the payload in argv on a stdin-capable backend: it carries tool results+ on a shared-host backend."""+ from tools.code_execution_rpc import _rpc_poll_loop++ commands, payloads = [], []++ class Env:+ def execute(self, command, cwd=None, timeout=None, stdin_data=None):+ commands.append(command)+ payloads.append(stdin_data)+ if command.startswith("ls "):+ return {"output": "/rpc/req_000001\n", "returncode": 0}+ if command.startswith("cat "):+ return {"output": json.dumps(+ {"tool": "not_allowed", "args": {}, "seq": 1,+ "token": "T"})}+ return {"output": "", "returncode": 0}++ stop = threading.Event()+ t = threading.Thread(+ target=_rpc_poll_loop,+ args=(Env(), "/rpc", "t1", [], [0], 5, frozenset(), stop, "T"),+ daemon=True)+ t.start()+ deadline = time.monotonic() + 10+ while not any("base64 -d" in c for c in commands):+ if time.monotonic() > deadline:+ stop.set()+ t.join(5)+ self.fail("rpc poll loop never wrote a response file")+ time.sleep(0.01)+ stop.set()+ t.join(5)+ res_write = next(c for c in commands if "base64 -d" in c)+ self.assertIn("umask 077", res_write)+ self.assertIn("res_000001", res_write)+ # On a pipe-capable backend the result rides stdin, not argv.+ res_idx = commands.index(res_write)+ self.assertIsNotNone(payloads[res_idx],+ "res payload should travel via stdin_data")++ def test_rpc_malformed_seq_request_removed_without_replay(self):+ """An authenticated req with a non-int seq cannot form the res name the+ caller polls. It must be removed without dispatch: formatting res_+ after dispatch raises, leaves the req in place, and replays the tool+ call every poll cycle."""+ from tools.code_execution_rpc import _rpc_poll_loop++ commands = []+ dispatched = []++ class Env:+ def execute(self, command, cwd=None, timeout=None, stdin_data=None):+ commands.append(command)+ if command.startswith("ls "):+ return {"output": "/rpc/req_000001\n", "returncode": 0}+ if command.startswith("cat "):+ return {"output": json.dumps(+ {"tool": "read_file", "args": {"path": "/x"},+ "seq": "not-an-int", "token": "T"})}+ return {"output": "", "returncode": 0}++ def fake_dispatch(name, args):+ dispatched.append(name)+ return "ok"++ stop = threading.Event()+ with patch("tools.code_execution_rpc._default_dispatch",+ return_value=fake_dispatch):+ t = threading.Thread(+ target=_rpc_poll_loop,+ args=(Env(), "/rpc", "t1", [], [0], 5,+ frozenset({"read_file"}), stop, "T"),+ daemon=True)+ t.start()+ deadline = time.monotonic() + 10+ while not any("rm -f" in c and "req_000001" in c for c in commands):+ if time.monotonic() > deadline:+ stop.set()+ t.join(5)+ self.fail("malformed-seq request was never removed")+ time.sleep(0.01)+ stop.set()+ t.join(5)+ self.assertEqual(dispatched, [],+ "malformed-seq request must not dispatch a tool call")+ self.assertFalse(any("base64 -d" in c for c in commands),+ "no res write for a request that cannot be answered")++@unittest.skipIf(sys.platform == "win32", "UDS not available on Windows")class TestExecuteCode(unittest.TestCase):"""Integration tests using the mock dispatcher."""@@ -744,10 +908,10 @@ class TestHeadTailTruncation(unittest.TestCase):def execute(self, command, cwd=None, timeout=None):self.commands.append((command, cwd, timeout))if "command -v python3" in command:- return {"output": "OK\n"}+ return {"output": "OK\n", "returncode": 0}if "python3 script.py" in command:return {"output": "HEAD\n" + ("x" * 80_000) + "\nTAIL\n", "returncode": 0}- return {"output": ""}+ return {"output": "", "returncode": 0}fake_thread = MagicMock()diff --git a/tests/tools/test_code_kernel_remote.py b/tests/tools/test_code_kernel_remote.pyindex 162aac30433..ada22b9299c 100644--- a/tests/tools/test_code_kernel_remote.py+++ b/tests/tools/test_code_kernel_remote.py@@ -10,6 +10,7 @@ state_lost/state_reset reporting, fail-open, and owner isolation."""import jsonimport os+import shutilimport sysimport timeimport unittest@@ -33,15 +34,19 @@ class ScriptedEnv:receives the command and returns the result dict."""+ _stdin_mode = "pipe" # contract-faithful: ssh/docker/local deliver stdin+def __init__(self, handlers):self.handlers = handlersself.commands = []+ self.stdin_payloads = []def get_temp_dir(self):return "/tmp"- def execute(self, command, cwd=None, timeout=None):+ def execute(self, command, cwd=None, timeout=None, stdin_data=None):self.commands.append(command)+ self.stdin_payloads.append(stdin_data)for needle, handler in self.handlers:if needle in command:return handler(command)@@ -340,5 +345,200 @@ class TestDispatchIntegration(unittest.TestCase):self.assertIn("per-call ran", result["output"])+class TestSharedHostLockdown(RemoteKernelBase):+ """Shared-host hardening: the kernel dir lives under a shared temp dir, so+ every dir must be owner-only, every remote write owner-only, and the RPC+ token must travel in a sourced env file rather than a ps-visible argv."""++ def test_spawn_locks_down_dirs_and_hides_token(self):+ self._ship.stop() # let the real ship commands reach env.commands+ env = ScriptedEnv(_spawn_ok_handlers([_cell(stdout="hi\n")]))+ result = _run(env)+ self.assertEqual(result["status"], "success", result)+ kernel = next(iter(_REMOTE_KERNELS.values()))+ # The token never rides a command line: a remote shell's argv is+ # world-readable via ps for the command's whole lifetime.+ self.assertFalse(+ any(kernel.rpc_token in c for c in env.commands),+ "rpc token appeared in a remote command line")+ spawn_cmd = next(c for c in env.commands if "nohup" in c)+ # The env file is sourced inside a subshell so set -a's exports never+ # reach the backend's session-snapshot dump (issue #71296 class).+ self.assertIn("( set -a", spawn_cmd)+ self.assertIn(". ./kernel.env", spawn_cmd)+ self.assertIn("rm -f ./kernel.env", spawn_cmd)+ self.assertNotIn("HERMES_RPC_TOKEN=", spawn_cmd)+ # Every dir under the shared temp dir is owner-only (mkdir -p's -m+ # applies only to the leaf, so the chmod must name all three; umask 077+ # covers the creation-time window).+ mkdir_cmd = next(c for c in env.commands if "mkdir -p" in c)+ self.assertIn("umask 077", mkdir_cmd)+ self.assertIn("chmod 700", mkdir_cmd)+ for d in (kernel.kernel_dir, f"{kernel.kernel_dir}/cells",+ f"{kernel.kernel_dir}/rpc"):+ self.assertIn(d, mkdir_cmd)+ # Ships write owner-only; on a pipe-capable backend the payload rides+ # stdin, so the base64 (which decodes to the token for kernel.env)+ # never enters argv either.+ ship_cmds = [c for c in env.commands if "base64 -d" in c]+ self.assertTrue(ship_cmds)+ self.assertTrue(all("umask 077" in c for c in ship_cmds))+ self.assertTrue(any("kernel.env" in c for c in ship_cmds))+ self.assertFalse(any("echo '" in c for c in ship_cmds),+ "payload echoed into argv on a stdin-capable backend")+ import base64+ env_ship = next(p for p, c in zip(env.stdin_payloads, env.commands)+ if p and "kernel.env" in c)+ env_content = base64.b64decode(env_ship).decode()+ self.assertIn(f"HERMES_RPC_TOKEN={kernel.rpc_token}", env_content)++ def test_remote_write_transport_follows_stdin_mode(self):+ """Pipe-mode backends carry the payload on stdin (never argv); heredoc+ backends embed stdin in the command anyway, so they keep the echo pipe."""+ import base64+ from tools.code_execution_rpc import _remote_write_cmd++ class HeredocEnv:+ _stdin_mode = "heredoc"++ cmd, stdin = _remote_write_cmd(HeredocEnv(), "/x/f", "data")+ self.assertIsNone(stdin)+ self.assertIn("echo '", cmd)+ cmd2, stdin2 = _remote_write_cmd(ScriptedEnv([]), "/x/f", "data")+ self.assertIsNotNone(stdin2)+ self.assertNotIn("echo '", cmd2)+ self.assertEqual(base64.b64decode(stdin2).decode(), "data")++ def test_stub_req_files_are_owner_only(self):+ """The generated file-RPC stub writes req files mode 600: they carry+ the token + tool args and sit in a dir a same-uid kernel shares."""+ import tempfile+ import types+ from tools.code_execution_tool import generate_hermes_tools_module+ src = generate_hermes_tools_module(["read_file"], transport="file")+ rpc_dir = tempfile.mkdtemp()+ self.addCleanup(shutil.rmtree, rpc_dir, True)+ with patch.dict(os.environ, {"HERMES_RPC_DIR": rpc_dir,+ "HERMES_RPC_TOKEN": "test-token"}):+ mod = types.ModuleType("hermes_tools")+ exec(compile(src, "hermes_tools.py", "exec"), mod.__dict__)+ with open(os.path.join(rpc_dir, "res_000001"), "w") as f:+ f.write(json.dumps("ok"))+ mod.read_file("/etc/hostname")+ req = os.path.join(rpc_dir, "req_000001")+ self.assertTrue(os.path.exists(req))+ self.assertEqual(os.stat(req).st_mode & 0o777, 0o600)++ def test_runner_cell_res_files_are_owner_only(self):+ """The remote runner writes cell_res files mode 600: they carry the+ cell's output in a dir under shared temp."""+ import tempfile+ import threading+ import types+ from tools.code_kernel import RUNNER_CELL_SOURCE+ from tools.code_kernel_remote import REMOTE_KERNEL_RUNNER_SOURCE+ kdir = tempfile.mkdtemp()+ self.addCleanup(shutil.rmtree, kdir, True)+ cells = os.path.join(kdir, "cells")+ os.makedirs(cells)+ src = REMOTE_KERNEL_RUNNER_SOURCE.format(+ cell_source=RUNNER_CELL_SOURCE, capture_limit=10000, idle_exit=2)+ with patch.dict(os.environ, {"HERMES_KERNEL_DIR": kdir,+ "HERMES_RPC_DIR": f"{kdir}/rpc",+ "HERMES_RPC_TOKEN": "t"}):+ mod = types.ModuleType("kernel_runner")+ exec(compile(src, "kernel_runner.py", "exec"), mod.__dict__)+ with open(os.path.join(cells, "cell_req_000001.json"), "w") as f:+ json.dump({"code": "print('hi')", "id": "000001"}, f)+ runner = threading.Thread(target=mod.main, daemon=True)+ runner.start()+ res = os.path.join(cells, "cell_res_000001.json")+ deadline = time.monotonic() + 10+ while not os.path.exists(res):+ self.assertLess(time.monotonic(), deadline,+ "runner never wrote the cell result")+ time.sleep(0.02)+ self.assertEqual(os.stat(res).st_mode & 0o777, 0o600)+ runner.join(5)++[email protected](os.name == "posix" and shutil.which("bash"),+ "needs a POSIX bash transport")+class TestRemoteKernelLocalEnvE2E(RemoteKernelBase):+ """Real end-to-end: spawn the remote kernel through LocalEnvironment's real+ bash transport, run a cell, and stat the modes on disk. This is the same+ code path an ssh backend drives, pointed at this host."""++ def test_kernel_tree_is_owner_only_on_real_fs(self):+ self._ship.stop()+ self._poll.stop()+ from tools.environments.local import LocalEnvironment+ env = LocalEnvironment(cwd="/", timeout=60)+ try:+ result = _run(env, code=(+ "import os\n"+ "print('KDIR_MODE=%o' % (os.stat(os.environ['HERMES_KERNEL_DIR']).st_mode & 0o777))\n"+ "print('RPC_MODE=%o' % (os.stat(os.environ['HERMES_RPC_DIR']).st_mode & 0o777))\n"+ "print('PP_DELIVERED=%s' % (os.environ.get('PYTHONPATH') == os.environ['HERMES_KERNEL_DIR']))\n"+ "print('TOKEN_DELIVERED=%s' % bool(os.environ.get('HERMES_RPC_TOKEN')))\n"+ ), timeout=60)+ self.assertEqual(result["status"], "success", result)+ blob = json.dumps(result)+ self.assertIn("KDIR_MODE=700", blob)+ self.assertIn("RPC_MODE=700", blob)+ # The env file must actually deliver its vars to the runner — a+ # broken source would silently degrade cells to no-RPC.+ self.assertIn("PP_DELIVERED=True", blob)+ self.assertIn("TOKEN_DELIVERED=True", blob)+ kernel = next(iter(_REMOTE_KERNELS.values()))+ # kernel.env is consumed by the subshell source: the token file is+ # gone after launch while the runner keeps the values in its env.+ self.assertFalse(os.path.exists(+ os.path.join(kernel.kernel_dir, "kernel.env")))+ for name in ("kernel_runner.py", "hermes_tools.py", "runner.log"):+ p = os.path.join(kernel.kernel_dir, name)+ self.assertTrue(os.path.exists(p), p)+ self.assertEqual(os.stat(p).st_mode & 0o777, 0o600, p)+ # The subshell confinement keeps the token and execution-scoped vars+ # out of the backend's session snapshot: they must not leak into the+ # snapshot file or the environ of a later command on the same env+ # (issue #71296 snapshot-leak class).+ probe = env.execute(+ "printenv HERMES_RPC_TOKEN; printenv HERMES_KERNEL_DIR; "+ "printenv HERMES_RPC_DIR; printenv PYTHONPATH",+ cwd="/", timeout=15)+ self.assertNotIn(kernel.rpc_token, probe.get("output", ""))+ self.assertNotIn(kernel.kernel_dir, probe.get("output", ""))+ self.assertNotIn(+ kernel.rpc_token,+ open(env._snapshot_path).read() if os.path.exists(env._snapshot_path) else "")+ finally:+ shutdown_all_remote_kernels()++ def test_per_call_sandbox_is_owner_only_on_real_fs(self):+ self._ship.stop()+ self._poll.stop()+ from tools.environments.local import LocalEnvironment+ from tools.code_execution_tool import _run_remote_per_call+ env = LocalEnvironment(cwd="/", timeout=60)+ code = (+ "import os\n"+ "print('SANDBOX_MODE=%o' % (os.stat(os.path.dirname(os.environ['HERMES_RPC_DIR'])).st_mode & 0o777))\n"+ "print('RPC_MODE=%o' % (os.stat(os.environ['HERMES_RPC_DIR']).st_mode & 0o777))\n"+ "print('SCRIPT_MODE=%o' % (os.stat('script.py').st_mode & 0o777))\n"+ "print('TOOLS_MODE=%o' % (os.stat('hermes_tools.py').st_mode & 0o777))\n"+ "print('ENVFILE_MODE=%o' % (os.stat('sandbox.env').st_mode & 0o777))\n"+ )+ out = json.loads(_run_remote_per_call(+ env, "local", code, "t-e2e", frozenset({"read_file"}),+ timeout=60, max_tool_calls=5, exec_start=time.monotonic()))+ self.assertEqual(out["status"], "success", out)+ self.assertIn("SANDBOX_MODE=700", out["output"])+ self.assertIn("RPC_MODE=700", out["output"])+ self.assertIn("SCRIPT_MODE=600", out["output"])+ self.assertIn("TOOLS_MODE=600", out["output"])+ self.assertIn("ENVFILE_MODE=600", out["output"])++if __name__ == "__main__":unittest.main()diff --git a/tests/tools/test_tool_result_storage.py b/tests/tools/test_tool_result_storage.pyindex 6c5fe835d0f..324477e9850 100644--- a/tests/tools/test_tool_result_storage.py+++ b/tests/tools/test_tool_result_storage.py@@ -49,6 +49,11 @@ class TestWriteToSandbox:# persisted size (unparseable probe output = best-effort success).cmd = env.execute.call_args_list[0][0][0]assert "mkdir -p" in cmd+ # The storage dir sits under shared temp and holds tool output that can+ # contain secrets: it must be owner-only at creation, and the umask must+ # cover the cat redirect too.+ assert "umask 077" in cmd+ assert "chmod 700" in cmd# Content travels through stdin, NOT inside the command string —# otherwise large content would hit Linux's 128 KB MAX_ARG_STRLEN# ceiling on `bash -c <cmd>` (#22906).diff --git a/tools/code_execution_rpc.py b/tools/code_execution_rpc.pyindex ea784c63f63..61c8918b160 100644--- a/tools/code_execution_rpc.py+++ b/tools/code_execution_rpc.py@@ -30,6 +30,46 @@ def _default_dispatch(task_id):return lambda tool_name, tool_args: handle_function_call(tool_name, tool_args, task_id=task_id)+def _private_dirs_cmd(mkdir_dirs, chmod_dirs) -> str:+ """Shell command creating remote dirs owner-only on a shared host. ``umask 077``+ makes intermediates and leaves private at creation (no mkdir-then-chmod window+ where a co-tenant could open a dir fd); ``chmod`` then repairs a dir that+ already existed with permissive modes."""+ mkdir = " ".join(shlex.quote(d) for d in mkdir_dirs)+ chmod = " ".join(shlex.quote(d) for d in chmod_dirs)+ return f"umask 077 && mkdir -p {mkdir} && chmod 700 {chmod}"+++def _remote_write_cmd(env, remote_path: str, content: str, *, atomic: bool = False) -> tuple:+ """Build ``(command, stdin_data)`` writing *content* owner-only to *remote_path*.++ Payload transport follows the backend's stdin capability: ``pipe`` mode+ (ssh, docker, local, singularity — the real shared-host backends) gets the+ base64 via real stdin so the content never enters argv, where a co-tenant+ can read it via ``/proc/*/cmdline`` for the command's lifetime.+ ``heredoc``/``payload`` modes (modal, daytona, vercel, managed_modal —+ isolated sandboxes where Modal-family stdin delivery is also unreliable)+ keep the base64 echo form: the argv window there is one short write rather+ than the whole run."""+ encoded = base64.b64encode(content.encode("utf-8")).decode("ascii")+ target = shlex.quote(remote_path)+ write = (f"base64 -d > {target}.tmp && mv -f {target}.tmp {target}"+ if atomic else f"base64 -d > {target}")+ if getattr(env, "_stdin_mode", "pipe") == "pipe":+ return f"umask 077 && {write}", encoded+ return f"umask 077 && echo '{encoded}' | {write}", None+++def _remote_write(env, remote_path: str, content: str, *, atomic: bool = False,+ timeout: int = 30):+ """Execute an owner-only remote write; returns the execute() result."""+ cmd, stdin_data = _remote_write_cmd(env, remote_path, content, atomic=atomic)+ kwargs = {"cwd": "/", "timeout": timeout}+ if stdin_data is not None:+ kwargs["stdin_data"] = stdin_data+ return env.execute(cmd, **kwargs)++def _rpc_token_ok(request: dict, rpc_token: str) -> bool:"""Constant-time token check; an empty server token fails closed. Compared as bytes:compare_digest raises TypeError on a non-ASCII str, and the token is script-supplied JSON."""@@ -161,20 +201,23 @@ def _rpc_poll_loop(env, rpc_dir: str, task_id: str, tool_call_log: list, tool_calogger.debug("Unauthorized RPC request in %s", req_file)env.execute(f"rm -f {quoted_req_file}", cwd="/", timeout=5)continue+ seq = request.get("seq", 0)+ if not isinstance(seq, int):+ # A non-int seq cannot form the res_NNNNNN name the caller+ # polls; formatting it after dispatch would raise, leave the+ # request in place, and replay the tool call every cycle.+ logger.debug("RPC request with malformed seq in %s", req_file)+ env.execute(f"rm -f {quoted_req_file}", cwd="/", timeout=5)+ continuetool_result = _handle_rpc_request(request, allowed_tools=allowed_tools, tool_call_counter=tool_call_counter,max_tool_calls=max_tool_calls, dispatch=dispatch, tool_call_log=tool_call_log,call_start=call_start, where="remote sandbox",)- # Write the response atomically (tmp + rename) via echo piping —- # Modal doesn't reliably deliver stdin_data to chained commands.- quoted_res_file = shlex.quote(f"{rpc_dir}/res_{request.get('seq', 0):06d}")- encoded_result = base64.b64encode(tool_result.encode("utf-8")).decode("ascii")- env.execute(- f"echo '{encoded_result}' | base64 -d > {quoted_res_file}.tmp"- f" && mv {quoted_res_file}.tmp {quoted_res_file}",- cwd="/", timeout=60,- )+ # Atomic (tmp + rename) and owner-only; results carry tool output+ # on a shared-host backend.+ _remote_write(env, f"{rpc_dir}/res_{seq:06d}", tool_result,+ atomic=True, timeout=60)env.execute(f"rm -f {quoted_req_file}", cwd="/", timeout=5)except Exception as e:if not stop_event.is_set():diff --git a/tools/code_execution_tool.py b/tools/code_execution_tool.pyindex 12e2e8985fc..8d7121fc010 100644--- a/tools/code_execution_tool.py+++ b/tools/code_execution_tool.py@@ -11,7 +11,6 @@ per-call script ship, tool calls as request files polled via env.execute()scrubbing, interpreter/cwd), tools/code_execution_rpc.py (RPC servers)."""-import base64import jsonimport loggingimport os@@ -30,7 +29,7 @@ from tools.registry import registry, tool_errorfrom hermes_time import get_timezone_namefrom tools.code_execution_env import _resolve_child_cwd, _resolve_child_python-from tools.code_execution_rpc import _rpc_poll_loop+from tools.code_execution_rpc import _private_dirs_cmd, _remote_write, _rpc_poll_loopfrom tools.tool_output_truncate import head_tail_split, truncation_noticelogger = logging.getLogger(__name__)@@ -358,7 +357,10 @@ def _call(tool_name, args):# (or any non-UTF-8 locale) the default open() mode would mangle# non-ASCII chars in tool args when encoding them as JSON.tmp = req_file + ".tmp"- with open(tmp, "w", encoding="utf-8") as f:+ # The request carries the RPC token and tool args: owner-only even under a+ # permissive process umask.+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)+ with os.fdopen(fd, "w", encoding="utf-8") as f:json.dump({"tool": tool_name,"args": args,@@ -451,10 +453,35 @@ def _get_or_create_env(task_id: str):def _ship_file_to_remote(env, remote_path: str, content: str) -> None:- """Write *content* to *remote_path* via ``echo … | base64 -d`` — some backends (Modal) don't- reliably deliver stdin_data to chained commands; base64 is shell-safe inside single quotes."""- encoded = base64.b64encode(content.encode("utf-8")).decode("ascii")- env.execute(f"echo '{encoded}' | base64 -d > {shlex.quote(remote_path)}", cwd="/", timeout=30)+ """Write *content* owner-only to *remote_path*. stdin-capable backends carry+ the payload on stdin so it never appears in remote argv; the rest get the+ base64 echo form (see _remote_write_cmd). Raises on write failure: the+ caller ships secrets and code into dirs it believes are locked down, so a+ silent failure would run the next step against a missing or half-written+ file."""+ result = _remote_write(env, remote_path, content)+ if not isinstance(result, dict) or result.get("returncode", 1) != 0:+ raise RuntimeError(+ f"remote file ship failed for {remote_path!r}: "+ f"{(result or {}).get('output', result)!r}")+++def _ship_env_file_and_launch_prefix(env, remote_dir: str, env_name: str,+ env_map: dict) -> str:+ """Ship *env_map* as KEY=value lines to ``remote_dir/env_name`` and return a+ command prefix that sources it inside a subshell; the caller appends the+ launch command and the closing ``)``.++ The subshell is load-bearing: every env.execute() runs inside the backend's+ session wrapper, which re-dumps ``export -p`` into the shared session+ snapshot after each command. A plain ``set -a; . file`` in the outer shell+ would export HERMES_RPC_TOKEN/PYTHONPATH/TZ into that snapshot and re-export+ them into every later command on the backend (the #71296 snapshot-leak+ class). The token also stays off the remote shell's argv, which co-tenant+ users can read via ps for the command's lifetime."""+ lines = "".join(f"{k}={shlex.quote(v)}\n" for k, v in env_map.items())+ _ship_file_to_remote(env, f"{remote_dir}/{env_name}", lines)+ return f"cd {shlex.quote(remote_dir)} && ( set -a && . ./{env_name} && set +a && "def _env_temp_dir(env: Any) -> str:@@ -565,10 +592,17 @@ def _run_remote_per_call(env, env_type: str, code: str, effective_task_id: str,serve file-RPC from a polling thread, run, clean up."""sandbox_dir = f"{_env_temp_dir(env)}/hermes_exec_{uuid.uuid4().hex[:12]}"quoted_sandbox_dir = shlex.quote(sandbox_dir)- quoted_rpc_dir = shlex.quote(f"{sandbox_dir}/rpc")tool_call_counter, stop_event, rpc_thread = [0], threading.Event(), Nonetry:- env.execute(f"mkdir -p {quoted_rpc_dir}", cwd="/", timeout=10)+ # Private dirs: the sandbox lives under a shared temp dir and carries the+ # RPC token (in req files) and tool results. Fail closed on setup+ # failure rather than ship secrets into a dir that stayed permissive.+ setup = env.execute(+ _private_dirs_cmd([f"{sandbox_dir}/rpc"], [sandbox_dir, f"{sandbox_dir}/rpc"]),+ cwd="/", timeout=10)+ if not isinstance(setup, dict) or setup.get("returncode", 1) != 0:+ raise RuntimeError(+ f"remote sandbox setup failed: {(setup or {}).get('output', setup)!r}")rpc_token = secrets.token_urlsafe(32)_ship_file_to_remote(env, f"{sandbox_dir}/hermes_tools.py",generate_hermes_tools_module(list(sandbox_tools), transport="file"))@@ -581,13 +615,19 @@ def _run_remote_per_call(env, env_type: str, code: str, effective_task_id: str,args=(env, f"{sandbox_dir}/rpc", effective_task_id, [], tool_call_counter,max_tool_calls, sandbox_tools, stop_event, rpc_token))rpc_thread.start()- env_prefix = (f"HERMES_RPC_DIR={quoted_rpc_dir} HERMES_RPC_TOKEN={shlex.quote(rpc_token)} "- "PYTHONDONTWRITEBYTECODE=1")+ # The token travels in a sourced env file, never in argv. No umask on+ # the launch command: the 700 dirs + explicit 0600 writes cover Hermes'+ # files, and user code keeps the remote's default file modes.+ env_map = {"HERMES_RPC_DIR": f"{sandbox_dir}/rpc",+ "HERMES_RPC_TOKEN": rpc_token,+ "PYTHONDONTWRITEBYTECODE": "1"}tz = get_timezone_name() # routed profile's timezone, not the bridged default'sif tz:- env_prefix += f" TZ={shlex.quote(tz)}"+ env_map["TZ"] = tz+ launch_prefix = _ship_env_file_and_launch_prefix(+ env, sandbox_dir, "sandbox.env", env_map)logger.info("Executing code on %s backend (task %s)...", env_type, effective_task_id[:8])- script_result = env.execute(f"cd {quoted_sandbox_dir} && {env_prefix} python3 script.py",+ script_result = env.execute(f"{launch_prefix} exec python3 script.py )",timeout=timeout)stdout_text = script_result.get("output", "") or ""exit_code = script_result.get("returncode", -1)diff --git a/tools/code_kernel_remote.py b/tools/code_kernel_remote.pyindex cc35a2304a2..35647545015 100644--- a/tools/code_kernel_remote.py+++ b/tools/code_kernel_remote.py@@ -83,7 +83,10 @@ def main():payload, _ = run_cell(request, execution_count)res_name = name.replace("cell_req_", "cell_res_")tmp = os.path.join(CELLS, res_name + ".tmp")- with open(tmp, "w", encoding="utf-8") as f:+ # Cell results carry the executed code's output: owner-only, even if+ # the process umask is permissive.+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)+ with os.fdopen(fd, "w", encoding="utf-8") as f:json.dump(payload, f, ensure_ascii=False)os.replace(tmp, os.path.join(CELLS, res_name))if payload["status"] == "exit":@@ -204,23 +207,51 @@ atexit.register(shutdown_all_remote_kernels)def _spawn_remote_kernel(env, env_type: str, owner: str, task_env_id: str,sandbox_tools: frozenset, *, idle_exit: int) -> Optional[RemoteKernel]:"""Start a detached kernel runner on the remote. None on failure (dir removed)."""+ from hermes_time import get_timezone_name+ from tools.code_execution_rpc import _private_dirs_cmdfrom tools.code_execution_tool import (- MAX_STDOUT_BYTES, _ship_file_to_remote, _env_temp_dir, generate_hermes_tools_module,+ MAX_STDOUT_BYTES, _ship_file_to_remote, _env_temp_dir,+ _ship_env_file_and_launch_prefix, generate_hermes_tools_module,)kernel_dir = f"{_env_temp_dir(env)}/hermes_rkernel_{uuid.uuid4().hex[:12]}"q_dir = shlex.quote(kernel_dir)kernel = Nonetry:- _sh(env, f"mkdir -p {q_dir}/cells {q_dir}/rpc")+ # Private dirs: the kernel dir lives under a shared temp dir and carries+ # the RPC token (in req files), tool results, and cell code/output.+ # Fail closed on setup failure rather than ship secrets into a dir that+ # stayed permissive.+ setup = env.execute(+ _private_dirs_cmd([f"{kernel_dir}/cells", f"{kernel_dir}/rpc"],+ [kernel_dir, f"{kernel_dir}/cells", f"{kernel_dir}/rpc"]),+ cwd="/", timeout=15)+ if not isinstance(setup, dict) or setup.get("returncode", 1) != 0:+ raise RuntimeError(+ f"remote kernel dir setup failed: {(setup or {}).get('output', setup)!r}")rpc_token = secrets.token_urlsafe(32)_ship_file_to_remote(env, f"{kernel_dir}/kernel_runner.py", REMOTE_KERNEL_RUNNER_SOURCE.format(cell_source=RUNNER_CELL_SOURCE, capture_limit=MAX_STDOUT_BYTES, idle_exit=idle_exit))_ship_file_to_remote(env, f"{kernel_dir}/hermes_tools.py",generate_hermes_tools_module(list(sandbox_tools), transport="file"))- env_prefix = (f"HERMES_KERNEL_DIR={q_dir} HERMES_RPC_DIR={shlex.quote(kernel_dir + '/rpc')} "- f"HERMES_RPC_TOKEN={shlex.quote(rpc_token)} PYTHONDONTWRITEBYTECODE=1 PYTHONPATH={q_dir}")- started = _sh(env, f"cd {q_dir} && nohup env {env_prefix} python3 kernel_runner.py "- f"> {q_dir}/runner.log 2>&1 & echo PID:$!", timeout=20)+ env_map = {"HERMES_KERNEL_DIR": kernel_dir,+ "HERMES_RPC_DIR": f"{kernel_dir}/rpc",+ "HERMES_RPC_TOKEN": rpc_token,+ "PYTHONDONTWRITEBYTECODE": "1",+ "PYTHONPATH": kernel_dir}+ tz = get_timezone_name() # routed profile's timezone, matching the per-call path+ if tz:+ env_map["TZ"] = tz+ launch_prefix = _ship_env_file_and_launch_prefix(+ env, kernel_dir, "kernel.env", env_map)+ # kernel.env is removed after sourcing: the runner's env keeps the+ # values, so the token file need not sit at rest for the kernel's+ # lifetime. runner.log is pre-created 600 so the launch redirect never+ # lands at the remote's default umask. The inner `&` stays inside the+ # subshell where `$!` resolves to the runner pid.+ started = _sh(env, f"{launch_prefix} rm -f ./kernel.env && "+ f"touch runner.log && chmod 600 runner.log && "+ f"{{ nohup python3 kernel_runner.py > runner.log 2>&1 & "+ f'echo "PID:$!"; }} )', timeout=20)pid = next((line.strip()[4:].strip() for line in started.splitlines()if line.strip().startswith("PID:")), "")if not pid.isdigit():diff --git a/tools/environments/base_session_env.py b/tools/environments/base_session_env.pyindex e0c095e484e..64fb24c99ef 100644--- a/tools/environments/base_session_env.py+++ b/tools/environments/base_session_env.py@@ -28,7 +28,8 @@ from typing import Iterable# name/prefix instead of grepping declare lines (see below / issue #71296)._SNAPSHOT_EXCLUDED_ENV_REGEX = ("^declare -x (HERMES_SESSION_|HERMES_UI_SESSION_ID|HERMES_CRON_AUTO_DELIVER_|"- "HERMES_CRON_SESSION|HERMES_BROWSER_CONTROL_|HERMES_DELEGATED_CHILD_CONTEXT)")+ "HERMES_CRON_SESSION|HERMES_BROWSER_CONTROL_|HERMES_DELEGATED_CHILD_CONTEXT|"+ "HERMES_RPC_|HERMES_KERNEL_DIR)")_SHELL_ENV_NAME_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")# mktemp template suffix + the shell variable holding the allocated temp path.@@ -76,6 +77,10 @@ def _export_dump_excluding_session_vars(tmp_path: str, excluded_names: Iterable[# env; a snapshot taken inside that window would re-assert them on every# later ``source`` and fence the PARENT session's kanban CLI (#90782)."HERMES_DELEGATED_CHILD_CONTEXT HERMES_CRON_SESSION "+ # Remote code-execution channel vars (RPC token, kernel/rpc dirs): a+ # leaked token in the snapshot would re-export into every later command+ # on the backend and outlive the private dir it protects.+ "${!HERMES_RPC_*} HERMES_KERNEL_DIR "f"HERMES_UI_SESSION_ID{extra_unset} 2>/dev/null; ""export -p; ) || true; } "f"> {tmp_path}")diff --git a/tools/tool_result_storage.py b/tools/tool_result_storage.pyindex 1b939ceb0be..e82c010decb 100644--- a/tools/tool_result_storage.py+++ b/tools/tool_result_storage.py@@ -183,7 +183,11 @@ def _write_to_sandbox(content: str, remote_path: str, env) -> bool:truncation on payload backends). A measured mismatch removes the archive and fails closed;an unprobeable backend (no ``wc``, exec error, unparseable output) stays best-effort success."""storage_dir = os.path.dirname(remote_path)- cmd = f"mkdir -p {shlex.quote(storage_dir)} && cat > {shlex.quote(remote_path)}"+ # Private dir: archived results carry tool output (can hold secrets) under a+ # shared temp root on remote backends. The umask also covers the cat redirect.+ from tools.code_execution_rpc import _private_dirs_cmd+ cmd = (f"{_private_dirs_cmd([storage_dir], [storage_dir])} "+ f"&& cat > {shlex.quote(remote_path)}")if env.execute(cmd, timeout=30, stdin_data=content).get("returncode", 1) != 0:return False