The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
Docker sandbox files can no longer carry setuid/setgid or file caps back to the host, persistent sandboxes included (#141086)
Tekniumb0be65c30a11
diff --git a/tests/tools/test_docker_ownership_handback.py b/tests/tools/test_docker_ownership_handback.pyindex 933e00ddb18..07c96ede2fd 100644--- a/tests/tools/test_docker_ownership_handback.py+++ b/tests/tools/test_docker_ownership_handback.py@@ -3,7 +3,9 @@ stops and before it is removed; the next root container takes back exactly thoseimport importlibimport json+import loggingimport os+import shutilimport subprocessimport pytest@@ -23,25 +25,34 @@ def _fake_docker(monkeypatch, security_options: str, fail: str = ""):passcalls: list[tuple[list[str], bytes]] = []- def _inspect() -> str: # like `docker inspect`: the real user and every -v, extra args included- run = next(argv for argv, _ in calls if argv[1] == "run")- mounts = [{"Destination": run[i + 1].split(":")[1]} for i, a in enumerate(run[:-1]) if a == "-v"]- user = next((run[i + 1] for i, a in enumerate(run[:-1]) if a == "--user"), "")- return json.dumps([{"Config": {"User": user}, "Image": "sha256:img", "Mounts": mounts}])+ def _inspect() -> str: # like `docker inspect` of the creating run: user, labels, caps, every -v+ run = next(argv for argv, _ in calls if argv[1:3] == ["run", "-d"])+ mounts = [{"Type": "bind", "Source": run[i + 1].split(":")[0], "Destination": run[i + 1].split(":")[1]}+ for i, a in enumerate(run[:-1]) if a == "-v"]+ flag = lambda name: [run[i + 1] for i, a in enumerate(run[:-1]) if a == name]+ labels = dict(v.split("=", 1) for v in flag("--label"))+ host = {"CapAdd": flag("--cap-add"), "Privileged": "--privileged" in run}+ return json.dumps([{"Config": {"User": (flag("--user") or [""])[0], "Labels": labels}, "HostConfig": host,+ "Image": "sha256:img", "Mounts": mounts}])def _run(cmd, **kwargs):argv = [str(a) for a in cmd]calls.append((argv, kwargs.get("input") or b""))sub = argv[1] if len(argv) > 1 else ""rc = 0- if "/bin/chown" in argv and fail == "chown-timeout":+ if "/usr/bin/xargs" in argv and fail == "chown-timeout":raise subprocess.TimeoutExpired(argv, 10)- if "/bin/chown" in argv and fail == "chown":+ if "/usr/bin/xargs" in argv and fail == "chown":rc = 1 # e.g. a container without CAP_CHOWNout = {"run": "fake-cid\n", "info": security_options}.get(sub, "")+ if sub == "ps" and "status=exited" in argv: # the orphan sweep finds the detached container+ out = "fake-cid\n"if sub == "inspect" and argv[-1] == "fake-cid":- out = _inspect() if len(argv) == 3 else json.dumps(json.loads(_inspect())[0]["Mounts"])- if "/usr/bin/find" in argv and "-user" in argv:+ out = _inspect() if len(argv) == 3 else "2020-01-01T00:00:00Z" if "FinishedAt" in argv[3] else json.dumps(+ json.loads(_inspect())[0]["Mounts"])+ if "--mount" in argv and fail == "strip":+ rc = 1 # e.g. an image without find+ elif "/usr/bin/find" in argv and "-user" in argv and "-print0" in argv:out = (_ROOT_OWNED if argv[argv.index("-user") + 1] == "0" else _HOST_OWNED).decode()rc = 1 if fail == "find" else 0 # e.g. find missing from the imageif kwargs.get("text") or kwargs.get("encoding"):@@ -60,6 +71,23 @@ _PLAIN = "[name=apparmor name=seccomp,profile=builtin name=cgroupns]"_EXTRA_USER = ["--user", "1000:1000"] # docker_extra_args, not docker_run_as_host_user+_CAP_ARGS = {name: args for name, args in [ # a container that could write file capabilities+ ("setfcap", ["--cap-add", "SETFCAP"]), ("cap_setfcap", ["--cap-add", "cap_setfcap"]),+ ("all", ["--cap-add", "ALL"]), ("privileged", ["--privileged"])]}+++def _assert_strip(argv, sandbox, caps):+ """One hardened throwaway that mounts only the creator's existing sandbox dirs and needs no stat."""+ assert [argv[i + 1] for i, a in enumerate(argv) if a == "--mount"] == [+ f"type=bind,src={sandbox}/home,dst=/root", f"type=bind,src={sandbox}/workspace,dst=/workspace"], argv+ assert "--volumes-from" not in argv and "-v" not in argv and "--cap-drop" in argv, argv+ tail = argv[argv.index("sha256:img") + 1:]+ if caps: # every regular file re-chowned to its own uid clears caps too; no owner changes+ assert tail[:2] == ["/bin/sh", "-c"] and "-perm" not in tail and 'chown -h "$u"' in tail[2], tail+ else:+ assert tail[0] == "find" and tail[-9:] == ["-type", "f", "-perm", "/6000", "-exec", "chmod", "ug-s", "{}", "+"], tail++def _to_root(calls):return [stdin for argv, stdin in calls if "/bin/chown" in argv and "0:0" in argv[argv.index("/bin/chown"):]]@@ -77,15 +105,34 @@ def _to_root(calls):(False, _EXTRA_USER, _PLAIN, "reclaim"),(False, [], _PLAIN, "reclaim-fails-find"), # a failed reclaim keeps the record; a retry succeeds(False, [], _PLAIN, "reclaim-fails-chown"),+ (False, [], _PLAIN, "persist"), # never removed: stripped on detach and reattach, owners unchanged+ (True, [], _PLAIN, "persist-none"),+ (False, [], _PLAIN, "persist-shared"), # another profile attaching strips the creator's dirs+ (False, [], _PLAIN, "persist-reap"), # the orphan sweep, with TERMINAL_SANDBOX_DIR behind a symlink+ (False, [], _PLAIN, "persist-gone"), # deleted sandbox dirs are never recreated root-owned+ (False, [], _PLAIN, "persist-fails-strip"), # warned once, not at debug+ (False, [], _PLAIN, "persist-label"), # container metadata never widens what the root strip touches+ *[(False, args, _PLAIN, scenario) for scenario in ("handback", "persist") for args in _CAP_ARGS.values()],])def test_root_container_teardown_hands_every_sandbox_mount_back_before_removal(- monkeypatch, tmp_path, run_as_host_user, user_args, security_options, scenario):- monkeypatch.setenv("TERMINAL_SANDBOX_DIR", str(tmp_path / "sandboxes"))+ monkeypatch, tmp_path, caplog, run_as_host_user, user_args, security_options, scenario):+ real_sandbox = tmp_path / "sandboxes"+ real_sandbox.mkdir()+ if scenario == "persist-reap":+ (tmp_path / "link").symlink_to(real_sandbox)+ monkeypatch.setenv("TERMINAL_SANDBOX_DIR", str(tmp_path / ("link" if scenario == "persist-reap" else "sandboxes")))+ if scenario == "persist-shared": # profiles of one Hermes root, each with its default sandbox dir+ monkeypatch.delenv("TERMINAL_SANDBOX_DIR")+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "root" / "profiles" / "creator"))+ caps = any(a in user_args for args in _CAP_ARGS.values() for a in args[-1:])fail = scenario.rsplit("-", 1)[1] if "fails" in scenario else scenario if scenario == "chown-timeout" else ""calls = _fake_docker(monkeypatch, security_options, fail=fail)- nested_ro, shared = tmp_path / "skills", tmp_path / "shared"+ nested_ro, shared, decoy = tmp_path / "skills", tmp_path / "shared", tmp_path / "outside" / "a" / "decoy"nested_ro.mkdir()shared.mkdir()+ decoy.mkdir(parents=True)+ if scenario == "persist-label": # extra args (or an image LABEL) claim a host dir as a sandbox root+ user_args = ["--label", f"hermes-sandbox={tmp_path / 'outside'}", "-v", f"{decoy}:/workspace"]record = tmp_path / "sandboxes" / "docker" / "chown-back" / ".hermes-owner-handback"if scenario.startswith("reclaim"): # an earlier root teardown handed these back; "link" is now a symlinkrecord.parent.mkdir(parents=True)@@ -94,7 +141,7 @@ def test_root_container_teardown_hands_every_sandbox_mount_back_before_removal(def _env():return docker_env.DockerEnvironment(image="python:3.12-slim", cwd="/root", timeout=5, task_id="chown-back", persistent_filesystem=True,- persist_across_processes=False, run_as_host_user=run_as_host_user,+ persist_across_processes=scenario.startswith("persist"), run_as_host_user=run_as_host_user,volumes=[f"{nested_ro}:/root/.hermes/skills:ro"],extra_args=["-v", f"{shared}:/workspace/shared", *user_args])env = _env()@@ -110,26 +157,57 @@ def test_root_container_teardown_hands_every_sandbox_mount_back_before_removal(assert all("PATH=/usr/sbin:/usr/bin:/sbin:/bin" in argv for argv, _ in calls if "/usr/bin/find" in argv), callsassert not record.exists()return+ sandbox = os.path.realpath(env._home_dir.rsplit("/", 1)[0]) # mounted resolved: a later symlink swap is inert+ if scenario == "persist-gone":+ shutil.rmtree(sandbox)env.cleanup()assert env.wait_for_cleanup(5)+ if scenario.startswith("persist"): # a running container: strip bits/caps in place, give nothing away+ if scenario == "persist-shared":+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "root" / "profiles" / "other"))+ monkeypatch.setattr(docker_env.DockerEnvironment, "_find_reusable_container", lambda *a: ("fake-cid", "running"))+ if scenario == "persist-gone":+ docker_env.reap_orphan_containers(max_age_seconds=0)+ assert not os.path.exists(sandbox)+ else:+ reattached = _env()+ assert reattached._container_id == "fake-cid"+ if scenario == "persist-reap":+ docker_env.reap_orphan_containers(max_age_seconds=0)+ # Filtered to this sandbox: an env another test holds may tear down (and strip) mid-test.+ strips = [argv for argv, _ in calls if "--rm" in argv and f"{sandbox}/home" in " ".join(argv)]+ assert "stop" not in [argv[1] for argv, _ in calls] and not record.exists(), calls+ assert len(strips) == {"persist-none": 0, "persist-gone": 0, "persist-reap": 3}.get(scenario, 2), calls+ assert not [argv for argv, _ in calls if "--mount" in argv and str(decoy) in " ".join(argv)], calls+ if scenario == "persist-label":+ return+ for argv in strips: # only the sandbox dirs are mounted: a swap mid-walk cannot reach host data+ _assert_strip(argv, sandbox, caps)+ warned = [r.levelno for r in caplog.records if "Could not strip" in r.getMessage() and sandbox in r.getMessage()]+ assert warned == ([logging.WARNING] if scenario == "persist-fails-strip" else []), warned # once, then debug+ returnsubcommands = [argv[1] for argv, _ in calls]- chowns = [(argv, stdin) for argv, stdin in calls if "/bin/chown" in argv]+ chowns = [(argv, stdin) for argv, stdin in calls if "/usr/bin/xargs" in argv]if scenario == "none":assert chowns == [], chownsassert subcommands[-1] == "rm" and "stop" in subcommandsreturnassert record.read_bytes() == _ROOT_OWNED+ # Handback first (its chown clears the bits it touches), then the strip on its own budget, before rm.+ (strip,) = [argv for argv, _ in calls if "--mount" in argv]+ _assert_strip(strip, sandbox, caps)if scenario == "chown-timeout": # the CLI is killed; the named throwaway must not run onname = chowns[0][0][chowns[0][0].index("--name") + 1]assert name.startswith("hermes-handback-fake-cid-") and [docker_env.find_docker(), "rm", "-f", name] in [argv for argv, _ in calls], calls+ assert calls.index((chowns[0][0], chowns[0][1])) < calls.index((strip, b"")) # a timeout never skips itreturn- (walk,) = [argv for argv, _ in calls if "/usr/bin/find" in argv]+ (walk,) = [argv for argv, _ in calls if "/usr/bin/find" in argv and "-print0" in argv]((chown, stdin),) = chowns# After stop (no writer left, shutdown writes included), before rm, from the stopped container's volumes.stop, rm = subcommands.index("stop"), subcommands.index("rm")- assert stop < calls.index((walk, b"")) < rm and stop < calls.index((chown, stdin)) < rm+ assert stop < calls.index((walk, b"")) < calls.index((chown, stdin)) < calls.index((strip, b"")) < rmfor argv in (walk, chown):assert argv[argv.index("--volumes-from") + 1] == "fake-cid" and "--user" in argv and "sha256:img" in argvfor argv in (walk, chown): # a binary planted on the image PATH under /root or /workspace never runsdiff --git a/tools/environments/docker.py b/tools/environments/docker.pyindex a3175e67058..5fdf38e4e9a 100644--- a/tools/environments/docker.py+++ b/tools/environments/docker.py@@ -23,7 +23,7 @@ from pathlib import Pathfrom typing import Optionalfrom hermes_constants import get_hermes_home-from tools.environments.base import BaseEnvironment, EnvironmentConnectionError, _SHELL_ENV_NAME_RE+from tools.environments.base import BaseEnvironment, EnvironmentConnectionError, _SHELL_ENV_NAME_RE, get_sandbox_dirfrom tools.terminal_tool_config import (_host_path_key, _is_windows_drive_path, cwd_follows_host_mount,)@@ -33,7 +33,8 @@ from tools.environments.docker_egress import (_egress_reuse_fingerprint, check_docker_env_collisions, check_extra_args_collisions,check_forward_env_collisions, merge_egress_env,)-from tools.environments.docker_ownership import hand_back_sandbox_files, reclaim_sandbox_files+from tools.environments.docker_ownership import (+ hand_back_sandbox_files, reclaim_sandbox_files, strip_sandbox_privileges)from tools.environments.path_utils import sanitize_task_id_for_pathfrom tools.environments.remote_common import (bash_argv, client_env_with, load_hermes_env_vars, prepend_unset, resolve_passthrough_env, run_capture)@@ -205,6 +206,7 @@ def reap_orphan_containers(age = (now - finished_at).total_seconds()if age < max_age_seconds:continue+ strip_sandbox_privileges(docker, cid) # its teardown never ran; owners stay (it may restart)# No -f: a sibling may have restarted the container between the ps snapshot# and now (FinishedAt still reports the previous exit), and the daemon refuses# a plain rm on a running container, which is the atomic recheck this sweep needs.@@ -752,6 +754,8 @@ class DockerEnvironment(BaseEnvironment):task_label, profile_name, egress_label, network)if not reused:self._container_id = self._docker_run(cwd)+ else: # it never stopped, so no teardown stripped what it left+ strip_sandbox_privileges(self._docker_exe, self._container_id)reclaim_sandbox_files(self._docker_exe, self._container_id, self._sandbox_mounts)# Init-time env forwarding args seed the snapshot.@@ -878,7 +882,6 @@ class DockerEnvironment(BaseEnvironment):writable_args: list[str] = []if self._persistent:- from tools.environments.base import get_sandbox_dir# _sandbox_dir_name(): a raw session-key task_id carries colons,# which `-v` reads as extra spec fields (exit 125).sandbox = get_sandbox_dir() / "docker" / _sandbox_dir_name(task_id)@@ -1278,17 +1281,19 @@ class DockerEnvironment(BaseEnvironment):self._remove_bind_dirs()return+ # Capture what the worker needs — the thread can outlive ``self``.+ docker_exe = self._docker_exe+ log_id = container_id[:12]+ sandbox_mounts = list(getattr(self, "_sandbox_mounts", []))+if not force_remove and self._persist_across_processes:# Drop the in-process handle so a fresh __init__ re-probes via# labels instead of reusing a stale Python reference.self._container_id = None+ # The host user may run what the container left before it is reattached.+ self._start_teardown(lambda: strip_sandbox_privileges(docker_exe, container_id), log_id)return- # Capture what the worker needs — the thread can outlive ``self``.- docker_exe = self._docker_exe- log_id = container_id[:12]- sandbox_mounts = list(getattr(self, "_sandbox_mounts", []))-def _do_cleanup() -> None:for argv, fail_msg in ((["stop", "-t", "10"], "docker stop %s timed out / failed: %s"),(["rm", "-f"], "docker rm -f %s failed: %s")):@@ -1301,11 +1306,7 @@ class DockerEnvironment(BaseEnvironment):except (subprocess.TimeoutExpired, OSError) as e:logger.warning(fail_msg, log_id, e)- t = threading.Thread(target=_do_cleanup, daemon=True, name=f"hermes-cleanup-{log_id}")- with _TEARDOWN_LOCK:- _TEARDOWN_THREADS.add(t)- t.start()- self._cleanup_thread = t+ self._start_teardown(_do_cleanup, log_id)self._container_id = None# Bind-mount dirs are the container's filesystem state; only drop them@@ -1313,6 +1314,14 @@ class DockerEnvironment(BaseEnvironment):if not self._persistent:self._remove_bind_dirs()+ def _start_teardown(self, work, log_id: str) -> None:+ """Run *work* on a daemon thread the atexit drain joins."""+ t = threading.Thread(target=work, daemon=True, name=f"hermes-cleanup-{log_id}")+ with _TEARDOWN_LOCK:+ _TEARDOWN_THREADS.add(t)+ t.start()+ self._cleanup_thread = t+@staticmethoddef wait_for_all_teardowns(timeout: float = 15.0) -> bool:"""Join every in-flight teardown worker, including those of envs the idle reaper alreadydiff --git a/tools/environments/docker_ownership.py b/tools/environments/docker_ownership.pyindex 426d9305405..aa3f01ba5e3 100644--- a/tools/environments/docker_ownership.py+++ b/tools/environments/docker_ownership.py@@ -14,6 +14,15 @@ mounts them gives exactly those paths back to root before its first command. Filon the host in between keep their owner. Every walk is ``find -P`` (no symlinks followed) and pruneseach mount Docker reports nested under the sandbox paths (read-only skills, credentials, caches,``docker_volumes`` and ``docker_extra_args`` binds), so host data outside the sandbox dir is never touched.++After the handback, a root pass strips setuid/setgid bits (``chmod ug-s``) from the sandbox files+whatever their owner (a host-user-owned group-root setgid file runs with host egid 0). A container+that could write file capabilities (SETFCAP, ALL, privileged) instead gets every regular file+re-chowned to its own uid, which clears the bits and ``security.capability`` and changes no owner.+A persistent container is never removed, so it gets this strip when a session detaches from it,+before reattaching and before the stale-container sweep removes it. The strip reads the sandbox+binds from the container itself (a container shared across profiles has its creator's dirs) but+only keeps those under a sandbox root this host derives from its own Hermes root."""from __future__ import annotations@@ -29,6 +38,8 @@ import timefrom pathlib import Pathfrom typing import Optional+from hermes_constants import get_default_hermes_root+from tools.environments.base import get_sandbox_dirfrom tools.environments.remote_common import run_capturelogger = logging.getLogger(__name__)@@ -94,24 +105,48 @@ def _runs_as_root(info: dict) -> bool:return ((info.get("Config") or {}).get("User") or "").split(":")[0] in ("", "root", "0")-def walk_argv(mounts: list[tuple[str, str]], mount_points: list[str], owner: int) -> list[str]:- """``find`` argv printing, NUL-terminated, every entry owned by *owner* under the sandbox- mounts. It never follows symlinks (``-P``) and prunes each mount point nested below them."""+def _may_set_file_caps(info: dict) -> bool:+ """Only a container granted SETFCAP (or privileged) can write file capabilities; the base+ args drop it. ``find`` cannot test xattrs, so then every regular file is re-chowned."""+ host = info.get("HostConfig") or {}+ return bool(host.get("Privileged")) or any(+ c.upper().removeprefix("CAP_") in ("SETFCAP", "ALL") for c in host.get("CapAdd") or [])+++def _sandbox_binds(info: dict) -> list[tuple[str, str]]:+ """The container's Hermes sandbox binds (``<root>/<task>/{home,workspace}`` at ``/root`` and+ ``/workspace``) as ``(realpath, destination)``. *root* is derived on this host only, never from+ container metadata (labels and binds are settable via extra args or the image): this process's+ ``<sandbox>/docker`` or the default one of any profile of this Hermes root (shared containers)."""+ hermes_root = get_default_hermes_root()+ roots = {os.path.realpath(d / "sandboxes" / "docker") for d in [hermes_root, *hermes_root.glob("profiles/*")]}+ roots.add(os.path.realpath(get_sandbox_dir() / "docker"))+ binds = [(os.path.realpath(m.get("Source") or "/nonexistent"), m.get("Destination")) for m in info.get("Mounts") or []+ if m.get("Type") == "bind" and m.get("Destination") in ("/root", "/workspace")]+ return [(src, dst) for src, dst in binds if os.path.isdir(src) and os.path.dirname(os.path.dirname(src)) in roots]+++def _owned(owner: int) -> list[str]:+ # Device nodes and FIFOs stay root's: a host-owned block device is raw disk access.+ return ["(", "-type", "f", "-o", "-type", "d", "-o", "-type", "l", ")", "-user", str(owner), "-print0"]+++def walk_argv(mounts: list[tuple[str, str]], mount_points: list[str], tail: list[str]) -> list[str]:+ """``find`` argv applying *tail* to every entry under the sandbox mounts. It never follows+ symlinks (``-P``) and prunes each mount point nested below them."""targets = [container for _, container in mounts]prune: list[str] = []for point in sorted({p.rstrip("/") for p in mount_points}):if any(point.startswith(t.rstrip("/") + "/") for t in targets):prune += [*(["-o"] if prune else []), "-path", re.sub(r"([][*?\\])", r"\\\1", point)]- return ["/usr/bin/find", "-P", *targets, "-xdev", *(["(", *prune, ")", "-prune", "-o"] if prune else []),- # Device nodes and FIFOs stay root's: a host-owned block device is raw disk access.- "(", "-type", "f", "-o", "-type", "d", "-o", "-type", "l", ")", "-user", str(owner), "-print0"]+ return ["/usr/bin/find", "-P", *targets, "-xdev", *(["(", *prune, ")", "-prune", "-o"] if prune else []), *tail]def _walk(docker_exe: str, target: list[str], mounts: list[tuple[str, str]], info: dict, owner: int,deadline: float) -> Optional[list[bytes]]:"""Entries owned by *owner*, or ``None`` when the walk failed (its output may be partial)."""points = [m["Destination"] for m in info.get("Mounts") or []]- result = _docker(docker_exe, target, walk_argv(mounts, points, owner), deadline)+ result = _docker(docker_exe, target, walk_argv(mounts, points, _owned(owner)), deadline)if result.returncode != 0:logger.debug("ownership walk exited %d: %s", result.returncode,result.stderr.decode("utf-8", "replace").strip()[:500])@@ -140,32 +175,73 @@ def _chown(docker_exe: str, target: list[str], paths: list[bytes], owner: str, dreturn result.returncode == 0+def _throwaway(container_id: str, info: dict, volumes: list[str]) -> list[str]:+ return ["run", "--rm", "-i", "--pull", "never", "--network", "none", "--user", "0:0", *_THROWAWAY_CONFINEMENT,+ *_SAFE_ENV, "--name", f"hermes-handback-{container_id[:12]}-{secrets.token_hex(4)}",+ *volumes, "--entrypoint", "", info["Image"]]+++# Re-chown each regular file to its own uid, one walk per distinct owner (uids read once; busybox+# find has no -printf, and stat sits in /usr/bin on some images and /bin on others).+_SAME_OWNER_CHOWN = ('uids=$("$@" -type f -exec stat -c %u -- {} +) || exit; '+ 'for u in $(printf "%s\\n" "$uids" | sort -u); do "$@" -type f -user "$u" -exec chown -h "$u" {} + '+ '|| exit; done')+_strip_warned: set[str] = set()+++def strip_sandbox_privileges(docker_exe: str, container_id: str, info: Optional[dict] = None) -> None:+ """Strip setuid/setgid bits (and file caps, when the container could set them) from the root+ container's existing sandbox binds in ONE throwaway that mounts only those dirs: owners stay,+ so a running container's git/ssh checks keep passing, and a path swapped mid-walk can only+ lead to sandbox files, never other host data. ``--mount`` refuses a missing source instead+ of creating it root-owned. A pass that cannot run warns once per sandbox dir."""+ if info is None:+ info = _inspect(docker_exe, container_id) if _handback_ids(docker_exe) else None+ if not (mounts := _sandbox_binds(info) if info and _runs_as_root(info) else []):+ return+ target = _throwaway(container_id, info, [a for src, dst in mounts+ for a in ("--mount", f"type=bind,src={src},dst={dst}")])+ # Only the sandbox dirs are mounted, so PATH (reset to system dirs) finds the image's own tools.+ walk = ["find", *walk_argv(mounts, [m["Destination"] for m in info.get("Mounts") or []], [])[1:]]+ argv = (["/bin/sh", "-c", _SAME_OWNER_CHOWN, "sh", *walk] if _may_set_file_caps(info)+ else [*walk, "-type", "f", "-perm", "/6000", "-exec", "chmod", "ug-s", "{}", "+"])+ try:+ result = _docker(docker_exe, target, argv, time.monotonic() + _CHOWN_TIMEOUT_S)+ error = result.returncode and f"exit {result.returncode}: {result.stderr.decode('utf-8', 'replace')[:300]}"+ except (subprocess.TimeoutExpired, OSError) as e:+ error = str(e)+ if error:+ where = os.path.dirname(mounts[0][0])+ (logger.debug if where in _strip_warned else logger.warning)(+ "Could not strip setuid/setgid bits and file capabilities from Docker sandbox %s (%s); "+ "files there may still run with elevated rights on the host", where, error.strip())+ _strip_warned.add(where)++def hand_back_sandbox_files(docker_exe: str, container_id: str, mounts: list[tuple[str, str]]) -> None:"""After a root container has stopped (so nothing writes any more) and before it is removed:give its root-owned sandbox files (``mounts`` are ``(host_dir, container_path)``) to the hostuser from a throwaway container of the same local image with the same volumes, and record- which. The paths are recorded before any of them changes owner, so a timeout mid-chown still- leaves a complete record. Best-effort: a gone container, an image without ``find`` or a- timeout logs at debug."""+ which, then strip what is left (the handback chown already cleared the bits it touched); each+ step has its own time budget. The paths are recorded before any of them changes owner, so a+ timeout mid-chown still leaves a complete record. Best-effort: a gone container, an image+ without ``find`` or a timeout logs at debug."""record = _record_path(mounts)ids = _handback_ids(docker_exe) if record else Noneinfo = _inspect(docker_exe, container_id) if ids else Noneif not info or not _runs_as_root(info):return- target = ["run", "--rm", "-i", "--pull", "never", "--network", "none", "--user", "0:0", *_THROWAWAY_CONFINEMENT,- *_SAFE_ENV, "--name", f"hermes-handback-{container_id[:12]}-{secrets.token_hex(4)}",- "--volumes-from", container_id, "--entrypoint", "", info["Image"]]+ target = _throwaway(container_id, info, ["--volumes-from", container_id])deadline = time.monotonic() + _CHOWN_TIMEOUT_Stry:- paths = _walk(docker_exe, target, mounts, info, 0, deadline)- if not paths:- return- known = set(record.read_bytes().split(b"\0")) if record.is_file() else set()- with record.open("ab") as fh: # append: an unreclaimed earlier record still applies- fh.write(b"".join(p + b"\0" for p in paths if p not in known))- _chown(docker_exe, target, paths, f"{ids[0]}:{ids[1]}", deadline)+ if paths := _walk(docker_exe, target, mounts, info, 0, deadline):+ known = set(record.read_bytes().split(b"\0")) if record.is_file() else set()+ with record.open("ab") as fh: # append: an unreclaimed earlier record still applies+ fh.write(b"".join(p + b"\0" for p in paths if p not in known))+ _chown(docker_exe, target, paths, f"{ids[0]}:{ids[1]}", deadline)except (subprocess.TimeoutExpired, OSError, KeyError) as e:logger.debug("ownership handback of %s failed: %s", container_id[:12], e)+ strip_sandbox_privileges(docker_exe, container_id, info)def reclaim_sandbox_files(docker_exe: str, container_id: str, mounts: list[tuple[str, str]]) -> None:diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 9a6edf5aaa0..fc5d1897c73 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -700,7 +700,7 @@ Anything listed in `docker_forward_env` becomes visible to commands run inside t### Running the Container as Your Host User-By default Docker containers run as `root` (UID 0). Files created inside `/workspace` or other bind-mounts end up owned by root on the host, so after a session you have to `sudo chown` them before you can edit them from your host editor. On Linux, when Hermes stops and removes a root container, it first hands the files in its own sandbox bind mounts (`/root` and `/workspace` under `TERMINAL_SANDBOX_DIR`) back to your user (not your `docker_volumes` or mounted host directory; skipped on rootless Docker and userns-remap). The `terminal.docker_run_as_host_user` flag fixes this for every mount and for long-lived containers that are never removed:+By default Docker containers run as `root` (UID 0). Files created inside `/workspace` or other bind-mounts end up owned by root on the host, so after a session you have to `sudo chown` them before you can edit them from your host editor. On Linux, when Hermes stops and removes a root container, it first hands the files in its own sandbox bind mounts (`/root` and `/workspace` under `TERMINAL_SANDBOX_DIR`) back to your user (not your `docker_volumes` or mounted host directory; skipped on rootless Docker and userns-remap). Those sandbox files also lose setuid/setgid bits and file capabilities, whatever their owner, so nothing the container left there runs with elevated rights when you execute it on the host; a long-lived container that is never removed gets that strip (without any owner change) whenever a session detaches from it or reattaches, and before the stale-container sweep removes it. The `terminal.docker_run_as_host_user` flag fixes this for every mount and for long-lived containers that are never removed:```yamlterminal: