Skip to content

The agent that grows with you

fix(desktop): refuse AppArmor glob paths and parse-check the profile before writing it

Teknium0ea873bef08b
diff --git a/hermes_cli/main_desktop_apparmor.py b/hermes_cli/main_desktop_apparmor.py
index 18e2d7d24b4..4067025d881 100644
--- a/hermes_cli/main_desktop_apparmor.py
+++ b/hermes_cli/main_desktop_apparmor.py
@@ -13,8 +13,10 @@ from __future__ import annotations
import hashlib
import mmap
import os
+import shlex
import subprocess
import sys
+import tempfile
from pathlib import Path
from typing import Optional
@@ -24,6 +26,10 @@ 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")
+# apparmor.d(5) "Globbing (AARE)": ``?*[]{}^`` stay glob syntax inside a quoted attachment path, so
+# they would widen the grant to other binaries or fail the parse; ``{`` also opens ``@{var}``
+# expansion, and ``"``/``\`` end or escape the quoted string. Such paths are refused, not escaped.
+_AARE_UNSAFE = frozenset('?*[]{}^"\\')
def apparmor_restricts_userns() -> bool:
@@ -85,7 +91,7 @@ def profile_name(packaged_executable: Path) -> str:
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('"', '\\"')
+ exe = str(packaged_executable.resolve())
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"
@@ -102,36 +108,82 @@ def profile_path(packaged_executable: Path) -> Path:
return _PROFILE_DIR / profile_name(packaged_executable)
+def unsafe_path_characters(packaged_executable: Path) -> str:
+ """The characters of the install path an AppArmor attachment cannot carry literally."""
+ path = str(packaged_executable.resolve())
+ return "".join(sorted({ch for ch in path if ch in _AARE_UNSAFE or not ch.isprintable()}))
+
+
+def _user_can_replace(packaged_executable: Path) -> bool:
+ exe = packaged_executable.resolve()
+ return os.access(exe, os.W_OK) or any(os.access(parent, os.W_OK) for parent in exe.parents)
+
+
+def _run(command: list[str], stdin_text: Optional[str] = None) -> Optional[subprocess.CompletedProcess]:
+ """Run one install step; ``None`` (after printing why) when it could not start or timed out."""
+ try:
+ return subprocess.run(
+ command, input=stdin_text, text=True, encoding="utf-8", errors="replace",
+ 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 None
+
+
+def _profile_parses(parser: str, text: str) -> bool:
+ """Compile *text* as this user without loading it, so a bad profile never reaches /etc."""
+ from hermes_constants import get_scratch_dir
+
+ with tempfile.TemporaryDirectory(dir=get_scratch_dir(), prefix="apparmor-") as scratch:
+ candidate = Path(scratch) / "hermes-desktop.profile"
+ candidate.write_text(text, encoding="utf-8")
+ completed = _run([parser, "--skip-kernel-load", "--skip-cache", str(candidate)])
+ if completed is None or completed.returncode != 0:
+ print("✗ apparmor_parser rejected the generated profile; nothing was written to /etc/apparmor.d.")
+ return False
+ return True
+
+
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)
+ unsafe = unsafe_path_characters(packaged_executable)
+ if unsafe:
+ print(f"✗ The install path {packaged_executable.resolve()} contains {unsafe!r}, which AppArmor reads as")
+ print(" pattern syntax (apparmor.d(5), Globbing), so a profile could not name this binary alone.")
+ print(" Move the checkout to a path without these characters, or use the setuid chrome-sandbox helper.")
+ return False
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")
+ text = profile_text(packaged_executable)
+ if _user_can_replace(packaged_executable):
+ print("⚠ This profile lets whatever program sits at this path, which your account can replace, use user"
+ " namespaces, so any code running as you gains what the restriction withholds; the setuid"
+ " chrome-sandbox helper avoids that.")
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" As root, write {target} with:\n\n{text}")
print(f" then load it: apparmor_parser -r {target}")
return False
+ if not _profile_parses(parser, text):
+ 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, encoding="utf-8", errors="replace",
- 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
+ written = _run([sudo, "tee", str(target)], text)
+ if written is None or written.returncode != 0:
+ print(f"✗ Could not write {target}.")
+ return False
+ loaded = _run([sudo, parser, "-r", str(target)])
+ if loaded is None or loaded.returncode != 0:
+ removed = _run([sudo, "rm", "-f", str(target)])
+ if removed is not None and removed.returncode == 0:
+ print(f"✗ apparmor_parser could not load {target}; removed it again.")
+ else:
+ print(f"✗ apparmor_parser could not load {target}, and removing it failed: run sudo rm {target}")
+ 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.")
@@ -142,8 +194,10 @@ def install_profile(packaged_executable: Path) -> bool:
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"
+ helper = shlex.quote(str(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)")
+ print(" user-namespace sandbox for Hermes Desktop. To keep the sandbox on, run ONE of these:")
+ print(f" sudo chown root:root {helper} && sudo chmod 4755 {helper}")
+ print(" Chromium's setuid sandbox helper (recommended; redo after each rebuild)")
+ print(" hermes desktop --install-apparmor-profile")
+ print(" AppArmor profile for this path (survives rebuilds; any program running as you can use it)")
diff --git a/tests/hermes_cli/test_desktop_apparmor_sandbox.py b/tests/hermes_cli/test_desktop_apparmor_sandbox.py
index 1c39ba5dfb1..465c48c2de0 100644
--- a/tests/hermes_cli/test_desktop_apparmor_sandbox.py
+++ b/tests/hermes_cli/test_desktop_apparmor_sandbox.py
@@ -8,6 +8,8 @@ real Electron build does: exit 0 when its sandbox starts, Chromium's FATAL when
from __future__ import annotations
+from pathlib import Path
+
import pytest
from hermes_cli import main_desktop, main_desktop_apparmor
@@ -64,3 +66,44 @@ def test_apparmor_profile_for_the_binary_enables_the_userns_path(tmp_path, monke
assert main_desktop._desktop_linux_sandbox_fixup(exe) is True
assert main_desktop._desktop_linux_needs_disable_setuid_sandbox(exe) is True
+
+
+def _fake_root_tools(tmp_path, monkeypatch, *, parser_fails_on: str = ""):
+ """``sudo`` that logs and runs its argv as this user; ``apparmor_parser`` failing on one flag."""
+ bin_dir = tmp_path / "fakebin"
+ bin_dir.mkdir()
+ sudo_log = tmp_path / "sudo.log"
+ (bin_dir / "sudo").write_text(f'#!/bin/sh\necho "$*" >> "{sudo_log}"\nexec "$@"\n', encoding="utf-8")
+ (bin_dir / "apparmor_parser").write_text(
+ f'#!/bin/sh\nfor a; do [ "$a" = "{parser_fails_on}" ] && exit 1; done\nexit 0\n', encoding="utf-8")
+ for tool in bin_dir.iterdir():
+ tool.chmod(0o755)
+ monkeypatch.setenv("PATH", f"{bin_dir}:/usr/bin:/bin")
+ profile_dir = tmp_path / "apparmor.d"
+ profile_dir.mkdir()
+ monkeypatch.setattr(main_desktop_apparmor, "_PROFILE_DIR", profile_dir)
+ return profile_dir, sudo_log
+
+
+def test_install_path_with_apparmor_glob_characters_is_refused_before_sudo(tmp_path, monkeypatch):
+ """``{x}`` breaks the profile parse and ``*``/``?``/``[`` widen it to other binaries."""
+ profile_dir, sudo_log = _fake_root_tools(tmp_path, monkeypatch)
+ exe = _packaged_app(tmp_path / "a{x}b", _ALLOWED)
+
+ assert main_desktop_apparmor.install_profile(exe) is False
+ assert not sudo_log.exists()
+ assert list(profile_dir.iterdir()) == []
+
+
[email protected]("failing_step", ["--skip-kernel-load", "-r"])
+def test_profile_that_fails_to_parse_or_load_leaves_nothing_in_the_profile_dir(tmp_path, monkeypatch, failing_step):
+ """The user-side parse check runs before any sudo write; a failed load removes the written file."""
+ profile_dir, sudo_log = _fake_root_tools(tmp_path, monkeypatch, parser_fails_on=failing_step)
+ exe = _packaged_app(tmp_path, _ALLOWED)
+
+ assert main_desktop_apparmor.install_profile(exe) is False
+ assert list(profile_dir.iterdir()) == []
+ sudo_calls = sudo_log.read_text(encoding="utf-8").splitlines() if sudo_log.exists() else []
+ # A parse failure never reaches sudo; a load failure wrote the file, then removed it again.
+ expected = ["tee", "apparmor_parser", "rm"] if failing_step == "-r" else []
+ assert [Path(call.split()[0]).name for call in sudo_calls] == expected
diff --git a/website/docs/user-guide/desktop.md b/website/docs/user-guide/desktop.md
index e96df9e7f99..6b3d7a860b7 100644
--- a/website/docs/user-guide/desktop.md
+++ b/website/docs/user-guide/desktop.md
@@ -825,7 +825,9 @@ bootstrap marker does not force installation when that launcher works.
On Linux, Chromium's own errors go to `HERMES_HOME/logs/desktop-chromium.log`, and a crash of the shell itself leaves a minidump under the app's `Crashpad/` directory (inside Electron's user-data directory, next to `connection.json`). If the window vanishes with `SIGTRAP` in the journal, the `FATAL:` line in that log names the check that fired; attach it to the bug report. Nothing is uploaded.
-On Ubuntu 23.10 and later, `kernel.apparmor_restrict_unprivileged_userns=1` blocks Chromium's user-namespace sandbox for any program without an AppArmor profile. `hermes desktop` checks this through the Hermes binary itself and then uses the setuid `chrome-sandbox` helper (a `sudo` prompt after each rebuild). To skip that prompt for good, run `hermes desktop --install-apparmor-profile` once: it installs a profile for this app under `/etc/apparmor.d/` (sudo required) that grants it user namespaces, as Ubuntu does for Chrome and VS Code. If neither route is available, Desktop starts with `--no-sandbox` and the launcher prints both commands.
+On Ubuntu 23.10 and later, `kernel.apparmor_restrict_unprivileged_userns=1` blocks Chromium's user-namespace sandbox for any program without an AppArmor profile. `hermes desktop` checks this through the Hermes binary itself and then uses Chromium's setuid `chrome-sandbox` helper (root-owned, mode 4755), which asks for `sudo` again after each rebuild. That helper is the recommended route. If the helper cannot be set up either, Desktop starts with `--no-sandbox` and the launcher prints both commands, the helper first.
+
+`hermes desktop --install-apparmor-profile` is the opt-in alternative that survives rebuilds: it installs a profile under `/etc/apparmor.d/` (sudo required) that grants user namespaces to this app's path. Chrome and VS Code get the same grant, but for root-owned binaries. This app's path is usually in a checkout your account can write, so any program running as you could put its own binary there and get the user namespaces the restriction withholds. For your account, that is about the same as turning the restriction off. The command refuses install paths containing AppArmor pattern characters (`? * [ ] { } ^ " \`, see apparmor.d(5) "Globbing"). It checks the profile with `apparmor_parser --skip-kernel-load` before writing anything, and removes the file again if loading it fails.
If Python dependencies are damaged, run the installation's `hermes pm repair`.
Then restart Desktop. Do not delete guessed `venv` paths or PM facts. For