gateway_runtime_service_identity.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. """Read-only binding checks; unknown supervisor syntax is not profile absence.
  2. These checks recognize the installed Hermes launch formats, not arbitrary shell
  3. programs. Manager-loaded values take precedence over filenames and disk copies.
  4. """
  5. from __future__ import annotations
  6. import json
  7. import os
  8. from pathlib import Path
  9. import re
  10. import shlex
  11. import stat
  12. from typing import NoReturn
  13. SYSTEMD_IDENTITY_PROPERTIES = (
  14. "User", "DynamicUser", "ExecStart", "Environment", "EnvironmentFiles",
  15. "PassEnvironment", "UnsetEnvironment", "PAMName", "RootDirectory", "RootImage",
  16. "ExecStartPre", "ExecCondition", "DropInPaths",
  17. )
  18. # `systemctl show --all` (systemd 259) prints no line at all for these when the
  19. # list is empty, so their absence carries no identity uncertainty.
  20. SYSTEMD_OMITTED_WHEN_EMPTY = ("EnvironmentFiles", "ExecStartPre", "ExecCondition")
  21. def _unverified() -> NoReturn:
  22. raise ValueError("service_identity_unverified")
  23. def _absolute(value: str) -> Path:
  24. if not value or not Path(value).is_absolute():
  25. _unverified()
  26. return Path(value).resolve()
  27. class ForeignRoot(ValueError):
  28. """The service serves another install root (a different HOME), not another profile of ours."""
  29. def _install_root(home: Path) -> Path:
  30. # <root>/.hermes or <root>/.hermes/profiles/<name>: the root is the HOME that anchors it.
  31. parts = home.parts
  32. if len(parts) >= 3 and parts[-3] == ".hermes" and parts[-2] == "profiles":
  33. return home.parents[2]
  34. return home.parent
  35. def verify_home(home: Path, configured: str) -> None:
  36. ours, theirs = home.resolve(), _absolute(configured)
  37. if os.path.normcase(str(theirs)) == os.path.normcase(str(ours)):
  38. return
  39. if os.path.normcase(str(_install_root(theirs))) != os.path.normcase(str(_install_root(ours))):
  40. raise ForeignRoot("foreign_root")
  41. raise ValueError("profile_mismatch")
  42. # ``python``, ``pythonw``, ``python3``, ``python3.12`` (``.exe`` on Windows): an interpreter launch.
  43. _PYTHON_EXECUTABLE = re.compile(r"python(?:w|\d+(?:\.\d+)*)?(?:\.exe)?")
  44. def _own_store_launcher(executable: str) -> bool:
  45. """Whether ``executable`` is the store launcher ``installation_command`` writes for THIS install
  46. root (``<root>/.hermes/bin/hermes``, root = gateway.PROJECT_ROOT), never another checkout's."""
  47. from hermes_cli import gateway
  48. launcher = Path(gateway.PROJECT_ROOT).resolve() / ".hermes" / "bin" / "hermes"
  49. return os.path.normcase(str(Path(executable).resolve())) == os.path.normcase(str(launcher))
  50. def _launch_module(argv: list[str], *, legacy: bool = True) -> tuple[str, list[str]] | None:
  51. """``(module, its argv)`` for the module launches the installer persists: ``python -m``, or
  52. ``_launchers.installation_command``'s two forms for THIS install root (gateway.PROJECT_ROOT): the
  53. store ``<root>/.hermes/bin/hermes --run-module`` launcher, or ``runtime_command``'s inline bootstrap
  54. regenerated byte for byte. A launcher or bootstrap of another checkout is not ours. None otherwise."""
  55. from hermes_cli import gateway
  56. from hermes_cli._launchers import runtime_command
  57. root = Path(gateway.PROJECT_ROOT).resolve()
  58. executable = Path(argv[0]).name.lower() if argv else ""
  59. if _PYTHON_EXECUTABLE.fullmatch(executable):
  60. # ``python -m`` is the legacy unwrapped plist form; no installer put it inside the osascript wrapper.
  61. if legacy and argv[1:2] == ["-m"] and len(argv) > 2:
  62. return argv[2], argv[3:]
  63. if argv[1:3] == ["-I", "-c"] and len(argv) > 3:
  64. module = next((name for name in ("hermes_cli.stderr_timestamp", "hermes_cli.main")
  65. if runtime_command(root, module=name, python=argv[0])[3] == argv[3]), None)
  66. return (module, argv[4:]) if module else None
  67. elif argv[1:2] == ["--run-module"] and len(argv) > 2 and _own_store_launcher(argv[0]):
  68. return argv[2], argv[3:]
  69. return None
  70. def verify_gateway_argv(argv: list[str], home: Path, *, wrapped: bool = False) -> None:
  71. """``wrapped``: a launcher wrapper (the osascript Local Network wrapper) was already stripped, so
  72. only this root's installer forms count: no legacy ``python -m``, and a ``hermes`` launcher must be
  73. ``<root>/.hermes/bin/hermes`` (``_own_store_launcher``). The stderr-timestamp wrapper holds its inner
  74. ``hermes`` to the same rule. A bare unwrapped ``hermes`` keeps verifying by name, as older
  75. systemd/schtasks/launchd definitions persisted it (binding those is a separate change)."""
  76. from gateway.status import looks_like_gateway_command_line
  77. # The installer wraps launchd stderr with this fixed, non-shell module.
  78. wrapper = _launch_module(argv, legacy=not wrapped)
  79. own_launcher_only = wrapped
  80. if wrapper is not None and wrapper[0] == "hermes_cli.stderr_timestamp":
  81. args = wrapper[1]
  82. if len(args) < 4 or args[0] != "--error-log" or args[2] != "--":
  83. _unverified()
  84. argv, own_launcher_only = args[3:], True
  85. if not argv or not looks_like_gateway_command_line(subprocess_command(argv)):
  86. _unverified()
  87. executable = Path(argv[0]).name.lower()
  88. if _PYTHON_EXECUTABLE.fullmatch(executable):
  89. entry = _launch_module(argv, legacy=not wrapped)
  90. if entry is None or entry[0] != "hermes_cli.main":
  91. _unverified()
  92. args = entry[1]
  93. elif executable in {"hermes", "hermes.exe"} and (not own_launcher_only or _own_store_launcher(argv[0])):
  94. args = argv[1:]
  95. else:
  96. _unverified()
  97. profiles = []
  98. filtered = []
  99. index = 0
  100. while index < len(args):
  101. token = args[index]
  102. if token in {"--profile", "-p"}:
  103. index += 1
  104. if index == len(args):
  105. _unverified()
  106. profiles.append(args[index])
  107. elif token.startswith("--profile="):
  108. profiles.append(token.split("=", 1)[1])
  109. else:
  110. filtered.append(token)
  111. index += 1
  112. if len(profiles) > 1:
  113. _unverified()
  114. if profiles:
  115. # An explicit selector must agree with the pinned environment. This
  116. # preserves custom-root profiles without borrowing the caller's root.
  117. from hermes_constants import profile_name_for_home
  118. expected = profile_name_for_home(home) or (home.name if home.parent.name == "profiles" else "default")
  119. if profiles[0] != expected:
  120. raise ValueError("profile_mismatch")
  121. if filtered[:2] != ["gateway", "run"] or any(
  122. arg not in {"--quiet", "--external-supervisor"} for arg in filtered[2:]
  123. ):
  124. _unverified()
  125. def subprocess_command(argv: list[str]) -> str:
  126. # The canonical matcher is quote-aware on both hosts.
  127. import subprocess
  128. return subprocess.list2cmdline(argv)
  129. def environment_pairs(value: str) -> dict[str, str]:
  130. # systemctl uses C escapes for unusual bytes. Do not silently reinterpret
  131. # those with shell escaping (not the same grammar).
  132. if "\\" in value:
  133. _unverified()
  134. result = {}
  135. for item in shlex.split(value):
  136. key, separator, val = item.partition("=")
  137. if not separator:
  138. _unverified()
  139. result[key] = val
  140. return result
  141. def verify_systemd(props: dict[str, str], manager_env: str, home: Path, *, system: bool) -> None:
  142. import pwd
  143. # systemd 259 omits empty exec-command lists and EnvironmentFiles from
  144. # `show --all` output entirely; an omitted list is empty, not unknown.
  145. props = {**{key: "" for key in SYSTEMD_OMITTED_WHEN_EMPTY}, **props}
  146. if not all(key in props for key in SYSTEMD_IDENTITY_PROPERTIES):
  147. _unverified()
  148. # These can change the execution account, environment, mount namespace, or
  149. # definitions at start time; show does not expose their resulting identity.
  150. if props["DynamicUser"] != "no" or any(props[key] for key in (
  151. "EnvironmentFiles", "PAMName", "RootDirectory", "RootImage", "ExecStartPre", "ExecCondition",
  152. )):
  153. _unverified()
  154. user = props["User"]
  155. uid = os.getuid() # windows-footgun: ok — native systemd only
  156. if user:
  157. try:
  158. service_uid = int(user) if user.isdecimal() else pwd.getpwnam(user).pw_uid
  159. except KeyError:
  160. _unverified()
  161. else:
  162. service_uid = 0 if system else uid
  163. if service_uid != uid:
  164. raise ValueError("service_account_mismatch")
  165. inherited = environment_pairs(manager_env)
  166. env = inherited if not system else {k: v for k, v in inherited.items() if k in props["PassEnvironment"].split()}
  167. env.update(environment_pairs(props["Environment"]))
  168. for item in shlex.split(props["UnsetEnvironment"]):
  169. key, sep, value = item.partition("=")
  170. if not sep or env.get(key) == value:
  171. env.pop(key, None)
  172. configured = env.get("HERMES_HOME", "").strip()
  173. if not configured:
  174. configured = str(_absolute(env.get("HOME") or pwd.getpwuid(uid).pw_dir) / ".hermes")
  175. verify_home(home, configured)
  176. match = re.fullmatch(r"\{ path=(.*?) ; argv\[\]=(.*?) ; ignore_errors=(?:yes|no) ;(?:.*?)\}", props["ExecStart"])
  177. if not match or any(char in match[2] for char in ("$", "\\", "{", "}")):
  178. _unverified()
  179. argv = shlex.split(match[2])
  180. if not argv or match[1] != argv[0]:
  181. _unverified()
  182. verify_gateway_argv(argv, home)
  183. def _verify_launchd_argv(argv: list[str], home: Path) -> None:
  184. command, wrapped = _launchd_command(argv)
  185. verify_gateway_argv(command, home, wrapped=wrapped)
  186. def _launchd_command(argv: list[str]) -> tuple[list[str], bool]:
  187. """``(command, wrapped)``: the command the launchd job runs, and whether it came out of the Local
  188. Network wrapper (gateway_launchd.launchd_program_arguments, #71206). The wrapper is accepted only when
  189. the installer regenerates it byte for byte from the inner command and the two log paths it carries,
  190. so no shell operator, substitution, extra JXA or foreign osascript rides along."""
  191. if argv[:1] != ["/usr/bin/osascript"]:
  192. return argv, False
  193. from hermes_cli.gateway_launchd import launchd_program_arguments
  194. # Recover the inputs, then let the installer rebuild the whole argv: the comparison is the check.
  195. script, opener = argv[-1], "$.system("
  196. try:
  197. shell = json.JSONDecoder().raw_decode(script, script.index(opener) + len(opener))[0]
  198. tokens = shlex.split(shell) if isinstance(shell, str) else []
  199. except ValueError:
  200. tokens = []
  201. if len(tokens) < 6 or tokens[0] != "exec" or tokens[-4] != ">>" or tokens[-2] != "2>>":
  202. _unverified()
  203. command = tokens[1:-4]
  204. if launchd_program_arguments(command, Path(tokens[-3]), Path(tokens[-1])) != argv:
  205. _unverified()
  206. return command, True
  207. def verify_launchd_loaded(output: str, home: Path, *, uid: int, username: str) -> None:
  208. # Only the job's own blocks, never inherited/default environments or a
  209. # different job embedded in launchctl diagnostic text.
  210. def block(name):
  211. found = re.findall(r"^\t" + name + r" = \{\n(.*?)^\t\}", output, re.MULTILINE | re.DOTALL)
  212. if len(found) != 1:
  213. _unverified()
  214. return found[0].splitlines()
  215. for key, expected in (("uid", str(uid)), ("username", username)):
  216. values = re.findall(r"^\t" + key + r" = (.+)$", output, re.MULTILINE)
  217. if values and values != [expected]:
  218. raise ValueError("service_account_mismatch")
  219. env = {}
  220. for line in block("environment"):
  221. if not line.strip():
  222. continue
  223. key, sep, value = line.strip().partition(" => ")
  224. if not sep or key in env:
  225. _unverified()
  226. env[key] = value
  227. verify_home(home, env.get("HERMES_HOME", ""))
  228. if home.parent.name != "profiles" and not env.get("HERMES_SUPERVISED_CHILD"):
  229. _unverified()
  230. argv = [line.strip() for line in block("arguments")]
  231. programs = re.findall(r"^\tprogram = (.+)$", output, re.MULTILINE)
  232. if len(programs) != 1 or not argv or programs[0] != argv[0]:
  233. _unverified()
  234. _verify_launchd_argv(argv, home)
  235. def verify_launchd_plist(definition: dict, label: str, home: Path) -> None:
  236. if definition.get("Label") != label:
  237. _unverified()
  238. if definition.get("Disabled"):
  239. raise ValueError("service_disabled")
  240. if definition.get("UserName") or definition.get("GroupName") or definition.get("RootDirectory"):
  241. _unverified()
  242. env = definition.get("EnvironmentVariables", {})
  243. if not isinstance(env, dict):
  244. _unverified()
  245. verify_home(home, env.get("HERMES_HOME", ""))
  246. argv = definition.get("ProgramArguments")
  247. if not isinstance(argv, list) or not all(isinstance(arg, str) for arg in argv):
  248. _unverified()
  249. if definition.get("Program", argv[0] if argv else None) != (argv[0] if argv else None):
  250. _unverified()
  251. _verify_launchd_argv(argv, home)
  252. if home.parent.name != "profiles" and not env.get("HERMES_SUPERVISED_CHILD"):
  253. _unverified()
  254. def read_definition(path: Path) -> bytes:
  255. # Nonblocking open precedes fstat: a FIFO replacement must not consume the
  256. # entire startup deadline waiting for a writer. Symlinked installs work.
  257. fd = os.open(path, os.O_RDONLY | getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_BINARY", 0))
  258. with os.fdopen(fd, "rb") as stream:
  259. info = os.fstat(stream.fileno())
  260. if not stat.S_ISREG(info.st_mode) or info.st_size > 1024 * 1024:
  261. _unverified()
  262. value = stream.read(1024 * 1024 + 1)
  263. if len(value) > 1024 * 1024:
  264. _unverified()
  265. return value
  266. def launcher_text(raw: bytes) -> str:
  267. """Current .vbs launchers are UTF-16 with a BOM (wscript.exe reads a BOM-less script in the ANSI
  268. code page); launchers written by older versions, and every other service definition, are UTF-8.
  269. Undecodable bytes raise ``ValueError``."""
  270. if raw[:2] in (b"\xff\xfe", b"\xfe\xff"):
  271. try:
  272. return raw.decode("utf-16")
  273. except UnicodeDecodeError:
  274. _unverified()
  275. try:
  276. return raw.decode("utf-8-sig")
  277. except UnicodeDecodeError:
  278. _unverified()
  279. def _vbs_identity(script: str) -> tuple[str, list[str]]:
  280. # Recognize the vendor's complete template, not a HERMES_HOME substring
  281. # inside an arbitrary executable script. Doubled quotes are VB literals.
  282. literal = r'"(?:[^"\r\n]|"")*"'
  283. lines = script.splitlines()
  284. if len(lines) < 16 or not lines[0].startswith("' "):
  285. _unverified()
  286. fixed = ["Option Explicit", "Dim sh, env, existing_pp",
  287. 'Set sh = CreateObject("WScript.Shell")', 'Set env = sh.Environment("PROCESS")']
  288. if lines[1:5] != fixed:
  289. _unverified()
  290. env = {}
  291. index = 5
  292. while index < len(lines):
  293. match = re.fullmatch(r'env.Item\("([A-Z_]+)"\) = (' + literal + ')', lines[index])
  294. if not match:
  295. break
  296. if match[1] not in {"HERMES_HOME", "HERMES_SUPERVISED_CHILD", "HERMES_GATEWAY_DETACHED", "PYTHONIOENCODING", "VIRTUAL_ENV"} or match[1] in env:
  297. _unverified()
  298. env[match[1]] = match[2][1:-1].replace('""', '"')
  299. index += 1
  300. tail = lines[index:]
  301. if len(tail) != 8 or tail[:2] != ['existing_pp = env.Item("PYTHONPATH")', 'If Len(existing_pp) > 0 Then'] or tail[3] != 'Else' or tail[5] != 'End If':
  302. _unverified()
  303. if not re.fullmatch(r' env.Item\("PYTHONPATH"\) = ' + literal + r' & existing_pp', tail[2]) or not re.fullmatch(r' env.Item\("PYTHONPATH"\) = ' + literal, tail[4]):
  304. _unverified()
  305. if not re.fullmatch(r'sh.CurrentDirectory = ' + literal, tail[6]):
  306. _unverified()
  307. run = re.fullmatch(r'sh.Run (' + literal + r'), 0, False', tail[7])
  308. if not run or not env.get("HERMES_SUPERVISED_CHILD"):
  309. _unverified()
  310. command = run[1][1:-1].replace('""', '"')
  311. if "%" in command or "%" in env.get("HERMES_HOME", ""):
  312. _unverified()
  313. # The template uses list2cmdline, with no embedded executable quote escapes.
  314. argv = [part.strip('"') for part in shlex.split(command, posix=False)]
  315. return env.get("HERMES_HOME", ""), argv
  316. def verify_windows_task(xml: str | bytes, home: Path, account: str, sid: str) -> None:
  317. import xml.etree.ElementTree as ET
  318. try:
  319. task = ET.fromstring(xml)
  320. except ET.ParseError:
  321. _unverified()
  322. ns = {"t": "http://schemas.microsoft.com/windows/2004/02/mit/task"}
  323. principals = task.findall("t:Principals/t:Principal", ns)
  324. actions = task.find("t:Actions", ns)
  325. if len(principals) != 1 or actions is None or len(actions) != 1:
  326. _unverified()
  327. principal = principals[0]
  328. user = principal.findtext("t:UserId", "", ns)
  329. if not user or not account or not sid or principal.find("t:GroupId", ns) is not None:
  330. _unverified()
  331. if user.casefold() not in {account.casefold(), sid.casefold()}:
  332. raise ValueError("service_account_mismatch")
  333. # schtasks /Query /XML omits elements that hold the Windows default (#139013): an absent RunLevel
  334. # is least privilege and an absent Enabled is enabled. An explicit other value is still refused.
  335. if principal.findtext("t:RunLevel", "LeastPrivilege", ns) != "LeastPrivilege" or actions.get("Context") != principal.get("id"):
  336. _unverified()
  337. if task.findtext("t:Settings/t:Enabled", "true", ns) != "true":
  338. raise ValueError("service_disabled")
  339. action = actions[0]
  340. if action.tag != '{' + ns['t'] + '}Exec' or action.findtext('t:Command', '', ns).lower() not in {"wscript.exe", r"c:\windows\system32\wscript.exe"}:
  341. _unverified()
  342. args = action.findtext("t:Arguments", "", ns)
  343. match = re.fullmatch(r'//B //Nologo "([^"\r\n]+)"', args)
  344. if not match:
  345. _unverified()
  346. script = _absolute(match[1])
  347. if script.suffix.lower() != '.vbs':
  348. _unverified()
  349. configured, argv = _vbs_identity(launcher_text(read_definition(script)))
  350. verify_home(home, configured)
  351. verify_gateway_argv(argv, home)