Skip to content

The agent that grows with you

fix(gateway): identify a Windows pipe peer by its token, not its PID

Tekniume665047411b2
diff --git a/gateway/runtime_bootstrap_windows.py b/gateway/runtime_bootstrap_windows.py
index e7e41f93195..2c1c4d96c4b 100644
--- a/gateway/runtime_bootstrap_windows.py
+++ b/gateway/runtime_bootstrap_windows.py
@@ -29,6 +29,29 @@ def _api(dll, name, result, args):
return fn
+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,
+ [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)])
+ token_info(token, 1, None, 0, ctypes.byref(length))
+ 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]
+ text = wintypes.LPWSTR()
+ convert = _api(a, 'ConvertSidToStringSidW', wintypes.BOOL,
+ [ctypes.c_void_p, ctypes.POINTER(wintypes.LPWSTR)])
+ if not convert(sid, ctypes.byref(text)):
+ raise PermissionError('cannot encode bootstrap peer identity')
+ try:
+ return text.value
+ finally:
+ _api(k, 'LocalFree', ctypes.c_void_p, [ctypes.c_void_p])(ctypes.cast(text, ctypes.c_void_p))
+
+
def _process_sid(pid: int) -> str:
k = ctypes.WinDLL('kernel32', use_last_error=True)
a = ctypes.WinDLL('advapi32', use_last_error=True)
@@ -43,37 +66,66 @@ def _process_sid(pid: int) -> str:
[wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE)])
if not open_token(process, 8, ctypes.byref(token)):
raise PermissionError('cannot verify bootstrap peer token')
- length = wintypes.DWORD()
- token_info = _api(a, 'GetTokenInformation', wintypes.BOOL,
- [wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD)])
- token_info(token, 1, None, 0, ctypes.byref(length))
- 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]
- text = wintypes.LPWSTR()
- convert = _api(a, 'ConvertSidToStringSidW', wintypes.BOOL,
- [ctypes.c_void_p, ctypes.POINTER(wintypes.LPWSTR)])
- if not convert(sid, ctypes.byref(text)):
- raise PermissionError('cannot encode bootstrap peer identity')
- try:
- return text.value
- finally:
- _api(k, 'LocalFree', ctypes.c_void_p, [ctypes.c_void_p])(ctypes.cast(text, ctypes.c_void_p))
+ return _token_sid(token)
finally:
if token:
close(token)
close(process)
-def _peer_subject(handle, *, server: bool) -> str:
+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."""
+
+
+def _pipe_client_sid(handle) -> str:
+ """The client's SID from the identification token the kernel captured when it opened the pipe
+ (the client dials with ``SECURITY_SQOS_PRESENT``). Unlike ``OpenProcess`` on the client's PID,
+ this still answers after a short-lived client (a one-shot ``gateway ensure``) has exited.
+ Windows only allows it once data has been read from the pipe."""
k = ctypes.WinDLL('kernel32', use_last_error=True)
- name = 'GetNamedPipeServerProcessId' if server else 'GetNamedPipeClientProcessId'
- get_pid = _api(k, name, wintypes.BOOL, [wintypes.HANDLE, ctypes.POINTER(wintypes.ULONG)])
- pid = wintypes.ULONG()
- if not get_pid(handle, ctypes.byref(pid)):
- raise PermissionError('cannot identify named-pipe peer')
- sid = _process_sid(pid.value)
+ a = ctypes.WinDLL('advapi32', use_last_error=True)
+ impersonate = _api(a, 'ImpersonateNamedPipeClient', wintypes.BOOL, [wintypes.HANDLE])
+ revert = _api(a, 'RevertToSelf', wintypes.BOOL, [])
+ open_thread_token = _api(a, 'OpenThreadToken', wintypes.BOOL,
+ [wintypes.HANDLE, wintypes.DWORD, wintypes.BOOL, ctypes.POINTER(wintypes.HANDLE)])
+ current_thread = _api(k, 'GetCurrentThread', wintypes.HANDLE, [])
+ close = _api(k, 'CloseHandle', wintypes.BOOL, [wintypes.HANDLE])
+ if not impersonate(handle):
+ raise PermissionError('cannot impersonate named-pipe peer')
+ token = wintypes.HANDLE()
+ try:
+ # OpenAsSelf: the access check runs against the gateway's own token, not the client's.
+ if not open_thread_token(current_thread(), 8, True, ctypes.byref(token)):
+ raise PermissionError('cannot read named-pipe peer token')
+ finally:
+ if not revert():
+ raise _ImpersonationLeak('RevertToSelf failed after reading a named-pipe peer')
+ try:
+ return _token_sid(token)
+ finally:
+ close(token)
+
+
+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."""
+ sid = None
+ if not server:
+ try:
+ sid = _pipe_client_sid(handle)
+ except PermissionError:
+ sid = None
+ if sid is None:
+ k = ctypes.WinDLL('kernel32', use_last_error=True)
+ name = 'GetNamedPipeServerProcessId' if server else 'GetNamedPipeClientProcessId'
+ get_pid = _api(k, name, wintypes.BOOL, [wintypes.HANDLE, ctypes.POINTER(wintypes.ULONG)])
+ pid = wintypes.ULONG()
+ if not get_pid(handle, ctypes.byref(pid)):
+ raise PermissionError('cannot identify named-pipe peer')
+ sid = _process_sid(pid.value)
if sid != _process_sid(os.getpid()):
raise PermissionError('named-pipe peer belongs to another user')
return 'sid:' + sid
@@ -157,6 +209,9 @@ def _write(handle, data, deadline):
data = data[sent:]
+_PIPE_CLIENT_SQOS = 0x00100000 | 0x00010000
+
+
def query_runtime_control(home: Path, request: bytes, timeout: float) -> bytes:
from gateway.control_socket import windows_pipe_name
win = _native()
@@ -165,8 +220,10 @@ def query_runtime_control(home: Path, request: bytes, timeout: float) -> bytes:
_remaining_ms(deadline)
while True:
try:
+ # SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION: the server may read (never act as)
+ # this client's token, captured now, so it can identify us even after we exit.
handle = win.CreateFile(name, 0xC0000000, 0, win.NULL, win.OPEN_EXISTING,
- win.FILE_FLAG_OVERLAPPED | 0x00100000, win.NULL)
+ win.FILE_FLAG_OVERLAPPED | _PIPE_CLIENT_SQOS, win.NULL)
break
except OSError as exc:
if exc.winerror == 2:
@@ -265,8 +322,10 @@ class NativeControlServer:
# the cancel. DisconnectNamedPipe here dropped that client mid-request (233).
continue
try:
- subject = _peer_subject(handle, server=False)
+ # Read first: ImpersonateNamedPipeClient needs data read from the pipe, and the
+ # handler runs only once the peer is identified (bounded: 64 KiB, 2 s).
raw = _read_line(handle, time.monotonic() + 2, 64 * 1024)
+ subject = _peer_subject(handle, server=False)
response = self.handler(raw, subject)
# The I/O budget bounds the peer, not the handler's own (client-bounded) work.
deadline = time.monotonic() + 2
diff --git a/tests/gateway/test_runtime_bootstrap.py b/tests/gateway/test_runtime_bootstrap.py
index a13d9793a5d..cf127d3caf7 100644
--- a/tests/gateway/test_runtime_bootstrap.py
+++ b/tests/gateway/test_runtime_bootstrap.py
@@ -132,6 +132,62 @@ def test_native_pipe_authenticated_peer_and_deadline(tmp_path):
assert not server._thread.is_alive()
+def _serve_one_child_query(tmp_path, monkeypatch):
+ """Serve one query from a separate process whose PID the gateway cannot open, as when a
+ one-shot ``gateway ensure`` child has already exited (#139084). Returns (subjects, child)."""
+ import subprocess
+ import sys
+ import gateway.runtime_bootstrap_windows as rbw
+ real_process_sid, own = rbw._process_sid, os.getpid()
+
+ def process_sid(pid):
+ if pid != own:
+ raise PermissionError('cannot verify bootstrap peer process') # OpenProcess on a gone PID
+ return real_process_sid(pid)
+ monkeypatch.setattr(rbw, '_process_sid', process_sid)
+ subjects = []
+
+ def handler(raw, subject):
+ subjects.append(subject)
+ return json.dumps({'ok': True}).encode() + b'\n'
+ server = rbw.NativeControlServer(tmp_path, handler)
+ server.start()
+ try:
+ child = subprocess.run(
+ [sys.executable, '-c', 'import sys; from pathlib import Path; '
+ 'from gateway.runtime_bootstrap_windows import query_runtime_control as q; '
+ 'sys.stdout.write(q(Path(sys.argv[1]), b"hello", 10).decode())', str(tmp_path)],
+ check=False, capture_output=True, text=True, timeout=30, cwd=os.getcwd())
+ finally:
+ server.close()
+ return subjects, child
+
+
+def test_native_pipe_identifies_a_peer_whose_process_is_gone(tmp_path, monkeypatch):
+ """The peer's identity comes from the token captured when it opened the pipe, so a same-user
+ client is served even when its PID can no longer be opened (#139084)."""
+ import gateway.runtime_bootstrap_windows as rbw
+ owner = rbw._process_sid(os.getpid())
+ subjects, child = _serve_one_child_query(tmp_path, monkeypatch)
+ assert child.returncode == 0, child.stderr
+ assert json.loads(child.stdout) == {'ok': True}
+ assert subjects == ['sid:' + owner]
+
+
+def test_native_pipe_refuses_a_peer_it_cannot_identify(tmp_path, monkeypatch):
+ """No token and no readable process: the peer stays refused, never served as anonymous."""
+ import gateway.runtime_bootstrap_windows as rbw
+
+ def no_token(handle):
+ raise PermissionError('cannot impersonate named-pipe peer')
+ monkeypatch.setattr(rbw, '_pipe_client_sid', no_token, raising=False)
+ subjects, child = _serve_one_child_query(tmp_path, monkeypatch)
+ assert subjects == []
+ assert child.returncode != 0
+
+
@pytest.mark.platforms("windows")
def test_native_pipe_handler_may_dial_its_own_pipe(tmp_path):
"""A hosted room whose source and member share one multiplexer re-enters the control pipe