main_desktop_apparmor.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  1. """Chromium's Linux sandbox under AppArmor's unprivileged-userns restriction (#130177).
  2. With ``kernel.apparmor_restrict_unprivileged_userns=1`` (Ubuntu 23.10+), any unconfined program
  3. may still create a user namespace, but it loses every capability inside it unless an AppArmor
  4. profile attached to that program's path grants ``userns``. ``unshare --user true`` therefore
  5. succeeds while Chromium, which needs those capabilities, aborts with ``No usable sandbox!``.
  6. Only the Hermes binary itself, under whatever profile attaches to its path, can answer whether
  7. its namespace sandbox starts, so on a restricted host the launcher asks that binary.
  8. """
  9. from __future__ import annotations
  10. import hashlib
  11. import mmap
  12. import os
  13. import shlex
  14. import subprocess
  15. import sys
  16. import tempfile
  17. from pathlib import Path
  18. from typing import Optional
  19. RESTRICT_SYSCTL = Path("/proc/sys/kernel/apparmor_restrict_unprivileged_userns")
  20. # Answered by apps/desktop/electron/entry.ts before any window, lock or backend exists.
  21. SANDBOX_PROBE_SWITCH = "--hermes-sandbox-probe"
  22. _PROBE_TIMEOUT_S = 15
  23. _SUDO_TIMEOUT_S = 300 # room for a typed password, never an unbounded hang
  24. _PROFILE_DIR = Path("/etc/apparmor.d")
  25. # apparmor.d(5) "Globbing (AARE)": ``?*[]{}^`` stay glob syntax inside a quoted attachment path, so
  26. # they would widen the grant to other binaries or fail the parse; ``{`` also opens ``@{var}``
  27. # expansion, and ``"``/``\`` end or escape the quoted string. Such paths are refused, not escaped.
  28. _AARE_UNSAFE = frozenset('?*[]{}^"\\')
  29. def apparmor_restricts_userns() -> bool:
  30. try:
  31. return RESTRICT_SYSCTL.read_text(encoding="utf-8-sig").strip() == "1"
  32. except OSError:
  33. return False
  34. def _build_answers_probe(packaged_executable: Path) -> bool:
  35. """True when this packaged build's entry point honours the probe switch.
  36. A build from before the switch would start the whole app instead of exiting, so the probe is
  37. only sent to a build whose main bundle carries the switch literal. electron-builder unpacks
  38. ``dist/`` beside the asar; a fully packed asar holds the bundle verbatim.
  39. """
  40. resources = packaged_executable.parent / "resources"
  41. needle = SANDBOX_PROBE_SWITCH.encode()
  42. for bundle in (resources / "app.asar.unpacked" / "dist" / "electron-main.mjs", resources / "app.asar"):
  43. try:
  44. with bundle.open("rb") as handle, mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ) as data:
  45. if data.find(needle) != -1:
  46. return True
  47. except (OSError, ValueError):
  48. continue
  49. return False
  50. def chromium_userns_sandbox_verdict(packaged_executable: Path) -> Optional[bool]:
  51. """Whether Chromium's namespace sandbox starts for *packaged_executable* on this host.
  52. ``None`` when the host has no AppArmor userns restriction or the build cannot answer the
  53. probe; the caller then keeps its generic probe. Chromium creates its sandboxed zygote before
  54. any app JavaScript runs, so a probe that reaches the entry point exits 0 and a blocked one
  55. dies with ``No usable sandbox!``. A probe that hangs or cannot start counts as blocked.
  56. """
  57. if sys.platform != "linux" or not apparmor_restricts_userns():
  58. return None
  59. if not _build_answers_probe(packaged_executable):
  60. return None
  61. env = {key: value for key, value in os.environ.items() if key != "ELECTRON_RUN_AS_NODE"}
  62. try:
  63. completed = subprocess.run(
  64. [str(packaged_executable), "--disable-setuid-sandbox", SANDBOX_PROBE_SWITCH],
  65. cwd=packaged_executable.parent, env=env, stdin=subprocess.DEVNULL,
  66. stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
  67. timeout=_PROBE_TIMEOUT_S, check=False)
  68. except (OSError, subprocess.TimeoutExpired):
  69. return False
  70. return completed.returncode == 0
  71. def profile_name(packaged_executable: Path) -> str:
  72. """One profile per install path, so two checkouts never overwrite each other's grant."""
  73. digest = hashlib.sha256(str(packaged_executable.resolve()).encode()).hexdigest()[:10]
  74. return f"hermes-desktop-{digest}"
  75. def profile_text(packaged_executable: Path) -> str:
  76. """The profile Chrome and VS Code ship for this case: unconfined, plus the ``userns`` grant."""
  77. name = profile_name(packaged_executable)
  78. exe = str(packaged_executable.resolve())
  79. return (
  80. "# Hermes Desktop: let Chromium's user-namespace sandbox start under\n"
  81. "# kernel.apparmor_restrict_unprivileged_userns=1 (written by `hermes desktop --install-apparmor-profile`).\n"
  82. "abi <abi/4.0>,\n"
  83. "include <tunables/global>\n\n"
  84. f'profile {name} "{exe}" flags=(unconfined) {{\n'
  85. " userns,\n\n"
  86. f" include if exists <local/{name}>\n"
  87. "}\n"
  88. )
  89. def profile_path(packaged_executable: Path) -> Path:
  90. return _PROFILE_DIR / profile_name(packaged_executable)
  91. def unsafe_path_characters(packaged_executable: Path) -> str:
  92. """The characters of the install path an AppArmor attachment cannot carry literally."""
  93. path = str(packaged_executable.resolve())
  94. return "".join(sorted({ch for ch in path if ch in _AARE_UNSAFE or not ch.isprintable()}))
  95. def _user_can_replace(packaged_executable: Path) -> bool:
  96. exe = packaged_executable.resolve()
  97. return os.access(exe, os.W_OK) or any(os.access(parent, os.W_OK) for parent in exe.parents)
  98. def _run(command: list[str], stdin_text: Optional[str] = None) -> Optional[subprocess.CompletedProcess]:
  99. """Run one install step; ``None`` (after printing why) when it could not start or timed out."""
  100. try:
  101. return subprocess.run(
  102. command, input=stdin_text, text=True, encoding="utf-8", errors="replace",
  103. check=False, timeout=_SUDO_TIMEOUT_S,
  104. stdout=subprocess.DEVNULL if stdin_text is not None else None)
  105. except (OSError, subprocess.TimeoutExpired) as exc:
  106. print(f"✗ {' '.join(command)} failed: {exc}")
  107. return None
  108. def _profile_parses(parser: str, text: str) -> bool:
  109. """Compile *text* as this user without loading it, so a bad profile never reaches /etc."""
  110. from hermes_constants import get_scratch_dir
  111. with tempfile.TemporaryDirectory(dir=get_scratch_dir(), prefix="apparmor-") as scratch:
  112. candidate = Path(scratch) / "hermes-desktop.profile"
  113. candidate.write_text(text, encoding="utf-8")
  114. completed = _run([parser, "--skip-kernel-load", "--skip-cache", str(candidate)])
  115. if completed is None:
  116. print("✗ Could not check the generated profile; nothing was written to /etc/apparmor.d.")
  117. return False
  118. if completed.returncode != 0:
  119. print("✗ apparmor_parser rejected the generated profile; nothing was written to /etc/apparmor.d.")
  120. return False
  121. return True
  122. def _write_and_load(sudo: str, parser: str, target: Path, text: str) -> bool:
  123. """Stage the profile beside ``target``, load it, and only then rename it into place, so a
  124. failed write or load leaves an already-installed profile intact. The stage is a dotfile,
  125. which apparmor_parser skips when it loads the directory at boot."""
  126. staged = target.with_name(f".{target.name}.hermes-new")
  127. failure = ""
  128. written = _run([sudo, "tee", str(staged)], text)
  129. if written is None or written.returncode != 0:
  130. failure = f"✗ Could not write {target}."
  131. else:
  132. loaded = _run([sudo, parser, "-r", str(staged)])
  133. if loaded is None or loaded.returncode != 0:
  134. failure = f"✗ apparmor_parser could not load the profile for {target}."
  135. else:
  136. moved = _run([sudo, "mv", "-f", str(staged), str(target)])
  137. if moved is not None and moved.returncode == 0:
  138. return True
  139. failure = f"✗ The profile is loaded until reboot, but moving it to {target} failed."
  140. removed = _run([sudo, "rm", "-f", str(staged)])
  141. print(failure + (" Any profile already there is unchanged."
  142. if removed is not None and removed.returncode == 0 else f" Remove {staged} with sudo rm."))
  143. return False
  144. def install_profile(packaged_executable: Path) -> bool:
  145. """Write and load the profile through sudo (prompting on a terminal). Prints the outcome."""
  146. if sys.platform != "linux":
  147. print("✗ --install-apparmor-profile is Linux only: AppArmor profiles do not exist on this OS.")
  148. return False
  149. target = profile_path(packaged_executable)
  150. unsafe = unsafe_path_characters(packaged_executable)
  151. if unsafe:
  152. print(f"✗ The install path {packaged_executable.resolve()} contains {unsafe!r}, which AppArmor reads as")
  153. print(" pattern syntax (apparmor.d(5), Globbing), so a profile could not name this binary alone.")
  154. print(" Move the checkout to a path without these characters, or use the setuid chrome-sandbox helper.")
  155. return False
  156. from hermes_platform.resolver import locate_command
  157. sudo = next(iter(locate_command("sudo").command), None)
  158. parser = next(iter(locate_command("apparmor_parser", known_dirs=("/usr/sbin", "/sbin")).command),
  159. "apparmor_parser")
  160. text = profile_text(packaged_executable)
  161. if _user_can_replace(packaged_executable):
  162. print("⚠ This profile lets whatever program sits at this path, which your account can replace, use user"
  163. " namespaces, so any code running as you gains what the restriction withholds; the setuid"
  164. " chrome-sandbox helper avoids that.")
  165. if not sudo:
  166. print("✗ Installing the AppArmor profile needs sudo, which was not found.")
  167. print(f" As root, write {target} with:\n\n{text}")
  168. print(f" then load it: apparmor_parser -r {target}")
  169. return False
  170. if not _profile_parses(parser, text):
  171. return False
  172. print(f"→ Installing AppArmor profile {target} (sudo required)...")
  173. if not _write_and_load(sudo, parser, target, text):
  174. return False
  175. verdict = chromium_userns_sandbox_verdict(packaged_executable)
  176. if verdict is False:
  177. print("✗ The profile is loaded, but Chromium's sandbox still cannot start for this binary.")
  178. return False
  179. print(f"✓ AppArmor profile installed; Hermes Desktop can use Chromium's user-namespace sandbox ({target}).")
  180. return True
  181. def print_no_sandbox_fallback(packaged_executable: Path) -> None:
  182. """Why the launch falls back to ``--no-sandbox``; the AppArmor fix-it lines only on a host whose
  183. userns restriction is the reason (``ELECTRON_DISABLE_SANDBOX=1`` alone is the user's choice)."""
  184. if not apparmor_restricts_userns():
  185. print("⚠ Falling back to --no-sandbox because ELECTRON_DISABLE_SANDBOX=1 is set and the Electron"
  186. " sandbox helper could not be configured.")
  187. return
  188. print("⚠ Falling back to --no-sandbox because this Linux host restricts unprivileged user namespaces"
  189. " and the Electron sandbox helper could not be configured.")
  190. helper = shlex.quote(str(packaged_executable.parent / "chrome-sandbox"))
  191. print(" Ubuntu's AppArmor policy (kernel.apparmor_restrict_unprivileged_userns=1) blocks Chromium's")
  192. print(" user-namespace sandbox for Hermes Desktop. To keep the sandbox on, run ONE of these:")
  193. print(f" sudo chown root:root {helper} && sudo chmod 4755 {helper}")
  194. print(" Chromium's setuid sandbox helper (recommended; redo after each rebuild)")
  195. print(" hermes desktop --install-apparmor-profile")
  196. print(" AppArmor profile for this path (survives rebuilds; any program running as you can use it)")