runtime_bootstrap_windows.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. """Native local-only bootstrap pipes with cancellable overlapped I/O.
  2. The pipe worker threads do not own session state. Handlers marshal authority
  3. operations to the gateway loop; the ticket store itself is thread-safe.
  4. """
  5. from __future__ import annotations
  6. import ctypes
  7. from ctypes import wintypes
  8. import logging
  9. import os
  10. from pathlib import Path
  11. import threading
  12. import time
  13. logger = logging.getLogger(__name__)
  14. def _native():
  15. if os.name != 'nt':
  16. raise OSError('native Windows bootstrap requires Windows')
  17. import _winapi
  18. return _winapi
  19. def _api(dll, name, result, args):
  20. fn = getattr(dll, name)
  21. fn.restype, fn.argtypes = result, args
  22. return fn
  23. def _token_sid(token) -> str:
  24. """String SID of a token's user (``TokenUser``)."""
  25. a = ctypes.WinDLL('advapi32', use_last_error=True)
  26. length = wintypes.DWORD()
  27. token_info = _api(a, 'GetTokenInformation', wintypes.BOOL,
  28. [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)])
  29. token_info(token, 1, None, 0, ctypes.byref(length))
  30. buf = ctypes.create_string_buffer(length.value)
  31. if not token_info(token, 1, buf, length, ctypes.byref(length)):
  32. raise PermissionError('cannot read bootstrap peer identity')
  33. return _sid_text(ctypes.cast(buf, ctypes.POINTER(ctypes.c_void_p))[0])
  34. def _sid_text(sid) -> str:
  35. """String form (``S-1-...``) of the SID at *sid*."""
  36. k = ctypes.WinDLL('kernel32', use_last_error=True)
  37. a = ctypes.WinDLL('advapi32', use_last_error=True)
  38. text = wintypes.LPWSTR()
  39. convert = _api(a, 'ConvertSidToStringSidW', wintypes.BOOL,
  40. [ctypes.c_void_p, ctypes.POINTER(wintypes.LPWSTR)])
  41. if not convert(sid, ctypes.byref(text)):
  42. raise PermissionError('cannot encode bootstrap peer identity')
  43. try:
  44. return text.value
  45. finally:
  46. _api(k, 'LocalFree', ctypes.c_void_p, [ctypes.c_void_p])(ctypes.cast(text, ctypes.c_void_p))
  47. def _process_sid(pid: int) -> str:
  48. k = ctypes.WinDLL('kernel32', use_last_error=True)
  49. a = ctypes.WinDLL('advapi32', use_last_error=True)
  50. open_process = _api(k, 'OpenProcess', wintypes.HANDLE, [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD])
  51. close = _api(k, 'CloseHandle', wintypes.BOOL, [wintypes.HANDLE])
  52. process = open_process(0x1000, False, pid)
  53. if not process:
  54. raise PermissionError('cannot verify bootstrap peer process')
  55. token = wintypes.HANDLE()
  56. try:
  57. open_token = _api(a, 'OpenProcessToken', wintypes.BOOL,
  58. [wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)])
  59. if not open_token(process, 8, ctypes.byref(token)):
  60. raise PermissionError('cannot verify bootstrap peer token')
  61. return _token_sid(token)
  62. finally:
  63. if token:
  64. close(token)
  65. close(process)
  66. class _AclHeader(ctypes.Structure):
  67. _fields_ = [('revision', ctypes.c_ubyte), ('sbz1', ctypes.c_ubyte), ('size', wintypes.WORD),
  68. ('count', wintypes.WORD), ('sbz2', wintypes.WORD)]
  69. def _pipe_security(handle) -> tuple[str, tuple[tuple[int, str], ...]]:
  70. """The pipe object's owner SID and its DACL as ``(ace_type, sid)`` pairs, read from *handle*
  71. (``GetSecurityInfo``; the client's GENERIC_READ carries READ_CONTROL). Unlike ``OpenProcess`` on
  72. the server's PID this needs no access to the server process, so it still answers when the
  73. server is elevated and this client is not (#140706)."""
  74. k = ctypes.WinDLL('kernel32', use_last_error=True)
  75. a = ctypes.WinDLL('advapi32', use_last_error=True)
  76. get_info = _api(a, 'GetSecurityInfo', wintypes.DWORD,
  77. [wintypes.HANDLE, ctypes.c_int, wintypes.DWORD] + [ctypes.POINTER(ctypes.c_void_p)] * 5)
  78. get_ace = _api(a, 'GetAce', wintypes.BOOL, [ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(ctypes.c_void_p)])
  79. owner, dacl, descriptor = ctypes.c_void_p(), ctypes.c_void_p(), ctypes.c_void_p()
  80. # SE_KERNEL_OBJECT; OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION
  81. if get_info(handle, 6, 0x1 | 0x4, ctypes.byref(owner), None, ctypes.byref(dacl), None,
  82. ctypes.byref(descriptor)):
  83. raise PermissionError('cannot read named-pipe owner')
  84. try:
  85. if not owner: # inside the try: the descriptor is freed on this refusal too
  86. raise PermissionError('cannot read named-pipe owner')
  87. aces = []
  88. # A NULL DACL (no entries to read) grants everyone: it is reported as no ACEs at all.
  89. for index in range(_AclHeader.from_address(dacl.value).count if dacl else 0):
  90. ace = ctypes.c_void_p()
  91. if not get_ace(dacl, index, ctypes.byref(ace)):
  92. raise PermissionError('cannot read named-pipe DACL')
  93. kind = ctypes.c_ubyte.from_address(ace.value).value
  94. # ACCESS_ALLOWED_ACE / ACCESS_DENIED_ACE: 4-byte ACE_HEADER, 4-byte mask, then the SID.
  95. aces.append((kind, _sid_text(ace.value + 8) if kind in (0, 1) else ''))
  96. return _sid_text(owner.value), tuple(aces)
  97. finally:
  98. _api(k, 'LocalFree', ctypes.c_void_p, [ctypes.c_void_p])(descriptor)
  99. def _pipe_server_session(handle) -> int | None:
  100. """The pipe server's logon session, from the pipe (no access to the server process needed)."""
  101. k = ctypes.WinDLL('kernel32', use_last_error=True)
  102. session = wintypes.ULONG()
  103. get = _api(k, 'GetNamedPipeServerSessionId', wintypes.BOOL, [wintypes.HANDLE, ctypes.POINTER(wintypes.ULONG)])
  104. return session.value if get(handle, ctypes.byref(session)) else None
  105. class _ImpersonationLeak(RuntimeError):
  106. """RevertToSelf failed: this thread may still carry the client's identity. Deliberately not an
  107. OSError, so the serving loop does not swallow it and the worker stops instead."""
  108. def _pipe_client_sid(handle) -> str:
  109. """The client's SID from the identification token the kernel captured when it opened the pipe
  110. (the client dials with ``SECURITY_SQOS_PRESENT``). Unlike ``OpenProcess`` on the client's PID,
  111. this still answers after a short-lived client (a one-shot ``gateway ensure``) has exited.
  112. Windows only allows it once data has been read from the pipe."""
  113. k = ctypes.WinDLL('kernel32', use_last_error=True)
  114. a = ctypes.WinDLL('advapi32', use_last_error=True)
  115. impersonate = _api(a, 'ImpersonateNamedPipeClient', wintypes.BOOL, [wintypes.HANDLE])
  116. revert = _api(a, 'RevertToSelf', wintypes.BOOL, [])
  117. open_thread_token = _api(a, 'OpenThreadToken', wintypes.BOOL,
  118. [wintypes.HANDLE, wintypes.DWORD, wintypes.BOOL, ctypes.POINTER(wintypes.HANDLE)])
  119. current_thread = _api(k, 'GetCurrentThread', wintypes.HANDLE, [])
  120. close = _api(k, 'CloseHandle', wintypes.BOOL, [wintypes.HANDLE])
  121. if not impersonate(handle):
  122. raise PermissionError('cannot impersonate named-pipe peer')
  123. token = wintypes.HANDLE()
  124. try:
  125. try:
  126. # OpenAsSelf: the access check runs against the gateway's own token, not the client's.
  127. if not open_thread_token(current_thread(), 8, True, ctypes.byref(token)):
  128. raise PermissionError('cannot read named-pipe peer token')
  129. finally:
  130. if not revert():
  131. raise _ImpersonationLeak('RevertToSelf failed after reading a named-pipe peer')
  132. return _token_sid(token)
  133. finally:
  134. if token:
  135. close(token)
  136. def _peer_subject(handle, *, server: bool) -> str:
  137. """``sid:<owner>`` for a same-user peer; PermissionError for another user or an unidentified one.
  138. The serving side (``server=False``) reads the identity from the pipe's client token first and
  139. falls back to the client's process; an unreadable peer is refused, never served as anonymous.
  140. The client side (``server=True``) is judged by :func:`judge_pipe_server`."""
  141. sid = None
  142. if not server:
  143. try:
  144. sid = _pipe_client_sid(handle)
  145. except PermissionError:
  146. sid = None
  147. if sid is None:
  148. k = ctypes.WinDLL('kernel32', use_last_error=True)
  149. name = 'GetNamedPipeServerProcessId' if server else 'GetNamedPipeClientProcessId'
  150. get_pid = _api(k, name, wintypes.BOOL, [wintypes.HANDLE, ctypes.POINTER(wintypes.ULONG)])
  151. pid = wintypes.ULONG()
  152. if not get_pid(handle, ctypes.byref(pid)):
  153. raise PermissionError('cannot identify named-pipe peer')
  154. if server:
  155. return _server_subject(handle, pid.value)
  156. sid = _process_sid(pid.value)
  157. if sid != _process_sid(os.getpid()):
  158. raise PermissionError('named-pipe peer belongs to another user')
  159. return 'sid:' + sid
  160. def _disconnect_pipe(handle) -> None:
  161. """``DisconnectNamedPipe`` via kernel32: CPython's ``_winapi`` does not export it, and the
  162. server thread must outlive its first client (a dead pipe leaves the gateway stuck in
  163. ``starting`` for every later ``identify``)."""
  164. k = ctypes.WinDLL('kernel32', use_last_error=True)
  165. disconnect = _api(k, 'DisconnectNamedPipe', wintypes.BOOL, [wintypes.HANDLE])
  166. if not disconnect(handle):
  167. error = ctypes.get_last_error()
  168. raise OSError(None, 'DisconnectNamedPipe failed', None, error)
  169. def _remaining_ms(deadline):
  170. remaining = deadline - time.monotonic()
  171. if remaining <= 0:
  172. raise TimeoutError('runtime control deadline exceeded')
  173. return max(1, int(remaining * 1000))
  174. def _complete(ov, deadline):
  175. win = _native()
  176. try:
  177. if win.WaitForSingleObject(ov.event, _remaining_ms(deadline)) != win.WAIT_OBJECT_0:
  178. raise TimeoutError('runtime control deadline exceeded')
  179. transferred, error = ov.GetOverlappedResult(False)
  180. if error:
  181. raise OSError(error, 'runtime pipe I/O failed')
  182. return transferred
  183. except BaseException:
  184. # Cancel the native operation, not merely its caller's wait. Completion is
  185. # reaped before the buffer/OVERLAPPED can be released.
  186. ov.cancel()
  187. ov.GetOverlappedResult(True)
  188. raise
  189. def _accept(handle, budget) -> bool:
  190. """Wait up to ``budget`` seconds for a client; True once one is connected.
  191. A client can connect between the wait timing out and the cancel reaching the kernel; the
  192. reaped result then reports success and that client is served. ERROR_OPERATION_ABORTED (995)
  193. is the only idle outcome. A client that is already connected completes the accept at once.
  194. """
  195. win = _native()
  196. ov = win.ConnectNamedPipe(handle, overlapped=True)
  197. if win.WaitForSingleObject(ov.event, max(1, int(budget * 1000))) != win.WAIT_OBJECT_0:
  198. ov.cancel()
  199. _, error = ov.GetOverlappedResult(True)
  200. if error == 995:
  201. return False
  202. if error:
  203. raise OSError(None, 'runtime pipe accept failed', None, error)
  204. return True
  205. def _read_line(handle, deadline, maximum):
  206. win = _native()
  207. chunks = bytearray()
  208. while b'\n' not in chunks:
  209. ov, _ = win.ReadFile(handle, min(4096, maximum + 1 - len(chunks)), overlapped=True)
  210. count = _complete(ov, deadline)
  211. if not count:
  212. raise ConnectionError('runtime pipe closed before response')
  213. chunks.extend(ov.getbuffer()[:count])
  214. if len(chunks) > maximum:
  215. raise PermissionError('runtime control message too large')
  216. return bytes(chunks).split(b'\n', 1)[0]
  217. def _write(handle, data, deadline):
  218. win = _native()
  219. while data:
  220. ov, _ = win.WriteFile(handle, data, overlapped=True)
  221. sent = _complete(ov, deadline)
  222. if not sent:
  223. raise ConnectionError('runtime pipe closed during write')
  224. data = data[sent:]
  225. _PIPE_CLIENT_SQOS = 0x00100000 | 0x00010000
  226. def query_runtime_control(home: Path, request: bytes, timeout: float) -> bytes:
  227. from gateway.control_socket import windows_pipe_name
  228. win = _native()
  229. deadline = time.monotonic() + timeout
  230. name = windows_pipe_name(home)
  231. _remaining_ms(deadline)
  232. while True:
  233. try:
  234. # SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION: the server may read (never act as)
  235. # this client's token, captured now, so it can identify us even after we exit.
  236. handle = win.CreateFile(name, 0xC0000000, 0, win.NULL, win.OPEN_EXISTING,
  237. win.FILE_FLAG_OVERLAPPED | _PIPE_CLIENT_SQOS, win.NULL)
  238. break
  239. except OSError as exc:
  240. if exc.winerror == 2:
  241. raise FileNotFoundError('runtime control pipe absent') from None
  242. if exc.winerror == 5:
  243. raise PermissionError('runtime control pipe inaccessible') from None
  244. if exc.winerror != 231:
  245. raise
  246. try:
  247. win.WaitNamedPipe(name, _remaining_ms(deadline))
  248. except OSError as wait_error:
  249. if wait_error.winerror == 121:
  250. raise TimeoutError('runtime control deadline exceeded') from None
  251. raise
  252. try:
  253. _peer_subject(handle, server=True)
  254. _write(handle, request.rstrip(b'\n') + b'\n', deadline)
  255. return _read_line(handle, deadline, 512 * 1024) + b'\n'
  256. finally:
  257. win.CloseHandle(handle)
  258. # Listening pipe instances, one worker each. Requests are served concurrently, as the POSIX
  259. # socket does through its executor: a handler may dial this same pipe (a hosted room whose
  260. # source and member share one multiplexer re-enters it via hosted-producer -> hosted-attest).
  261. _PIPE_INSTANCES = 8
  262. class NativeControlServer:
  263. """Bounded native workers, independent of asyncio event-loop policy."""
  264. def __init__(self, home, handler):
  265. self.home, self.handler = home, handler
  266. self._stop = threading.Event()
  267. self._ready = threading.Event()
  268. self._error = None
  269. self._threads = [threading.Thread(target=self._run, args=(index == 0,), daemon=True,
  270. name=f'runtime-control-pipe-{index}')
  271. for index in range(_PIPE_INSTANCES)]
  272. self._thread = self._threads[0]
  273. def start(self):
  274. # The first instance claims the name (FILE_FLAG_FIRST_PIPE_INSTANCE) before any other.
  275. self._thread.start()
  276. if not self._ready.wait(5):
  277. self.close()
  278. raise TimeoutError('runtime control pipe startup deadline exceeded')
  279. if self._error:
  280. raise self._error
  281. for thread in self._threads[1:]:
  282. thread.start()
  283. def close(self):
  284. self._stop.set()
  285. for thread in self._threads:
  286. if thread.ident is not None:
  287. thread.join(timeout=5)
  288. if any(thread.is_alive() for thread in self._threads):
  289. raise TimeoutError('runtime control pipe did not stop')
  290. def _create_pipe(self, first=True):
  291. from gateway.control_socket import windows_pipe_name
  292. win = _native()
  293. class SecurityAttributes(ctypes.Structure):
  294. _fields_ = [('length', wintypes.DWORD), ('descriptor', ctypes.c_void_p), ('inherit', wintypes.BOOL)]
  295. a = ctypes.WinDLL('advapi32', use_last_error=True)
  296. descriptor = ctypes.c_void_p()
  297. convert = _api(a, 'ConvertStringSecurityDescriptorToSecurityDescriptorW', wintypes.BOOL,
  298. [wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(ctypes.c_void_p), ctypes.c_void_p])
  299. # Protected DACL: exactly the current user, no inherited Everyone/Users ACEs.
  300. if not convert('D:P(A;;GA;;;' + _process_sid(os.getpid()) + ')', 1, ctypes.byref(descriptor), None):
  301. raise PermissionError('cannot create private pipe DACL')
  302. attrs = SecurityAttributes(ctypes.sizeof(SecurityAttributes), descriptor, False)
  303. try:
  304. return win.CreateNamedPipe(windows_pipe_name(self.home),
  305. 3 | win.FILE_FLAG_OVERLAPPED | (0x00080000 if first else 0),
  306. 8, _PIPE_INSTANCES, 65536, 65536, 2000, ctypes.addressof(attrs))
  307. finally:
  308. k = ctypes.WinDLL('kernel32', use_last_error=True)
  309. _api(k, 'LocalFree', ctypes.c_void_p, [ctypes.c_void_p])(descriptor)
  310. def _run(self, first=True):
  311. win = _native()
  312. handle = None
  313. try:
  314. handle = self._create_pipe(first)
  315. self._ready.set()
  316. while not self._stop.is_set():
  317. try:
  318. connected = _accept(handle, 0.5)
  319. except OSError:
  320. # e.g. ERROR_NO_DATA: a client came and went. Fall through so the serve path
  321. # fails fast and the instance is recycled by DisconnectNamedPipe below.
  322. connected = True
  323. if not connected:
  324. # Idle: the instance is still listening and a client may have opened it after
  325. # the cancel. DisconnectNamedPipe here dropped that client mid-request (233).
  326. continue
  327. try:
  328. # Read first: ImpersonateNamedPipeClient needs data read from the pipe, and the
  329. # handler runs only once the peer is identified (bounded: 64 KiB, 2 s).
  330. raw = _read_line(handle, time.monotonic() + 2, 64 * 1024)
  331. subject = _peer_subject(handle, server=False)
  332. response = self.handler(raw, subject)
  333. # The I/O budget bounds the peer, not the handler's own (client-bounded) work.
  334. deadline = time.monotonic() + 2
  335. _write(handle, response, deadline)
  336. # DisconnectNamedPipe discards unread output. Let the client
  337. # consume and close, bounded by the same I/O deadline.
  338. _read_line(handle, deadline, 64 * 1024)
  339. except (OSError, TimeoutError, ConnectionError):
  340. pass
  341. finally:
  342. try:
  343. _disconnect_pipe(handle)
  344. except OSError as exc:
  345. if exc.winerror != 233: # ERROR_PIPE_NOT_CONNECTED: the client already left
  346. raise
  347. except BaseException as exc:
  348. # Hand-off to the owning thread: start() re-raises the stored error.
  349. logger.debug('runtime control pipe stopped', exc_info=True)
  350. self._error = exc
  351. self._ready.set()
  352. finally:
  353. if handle is not None:
  354. win.CloseHandle(handle)
  355. # Why a same-user gateway's control pipe or process refused this client (#139845, #140252). The
  356. # pipe DACL names the user's SID, so a refusal between two processes of one user means a boundary
  357. # the SID does not cross: an elevated owner (High integrity) seen from a filtered token, or an
  358. # owner in another logon session (a session-0 S4U boot task). ``authorization`` reads as a
  359. # credential problem and names neither.
  360. GATEWAY_ELEVATED = "gateway_elevated"
  361. GATEWAY_OTHER_SESSION = "gateway_other_session"
  362. def classify_refused_owner(*, own_session: int | None, owner_session: int | None,
  363. own_elevated: bool, owner_elevated: bool | None) -> str | None:
  364. """Pure decision over probed facts; ``None`` keeps the generic ``authorization`` code.
  365. ``owner_elevated`` is None when the owner's token could not be opened; from a non-elevated
  366. client in the same session that refusal is itself the elevation boundary."""
  367. if own_session is not None and owner_session is not None and own_session != owner_session:
  368. return GATEWAY_OTHER_SESSION
  369. if own_elevated:
  370. return None
  371. if owner_elevated or (owner_elevated is None and owner_session is not None):
  372. return GATEWAY_ELEVATED
  373. return None
  374. def refused_owner_remedy(reason: str, pid: int, owner_session: int | None) -> str:
  375. if reason == GATEWAY_ELEVATED:
  376. return (f"The running gateway (PID {pid}) was started as administrator, so this non-elevated "
  377. "app cannot reach it. Stop it from an administrator prompt (hermes gateway stop), then "
  378. "start Hermes without elevation")
  379. where = f"session {owner_session}" if owner_session is not None else "another session"
  380. return (f"The running gateway (PID {pid}) runs in another Windows logon session ({where}, e.g. a "
  381. "boot-time scheduled task), so this app cannot reach it. Stop it (hermes gateway stop from an "
  382. "administrator prompt) and let only one auto-start task launch the gateway")
  383. _ADMINISTRATORS_SID = 'S-1-5-32-544' # BUILTIN\Administrators: default owner of what an elevated admin creates
  384. _ACCESS_ALLOWED_ACE = 0
  385. class RefusedOwner(PermissionError):
  386. """This user's gateway, behind a boundary this client must not cross. ``str()`` is the remedy
  387. (the refused-owner wording above); ``reason_code`` is the bounded code discovery reports."""
  388. def __init__(self, reason_code: str, pid: int, remedy: str):
  389. super().__init__(remedy)
  390. self.reason_code, self.pid = reason_code, pid
  391. def judge_pipe_server(*, own_sid: str, process_sid: str | None, pipe: tuple[str, tuple] | None, pid: int,
  392. own_elevated: bool, own_session: int | None, server_session: int | None,
  393. server_elevated: bool | None = None) -> str:
  394. """``sid:<own>`` when this client may talk to the pipe's server; raises otherwise. Pure: the
  395. Win32 facts are passed in (#140706).
  396. *process_sid* is the server process's token user, None when this client cannot open the
  397. process; *pipe* is the pipe object's ``(owner, dacl)`` (:func:`_pipe_security`), None when
  398. unreadable; *server_elevated* is the readable server token's ``TokenElevation``, None when
  399. that probe failed.
  400. * Server process readable: its token user must be this user, and a non-elevated client never
  401. hands its requests to an elevated server (its tools would run with the full administrator
  402. token). The server token's elevation says so whatever owns the pipe (the 'Object creator'
  403. owner policy gives an elevated process's pipe to the user); only when that probe fails does
  404. the owner decide: BUILTIN\\Administrators means an elevated process made the pipe.
  405. * Server process unreadable (an elevated server seen from a filtered token): never attached.
  406. The pipe object says who made it: owner this user or BUILTIN\\Administrators, and a DACL
  407. granting exactly this user, the gateway's own private shape (``_create_pipe``). Another
  408. non-administrator account can set neither owner, so that is this user's elevated gateway
  409. (or an administrator, who already controls this account) and the refusal names it. Any
  410. other pipe stays the generic refusal."""
  411. owner, aces = pipe if pipe is not None else (None, ())
  412. if process_sid is not None:
  413. if process_sid != own_sid:
  414. raise PermissionError('named-pipe peer belongs to another user')
  415. if server_elevated is None:
  416. server_elevated = owner == _ADMINISTRATORS_SID
  417. if own_elevated or not server_elevated:
  418. return 'sid:' + own_sid
  419. owner_elevated = True
  420. else:
  421. if pipe is None:
  422. raise PermissionError('cannot verify bootstrap peer process')
  423. # The owner check carries the trust (no other non-administrator account can set either
  424. # owner). The ACE shape ignores AceFlags and the access mask: it only filters out pipes
  425. # that are not the gateway's private shape, it proves nothing on its own.
  426. if owner not in (own_sid, _ADMINISTRATORS_SID) or tuple(aces) != ((_ACCESS_ALLOWED_ACE, own_sid),):
  427. raise PermissionError('named-pipe peer belongs to another user')
  428. owner_elevated = True if owner == _ADMINISTRATORS_SID else None
  429. reason = classify_refused_owner(own_session=own_session, owner_session=server_session,
  430. own_elevated=own_elevated, owner_elevated=owner_elevated)
  431. if reason is None:
  432. raise PermissionError('cannot verify bootstrap peer process')
  433. logger.info('control pipe server PID %s refused as %s: pipe owner %s, server process %s, '
  434. 'server elevated %s, server session %s, own session %s', pid, reason, owner,
  435. 'readable' if process_sid else 'unreadable', server_elevated, server_session, own_session)
  436. raise RefusedOwner(reason, pid, refused_owner_remedy(reason, pid, server_session))
  437. def _server_subject(handle, pid: int) -> str:
  438. """The client half of the pipe identity check: the Win32 facts for :func:`judge_pipe_server`."""
  439. from hermes_dir_acl import process_elevation, process_is_elevated
  440. try:
  441. process_sid = _process_sid(pid)
  442. except PermissionError:
  443. process_sid = None
  444. # A readable process's token answers TokenElevation too (the same OpenProcess + TOKEN_QUERY);
  445. # None, the probe failing, leaves the pipe owner to decide.
  446. server_elevated = process_elevation(pid) if process_sid is not None else None
  447. try:
  448. pipe = _pipe_security(handle)
  449. except PermissionError:
  450. pipe = None
  451. return judge_pipe_server(own_sid=_process_sid(os.getpid()), process_sid=process_sid, pipe=pipe, pid=pid,
  452. own_elevated=process_is_elevated(), own_session=_session_of(os.getpid()),
  453. server_session=_pipe_server_session(handle), server_elevated=server_elevated)
  454. def _session_of(pid: int) -> int | None:
  455. k = ctypes.WinDLL('kernel32', use_last_error=True)
  456. session = wintypes.DWORD()
  457. to_session = _api(k, 'ProcessIdToSessionId', wintypes.BOOL, [wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)])
  458. return session.value if to_session(pid, ctypes.byref(session)) else None
  459. def probe_refused_owner(pid: int) -> tuple[str, str] | None:
  460. """``(reason_code, remedy)`` naming why *pid*'s gateway refused this client, or None."""
  461. from hermes_dir_acl import process_elevation, process_is_elevated
  462. own_session, owner_session = _session_of(os.getpid()), _session_of(pid)
  463. reason = classify_refused_owner(own_session=own_session, owner_session=owner_session,
  464. own_elevated=process_is_elevated(), owner_elevated=process_elevation(pid))
  465. return (reason, refused_owner_remedy(reason, pid, owner_session)) if reason else None