Skip to content

The agent that grows with you

fix(gateway): name an elevated gateway from its control pipe instead of OpenProcess

unsupportedpastelsdc38e0bd8ec9
diff --git a/gateway/runtime_bootstrap_windows.py b/gateway/runtime_bootstrap_windows.py
index 450af5936b2..a9fa5ab63c4 100644
--- a/gateway/runtime_bootstrap_windows.py
+++ b/gateway/runtime_bootstrap_windows.py
@@ -31,7 +31,6 @@ def _api(dll, name, result, args):
def _token_sid(token) -> str:
"""String SID of a token's user (``TokenUser``)."""
- k = ctypes.WinDLL('kernel32', use_last_error=True)
a = ctypes.WinDLL('advapi32', use_last_error=True)
length = wintypes.DWORD()
token_info = _api(a, 'GetTokenInformation', wintypes.BOOL,
@@ -40,7 +39,13 @@ def _token_sid(token) -> str:
buf = ctypes.create_string_buffer(length.value)
if not token_info(token, 1, buf, length, ctypes.byref(length)):
raise PermissionError('cannot read bootstrap peer identity')
- sid = ctypes.cast(buf, ctypes.POINTER(ctypes.c_void_p))[0]
+ return _sid_text(ctypes.cast(buf, ctypes.POINTER(ctypes.c_void_p))[0])
+
+
+def _sid_text(sid) -> str:
+ """String form (``S-1-...``) of the SID at *sid*."""
+ k = ctypes.WinDLL('kernel32', use_last_error=True)
+ a = ctypes.WinDLL('advapi32', use_last_error=True)
text = wintypes.LPWSTR()
convert = _api(a, 'ConvertSidToStringSidW', wintypes.BOOL,
[ctypes.c_void_p, ctypes.POINTER(wintypes.LPWSTR)])
@@ -73,6 +78,49 @@ def _process_sid(pid: int) -> str:
close(process)
+class _AclHeader(ctypes.Structure):
+ _fields_ = [('revision', ctypes.c_ubyte), ('sbz1', ctypes.c_ubyte), ('size', wintypes.WORD),
+ ('count', wintypes.WORD), ('sbz2', wintypes.WORD)]
+
+
+def _pipe_security(handle) -> tuple[str, tuple[tuple[int, str], ...]]:
+ """The pipe object's owner SID and its DACL as ``(ace_type, sid)`` pairs, read from *handle*
+ (``GetSecurityInfo``; the client's GENERIC_READ carries READ_CONTROL). Unlike ``OpenProcess`` on
+ the server's PID this needs no access to the server process, so it still answers when the
+ server is elevated and this client is not (#140706)."""
+ k = ctypes.WinDLL('kernel32', use_last_error=True)
+ a = ctypes.WinDLL('advapi32', use_last_error=True)
+ get_info = _api(a, 'GetSecurityInfo', wintypes.DWORD,
+ [wintypes.HANDLE, ctypes.c_int, wintypes.DWORD] + [ctypes.POINTER(ctypes.c_void_p)] * 5)
+ get_ace = _api(a, 'GetAce', wintypes.BOOL, [ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(ctypes.c_void_p)])
+ owner, dacl, descriptor = ctypes.c_void_p(), ctypes.c_void_p(), ctypes.c_void_p()
+ # SE_KERNEL_OBJECT; OWNER_SECURITY_INFORMATION | DACL_SECURITY_INFORMATION
+ if get_info(handle, 6, 0x1 | 0x4, ctypes.byref(owner), None, ctypes.byref(dacl), None,
+ ctypes.byref(descriptor)) or not owner:
+ raise PermissionError('cannot read named-pipe owner')
+ try:
+ aces = []
+ # A NULL DACL (no entries to read) grants everyone: it is reported as no ACEs at all.
+ for index in range(_AclHeader.from_address(dacl.value).count if dacl else 0):
+ ace = ctypes.c_void_p()
+ if not get_ace(dacl, index, ctypes.byref(ace)):
+ raise PermissionError('cannot read named-pipe DACL')
+ kind = ctypes.c_ubyte.from_address(ace.value).value
+ # ACCESS_ALLOWED_ACE / ACCESS_DENIED_ACE: 4-byte ACE_HEADER, 4-byte mask, then the SID.
+ aces.append((kind, _sid_text(ace.value + 8) if kind in (0, 1) else ''))
+ return _sid_text(owner.value), tuple(aces)
+ finally:
+ _api(k, 'LocalFree', ctypes.c_void_p, [ctypes.c_void_p])(descriptor)
+
+
+def _pipe_server_session(handle) -> int | None:
+ """The pipe server's logon session, from the pipe (no access to the server process needed)."""
+ k = ctypes.WinDLL('kernel32', use_last_error=True)
+ session = wintypes.ULONG()
+ get = _api(k, 'GetNamedPipeServerSessionId', wintypes.BOOL, [wintypes.HANDLE, ctypes.POINTER(wintypes.ULONG)])
+ return session.value if get(handle, ctypes.byref(session)) else None
+
+
class _ImpersonationLeak(RuntimeError):
"""RevertToSelf failed: this thread may still carry the client's identity. Deliberately not an
OSError, so the serving loop does not swallow it and the worker stops instead."""
@@ -112,7 +160,8 @@ def _peer_subject(handle, *, server: bool) -> str:
"""``sid:<owner>`` for a same-user peer; PermissionError for another user or an unidentified one.
The serving side (``server=False``) reads the identity from the pipe's client token first and
- falls back to the client's process; an unreadable peer is refused, never served as anonymous."""
+ falls back to the client's process; an unreadable peer is refused, never served as anonymous.
+ The client side (``server=True``) is judged by :func:`judge_pipe_server`."""
sid = None
if not server:
try:
@@ -126,6 +175,8 @@ def _peer_subject(handle, *, server: bool) -> str:
pid = wintypes.ULONG()
if not get_pid(handle, ctypes.byref(pid)):
raise PermissionError('cannot identify named-pipe peer')
+ if server:
+ return _server_subject(handle, pid.value)
sid = _process_sid(pid.value)
if sid != _process_sid(os.getpid()):
raise PermissionError('named-pipe peer belongs to another user')
@@ -387,6 +438,76 @@ def refused_owner_remedy(reason: str, pid: int, owner_session: int | None) -> st
"administrator prompt) and let only one auto-start task launch the gateway")
+_ADMINISTRATORS_SID = 'S-1-5-32-544' # BUILTIN\Administrators: default owner of what an elevated admin creates
+_ACCESS_ALLOWED_ACE = 0
+
+
+class RefusedOwner(PermissionError):
+ """This user's gateway, behind a boundary this client must not cross. ``str()`` is the remedy
+ (the refused-owner wording above); ``reason_code`` is the bounded code discovery reports."""
+
+ def __init__(self, reason_code: str, pid: int, remedy: str):
+ super().__init__(remedy)
+ self.reason_code, self.pid = reason_code, pid
+
+
+def judge_pipe_server(*, own_sid: str, process_sid: str | None, pipe: tuple[str, tuple] | None, pid: int,
+ own_elevated: bool, own_session: int | None, server_session: int | None) -> str:
+ """``sid:<own>`` when this client may talk to the pipe's server; raises otherwise. Pure: the
+ Win32 facts are passed in (#140706).
+
+ *process_sid* is the server process's token user, None when this client cannot open the
+ process; *pipe* is the pipe object's ``(owner, dacl)`` (:func:`_pipe_security`), None when
+ unreadable.
+
+ * Server process readable: its token user must be this user. A pipe owned by
+ BUILTIN\\Administrators was made by an elevated process, and a non-elevated client never
+ hands its requests to one (its tools would run with the full administrator token).
+ * Server process unreadable (an elevated server seen from a filtered token): never attached.
+ The pipe object says who made it: owner this user or BUILTIN\\Administrators, and a DACL
+ granting exactly this user, the gateway's own private shape (``_create_pipe``). Another
+ non-administrator account can set neither owner, so that is this user's elevated gateway
+ (or an administrator, who already controls this account) and the refusal names it. Any
+ other pipe stays the generic refusal."""
+ owner, aces = pipe if pipe is not None else (None, ())
+ if process_sid is not None:
+ if process_sid != own_sid:
+ raise PermissionError('named-pipe peer belongs to another user')
+ if owner != _ADMINISTRATORS_SID or own_elevated:
+ return 'sid:' + own_sid
+ owner_elevated = True
+ else:
+ if pipe is None:
+ raise PermissionError('cannot verify bootstrap peer process')
+ if owner not in (own_sid, _ADMINISTRATORS_SID) or tuple(aces) != ((_ACCESS_ALLOWED_ACE, own_sid),):
+ raise PermissionError('named-pipe peer belongs to another user')
+ owner_elevated = True if owner == _ADMINISTRATORS_SID else None
+ reason = classify_refused_owner(own_session=own_session, owner_session=server_session,
+ own_elevated=own_elevated, owner_elevated=owner_elevated)
+ if reason is None:
+ raise PermissionError('cannot verify bootstrap peer process')
+ logger.info('control pipe server PID %s refused as %s: pipe owner %s, server process %s, '
+ 'server session %s, own session %s', pid, reason, owner,
+ 'readable' if process_sid else 'unreadable', server_session, own_session)
+ raise RefusedOwner(reason, pid, refused_owner_remedy(reason, pid, server_session))
+
+
+def _server_subject(handle, pid: int) -> str:
+ """The client half of the pipe identity check: the Win32 facts for :func:`judge_pipe_server`."""
+ from hermes_dir_acl import process_is_elevated
+ try:
+ process_sid = _process_sid(pid)
+ except PermissionError:
+ process_sid = None
+ try:
+ pipe = _pipe_security(handle)
+ except PermissionError:
+ pipe = None
+ return judge_pipe_server(own_sid=_process_sid(os.getpid()), process_sid=process_sid, pipe=pipe, pid=pid,
+ own_elevated=process_is_elevated(), own_session=_session_of(os.getpid()),
+ server_session=_pipe_server_session(handle))
+
+
def _session_of(pid: int) -> int | None:
k = ctypes.WinDLL('kernel32', use_last_error=True)
session = wintypes.DWORD()
diff --git a/hermes_cli/gateway_runtime.py b/hermes_cli/gateway_runtime.py
index 4c0556f608d..638f33930f6 100644
--- a/hermes_cli/gateway_runtime.py
+++ b/hermes_cli/gateway_runtime.py
@@ -295,7 +295,10 @@ def discover_gateway_endpoint(profile_home: str | Path, *, timeout: float = 2.0)
except DiscoveryError as exc:
# The code stays bounded; the detail names the local node, its owner or mode, and the fix.
return GatewayDiscovery("inaccessible", reason_code=exc.reason, detail=exc.bounded_detail(500))
- except PermissionError:
+ except PermissionError as exc:
+ from gateway.runtime_bootstrap_windows import RefusedOwner
+ if isinstance(exc, RefusedOwner): # the client proved the boundary from the control pipe (#140706)
+ return GatewayDiscovery("inaccessible", reason_code=exc.reason_code, detail=str(exc))
return _refused(home)
except (OSError, ValueError, TypeError):
# Raw peer data, paths and URLs may contain secrets; report bounded codes.
diff --git a/tests/e2e/core/windows_update/test_elevated_gateway_attach.py b/tests/e2e/core/windows_update/test_elevated_gateway_attach.py
new file mode 100644
index 00000000000..f80abbdabcd
--- /dev/null
+++ b/tests/e2e/core/windows_update/test_elevated_gateway_attach.py
@@ -0,0 +1,89 @@
+"""A standard-user client dialing an elevated gateway's control pipe (#140706, #134889 W9).
+
+The runner session is elevated, so this process hosts the real control pipe
+(``NativeControlServer``) as an elevated gateway would. A child under the UAC filtered-shape
+token (``_tokens.StandardUserProcess``: Administrators deny-only, Medium integrity) then dials it
+the way the Desktop and CLI do:
+
+* ``query_runtime_control``: the client half of the pipe identity check must refuse before
+ sending anything, with the named ``gateway_elevated`` reason and its remedy, never the
+ generic ``cannot verify bootstrap peer process``;
+* ``discover_gateway_endpoint`` (what ``hermes gateway ensure`` and the Desktop boot read):
+ ``inaccessible`` / ``gateway_elevated`` with the same remedy, without any gateway record.
+
+The gateway's handler must never run: no request crosses the elevation boundary.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+from pathlib import Path
+
+import pytest
+
+pytestmark = [pytest.mark.platforms("windows"), pytest.mark.integration, pytest.mark.live_system_guard_bypass]
+
+_REPO = Path(__file__).resolve().parents[4]
+
+_CLIENT = r"""
+import json, sys
+from pathlib import Path
+from gateway.control_socket import windows_pipe_name
+from gateway import runtime_bootstrap_windows as native
+from hermes_dir_acl import process_is_elevated
+from hermes_cli.gateway_runtime import discover_gateway_endpoint
+home = Path(sys.argv[1])
+out = {"pipe": windows_pipe_name(home), "elevated": process_is_elevated()}
+try:
+ native.query_runtime_control(home, b'{"protocol": 1, "id": 1, "verb": "identify"}', 10)
+ out["outcome"] = "attached"
+except PermissionError as exc:
+ out.update(outcome="refused", reason_code=getattr(exc, "reason_code", None), message=str(exc))
+found = discover_gateway_endpoint(home, timeout=10)
+out["discovery"] = [found.state, found.reason_code, found.detail]
+print("RESULT " + json.dumps(out))
+"""
+
+
+def test_a_standard_user_client_gets_the_named_refusal_from_an_elevated_gateway(tmp_path):
+ from gateway import runtime_bootstrap_windows as native
+ from gateway.control_socket import windows_pipe_name
+ from hermes_dir_acl import process_is_elevated
+ from tests.e2e.core.windows_update._tokens import StandardUserProcess, hand_to_user, probe_token_elevation
+
+ if not process_is_elevated():
+ pytest.skip("the gateway side needs an elevated session (the Windows E2E runner's)")
+ home, temp = tmp_path / "home", tmp_path / "temp"
+ home.mkdir()
+ temp.mkdir()
+ hand_to_user(tmp_path) # the user's own home, as on a real machine
+ env = {**os.environ, "PYTHONPATH": str(_REPO), "TEMP": str(temp), "TMP": str(temp),
+ "HERMES_HOME": str(home), "HERMES_STATE_DB_GUARD_BYPASS": "1"}
+ # Harness control: the child really is a standard user (Medium, Administrators deny-only).
+ assert probe_token_elevation(tmp_path, env, tmp_path / "token.log") == "elevated=False admin=False"
+
+ served = []
+
+ def handler(raw, subject):
+ served.append((raw, subject))
+ return b'{"ok": false}\n'
+ server = native.NativeControlServer(home, handler)
+ server.start()
+ try:
+ log = tmp_path / "client.log"
+ child = StandardUserProcess([sys.executable, "-c", _CLIENT, str(home)], cwd=_REPO, env=env, log=log)
+ rc = child.wait(120)
+ finally:
+ server.close()
+ text = log.read_text(encoding="utf-8", errors="replace")
+ assert rc == 0, text
+ result = json.loads(next(line for line in text.splitlines() if line.startswith("RESULT "))[7:])
+ assert result["pipe"] == windows_pipe_name(home), "harness: the child dialed another pipe"
+ assert result["elevated"] is False
+ remedy = native.refused_owner_remedy(native.GATEWAY_ELEVATED, os.getpid(), native._session_of(os.getpid()))
+ assert (result["outcome"], result.get("reason_code"), result.get("message")) == (
+ "refused", native.GATEWAY_ELEVATED, remedy), text
+ assert result["discovery"] == ["inaccessible", native.GATEWAY_ELEVATED, remedy], text
+ assert served == [], "a request from the standard-user client reached the elevated gateway"
diff --git a/tests/gateway/test_runtime_bootstrap.py b/tests/gateway/test_runtime_bootstrap.py
index cf127d3caf7..4a8411c1f98 100644
--- a/tests/gateway/test_runtime_bootstrap.py
+++ b/tests/gateway/test_runtime_bootstrap.py
@@ -288,3 +288,31 @@ def test_native_pipe_never_drops_a_client_that_lands_between_idle_accepts(tmp_pa
server.close()
assert injected.get("reply") == {"echo": "injected"}, injected.get("error")
assert server._error is None, server._error
+
+
+def test_client_reads_a_real_gateway_pipes_owner_dacl_and_session(tmp_path):
+ """The facts the client half judges a server by when it cannot open the server process
+ (#140706), read from a live gateway pipe through the client's own handle: owner this user, or
+ Administrators when this process is elevated; a DACL of exactly this user; this session."""
+ import _winapi
+ import gateway.runtime_bootstrap_windows as rbw
+ from gateway.control_socket import windows_pipe_name
+ from hermes_dir_acl import process_is_elevated
+ server = rbw.NativeControlServer(tmp_path, lambda raw, subject: b'{}\n')
+ server.start()
+ try:
+ handle = _winapi.CreateFile(windows_pipe_name(tmp_path), 0xC0000000, 0, _winapi.NULL,
+ _winapi.OPEN_EXISTING, 0, _winapi.NULL)
+ try:
+ own = rbw._process_sid(os.getpid())
+ owner, aces = rbw._pipe_security(handle)
+ assert owner == own or (owner == rbw._ADMINISTRATORS_SID and process_is_elevated()), owner
+ assert aces == ((rbw._ACCESS_ALLOWED_ACE, own),)
+ assert rbw._pipe_server_session(handle) == rbw._session_of(os.getpid())
+ # Same token on both ends: attached, whichever owner this runner's token gives the pipe.
+ assert rbw._peer_subject(handle, server=True) == 'sid:' + own
+ finally:
+ _winapi.CloseHandle(handle)
+ finally:
+ server.close()
diff --git a/tests/gateway/test_runtime_bootstrap_server_identity.py b/tests/gateway/test_runtime_bootstrap_server_identity.py
new file mode 100644
index 00000000000..4bd83fc4791
--- /dev/null
+++ b/tests/gateway/test_runtime_bootstrap_server_identity.py
@@ -0,0 +1,186 @@
+"""#140706: a non-elevated client identifies an elevated gateway from the control pipe itself.
+
+``_peer_subject(handle, server=True)`` is the client half of the control-pipe identity check
+(``query_runtime_control`` calls it before sending anything). A filtered (non-elevated) token
+cannot ``OpenProcess`` an elevated gateway, so every Desktop/CLI attach failed with
+``cannot verify bootstrap peer process`` and discovery reported ``authorization``.
+
+These tests drive that entry on any host by injecting the Win32 calls, never ``sys.platform``:
+``ctypes.WinDLL`` answers the ULONG-out queries (server PID and session, own session),
+``_process_sid`` stands in for OpenProcess + token (raising for an elevated server),
+``_pipe_security`` for ``GetSecurityInfo`` on the pipe handle, and ``process_is_elevated`` for
+this client's token. ``test_runtime_bootstrap.py`` reads a real pipe's facts on Windows, and
+``tests/e2e/core/windows_update/test_elevated_gateway_attach.py`` runs the real
+elevated-server / standard-user-client attach.
+"""
+import ctypes
+
+import pytest
+
+from gateway import runtime_bootstrap_windows as native
+
+OWN = "S-1-5-21-1-2-3-1001"
+OTHER = "S-1-5-21-1-2-3-1002"
+ADMINS = "S-1-5-32-544"
+EVERYONE = "S-1-1-0"
+SERVER_PID = 5_000_000 # above any Linux pid_max, so never this process
+HANDLE = object()
+
+
+class _Kernel32:
+ """``WinDLL('kernel32')`` answering only the ULONG-out queries the identity check makes."""
+
+ def __init__(self, values):
+ self.values = values
+
+ def __getattr__(self, name):
+ if name not in self.values:
+ raise AttributeError(name)
+
+ def call(_first, out):
+ value = self.values[name]
+ if value is None:
+ return 0
+ out._obj.value = value
+ return 1
+ return call
+
+
+def pipe(monkeypatch):
+ """Install one pipe server's facts as the Win32 layer reports them to this client."""
+ import hermes_dir_acl
+
+ def install(*, process_sid, owner=OWN, aces=((0, OWN),), readable=True, own_elevated=False,
+ own_session=1, server_session=1, client_pid=None):
+ kernel = _Kernel32({"GetNamedPipeServerProcessId": SERVER_PID, "GetNamedPipeClientProcessId": client_pid,
+ "GetNamedPipeServerSessionId": server_session, "ProcessIdToSessionId": own_session})
+ monkeypatch.setattr(ctypes, "WinDLL", lambda name, use_last_error=False: kernel, raising=False)
+
+ def process_sid_(pid):
+ if pid not in (SERVER_PID, client_pid):
+ return OWN # this process
+ if process_sid is None:
+ raise PermissionError("cannot verify bootstrap peer process") # OpenProcess err=5
+ return process_sid
+ monkeypatch.setattr(native, "_process_sid", process_sid_)
+
+ def security(handle):
+ assert handle is HANDLE
+ if not readable:
+ raise PermissionError("cannot read named-pipe owner")
+ return owner, tuple(aces)
+ monkeypatch.setattr(native, "_pipe_security", security, raising=False)
+ monkeypatch.setattr(hermes_dir_acl, "process_is_elevated", lambda: own_elevated)
+ return install
+
+
+def _refusal() -> PermissionError:
+ with pytest.raises(PermissionError) as info:
+ native._peer_subject(HANDLE, server=True)
+ return info.value
+
+
+# -- the bug: an elevated gateway seen from a filtered token ------------------------------------
+
+
[email protected]("process_sid", [None, OWN], ids=["process-unopenable", "process-readable"])
+def test_a_filtered_client_names_an_elevated_gateway_from_its_pipe(pipe, process_sid):
+ """The pipe is this user's (DACL) and was made by an elevated process (owner Administrators):
+ the refusal is the named ``gateway_elevated`` one, with #140490's remedy for the pipe server's PID."""
+ pipe(process_sid=process_sid, owner=ADMINS)
+ refused = _refusal()
+ assert getattr(refused, "reason_code", None) == "gateway_elevated", refused
+ assert str(refused) == native.refused_owner_remedy("gateway_elevated", SERVER_PID, 1)
+ assert refused.pid == SERVER_PID
+
+
+def test_an_unopenable_same_user_pipe_is_the_elevation_boundary(pipe):
+ """Owner this user (the 'object creator' default-owner policy) but the process is unopenable
+ from this filtered token in the same session: the same boundary, as ``classify_refused_owner``
+ reads an unopenable owner token."""
+ pipe(process_sid=None, owner=OWN)
+ assert getattr(_refusal(), "reason_code", None) == "gateway_elevated"
+
+
+def test_an_unopenable_gateway_in_another_session_is_named_as_such(pipe):
+ pipe(process_sid=None, owner=ADMINS, own_session=1, server_session=0)
+ refused = _refusal()
+ assert getattr(refused, "reason_code", None) == "gateway_other_session"
+ assert str(refused) == native.refused_owner_remedy("gateway_other_session", SERVER_PID, 0)
+
+
+def test_discovery_reports_the_named_refusal_without_any_owner_record(pipe, monkeypatch, tmp_path):
+ """The real discovery path: the pipe check raising inside ``query_identify`` reaches
+ ``discover_gateway_endpoint``, which reports the pipe-proven reason; no ``gateway.pid`` or
+ ``gateway.lock`` record is needed to name it."""
+ from hermes_cli import gateway_runtime as runtime
+ from hermes_cli import gateway_runtime_discovery as discovery
+ from hermes_cli.gateway_runtime_cli import ensure_exit_code
+ pipe(process_sid=None, owner=ADMINS)
+ home = tmp_path / "home"
+ home.mkdir()
+ monkeypatch.setattr(discovery, "query_identify",
+ lambda *_a, **_k: native._peer_subject(HANDLE, server=True))
+ result = runtime.discover_gateway_endpoint(home, timeout=1)
+ assert (result.state, result.reason_code) == ("inaccessible", "gateway_elevated")
+ assert result.detail == native.refused_owner_remedy("gateway_elevated", SERVER_PID, 1)
+ assert ensure_exit_code(result) == 4
+
+
+# -- what must stay refused, never attached and never named -------------------------------------
+
+
[email protected](("owner", "aces", "readable"), [
+ (OTHER, ((0, OTHER),), True), # another user's pipe squatting the name
+ (OTHER, ((0, OWN),), True), # ... even one that grants this user
+ (ADMINS, ((0, EVERYONE),), True), # an elevated pipe not made for this user
+ (ADMINS, ((0, OWN), (0, EVERYONE)), True), # ... or opened to everyone besides
+ (ADMINS, ((1, OWN), (0, OWN)), True), # not the gateway's single-ACE shape
+ (ADMINS, (), True), # NULL DACL: everyone
+ (OWN, ((0, OTHER),), True),
+ (None, (), False), # the pipe's security is unreadable
+], ids=["other-owner", "other-owner-own-dacl", "admins-everyone", "admins-extra-ace", "deny-ace",
+ "null-dacl", "own-owner-other-dacl", "unreadable"])
+def test_an_unprovable_pipe_server_stays_the_generic_refusal(pipe, owner, aces, readable):
+ pipe(process_sid=None, owner=owner, aces=aces, readable=readable)
+ refused = _refusal()
+ assert getattr(refused, "reason_code", None) is None
+ assert "cannot verify" in str(refused) or "another user" in str(refused)
+
+
+def test_an_elevated_client_never_attaches_to_a_server_it_cannot_open(pipe):
+ """Not this lane's boundary to name, and no identity read: stays the generic refusal."""
+ pipe(process_sid=None, owner=ADMINS, own_elevated=True)
+ refused = _refusal()
+ assert getattr(refused, "reason_code", None) is None
+ assert str(refused) == "cannot verify bootstrap peer process"
+
+
+def test_another_users_readable_server_is_refused(pipe):
+ pipe(process_sid=OTHER, owner=OTHER, aces=((0, OTHER),))
+ assert str(_refusal()) == "named-pipe peer belongs to another user"
+
+
+# -- what keeps working --------------------------------------------------------------------------
+
+
[email protected](("owner", "own_elevated", "readable"), [
+ (OWN, False, True), # same user, neither elevated
+ (ADMINS, True, True), # both elevated
+ (None, False, False), # pipe security unreadable: the process identity alone, as before
+])
+def test_a_same_user_server_at_the_clients_level_is_attached(pipe, owner, own_elevated, readable):
+ pipe(process_sid=OWN, owner=owner, own_elevated=own_elevated, readable=readable)
+ assert native._peer_subject(HANDLE, server=True) == "sid:" + OWN
+
+
+def test_the_serving_side_never_judges_a_client_by_the_pipe_owner(pipe, monkeypatch):
+ """Identifying a CLIENT is unchanged: no token and no readable process stays refused."""
+ pipe(process_sid=None, client_pid=SERVER_PID + 1)
+ monkeypatch.setattr(native, "_pipe_client_sid",
+ lambda handle: (_ for _ in ()).throw(PermissionError("no token")))
+ monkeypatch.setattr(native, "_pipe_security", lambda handle: pytest.fail("pipe owner read for a client"),
+ raising=False)
+ with pytest.raises(PermissionError, match="cannot verify bootstrap peer process"):
+ native._peer_subject(HANDLE, server=False)