Skip to content

Commit b45bb2d

Browse files
authored
fix: take the named pipe user SID from the process token (#286)
* fix: take the named pipe user SID from the process token NamedPipeHelper.create_security_attributes() resolved the DACL's user SID with LookupAccountName("", getpass.getuser()). getpass.getuser() only reads the LOGNAME, USER, LNAME and USERNAME environment variables, and the name lookup goes through LSA, which can fail with ERROR_NONE_MAPPED (1332). A Windows CI host running as SYSTEM hit 1332 on both the server path (create_named_pipe_server) and the client path (establish_named_pipe_connection), and the 3-attempt retry from #262 ran out. - Read the SID from the process token: OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY) and GetTokenInformation(token, TokenUser)[0], closing the token in a finally. No name lookup, so 1332 cannot occur. The #262 retry and the getpass import are removed. - The client no longer builds a DACL. CreateFile ignores the security descriptor when opening an existing pipe and reads only bInheritHandle. It passes SECURITY_ATTRIBUTES with SECURITY_DESCRIPTOR = None and bInheritHandle = True. pywin32's SECURITY_ATTRIBUTES() defaults bInheritHandle to TRUE (PySECURITY_ATTRIBUTES.cpp), so the client handle stays inheritable, as before. Passing None would have made it non-inheritable. - The server DACL is unchanged: GENERIC_READ|GENERIC_WRITE allowed to the user SID, then GENERIC_ALL denied to S-1-5-2 (NETWORK). Tests: - Unit: the token SID ends up in the DACL; with the env user name set to an unmapped name, LookupAccountName is not called; the token is closed when GetTokenInformation raises; the client passes no descriptor, an inheritable handle and OPEN_EXISTING, and does not call create_security_attributes. The three LookupAccountName/retry tests pinned the removed behaviour and are replaced. - Integ: test_pipe_security_does_not_depend_on_user_name runs a real pipe round-trip with LOGNAME, USER, LNAME and USERNAME set to no-such-user-1332, once for server and client and once for the client only, plus an ambient-environment control. It asserts the precondition that LookupAccountName("", "no-such-user-1332") raises 1332, and reads the DACL back with GetSecurityInfo. The old code fails this test deterministically. - CI: code_quality.yml runs windows-latest x Python 3.9-3.14 through OpenJobDescription/.github reusable_python_build.yml, whose last step (line 72) is `hatch run test`, which is `pytest ... test -vv`. That collects test/openjd/adaptor_runtime/integ/_named_pipe/. No marker gates the new test. Ran on macOS (Python 3.13, hatch 1.14.1): - hatch run lint, before and after: ruff "All checks passed!", black "146 files would be left unchanged", mypy "no issues found in 146 source files". - hatch run mypy --platform win32 src test, before and after: no issues in 146 source files. - hatch run test: before (mainline d9044ea) 482 passed, 26 skipped, coverage 93.39%. After: 482 passed, 29 skipped, coverage 93.39%. The 3 new skips are the 3 new integ cases. The Windows-only unit module is one module-level skip before and after. - Windows tests skip on macOS. To run them anyway, a fake pywin32 plugin (not committed) models the APIs these tests touch, using the pywin32 C sources. Fidelity control: mainline code with mainline tests passes on it (11 passed). Branch: 15 passed, 1 skipped (the GITHUB_ACTIONS-only different-user test). Mutation check, EXECUTED on the fake (sha256 restore, __pycache__ cleared between mutants), all caught: - M1 restore LookupAccountName(getpass.getuser()) plus retry: fails test_create_security_attributes_uses_process_token_user, ..._does_not_look_up_user_name, ..._closes_token_when_query_fails and integ [unmapped-user-name-for-server-and-client]. - M2 restore the client DACL: fails test_establish_named_pipe_connection_builds_no_dacl. - M3 original code (M1+M2): also fails integ [unmapped-user-name-for-client]. - M4 no finally, M5 no close, M6 client not inheritable, M7 client None, M8 client keeps blank descriptor, M9 allow Everyone, M10 drop network deny: each caught. M4-M8 by the token-close or client unit test, M9 and M10 also by all three integ cases. ARGUED for real Windows, not run: with the old code, LookupAccountName raises 1332 on every attempt (the test asserts this as a precondition), so both unmapped integ cases fail. M2 alone is equivalent at the OS level, because CreateFile ignores the descriptor. Only the unit test catches it. Auditors (three, independent; each returned PASS): - Pin/mutation: 27 of their own mutants, 26 killed. The survivor removes the bInheritHandle = True line, which is equivalent because pywin32 defaults it to TRUE. Kept the explicit line for the reader. The CloseHandle-call assertion rejects an equivalent token.Close(). Kept, since it matches the repo's mock style. - Gap analysis: 9 mutants, all killed. Pre-existing: test_fail_to_connect_to_named_pipe_with_different_user has its assert inside pytest.raises, so the assert never runs. Not in this diff, and tightening it to winerror 5 would gate CI on a claim nobody has run. Recorded as a follow-up. _secure_open.py has the same LookupAccountName pattern; follow-up. - Craft/cross-platform: lint, win32 mypy and collection green; pywin32 API shapes checked against source. Fixed: the client-only case now sets the unmapped name inside the try, so a failed precondition still closes the server handle. Declined: cross-checking the SID with an LSA name lookup. It would bring back the lookup this fix removes. The test helper hard-codes TokenUser independently, and a TokenOwner mutant is killed. Follow-up, out of scope: openjd-sessions-for-python _get_process_user_sid() uses the same name-lookup pattern. Signed-off-by: David Leong <116610336+leongdl@users.noreply.github.com> * test: expect the deny-first ACE order on the named pipe DACL Windows CI showed the pipe DACL reads back with the NETWORK deny ACE before the user allow ACE, both in the in-memory security attributes and on the created pipe. That is canonical order, and the order that makes the deny apply to the user's own network logons. The new tests asserted allow-first and failed on all six Windows jobs; production code was not involved, since mainline builds the same DACL. Assert the canonical order exactly, and find the allowed SID by ACE type rather than by index. Signed-off-by: David Leong <116610336+leongdl@users.noreply.github.com> --------- Signed-off-by: David Leong <116610336+leongdl@users.noreply.github.com>
1 parent 9c8d54e commit b45bb2d

3 files changed

Lines changed: 266 additions & 57 deletions

File tree

‎src/openjd/adaptor_runtime_client/named_pipe/named_pipe_helper.py‎

Lines changed: 18 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@
44
from concurrent.futures import ThreadPoolExecutor, TimeoutError
55
from random import randint
66

7+
import win32api
78
import win32file
89
import pywintypes
910
import win32security
1011
import win32con
11-
import getpass
1212
import winerror
1313
import time
1414
import win32pipe
@@ -116,7 +116,7 @@ class NamedPipeHelper:
116116
"""
117117

118118
@staticmethod
119-
def create_security_attributes():
119+
def create_security_attributes() -> win32security.SECURITY_ATTRIBUTES:
120120
"""
121121
Creates and returns security attributes for a named pipe,
122122
allowing access only to the current user and denying network access.
@@ -125,26 +125,14 @@ def create_security_attributes():
125125
win32security.SECURITY_ATTRIBUTES: A SECURITY_ATTRIBUTES object configured with the custom security descriptor.
126126
"""
127127

128-
# Get the username of the current user
129-
username = getpass.getuser()
130-
131-
# Retry with exponential backoff to handle ERROR_NONE_MAPPED (1332) which occurs
132-
# when the LSA service hasn't finished initializing on freshly started EC2 instances.
133-
_LOOKUP_MAX_RETRIES = 3
134-
for attempt in range(_LOOKUP_MAX_RETRIES):
135-
try:
136-
user_sid, _, _ = win32security.LookupAccountName(
137-
"", # systemName: The name of the system or server where the account resides.
138-
# Search for the account on the local computer.
139-
# If Domain/User Format is used here, it will fetch the Name from the AD.
140-
username,
141-
)
142-
break
143-
except pywintypes.error as e:
144-
if e.winerror == 1332 and attempt < _LOOKUP_MAX_RETRIES - 1:
145-
time.sleep(2**attempt)
146-
continue
147-
raise
128+
# Take the SID from the process token, not from a user name. A name lookup goes through
129+
# LSA and can fail with ERROR_NONE_MAPPED (1332), and getpass.getuser() only reads
130+
# environment variables, which need not name the process's account.
131+
token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_QUERY)
132+
try:
133+
user_sid = win32security.GetTokenInformation(token, win32security.TokenUser)[0]
134+
finally:
135+
win32api.CloseHandle(token)
148136

149137
# Users who log on across a network. "S-1-5-2" is a group identifier added to the token of a process
150138
# when it was logged on across a network.
@@ -320,6 +308,13 @@ def establish_named_pipe_connection(pipe_name: str, timeout_in_seconds: float) -
320308
or due to other errors.
321309
322310
"""
311+
# CreateFile ignores the security descriptor when opening an existing pipe and reads only
312+
# bInheritHandle, so build no DACL here. Inheritable matches pywin32's SECURITY_ATTRIBUTES
313+
# default, which the server pipe handle also uses.
314+
security_attributes = win32security.SECURITY_ATTRIBUTES()
315+
security_attributes.SECURITY_DESCRIPTOR = None
316+
security_attributes.bInheritHandle = True
317+
323318
start_time = time.time()
324319
# Wait for the server pipe to become available.
325320
handle = None
@@ -330,7 +325,7 @@ def establish_named_pipe_connection(pipe_name: str, timeout_in_seconds: float) -
330325
# Give the read / write permission
331326
win32file.GENERIC_READ | win32file.GENERIC_WRITE,
332327
0, # Disable the sharing Mode
333-
NamedPipeHelper.create_security_attributes(),
328+
security_attributes,
334329
win32file.OPEN_EXISTING, # Open existing pipe
335330
0, # No Additional flags
336331
None, # A valid handle to a template file, This parameter is ignored when opening an existing pipe.

‎test/openjd/adaptor_runtime/integ/_named_pipe/test_named_pipe_helper.py‎

Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,23 @@
22
import time
33

44
from openjd.adaptor_runtime._osname import OSName
5+
import getpass
56
import json
67
import os
78
import pytest
89
import threading
10+
import uuid
11+
from typing import Any, List, Optional, Tuple
912

1013
if OSName.is_windows():
14+
import ntsecuritycon
1115
import pywintypes
16+
import win32con
1217
import win32file
1318
import win32pipe
1419
import win32security
1520
import win32api
21+
import winerror
1622
from openjd.adaptor_runtime_client.named_pipe.named_pipe_helper import NamedPipeHelper
1723
else:
1824
# Cannot put this on the top of this file or mypy will complain
@@ -21,6 +27,12 @@
2127
PIPE_NAME = r"\\.\pipe\TestPipe"
2228
TIMEOUT_SECONDS = 5
2329

30+
# getpass.getuser() returns the first of these that is set. No account has this name, so
31+
# resolving it with LookupAccountName fails with ERROR_NONE_MAPPED (1332).
32+
USER_NAME_ENV_VARS = ("LOGNAME", "USER", "LNAME", "USERNAME")
33+
UNMAPPED_USER_NAME = "no-such-user-1332"
34+
NETWORK_SID = "S-1-5-2"
35+
2436

2537
def pipe_server(pipe_name, message_to_send, return_message):
2638
"""
@@ -52,6 +64,64 @@ def start_pipe_server():
5264
server_thread.join()
5365

5466

67+
def set_unmapped_user_name(monkeypatch: pytest.MonkeyPatch) -> None:
68+
"""Makes getpass.getuser() return a name that LookupAccountName cannot resolve."""
69+
for name in USER_NAME_ENV_VARS:
70+
monkeypatch.setenv(name, UNMAPPED_USER_NAME)
71+
assert getpass.getuser() == UNMAPPED_USER_NAME
72+
# Precondition: if this name resolved, a name-based SID lookup would pass too and the
73+
# tests using it would pin nothing.
74+
with pytest.raises(pywintypes.error) as excinfo:
75+
win32security.LookupAccountName("", UNMAPPED_USER_NAME)
76+
assert excinfo.value.winerror == winerror.ERROR_NONE_MAPPED
77+
78+
79+
def process_token_user_sid() -> str:
80+
token = win32security.OpenProcessToken(win32api.GetCurrentProcess(), win32con.TOKEN_QUERY)
81+
try:
82+
sid = win32security.GetTokenInformation(token, win32security.TokenUser)[0]
83+
finally:
84+
win32api.CloseHandle(token)
85+
return win32security.ConvertSidToStringSid(sid)
86+
87+
88+
def as_file_rights(mask: int) -> int:
89+
"""Maps generic rights to file rights, since Windows may store an ACE mask in either form."""
90+
mask &= 0xFFFFFFFF
91+
for generic, specific in (
92+
(win32con.GENERIC_READ & 0xFFFFFFFF, ntsecuritycon.FILE_GENERIC_READ),
93+
(win32con.GENERIC_WRITE, ntsecuritycon.FILE_GENERIC_WRITE),
94+
(win32con.GENERIC_ALL, ntsecuritycon.FILE_ALL_ACCESS),
95+
):
96+
if mask & generic:
97+
mask = (mask & ~generic) | specific
98+
return mask
99+
100+
101+
def read_pipe_dacl(pipe_handle: Any) -> List[Tuple[int, int, str]]:
102+
"""Returns (ACE type, access mask as file rights, SID string) for each ACE on the pipe."""
103+
security_descriptor = win32security.GetSecurityInfo(
104+
pipe_handle, win32security.SE_KERNEL_OBJECT, win32security.DACL_SECURITY_INFORMATION
105+
)
106+
dacl = security_descriptor.GetSecurityDescriptorDacl()
107+
entries = []
108+
for index in range(dacl.GetAceCount()):
109+
(ace_type, _ace_flags), mask, sid = dacl.GetAce(index)
110+
entries.append((ace_type, as_file_rights(mask), win32security.ConvertSidToStringSid(sid)))
111+
return entries
112+
113+
114+
def serve_one_request(
115+
server_handle: Any, response: str, received: List[str], errors: List[Exception]
116+
) -> None:
117+
try:
118+
win32pipe.ConnectNamedPipe(server_handle, None)
119+
received.append(NamedPipeHelper.read_from_pipe(server_handle))
120+
NamedPipeHelper.write_to_pipe(server_handle, response)
121+
except Exception as e:
122+
errors.append(e)
123+
124+
55125
@pytest.mark.skipif(not OSName.is_windows(), reason="NamedPipe is only implemented in Windows.")
56126
class TestNamedPipeHelper:
57127
def test_named_pipe_communication(self, start_pipe_server):
@@ -129,3 +199,71 @@ def test_fail_to_connect_to_named_pipe_with_different_user(
129199

130200
# Send a message to unblock the I/O
131201
NamedPipeHelper.send_named_pipe_request(PIPE_NAME, TIMEOUT_SECONDS, **message_to_send)
202+
203+
@pytest.mark.parametrize(
204+
"unmapped_user_name_for",
205+
[
206+
pytest.param(None, id="ambient-user-name"),
207+
pytest.param("server-and-client", id="unmapped-user-name-for-server-and-client"),
208+
pytest.param("client", id="unmapped-user-name-for-client"),
209+
],
210+
)
211+
def test_pipe_security_does_not_depend_on_user_name(
212+
self, monkeypatch: pytest.MonkeyPatch, unmapped_user_name_for: Optional[str]
213+
) -> None:
214+
"""
215+
The pipe's DACL comes from the process token, so a getpass.getuser() name that maps to
216+
no account (ERROR_NONE_MAPPED, 1332) breaks neither the server nor the client.
217+
The ambient-user-name case is the control: the normal environment must still work.
218+
"""
219+
# GIVEN
220+
pipe_name = rf"\\.\pipe\openjd_token_sid_{os.getpid()}_{uuid.uuid4().hex}"
221+
request_body = {"message": "Hello from client"}
222+
server_response = '{"Response": "Hello from server"}'
223+
received: List[str] = []
224+
errors: List[Exception] = []
225+
if unmapped_user_name_for == "server-and-client":
226+
set_unmapped_user_name(monkeypatch)
227+
server_handle = NamedPipeHelper.create_named_pipe_server(pipe_name, TIMEOUT_SECONDS)
228+
assert server_handle is not None
229+
# A daemon thread, so a failed client cannot hang the run in ConnectNamedPipe.
230+
server_thread = threading.Thread(
231+
target=serve_one_request,
232+
args=(server_handle, server_response, received, errors),
233+
daemon=True,
234+
)
235+
236+
try:
237+
if unmapped_user_name_for == "client":
238+
set_unmapped_user_name(monkeypatch)
239+
dacl = read_pipe_dacl(server_handle)
240+
server_thread.start()
241+
242+
# WHEN
243+
response = NamedPipeHelper.send_named_pipe_request(
244+
pipe_name, TIMEOUT_SECONDS, "POST", "/token-sid", json_body=request_body
245+
)
246+
server_thread.join(TIMEOUT_SECONDS)
247+
finally:
248+
win32file.CloseHandle(server_handle)
249+
250+
# THEN
251+
assert not server_thread.is_alive()
252+
assert errors == []
253+
assert [json.loads(message) for message in received] == [
254+
{"method": "POST", "path": "/token-sid", "body": json.dumps(request_body)}
255+
]
256+
assert response == json.loads(server_response)
257+
# Canonical order: the NETWORK deny comes first, so it applies to the user's own network logons.
258+
assert dacl == [
259+
(
260+
win32security.ACCESS_DENIED_ACE_TYPE,
261+
as_file_rights(win32con.GENERIC_ALL),
262+
NETWORK_SID,
263+
),
264+
(
265+
win32security.ACCESS_ALLOWED_ACE_TYPE,
266+
as_file_rights(win32con.GENERIC_READ | win32con.GENERIC_WRITE),
267+
process_token_user_sid(),
268+
),
269+
]

0 commit comments

Comments
 (0)