gateway_runtime_discovery.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. """Bounded local-control discovery without diagnostic fallback or mutation (the one exception: an
  2. upgraded same-owner ``gateway.lock`` is narrowed to 0600, see :func:`_private_lock`)."""
  3. from __future__ import annotations
  4. import errno
  5. import json
  6. import os
  7. from pathlib import Path
  8. import shlex
  9. import socket
  10. import stat
  11. import sys
  12. from typing import Literal
  13. import time
  14. class DiscoveryError(ValueError):
  15. def __init__(self, reason: str, detail: str | None = None, fix: str | None = None):
  16. # The stable code callers match on stays in ``reason``; ``detail`` is what the user reads,
  17. # ending in the shell command that repairs the node (``fix``) when there is one.
  18. self.reason, self.cause, self.fix = reason, detail, fix
  19. self.detail = f"{detail}; {fix}" if detail and fix else detail
  20. super().__init__(f"{reason}: {self.detail}" if self.detail else reason)
  21. def bounded_detail(self, limit: int) -> str | None:
  22. """``detail`` within ``limit`` characters, never with a cut-off command: a repair command
  23. that does not fit is dropped with a notice, and an overlong description is cut visibly."""
  24. if self.detail is None or len(self.detail) <= limit:
  25. return self.detail
  26. notice = "; repair command omitted (path too long to print)" if self.fix else ""
  27. room, marker, cause = limit - len(notice), "… [truncated]", self.cause or ""
  28. cause = cause if len(cause) <= room else cause[:room - len(marker)] + marker
  29. return cause + notice
  30. def _may_have_access_acl(path: Path) -> bool:
  31. """A Linux POSIX access ACL is present, or its absence cannot be established. Python has no
  32. os.listxattr on macOS (whose chmod +a ACLs are separate); mode bits stay the policy there."""
  33. if not hasattr(os, "listxattr"):
  34. return False
  35. try:
  36. return "system.posix_acl_access" in os.listxattr(path, follow_symlinks=False)
  37. except OSError as exc:
  38. if exc.errno in {errno.ENOTSUP, errno.EOPNOTSUPP}:
  39. return False # filesystem without xattrs cannot carry an ACL
  40. return True
  41. def home_mode_unsafe(node: os.stat_result, path: Path) -> bool:
  42. """The profile home keeps the operator's mode (main's home policy: symlinked homes,
  43. HERMES_HOME_MODE 0701/0750). Only write by another user lets them swap the socket; read/search
  44. bits grant nothing against our 0600 socket, and group-write is harmless when the group is the
  45. owner's private group (the umask-002 user-private-group default). What we create stays 0700."""
  46. mode = stat.S_IMODE(node.st_mode)
  47. if mode & 0o002:
  48. return True
  49. if not mode & 0o020:
  50. return False
  51. # With an access ACL the group bits are the mask: a named user (setfacl u:other:rwx) may
  52. # hold write even though the owning group is private.
  53. if _may_have_access_acl(path):
  54. return True
  55. # ``gr_mem`` never lists accounts whose PRIMARY gid is the group, so privacy also needs the
  56. # passwd scan; membership we cannot establish is treated as shared.
  57. try:
  58. import grp
  59. import pwd
  60. user, group = pwd.getpwuid(node.st_uid), grp.getgrgid(node.st_gid)
  61. primary_members = {p.pw_uid for p in pwd.getpwall() if p.pw_gid == group.gr_gid}
  62. except (ImportError, KeyError, OSError):
  63. return True
  64. return not (group.gr_gid == user.pw_gid and group.gr_name == user.pw_name
  65. and set(group.gr_mem) <= {user.pw_name} and primary_members <= {node.st_uid})
  66. def _private_node(path: Path, *, kind: str, home: bool = False) -> os.stat_result:
  67. node = path.lstat()
  68. predicates = {"socket": stat.S_ISSOCK, "file": stat.S_ISREG, "directory": stat.S_ISDIR}
  69. if not predicates[kind](node.st_mode):
  70. raise DiscoveryError(
  71. "unsafe_control_path",
  72. f"{path} is {stat.filemode(node.st_mode)}, expected {kind}",
  73. )
  74. expected_uid = os.getuid() # windows-footgun: ok — POSIX socket path only
  75. if node.st_uid != expected_uid: # windows-footgun: ok — POSIX socket path only
  76. raise DiscoveryError(
  77. "unsafe_control_path",
  78. f"{path} is owned by uid {node.st_uid}, expected uid {expected_uid} (gateway user); "
  79. "chown it to the gateway user",
  80. )
  81. mode = stat.S_IMODE(node.st_mode)
  82. if home and home_mode_unsafe(node, path):
  83. raise DiscoveryError("unsafe_control_permissions", f"{path} has mode {mode:04o}, writable by another user",
  84. f"chmod go-w {shlex.quote(str(path))}")
  85. if not home and mode & 0o077:
  86. raise _open_mode(path, mode, 0o700 if kind == "directory" else 0o600)
  87. return node
  88. def _open_mode(path: Path, mode: int, expected: int) -> DiscoveryError:
  89. return DiscoveryError("unsafe_control_permissions", f"{path} has mode {mode:04o}, expected {expected:04o}",
  90. f"chmod {expected:o} {shlex.quote(str(path))}")
  91. def socket_peer_uid(sock: socket.socket) -> int | None:
  92. """Kernel-reported uid of the process on the other end of a connected AF_UNIX socket
  93. (SO_PEERCRED on Linux, getpeereid on macOS); None where neither exists."""
  94. if hasattr(socket, "SO_PEERCRED"):
  95. import struct
  96. return struct.unpack("3i", sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))[1]
  97. if sys.platform != "darwin":
  98. return None
  99. import ctypes
  100. uid, gid = ctypes.c_uint(), ctypes.c_uint()
  101. getpeereid = ctypes.CDLL(None, use_errno=True).getpeereid
  102. getpeereid.argtypes = [ctypes.c_int, ctypes.POINTER(ctypes.c_uint), ctypes.POINTER(ctypes.c_uint)]
  103. getpeereid.restype = ctypes.c_int
  104. if getpeereid(sock.fileno(), ctypes.byref(uid), ctypes.byref(gid)) != 0:
  105. raise OSError(ctypes.get_errno(), "getpeereid failed")
  106. return uid.value
  107. def connect_private(home: Path, timeout: float) -> socket.socket:
  108. """Connected control socket for *home* whose listener runs as this user (caller closes it).
  109. The path is validated by lstat first, but connect() follows a symlink swapped in afterwards,
  110. so the listening process itself is authenticated. Platforms without a peer-credential API
  111. (neither SO_PEERCRED nor getpeereid) fall back to the path checks alone."""
  112. path = _socket_path(home)
  113. peer = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
  114. try:
  115. peer.settimeout(timeout)
  116. peer.connect(str(path))
  117. uid = socket_peer_uid(peer)
  118. if uid is not None and uid != os.getuid(): # windows-footgun: ok — POSIX socket peer only
  119. raise DiscoveryError("unsafe_control_peer")
  120. return peer
  121. except BaseException:
  122. peer.close()
  123. raise
  124. def _socket_path(home: Path) -> Path:
  125. _private_node(home, kind="directory", home=True)
  126. direct = home / "gateway.sock"
  127. if os.path.lexists(direct):
  128. _private_node(direct, kind="socket")
  129. return direct
  130. pointer = home / "gateway.sock.path"
  131. # Reject non-regular metadata before a FIFO can wait for a writer.
  132. flags = os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK # windows-footgun: ok — POSIX socket discovery only
  133. with os.fdopen(os.open(pointer, flags), "rb") as stream: # windows-footgun: ok — binary POSIX descriptor
  134. metadata = os.fstat(stream.fileno())
  135. if (not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != os.getuid() # windows-footgun: ok — POSIX pointer only
  136. or stat.S_IMODE(metadata.st_mode) & 0o077):
  137. raise DiscoveryError("unsafe_control_pointer")
  138. data = stream.read(4097)
  139. if len(data) > 4096:
  140. raise DiscoveryError("invalid_control_pointer")
  141. target = Path(data.decode("utf-8").strip())
  142. if not target.is_absolute():
  143. raise DiscoveryError("invalid_control_pointer")
  144. from gateway.control_socket import _home_hash
  145. # The owner may have a different TMPDIR (notably launchd/native apps).
  146. # Authenticate its private pointer and profile-specific directory, not our
  147. # process-local temporary-root preference.
  148. if target.name != "control.sock" or target.parent.name != f"hermes-gw-{_home_hash(home)}":
  149. raise DiscoveryError("invalid_control_pointer")
  150. _private_node(target.parent, kind="directory")
  151. _private_node(target, kind="socket")
  152. return target
  153. def query_identify(home: Path, *, timeout: float) -> dict:
  154. """Unlike diagnostic queries, retain timeout/access/protocol failures."""
  155. if os.name == "nt":
  156. from gateway.runtime_bootstrap_windows import query_runtime_control
  157. return _identify_response(query_runtime_control(
  158. home, b'{"protocol":1,"verb":"identify","id":1}\n', timeout))
  159. deadline = time.monotonic() + timeout
  160. request = b'{"protocol":1,"verb":"identify","id":1}\n'
  161. with connect_private(home, timeout) as client:
  162. budget = deadline - time.monotonic()
  163. if budget <= 0:
  164. raise TimeoutError
  165. client.settimeout(budget)
  166. client.sendall(request)
  167. data = bytearray()
  168. while b"\n" not in data:
  169. remaining = deadline - time.monotonic()
  170. if remaining <= 0:
  171. raise TimeoutError
  172. client.settimeout(remaining)
  173. chunk = client.recv(min(65536, 524289 - len(data)))
  174. if not chunk:
  175. raise DiscoveryError("incomplete_control_response")
  176. data.extend(chunk)
  177. if len(data) > 524288:
  178. raise DiscoveryError("oversized_control_response")
  179. return _identify_response(bytes(data))
  180. def _identify_response(data: bytes) -> dict:
  181. response = json.loads(data.split(b"\n", 1)[0])
  182. if (not isinstance(response, dict) or response.get("ok") is not True
  183. or response.get("protocol") != 1 or response.get("id") != 1
  184. or not isinstance(response.get("result"), dict)):
  185. raise DiscoveryError("invalid_control_response")
  186. return response["result"]
  187. def _private_lock(lock: Path) -> None:
  188. """Validate ``gateway.lock``; narrow an upgraded same-owner lock to 0600 first.
  189. Main created the inode with ``open(path, "a+")`` under the umask (0644), and lock inodes are
  190. never replaced, so without this an upgraded home reads ``inaccessible`` forever and nothing
  191. auto-starts its owner. Only the mode is touched, only on a regular single-link inode this user
  192. owns, through a NOFOLLOW descriptor; a foreign or non-regular node still raises."""
  193. try:
  194. _private_node(lock, kind="file")
  195. except DiscoveryError as exc:
  196. if exc.reason != "unsafe_control_permissions":
  197. raise
  198. from gateway.runtime_ownership import tighten_lock_mode
  199. fd = os.open(lock, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK) # windows-footgun: ok — POSIX lock only
  200. try:
  201. tighten_lock_mode(fd)
  202. finally:
  203. os.close(fd)
  204. _private_node(lock, kind="file")
  205. def missing_owner_state(home: Path) -> Literal["starting", "absent", "inaccessible"]:
  206. """A reservation before PID/control publication already excludes a new owner."""
  207. from gateway.status import _is_gateway_runtime_lock_active_strict
  208. lock = home / "gateway.lock"
  209. try:
  210. if os.name != "nt":
  211. _private_lock(lock)
  212. return "starting" if _is_gateway_runtime_lock_active_strict(lock) else "absent"
  213. except FileNotFoundError:
  214. return "absent"
  215. except (OSError, RuntimeError, DiscoveryError):
  216. return "inaccessible"