Skip to content

The agent that grows with you

fix(desktop): ask the Hermes binary whether Chromium's sandbox starts under AppArmor (#130177)

Tekniumf5e4f7ac2613
diff --git a/apps/desktop/electron/entry.ts b/apps/desktop/electron/entry.ts
index ae3be8d579e..85720e42381 100644
--- a/apps/desktop/electron/entry.ts
+++ b/apps/desktop/electron/entry.ts
@@ -10,6 +10,13 @@ import { readDesktopLaunchConfig } from './renderer-heap-flags'
import { wslgLaunchArgs } from './wslg-launch'
import { spawnWslgLaunch } from './wslg-launch-process'
+// `hermes desktop` asks this binary whether Chromium's namespace sandbox starts under the host's
+// AppArmor policy (#130177). Chromium creates its sandboxed zygote before any JS runs, so reaching
+// this line answers yes; exit before any window, single-instance lock, backend or relaunch.
+if (process.argv.includes('--hermes-sandbox-probe')) {
+ process.exit(0)
+}
+
// Run before main creates windows/IME integrations or spawns resident helpers.
// Closing Hermes cannot release a CWD inherited by an out-of-tree process.
releasePackagedWorkingDirectory(app.isPackaged || Boolean(process.env.HERMES_DESKTOP_IS_PACKAGED))
diff --git a/hermes_cli/main_desktop.py b/hermes_cli/main_desktop.py
index 729d5f3d28f..072533d4ff2 100644
--- a/hermes_cli/main_desktop.py
+++ b/hermes_cli/main_desktop.py
@@ -1246,7 +1246,10 @@ def _desktop_linux_sandbox_fixup(packaged_executable: Path) -> bool:
if _sandbox_helper_is_setuid_root(st):
return True
- if _desktop_linux_userns_sandbox_available():
+ from hermes_cli.main_desktop_apparmor import chromium_userns_sandbox_verdict
+
+ verdict = chromium_userns_sandbox_verdict(packaged_executable)
+ if verdict if verdict is not None else _desktop_linux_userns_sandbox_available():
print("✓ Using Chromium's user-namespace sandbox (setuid helper not needed).")
return True
@@ -1622,10 +1625,13 @@ def _check_desktop_skip_build(
def _packaged_desktop_launch_command(packaged_executable: Path) -> list[str]:
"""``[exe, *sandbox flags]`` after the Linux sandbox fixup; exits when the sandbox can't be configured."""
+ from hermes_cli.main_desktop_apparmor import print_blocked_remedies
+
launch_command = [str(packaged_executable)]
if not _desktop_linux_sandbox_fixup(packaged_executable):
if _desktop_linux_needs_no_sandbox() and _desktop_linux_sandbox_helper_is_regular_file(packaged_executable):
print("⚠ Falling back to --no-sandbox because this Linux host restricts unprivileged user namespaces and the Electron sandbox helper could not be configured.")
+ print_blocked_remedies(packaged_executable)
launch_command.append("--no-sandbox")
else:
sys.exit(1)
@@ -1668,6 +1674,27 @@ def _launch_installed_macos_desktop_app() -> bool:
return True
+def _run_desktop_one_shot(args: argparse.Namespace, desktop_dir: Path, *, bundled: bool) -> None:
+ """Run a host-setup one-shot flag, then exit without building or launching."""
+ # macOS: a self-signed code-signing identity so TCC grants survive rebuilds.
+ if getattr(args, "setup_tcc_identity", False):
+ from hermes_cli.main_desktop_tcc import _desktop_macos_setup_tcc_identity
+ identity = getattr(args, "identity", None) or "Hermes Local Signing"
+ sys.exit(0 if _desktop_macos_setup_tcc_identity(identity) else 1)
+ # Linux: the per-binary AppArmor profile for Chromium's namespace sandbox (#130177).
+ if getattr(args, "install_apparmor_profile", False):
+ from hermes_cli.bundled_app import NotBundledApp, resolve_bundle_layout
+ from hermes_cli.main import PROJECT_ROOT
+ from hermes_cli.main_desktop_apparmor import install_profile
+ exe = _desktop_packaged_executable(desktop_dir)
+ if bundled:
+ with contextlib.suppress(NotBundledApp):
+ exe = resolve_bundle_layout(PROJECT_ROOT).launcher
+ if exe is None:
+ print(f"✗ No packaged Hermes Desktop found under {desktop_dir / 'release'}; run `hermes desktop` first.")
+ sys.exit(0 if exe is not None and install_profile(exe) else 1)
+
+
def cmd_gui(args: argparse.Namespace):
"""Build and launch the native Electron desktop GUI."""
from hermes_cli.main import PROJECT_ROOT
@@ -1708,12 +1735,7 @@ def cmd_gui(args: argparse.Namespace):
skip_build = getattr(args, "skip_build", False)
force_build = getattr(args, "force_build", False)
- # macOS-only one-shot: create a self-signed code-signing identity so TCC
- # grants survive rebuilds, then exit without building/launching.
- if getattr(args, "setup_tcc_identity", False):
- from hermes_cli.main_desktop_tcc import _desktop_macos_setup_tcc_identity
- identity = getattr(args, "identity", None) or "Hermes Local Signing"
- sys.exit(0 if _desktop_macos_setup_tcc_identity(identity) else 1)
+ _run_desktop_one_shot(args, desktop_dir, bundled=bundled)
if bundled:
_launch_bundled_desktop(args, env, config_electron_flags)
@@ -1958,10 +1980,13 @@ def _launch_bundled_desktop(
print(" The install is damaged — reinstall Hermes from the website.")
sys.exit(1)
+ from hermes_cli.main_desktop_apparmor import print_blocked_remedies
+
launch_command = [str(layout.launcher)]
if not _desktop_linux_sandbox_fixup(layout.launcher):
if _desktop_linux_needs_no_sandbox() and _desktop_linux_sandbox_helper_is_regular_file(layout.launcher):
print("⚠ Falling back to --no-sandbox because this Linux host restricts unprivileged user namespaces and the Electron sandbox helper could not be configured.")
+ print_blocked_remedies(layout.launcher)
launch_command.append("--no-sandbox")
else:
sys.exit(1)
diff --git a/hermes_cli/main_desktop_apparmor.py b/hermes_cli/main_desktop_apparmor.py
new file mode 100644
index 00000000000..d0a17b60300
--- /dev/null
+++ b/hermes_cli/main_desktop_apparmor.py
@@ -0,0 +1,143 @@
+"""Chromium's Linux sandbox under AppArmor's unprivileged-userns restriction (#130177).
+
+With ``kernel.apparmor_restrict_unprivileged_userns=1`` (Ubuntu 23.10+), any unconfined program
+may still create a user namespace, but it loses every capability inside it unless an AppArmor
+profile attached to that program's path grants ``userns``. ``unshare --user true`` therefore
+succeeds while Chromium, which needs those capabilities, aborts with ``No usable sandbox!``.
+Only the Hermes binary itself, under whatever profile attaches to its path, can answer whether
+its namespace sandbox starts, so on a restricted host the launcher asks that binary.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import mmap
+import os
+import subprocess
+import sys
+from pathlib import Path
+from typing import Optional
+
+RESTRICT_SYSCTL = Path("/proc/sys/kernel/apparmor_restrict_unprivileged_userns")
+# Answered by apps/desktop/electron/entry.ts before any window, lock or backend exists.
+SANDBOX_PROBE_SWITCH = "--hermes-sandbox-probe"
+_PROBE_TIMEOUT_S = 15
+_SUDO_TIMEOUT_S = 300 # room for a typed password, never an unbounded hang
+_PROFILE_DIR = Path("/etc/apparmor.d")
+
+
+def apparmor_restricts_userns() -> bool:
+ try:
+ return RESTRICT_SYSCTL.read_text(encoding="utf-8-sig").strip() == "1"
+ except OSError:
+ return False
+
+
+def _build_answers_probe(packaged_executable: Path) -> bool:
+ """True when this packaged build's entry point honours the probe switch.
+
+ A build from before the switch would start the whole app instead of exiting, so the probe is
+ only sent to a build whose ``app.asar`` carries the switch literal.
+ """
+ asar = packaged_executable.parent / "resources" / "app.asar"
+ try:
+ with asar.open("rb") as handle, mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ) as data:
+ return data.find(SANDBOX_PROBE_SWITCH.encode()) != -1
+ except (OSError, ValueError):
+ return False
+
+
+def chromium_userns_sandbox_verdict(packaged_executable: Path) -> Optional[bool]:
+ """Whether Chromium's namespace sandbox starts for *packaged_executable* on this host.
+
+ ``None`` when the host has no AppArmor userns restriction or the build cannot answer the
+ probe; the caller then keeps its generic probe. Chromium creates its sandboxed zygote before
+ any app JavaScript runs, so a probe that reaches the entry point exits 0 and a blocked one
+ dies with ``No usable sandbox!``. A probe that hangs or cannot start counts as blocked.
+ """
+ if sys.platform != "linux" or not apparmor_restricts_userns():
+ return None
+ if not _build_answers_probe(packaged_executable):
+ return None
+ env = {key: value for key, value in os.environ.items() if key != "ELECTRON_RUN_AS_NODE"}
+ try:
+ completed = subprocess.run(
+ [str(packaged_executable), "--disable-setuid-sandbox", SANDBOX_PROBE_SWITCH],
+ cwd=packaged_executable.parent, env=env, stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
+ timeout=_PROBE_TIMEOUT_S, check=False)
+ except (OSError, subprocess.TimeoutExpired):
+ return False
+ return completed.returncode == 0
+
+
+def profile_name(packaged_executable: Path) -> str:
+ """One profile per install path, so two checkouts never overwrite each other's grant."""
+ digest = hashlib.sha256(str(packaged_executable.resolve()).encode()).hexdigest()[:10]
+ return f"hermes-desktop-{digest}"
+
+
+def profile_text(packaged_executable: Path) -> str:
+ """The profile Chrome and VS Code ship for this case: unconfined, plus the ``userns`` grant."""
+ name = profile_name(packaged_executable)
+ exe = str(packaged_executable.resolve()).replace("\\", "\\\\").replace('"', '\\"')
+ return (
+ "# Hermes Desktop: let Chromium's user-namespace sandbox start under\n"
+ "# kernel.apparmor_restrict_unprivileged_userns=1 (written by `hermes desktop --install-apparmor-profile`).\n"
+ "abi <abi/4.0>,\n"
+ "include <tunables/global>\n\n"
+ f'profile {name} "{exe}" flags=(unconfined) {{\n'
+ " userns,\n\n"
+ f" include if exists <local/{name}>\n"
+ "}\n"
+ )
+
+
+def profile_path(packaged_executable: Path) -> Path:
+ return _PROFILE_DIR / profile_name(packaged_executable)
+
+
+def install_profile(packaged_executable: Path) -> bool:
+ """Write and load the profile through sudo (prompting on a terminal). Prints the outcome."""
+ target = profile_path(packaged_executable)
+ from hermes_platform.resolver import locate_command
+
+ sudo = next(iter(locate_command("sudo").command), None)
+ parser = next(iter(locate_command("apparmor_parser", known_dirs=("/usr/sbin", "/sbin")).command),
+ "apparmor_parser")
+ if not sudo:
+ print("✗ Installing the AppArmor profile needs sudo, which was not found.")
+ print(f" As root, write {target} with:\n\n{profile_text(packaged_executable)}")
+ print(f" then load it: apparmor_parser -r {target}")
+ return False
+ print(f"→ Installing AppArmor profile {target} (sudo required)...")
+ steps = (
+ ([sudo, "tee", str(target)], profile_text(packaged_executable)),
+ ([sudo, parser, "-r", str(target)], None),
+ )
+ for command, stdin_text in steps:
+ try:
+ completed = subprocess.run(
+ command, input=stdin_text, text=True, check=False, timeout=_SUDO_TIMEOUT_S,
+ stdout=subprocess.DEVNULL if stdin_text is not None else None)
+ except (OSError, subprocess.TimeoutExpired) as exc:
+ print(f"✗ {' '.join(command)} failed: {exc}")
+ return False
+ if completed.returncode != 0:
+ print(f"✗ {' '.join(command)} exited {completed.returncode}")
+ return False
+ verdict = chromium_userns_sandbox_verdict(packaged_executable)
+ if verdict is False:
+ print("✗ The profile is loaded, but Chromium's sandbox still cannot start for this binary.")
+ return False
+ print(f"✓ AppArmor profile installed; Hermes Desktop can use Chromium's user-namespace sandbox ({target}).")
+ return True
+
+
+def print_blocked_remedies(packaged_executable: Path) -> None:
+ """The actionable lines for a restricted host where the setuid helper could not be set up."""
+ helper = packaged_executable.parent / "chrome-sandbox"
+ print(" Ubuntu's AppArmor policy (kernel.apparmor_restrict_unprivileged_userns=1) blocks Chromium's")
+ print(" user-namespace sandbox for Hermes Desktop. To keep the sandbox on, run ONE of these once:")
+ print(" hermes desktop --install-apparmor-profile (AppArmor profile for this app; survives rebuilds)")
+ print(f" sudo chown root:root {helper} && sudo chmod 4755 {helper} (redo after each rebuild)")
diff --git a/hermes_cli/subcommands/gui.py b/hermes_cli/subcommands/gui.py
index a4dd29d50af..e4fb503d50e 100644
--- a/hermes_cli/subcommands/gui.py
+++ b/hermes_cli/subcommands/gui.py
@@ -54,6 +54,11 @@ def build_gui_parser(subparsers, *, cmd_gui: Callable) -> None:
"--identity", default="Hermes Local Signing",
help="Certificate name to create/use for --setup-tcc-identity (default: Hermes Local Signing)",
)
+ gui_parser.add_argument(
+ "--install-apparmor-profile", action="store_true",
+ help="Linux only: install an AppArmor profile (sudo) that lets the packaged app use Chromium's "
+ "user-namespace sandbox on hosts with kernel.apparmor_restrict_unprivileged_userns=1 "
+ "(Ubuntu 23.10+), then exit. Survives rebuilds of the same checkout.")
gui_parser.add_argument(
"--close-preview",
action="store_true",
diff --git a/tests/hermes_cli/test_desktop_apparmor_sandbox.py b/tests/hermes_cli/test_desktop_apparmor_sandbox.py
new file mode 100644
index 00000000000..33bcc110859
--- /dev/null
+++ b/tests/hermes_cli/test_desktop_apparmor_sandbox.py
@@ -0,0 +1,63 @@
+"""The Linux launcher asks the Hermes binary itself whether Chromium's sandbox starts (#130177).
+
+Under ``kernel.apparmor_restrict_unprivileged_userns=1`` a generic ``unshare --user`` succeeds while
+Chromium, unconfined, aborts with ``No usable sandbox!``; an AppArmor profile attached to the Hermes
+path flips that answer for Hermes alone. The fake packaged app below answers the probe the way the
+real Electron build does: exit 0 when its sandbox starts, Chromium's FATAL when it does not.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from hermes_cli import main_desktop, main_desktop_apparmor
+
+pytestmark = pytest.mark.platforms("linux")
+
+_BLOCKED = (
+ "#!/bin/sh\n"
+ "echo 'FATAL:zygote_host_impl_linux.cc(128)] No usable sandbox!' >&2\n"
+ "kill -TRAP $$\n"
+)
+_ALLOWED = "#!/bin/sh\nexit 0\n"
+
+
+def _packaged_app(tmp_path, script: str):
+ unpacked = tmp_path / "linux-unpacked"
+ (unpacked / "resources").mkdir(parents=True)
+ # The bundled entry point carries the probe switch, so the launcher knows this build answers it.
+ (unpacked / "resources" / "app.asar").write_bytes(
+ b"\0asar\0" + main_desktop_apparmor.SANDBOX_PROBE_SWITCH.encode() + b"\0")
+ exe = unpacked / "Hermes"
+ exe.write_text(script, encoding="utf-8")
+ exe.chmod(0o755)
+ helper = unpacked / "chrome-sandbox"
+ helper.write_text("", encoding="utf-8")
+ helper.chmod(0o755) # user-owned, not setuid: the reporter's layout
+ return exe
+
+
+def restricted_host(tmp_path, monkeypatch):
+ sysctl = tmp_path / "apparmor_restrict_unprivileged_userns"
+ sysctl.write_text("1\n", encoding="utf-8")
+ monkeypatch.setattr(main_desktop_apparmor, "RESTRICT_SYSCTL", sysctl)
+ # No sudo on this host, so the setuid helper cannot be configured either.
+ monkeypatch.setattr(main_desktop.shutil, "which", lambda name: None)
+
+
+def test_generic_unshare_success_does_not_override_a_blocked_binary(tmp_path, monkeypatch, restricted_host):
+ """The reporter's host: unshare passes, Chromium cannot sandbox -> never the userns path."""
+ exe = _packaged_app(tmp_path, _BLOCKED)
+ monkeypatch.setattr(main_desktop, "_desktop_linux_userns_sandbox_available", lambda: True)
+
+ assert main_desktop._desktop_linux_sandbox_fixup(exe) is False
+
+
+def test_apparmor_profile_for_the_binary_enables_the_userns_path(tmp_path, monkeypatch, restricted_host):
+ """A profile granting Hermes ``userns`` is honoured although unconfined probes fail."""
+ exe = _packaged_app(tmp_path, _ALLOWED)
+ monkeypatch.setattr(main_desktop, "_desktop_linux_userns_sandbox_available", lambda: False)
+
+ assert main_desktop._desktop_linux_sandbox_fixup(exe) is True
+ assert main_desktop._desktop_linux_needs_disable_setuid_sandbox(exe) is True