Privilege split 3/11: the access-controlled named pipe (server and client)
- kurgan/hw/pipe.py, ctypes with overlapped I/O and timeouts throughout. - Server: each connection on its own thread (the fan loop never waits on a client); up to 8 at once. A client that sends nothing, or leaves a line unfinished, for 30 s is dropped, and so is one that won't read its replies (5 s write timeout). An oversized line gets a too_large reply, then the connection closes. Remote clients are rejected. - Access list (pipe_sddl): SYSTEM and Administrators full, the installing user's SID FILE_GENERIC_READ | FILE_WRITE_DATA | FILE_WRITE_ATTRIBUTES, and nobody else. GENERIC_WRITE is avoided because for a pipe it includes FILE_CREATE_PIPE_INSTANCE, which would let the user's other programs add an instance and answer in the service's name. The first instance uses FILE_FLAG_FIRST_PIPE_INSTANCE, so a squatter makes the service fail loudly. - Client: identification-level impersonation only, and it refuses a pipe whose owner isn't SYSTEM or Administrators (one an unelevated program created while the service was down). Clear errors for "not running" and "refused this user". - Tests: 11 new, against real pipes: round trip, several clients at once, silent and trickling clients dropped without affecting others, oversized lines, prompt shutdown, owner check, and (unelevated) a user missing from the access list is refused and the user can't add a pipe instance. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b1404ac4ba
commit
73a424f6a8
2 files changed
+655
No files matched your search
@@ -0,0 +1,478 @@
|
|||||||
|
"""The named pipe between the hardware service and the app: server and client, with timeouts.
|
||||||
|
|
||||||
|
Server (the service): every connection gets its own thread, so a slow or hostile client can
|
||||||
|
only waste its own slot, never the fan loop's time. A connection that sends nothing, or leaves
|
||||||
|
a line unfinished, for READ_TIMEOUT seconds is dropped, and so is one that won't read its
|
||||||
|
replies. The pipe refuses remote clients, and its access list (pipe_sddl) allows SYSTEM and
|
||||||
|
Administrators full access and the installing user read/write only: no
|
||||||
|
FILE_CREATE_PIPE_INSTANCE, so the user's other programs can't add an instance of their own and
|
||||||
|
answer in the service's name. The first instance is created with FILE_FLAG_FIRST_PIPE_INSTANCE,
|
||||||
|
so a program that took the name first makes the service fail loudly instead of sharing it.
|
||||||
|
|
||||||
|
Client (the app): connects at identification level only (the service can't act as the user),
|
||||||
|
and refuses a pipe whose owner isn't SYSTEM or Administrators, i.e. one that some unelevated
|
||||||
|
program created while the service was down.
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import ctypes
|
||||||
|
import ctypes.wintypes as wt
|
||||||
|
import logging
|
||||||
|
import re
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
from typing import Callable
|
||||||
|
|
||||||
|
from kurgan.hw.protocol import READ_TIMEOUT, TOO_LARGE, LineBuffer, ProtocolError, encode_error
|
||||||
|
|
||||||
|
log = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||||
|
_adv = ctypes.WinDLL("advapi32", use_last_error=True)
|
||||||
|
|
||||||
|
ERROR_FILE_NOT_FOUND = 2
|
||||||
|
ERROR_ACCESS_DENIED = 5
|
||||||
|
ERROR_BROKEN_PIPE = 109
|
||||||
|
ERROR_PIPE_BUSY = 231
|
||||||
|
ERROR_NO_DATA = 232
|
||||||
|
ERROR_MORE_DATA = 234
|
||||||
|
ERROR_PIPE_CONNECTED = 535
|
||||||
|
ERROR_OPERATION_ABORTED = 995
|
||||||
|
ERROR_IO_PENDING = 997
|
||||||
|
WAIT_OBJECT_0, WAIT_TIMEOUT = 0, 0x102
|
||||||
|
INFINITE = 0xFFFFFFFF
|
||||||
|
INVALID_HANDLE = wt.HANDLE(-1).value
|
||||||
|
|
||||||
|
PIPE_ACCESS_DUPLEX = 0x3
|
||||||
|
FILE_FLAG_OVERLAPPED = 0x40000000
|
||||||
|
FILE_FLAG_FIRST_PIPE_INSTANCE = 0x00080000
|
||||||
|
PIPE_TYPE_BYTE = PIPE_READMODE_BYTE = PIPE_WAIT = 0
|
||||||
|
PIPE_REJECT_REMOTE_CLIENTS = 0x8
|
||||||
|
GENERIC_READ = 0x80000000
|
||||||
|
FILE_WRITE_DATA = 0x2
|
||||||
|
OPEN_EXISTING = 3
|
||||||
|
SECURITY_SQOS_PRESENT = 0x00100000
|
||||||
|
SECURITY_IDENTIFICATION = 0x00010000
|
||||||
|
SE_KERNEL_OBJECT = 6
|
||||||
|
OWNER_SECURITY_INFORMATION = 0x1
|
||||||
|
TOKEN_QUERY, TOKEN_USER = 0x8, 1
|
||||||
|
|
||||||
|
# What the installing user gets on the pipe: FILE_GENERIC_READ | FILE_WRITE_DATA |
|
||||||
|
# FILE_WRITE_ATTRIBUTES. Deliberately not GENERIC_WRITE, which includes FILE_APPEND_DATA, i.e.
|
||||||
|
# FILE_CREATE_PIPE_INSTANCE for a pipe.
|
||||||
|
USER_ACCESS = 0x0012018B
|
||||||
|
SYSTEM_SID, ADMINISTRATORS_SID = "S-1-5-18", "S-1-5-32-544"
|
||||||
|
TRUSTED_OWNERS = (SYSTEM_SID, ADMINISTRATORS_SID)
|
||||||
|
BUFFER_SIZE = 128 * 1024
|
||||||
|
_SID = re.compile(r"S-1-\d+(-\d+)+")
|
||||||
|
|
||||||
|
|
||||||
|
class _Overlapped(ctypes.Structure):
|
||||||
|
_fields_ = [("Internal", ctypes.c_size_t), ("InternalHigh", ctypes.c_size_t),
|
||||||
|
("Offset", wt.DWORD), ("OffsetHigh", wt.DWORD), ("hEvent", wt.HANDLE)]
|
||||||
|
|
||||||
|
|
||||||
|
class _SecurityAttributes(ctypes.Structure):
|
||||||
|
_fields_ = [("nLength", wt.DWORD), ("lpSecurityDescriptor", ctypes.c_void_p), ("bInheritHandle", wt.BOOL)]
|
||||||
|
|
||||||
|
|
||||||
|
class _SidAndAttributes(ctypes.Structure):
|
||||||
|
_fields_ = [("Sid", ctypes.c_void_p), ("Attributes", wt.DWORD)]
|
||||||
|
|
||||||
|
|
||||||
|
_k32.CreateNamedPipeW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, wt.DWORD, wt.DWORD, wt.DWORD, wt.DWORD,
|
||||||
|
ctypes.POINTER(_SecurityAttributes)]
|
||||||
|
_k32.CreateNamedPipeW.restype = wt.HANDLE
|
||||||
|
_k32.ConnectNamedPipe.argtypes = [wt.HANDLE, ctypes.POINTER(_Overlapped)]
|
||||||
|
_k32.ConnectNamedPipe.restype = wt.BOOL
|
||||||
|
_k32.CreateFileW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.c_void_p, wt.DWORD, wt.DWORD, wt.HANDLE]
|
||||||
|
_k32.CreateFileW.restype = wt.HANDLE
|
||||||
|
_k32.WaitNamedPipeW.argtypes = [wt.LPCWSTR, wt.DWORD]
|
||||||
|
_k32.WaitNamedPipeW.restype = wt.BOOL
|
||||||
|
_k32.ReadFile.argtypes = [wt.HANDLE, ctypes.c_void_p, wt.DWORD, ctypes.POINTER(wt.DWORD), ctypes.POINTER(_Overlapped)]
|
||||||
|
_k32.ReadFile.restype = wt.BOOL
|
||||||
|
_k32.WriteFile.argtypes = [wt.HANDLE, ctypes.c_void_p, wt.DWORD, ctypes.POINTER(wt.DWORD), ctypes.POINTER(_Overlapped)]
|
||||||
|
_k32.WriteFile.restype = wt.BOOL
|
||||||
|
_k32.GetOverlappedResult.argtypes = [wt.HANDLE, ctypes.POINTER(_Overlapped), ctypes.POINTER(wt.DWORD), wt.BOOL]
|
||||||
|
_k32.GetOverlappedResult.restype = wt.BOOL
|
||||||
|
_k32.CancelIoEx.argtypes = [wt.HANDLE, ctypes.POINTER(_Overlapped)]
|
||||||
|
_k32.CancelIoEx.restype = wt.BOOL
|
||||||
|
_k32.CreateEventW.argtypes = [ctypes.c_void_p, wt.BOOL, wt.BOOL, wt.LPCWSTR]
|
||||||
|
_k32.CreateEventW.restype = wt.HANDLE
|
||||||
|
_k32.SetEvent.argtypes = [wt.HANDLE]
|
||||||
|
_k32.SetEvent.restype = wt.BOOL
|
||||||
|
_k32.ResetEvent.argtypes = [wt.HANDLE]
|
||||||
|
_k32.ResetEvent.restype = wt.BOOL
|
||||||
|
_k32.WaitForSingleObject.argtypes = [wt.HANDLE, wt.DWORD]
|
||||||
|
_k32.WaitForSingleObject.restype = wt.DWORD
|
||||||
|
_k32.WaitForMultipleObjects.argtypes = [wt.DWORD, ctypes.POINTER(wt.HANDLE), wt.BOOL, wt.DWORD]
|
||||||
|
_k32.WaitForMultipleObjects.restype = wt.DWORD
|
||||||
|
_k32.CloseHandle.argtypes = [wt.HANDLE]
|
||||||
|
_k32.CloseHandle.restype = wt.BOOL
|
||||||
|
_k32.LocalFree.argtypes = [ctypes.c_void_p]
|
||||||
|
_k32.LocalFree.restype = ctypes.c_void_p
|
||||||
|
_k32.GetCurrentProcess.restype = wt.HANDLE
|
||||||
|
_adv.ConvertStringSecurityDescriptorToSecurityDescriptorW.argtypes = [
|
||||||
|
wt.LPCWSTR, wt.DWORD, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(wt.ULONG)]
|
||||||
|
_adv.ConvertStringSecurityDescriptorToSecurityDescriptorW.restype = wt.BOOL
|
||||||
|
_adv.ConvertSidToStringSidW.argtypes = [ctypes.c_void_p, ctypes.POINTER(wt.LPWSTR)]
|
||||||
|
_adv.ConvertSidToStringSidW.restype = wt.BOOL
|
||||||
|
_adv.GetSecurityInfo.argtypes = [wt.HANDLE, ctypes.c_int, wt.DWORD, ctypes.POINTER(ctypes.c_void_p),
|
||||||
|
ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_void_p),
|
||||||
|
ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_void_p)]
|
||||||
|
_adv.GetSecurityInfo.restype = wt.DWORD
|
||||||
|
_adv.OpenProcessToken.argtypes = [wt.HANDLE, wt.DWORD, ctypes.POINTER(wt.HANDLE)]
|
||||||
|
_adv.OpenProcessToken.restype = wt.BOOL
|
||||||
|
_adv.GetTokenInformation.argtypes = [wt.HANDLE, ctypes.c_int, ctypes.c_void_p, wt.DWORD, ctypes.POINTER(wt.DWORD)]
|
||||||
|
_adv.GetTokenInformation.restype = wt.BOOL
|
||||||
|
|
||||||
|
|
||||||
|
class PipeError(OSError):
|
||||||
|
"""The pipe couldn't be opened, read or written; .code is the Windows error, when there was one."""
|
||||||
|
|
||||||
|
def __init__(self, message: str, code: int | None = None):
|
||||||
|
super().__init__(message)
|
||||||
|
self.code = code
|
||||||
|
|
||||||
|
|
||||||
|
def _error(what: str, code: int | None = None) -> PipeError:
|
||||||
|
code = ctypes.get_last_error() if code is None else code
|
||||||
|
return PipeError(f"{what}: [{code}] {ctypes.FormatError(code).strip()}", code)
|
||||||
|
|
||||||
|
|
||||||
|
def _sid_string(sid: int) -> str:
|
||||||
|
text = wt.LPWSTR()
|
||||||
|
if not _adv.ConvertSidToStringSidW(sid, ctypes.byref(text)):
|
||||||
|
raise _error("ConvertSidToStringSid")
|
||||||
|
try:
|
||||||
|
return text.value
|
||||||
|
finally:
|
||||||
|
_k32.LocalFree(text)
|
||||||
|
|
||||||
|
|
||||||
|
def current_user_sid() -> str:
|
||||||
|
"""This process's user SID, e.g. S-1-5-21-...-1001."""
|
||||||
|
token = wt.HANDLE()
|
||||||
|
if not _adv.OpenProcessToken(_k32.GetCurrentProcess(), TOKEN_QUERY, ctypes.byref(token)):
|
||||||
|
raise _error("OpenProcessToken")
|
||||||
|
try:
|
||||||
|
size = wt.DWORD()
|
||||||
|
_adv.GetTokenInformation(token, TOKEN_USER, None, 0, ctypes.byref(size))
|
||||||
|
buf = ctypes.create_string_buffer(size.value)
|
||||||
|
if not _adv.GetTokenInformation(token, TOKEN_USER, buf, size, ctypes.byref(size)):
|
||||||
|
raise _error("GetTokenInformation(TokenUser)")
|
||||||
|
return _sid_string(_SidAndAttributes.from_buffer(buf).Sid)
|
||||||
|
finally:
|
||||||
|
_k32.CloseHandle(token)
|
||||||
|
|
||||||
|
|
||||||
|
def valid_sid(text: object) -> bool:
|
||||||
|
return isinstance(text, str) and _SID.fullmatch(text) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def pipe_sddl(user_sid: str | None, server_sid: str | None = None) -> str:
|
||||||
|
"""The pipe's access list: SYSTEM and Administrators full, `user_sid` read/write, nobody else.
|
||||||
|
|
||||||
|
server_sid also gets full access; only for a server that isn't SYSTEM or an elevated admin
|
||||||
|
(tests), since creating each further instance of the pipe needs FILE_CREATE_PIPE_INSTANCE."""
|
||||||
|
aces = ["(A;;GA;;;SY)", "(A;;GA;;;BA)"]
|
||||||
|
for sid, access in ((server_sid, "GA"), (user_sid, f"0x{USER_ACCESS:x}")):
|
||||||
|
if sid is not None:
|
||||||
|
if not valid_sid(sid):
|
||||||
|
raise ValueError(f"not a SID: {sid!r}")
|
||||||
|
aces.append(f"(A;;{access};;;{sid})")
|
||||||
|
return "D:P" + "".join(aces)
|
||||||
|
|
||||||
|
|
||||||
|
def pipe_owner(handle) -> str:
|
||||||
|
owner, descriptor = ctypes.c_void_p(), ctypes.c_void_p()
|
||||||
|
code = _adv.GetSecurityInfo(handle, SE_KERNEL_OBJECT, OWNER_SECURITY_INFORMATION, ctypes.byref(owner),
|
||||||
|
None, None, None, ctypes.byref(descriptor))
|
||||||
|
if code != 0:
|
||||||
|
raise _error("GetSecurityInfo", code)
|
||||||
|
try:
|
||||||
|
return _sid_string(owner.value)
|
||||||
|
finally:
|
||||||
|
_k32.LocalFree(descriptor)
|
||||||
|
|
||||||
|
|
||||||
|
def _event() -> wt.HANDLE:
|
||||||
|
event = _k32.CreateEventW(None, True, False, None)
|
||||||
|
if not event:
|
||||||
|
raise _error("CreateEvent")
|
||||||
|
return event
|
||||||
|
|
||||||
|
|
||||||
|
def _ms(seconds: float | None) -> int:
|
||||||
|
return INFINITE if seconds is None else max(0, min(int(seconds * 1000), INFINITE - 1))
|
||||||
|
|
||||||
|
|
||||||
|
def _finish(handle, ov: _Overlapped, events: list, timeout: float | None) -> int | None:
|
||||||
|
"""Wait for a pending overlapped call: bytes transferred, or None if it timed out or another
|
||||||
|
event (a stop request) fired first, in which case the call is cancelled and waited for, so
|
||||||
|
its buffer and OVERLAPPED can be freed. Raises PipeError if the call failed."""
|
||||||
|
handles = (wt.HANDLE * (1 + len(events)))(ov.hEvent, *events)
|
||||||
|
which = _k32.WaitForMultipleObjects(len(handles), handles, False, _ms(timeout))
|
||||||
|
done = wt.DWORD()
|
||||||
|
if which != WAIT_OBJECT_0:
|
||||||
|
_k32.CancelIoEx(handle, ctypes.byref(ov))
|
||||||
|
if _k32.GetOverlappedResult(handle, ctypes.byref(ov), ctypes.byref(done), True):
|
||||||
|
return done.value # it completed before the cancel landed
|
||||||
|
return None
|
||||||
|
if not _k32.GetOverlappedResult(handle, ctypes.byref(ov), ctypes.byref(done), False):
|
||||||
|
code = ctypes.get_last_error()
|
||||||
|
if code == ERROR_MORE_DATA:
|
||||||
|
return done.value
|
||||||
|
raise _error("pipe I/O", code)
|
||||||
|
return done.value
|
||||||
|
|
||||||
|
|
||||||
|
def _read(handle, event, timeout: float | None, stop_events=(), size: int = 65536) -> bytes | None:
|
||||||
|
"""Up to `size` bytes; b"" when the other end has closed; None on timeout or stop."""
|
||||||
|
buf = ctypes.create_string_buffer(size)
|
||||||
|
ov = _Overlapped(hEvent=event)
|
||||||
|
_k32.ResetEvent(event)
|
||||||
|
if not _k32.ReadFile(handle, buf, size, None, ctypes.byref(ov)):
|
||||||
|
code = ctypes.get_last_error()
|
||||||
|
if code in (ERROR_BROKEN_PIPE, ERROR_NO_DATA):
|
||||||
|
return b""
|
||||||
|
if code not in (ERROR_IO_PENDING, ERROR_MORE_DATA):
|
||||||
|
raise _error("ReadFile", code)
|
||||||
|
try:
|
||||||
|
got = _finish(handle, ov, list(stop_events), timeout)
|
||||||
|
except PipeError as e:
|
||||||
|
if e.code in (ERROR_BROKEN_PIPE, ERROR_NO_DATA, ERROR_OPERATION_ABORTED):
|
||||||
|
return b""
|
||||||
|
raise
|
||||||
|
return None if got is None else buf.raw[:got]
|
||||||
|
|
||||||
|
|
||||||
|
def _write(handle, event, data: bytes, timeout: float, stop_events=()) -> None:
|
||||||
|
buf = ctypes.create_string_buffer(data, len(data))
|
||||||
|
ov = _Overlapped(hEvent=event)
|
||||||
|
_k32.ResetEvent(event)
|
||||||
|
if not _k32.WriteFile(handle, buf, len(data), None, ctypes.byref(ov)):
|
||||||
|
code = ctypes.get_last_error()
|
||||||
|
if code != ERROR_IO_PENDING:
|
||||||
|
raise _error("WriteFile", code)
|
||||||
|
sent = _finish(handle, ov, list(stop_events), timeout)
|
||||||
|
if sent is None:
|
||||||
|
raise PipeError("pipe write timed out (the other end isn't reading)")
|
||||||
|
if sent != len(data):
|
||||||
|
raise PipeError(f"pipe write sent {sent} of {len(data)} bytes")
|
||||||
|
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------------------- server
|
||||||
|
|
||||||
|
class PipeServer:
|
||||||
|
"""Serves `session_factory()` sessions (protocol.Session) on a named pipe, one thread each."""
|
||||||
|
|
||||||
|
def __init__(self, name: str, sddl: str, session_factory: Callable, *, max_clients: int = 8,
|
||||||
|
read_timeout: float = READ_TIMEOUT, write_timeout: float = 5.0):
|
||||||
|
self.name = name
|
||||||
|
self.max_clients = max_clients
|
||||||
|
self.read_timeout = read_timeout
|
||||||
|
self.write_timeout = write_timeout
|
||||||
|
self._sessions = session_factory
|
||||||
|
self._descriptor = ctypes.c_void_p()
|
||||||
|
if not _adv.ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl, 1, ctypes.byref(self._descriptor),
|
||||||
|
None):
|
||||||
|
raise _error(f"Invalid pipe security descriptor {sddl!r}")
|
||||||
|
self._attributes = _SecurityAttributes(ctypes.sizeof(_SecurityAttributes), self._descriptor, False)
|
||||||
|
self._stop = _event()
|
||||||
|
self._stopping = False
|
||||||
|
self._lock = threading.Condition()
|
||||||
|
self._clients = 0
|
||||||
|
self._threads: list[threading.Thread] = []
|
||||||
|
self._listener: threading.Thread | None = None
|
||||||
|
self.error: str | None = None # why the pipe can't be created right now, for the snapshot
|
||||||
|
|
||||||
|
def start(self) -> None:
|
||||||
|
self._listener = threading.Thread(target=self._listen, name="hw-pipe", daemon=True)
|
||||||
|
self._listener.start()
|
||||||
|
|
||||||
|
def close(self, timeout: float = 5.0) -> None:
|
||||||
|
self._stopping = True
|
||||||
|
_k32.SetEvent(self._stop)
|
||||||
|
with self._lock:
|
||||||
|
self._lock.notify_all()
|
||||||
|
deadline = time.monotonic() + timeout
|
||||||
|
for thread in [self._listener, *list(self._threads)]:
|
||||||
|
if thread is not None:
|
||||||
|
thread.join(max(0.0, deadline - time.monotonic()))
|
||||||
|
if self._descriptor and not (self._listener is not None and self._listener.is_alive()):
|
||||||
|
_k32.LocalFree(self._descriptor)
|
||||||
|
self._descriptor = ctypes.c_void_p()
|
||||||
|
|
||||||
|
@property
|
||||||
|
def clients(self) -> int:
|
||||||
|
with self._lock:
|
||||||
|
return self._clients
|
||||||
|
|
||||||
|
def _create(self) -> wt.HANDLE | None:
|
||||||
|
with self._lock:
|
||||||
|
first = self._clients == 0
|
||||||
|
mode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | (FILE_FLAG_FIRST_PIPE_INSTANCE if first else 0)
|
||||||
|
handle = _k32.CreateNamedPipeW(self.name, mode, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT
|
||||||
|
| PIPE_REJECT_REMOTE_CLIENTS, self.max_clients, BUFFER_SIZE, BUFFER_SIZE,
|
||||||
|
0, ctypes.byref(self._attributes))
|
||||||
|
if handle == INVALID_HANDLE or not handle:
|
||||||
|
code = ctypes.get_last_error()
|
||||||
|
hint = (" (another program holds the pipe's name)" if code == ERROR_ACCESS_DENIED and first
|
||||||
|
else "")
|
||||||
|
message = f"can't create {self.name}: [{code}] {ctypes.FormatError(code).strip()}{hint}"
|
||||||
|
if message != self.error:
|
||||||
|
log.error("Pipe server %s; retrying", message)
|
||||||
|
self.error = message
|
||||||
|
return None
|
||||||
|
if self.error is not None:
|
||||||
|
log.info("Pipe server listening on %s again", self.name)
|
||||||
|
self.error = None
|
||||||
|
return handle
|
||||||
|
|
||||||
|
def _listen(self) -> None:
|
||||||
|
event = _event()
|
||||||
|
try:
|
||||||
|
while not self._stopping:
|
||||||
|
with self._lock:
|
||||||
|
if self._clients >= self.max_clients: # wait for a slot (each times out eventually)
|
||||||
|
self._lock.wait(0.5)
|
||||||
|
continue
|
||||||
|
handle = self._create()
|
||||||
|
if handle is None:
|
||||||
|
if _k32.WaitForSingleObject(self._stop, 5000) == WAIT_OBJECT_0:
|
||||||
|
break
|
||||||
|
continue
|
||||||
|
ov = _Overlapped(hEvent=event)
|
||||||
|
_k32.ResetEvent(event)
|
||||||
|
connected = bool(_k32.ConnectNamedPipe(handle, ctypes.byref(ov)))
|
||||||
|
if not connected:
|
||||||
|
code = ctypes.get_last_error()
|
||||||
|
if code == ERROR_PIPE_CONNECTED:
|
||||||
|
connected = True
|
||||||
|
elif code == ERROR_IO_PENDING:
|
||||||
|
try:
|
||||||
|
connected = _finish(handle, ov, [self._stop], None) is not None
|
||||||
|
except PipeError as e:
|
||||||
|
log.debug("Pipe connect failed: %s", e)
|
||||||
|
else:
|
||||||
|
log.debug("ConnectNamedPipe failed: [%d]", code)
|
||||||
|
if not connected or self._stopping:
|
||||||
|
_k32.CloseHandle(handle)
|
||||||
|
continue
|
||||||
|
with self._lock:
|
||||||
|
self._clients += 1
|
||||||
|
thread = threading.Thread(target=self._serve, args=(handle,), name="hw-pipe-client", daemon=True)
|
||||||
|
self._threads = [t for t in self._threads if t.is_alive()] + [thread]
|
||||||
|
thread.start()
|
||||||
|
except Exception:
|
||||||
|
log.exception("Pipe listener failed")
|
||||||
|
self.error = "pipe listener failed; see the service log"
|
||||||
|
finally:
|
||||||
|
_k32.CloseHandle(event)
|
||||||
|
|
||||||
|
def _serve(self, handle) -> None:
|
||||||
|
read_event, write_event = _event(), _event()
|
||||||
|
session = self._sessions()
|
||||||
|
buffer = LineBuffer()
|
||||||
|
line_started: float | None = None
|
||||||
|
try:
|
||||||
|
while not self._stopping:
|
||||||
|
now = time.monotonic()
|
||||||
|
deadline = (line_started or now) + self.read_timeout
|
||||||
|
data = _read(handle, read_event, max(0.0, deadline - now), [self._stop])
|
||||||
|
if not data: # closed, timed out (silent too long, or a line left unfinished), or stopping
|
||||||
|
if data is None and not self._stopping:
|
||||||
|
log.debug("Dropping a pipe client that sent nothing for %.0f s", self.read_timeout)
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
lines = buffer.feed(data)
|
||||||
|
except ProtocolError as e:
|
||||||
|
_write(handle, write_event, encode_error(None, TOO_LARGE, str(e)), self.write_timeout,
|
||||||
|
[self._stop])
|
||||||
|
return
|
||||||
|
line_started = (line_started or time.monotonic()) if buffer.partial else None
|
||||||
|
for line in lines:
|
||||||
|
reply, close = session.handle(line)
|
||||||
|
_write(handle, write_event, reply, self.write_timeout, [self._stop])
|
||||||
|
if close:
|
||||||
|
return
|
||||||
|
except PipeError as e:
|
||||||
|
log.debug("Pipe client dropped: %s", e)
|
||||||
|
except Exception:
|
||||||
|
log.exception("Pipe client failed")
|
||||||
|
finally:
|
||||||
|
# No DisconnectNamedPipe: it would discard a last reply the client hasn't read yet.
|
||||||
|
_k32.CloseHandle(handle)
|
||||||
|
for event in (read_event, write_event):
|
||||||
|
_k32.CloseHandle(event)
|
||||||
|
with self._lock:
|
||||||
|
self._clients -= 1
|
||||||
|
self._lock.notify_all()
|
||||||
|
|
||||||
|
|
||||||
|
# ----------------------------------------------------------------------------- client
|
||||||
|
|
||||||
|
class PipeClient:
|
||||||
|
"""One connection to the service. Not thread-safe: callers serialise request()."""
|
||||||
|
|
||||||
|
def __init__(self, name: str, timeout: float = 2.0, trusted_owners: tuple[str, ...] | None = TRUSTED_OWNERS):
|
||||||
|
deadline = time.monotonic() + timeout
|
||||||
|
while True:
|
||||||
|
handle = _k32.CreateFileW(name, GENERIC_READ | FILE_WRITE_DATA, 0, None, OPEN_EXISTING,
|
||||||
|
FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION, None)
|
||||||
|
if handle != INVALID_HANDLE and handle:
|
||||||
|
break
|
||||||
|
code = ctypes.get_last_error()
|
||||||
|
left = deadline - time.monotonic()
|
||||||
|
if code == ERROR_PIPE_BUSY and left > 0:
|
||||||
|
_k32.WaitNamedPipeW(name, max(1, int(left * 1000)))
|
||||||
|
continue
|
||||||
|
if code == ERROR_FILE_NOT_FOUND:
|
||||||
|
raise _error("the hardware service isn't running (no pipe)", code)
|
||||||
|
if code == ERROR_ACCESS_DENIED:
|
||||||
|
raise _error("the hardware service's pipe refused this user", code)
|
||||||
|
raise _error(f"can't open {name}", code)
|
||||||
|
self._handle = handle
|
||||||
|
self._read_event, self._write_event = _event(), _event()
|
||||||
|
self._buffer = LineBuffer()
|
||||||
|
self._lines: list[bytes] = []
|
||||||
|
if trusted_owners is not None:
|
||||||
|
try:
|
||||||
|
owner = pipe_owner(handle)
|
||||||
|
except OSError:
|
||||||
|
self.close()
|
||||||
|
raise
|
||||||
|
if owner not in trusted_owners:
|
||||||
|
self.close()
|
||||||
|
raise PipeError(f"{name} belongs to {owner}, not the hardware service; not using it")
|
||||||
|
|
||||||
|
def request(self, data: bytes, timeout: float) -> bytes:
|
||||||
|
"""Send one line, return the next line received (without its newline)."""
|
||||||
|
if self._handle is None:
|
||||||
|
raise PipeError("pipe closed")
|
||||||
|
deadline = time.monotonic() + timeout
|
||||||
|
_write(self._handle, self._write_event, data, timeout)
|
||||||
|
while not self._lines:
|
||||||
|
left = deadline - time.monotonic()
|
||||||
|
chunk = _read(self._handle, self._read_event, max(0.0, left)) if left > 0 else None
|
||||||
|
if chunk is None:
|
||||||
|
raise PipeError(f"no reply from the hardware service within {timeout:g} s")
|
||||||
|
if not chunk:
|
||||||
|
raise _error("the hardware service closed the connection", ERROR_BROKEN_PIPE)
|
||||||
|
self._lines += self._buffer.feed(chunk)
|
||||||
|
return self._lines.pop(0)
|
||||||
|
|
||||||
|
def close(self) -> None:
|
||||||
|
for name in ("_handle", "_read_event", "_write_event"):
|
||||||
|
handle = getattr(self, name, None)
|
||||||
|
if handle:
|
||||||
|
_k32.CloseHandle(handle)
|
||||||
|
setattr(self, name, None)
|
||||||
|
|
||||||
|
def __del__(self):
|
||||||
|
try:
|
||||||
|
self.close()
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
import ctypes
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import unittest
|
||||||
|
import uuid
|
||||||
|
|
||||||
|
from kurgan.ai.launcher import token_info
|
||||||
|
from kurgan.hw import pipe
|
||||||
|
from kurgan.hw.protocol import MAX_MESSAGE, PROTOCOL_VERSION, Session, decode_reply, encode_request
|
||||||
|
from kurgan.hw.pipe import PipeClient, PipeError, PipeServer, current_user_sid, pipe_sddl
|
||||||
|
|
||||||
|
ME = current_user_sid()
|
||||||
|
ELEVATED = token_info()["elevated"]
|
||||||
|
|
||||||
|
|
||||||
|
def pipe_name() -> str:
|
||||||
|
return rf"\\.\pipe\kurgan-hw-test-{os.getpid()}-{uuid.uuid4().hex[:8]}"
|
||||||
|
|
||||||
|
|
||||||
|
class Calls:
|
||||||
|
def __init__(self):
|
||||||
|
self.ops = []
|
||||||
|
self.threads = set()
|
||||||
|
self.lock = threading.Lock()
|
||||||
|
|
||||||
|
def dispatch(self, op, args):
|
||||||
|
with self.lock:
|
||||||
|
self.ops.append(op)
|
||||||
|
self.threads.add(threading.get_ident())
|
||||||
|
return {"op": op}
|
||||||
|
|
||||||
|
def session(self):
|
||||||
|
return Session(self.dispatch, "test")
|
||||||
|
|
||||||
|
|
||||||
|
def ask(client, op, args=None, request_id=1, timeout=2.0):
|
||||||
|
return decode_reply(client.request(encode_request(op, args, request_id), timeout), request_id)
|
||||||
|
|
||||||
|
|
||||||
|
def greet(client):
|
||||||
|
return ask(client, "hello", {"protocol": PROTOCOL_VERSION, "client": "test"}, 0)
|
||||||
|
|
||||||
|
|
||||||
|
class PipeTest(unittest.TestCase):
|
||||||
|
def serve(self, sddl=None, **options):
|
||||||
|
name = pipe_name()
|
||||||
|
calls = Calls()
|
||||||
|
server = PipeServer(name, sddl or pipe_sddl(ME, server_sid=ME), calls.session, **options)
|
||||||
|
server.start()
|
||||||
|
self.addCleanup(server.close)
|
||||||
|
return name, server, calls
|
||||||
|
|
||||||
|
def connect(self, name, **options):
|
||||||
|
options.setdefault("trusted_owners", None)
|
||||||
|
deadline = time.monotonic() + 2
|
||||||
|
while True: # the listener thread may not have created the pipe yet
|
||||||
|
try:
|
||||||
|
client = PipeClient(name, **options)
|
||||||
|
break
|
||||||
|
except PipeError as e:
|
||||||
|
if e.code != pipe.ERROR_FILE_NOT_FOUND or time.monotonic() > deadline:
|
||||||
|
raise
|
||||||
|
time.sleep(0.02)
|
||||||
|
self.addCleanup(client.close)
|
||||||
|
return client
|
||||||
|
|
||||||
|
def test_round_trip(self):
|
||||||
|
name, server, calls = self.serve()
|
||||||
|
client = self.connect(name)
|
||||||
|
self.assertEqual(greet(client), {"protocol": PROTOCOL_VERSION, "service": "test"})
|
||||||
|
self.assertEqual(ask(client, "state", request_id=2)["op"], "state")
|
||||||
|
self.assertEqual(ask(client, "set_profile", {"profile": "quiet"}, request_id=3)["op"], "set_profile")
|
||||||
|
self.assertEqual(calls.ops, ["state", "set_profile"])
|
||||||
|
|
||||||
|
def test_several_clients_at_once_each_on_its_own_thread(self):
|
||||||
|
name, server, calls = self.serve()
|
||||||
|
clients = [self.connect(name) for _ in range(3)]
|
||||||
|
for client in clients:
|
||||||
|
greet(client)
|
||||||
|
for i, client in enumerate(clients * 2): # interleaved: each gets its own replies
|
||||||
|
self.assertEqual(ask(client, "state", request_id=i)["op"], "state")
|
||||||
|
self.assertEqual(server.clients, 3)
|
||||||
|
self.assertEqual(len(calls.threads), 3)
|
||||||
|
|
||||||
|
def test_a_silent_client_is_dropped_without_affecting_the_others(self):
|
||||||
|
name, server, calls = self.serve(read_timeout=0.3)
|
||||||
|
silent = self.connect(name)
|
||||||
|
busy = self.connect(name)
|
||||||
|
greet(busy)
|
||||||
|
for i in range(5): # keeps talking, so keeps its connection
|
||||||
|
time.sleep(0.1)
|
||||||
|
ask(busy, "state", request_id=i)
|
||||||
|
with self.assertRaises(PipeError):
|
||||||
|
ask(silent, "state")
|
||||||
|
ask(busy, "state", request_id=99)
|
||||||
|
|
||||||
|
def test_a_line_left_unfinished_is_dropped_at_the_timeout(self):
|
||||||
|
name, server, calls = self.serve(read_timeout=0.4)
|
||||||
|
client = self.connect(name)
|
||||||
|
greet(client)
|
||||||
|
handle_event = pipe._event()
|
||||||
|
try:
|
||||||
|
for _ in range(6): # trickles a byte every 0.1 s but never ends the line
|
||||||
|
pipe._write(client._handle, handle_event, b" ", 1.0)
|
||||||
|
time.sleep(0.1)
|
||||||
|
except PipeError:
|
||||||
|
pass # already dropped
|
||||||
|
finally:
|
||||||
|
pipe._k32.CloseHandle(handle_event)
|
||||||
|
with self.assertRaises(PipeError):
|
||||||
|
ask(client, "state")
|
||||||
|
|
||||||
|
def test_an_oversized_line_gets_an_error_then_the_connection_closes(self):
|
||||||
|
name, server, calls = self.serve()
|
||||||
|
client = self.connect(name)
|
||||||
|
greet(client)
|
||||||
|
reply = json.loads(client.request(b"x" * (MAX_MESSAGE + 10) + b"\n", 2.0))
|
||||||
|
self.assertEqual((reply["ok"], reply["error"]["code"]), (False, "too_large"))
|
||||||
|
with self.assertRaises(PipeError):
|
||||||
|
ask(client, "state")
|
||||||
|
self.assertEqual(calls.ops, [])
|
||||||
|
|
||||||
|
def test_closing_the_server_ends_connections_promptly(self):
|
||||||
|
name, server, calls = self.serve()
|
||||||
|
client = self.connect(name)
|
||||||
|
greet(client)
|
||||||
|
started = time.monotonic()
|
||||||
|
server.close()
|
||||||
|
self.assertLess(time.monotonic() - started, 2)
|
||||||
|
with self.assertRaises(PipeError):
|
||||||
|
ask(client, "state")
|
||||||
|
|
||||||
|
def test_a_pipe_not_owned_by_system_or_administrators_is_refused(self):
|
||||||
|
name, server, calls = self.serve()
|
||||||
|
with self.assertRaisesRegex(PipeError, "not the hardware service"):
|
||||||
|
self.connect(name, trusted_owners=pipe.TRUSTED_OWNERS)
|
||||||
|
self.connect(name, trusted_owners=(ME,))
|
||||||
|
|
||||||
|
def test_no_service_means_a_clear_error(self):
|
||||||
|
with self.assertRaisesRegex(PipeError, "isn't running") as caught:
|
||||||
|
PipeClient(pipe_name(), timeout=0.1, trusted_owners=None)
|
||||||
|
self.assertEqual(caught.exception.code, pipe.ERROR_FILE_NOT_FOUND)
|
||||||
|
|
||||||
|
@unittest.skipIf(ELEVATED, "an elevated test process is an Administrator, which the pipe allows")
|
||||||
|
def test_a_user_not_on_the_access_list_is_refused(self):
|
||||||
|
other = "S-1-5-21-1000000001-1000000002-1000000003-1001"
|
||||||
|
name, server, calls = self.serve(sddl=pipe_sddl(other))
|
||||||
|
time.sleep(0.2)
|
||||||
|
with self.assertRaises(PipeError) as caught:
|
||||||
|
PipeClient(name, timeout=0.5, trusted_owners=None)
|
||||||
|
self.assertEqual(caught.exception.code, pipe.ERROR_ACCESS_DENIED)
|
||||||
|
|
||||||
|
@unittest.skipIf(ELEVATED, "an elevated test process is an Administrator, which may add instances")
|
||||||
|
def test_the_user_may_not_add_an_instance_of_the_pipe(self):
|
||||||
|
name, server, calls = self.serve(sddl=pipe_sddl(ME))
|
||||||
|
self.connect(name) # the user can connect ...
|
||||||
|
handle = pipe._k32.CreateNamedPipeW(name, pipe.PIPE_ACCESS_DUPLEX, 0, 8, 4096, 4096, 0, None)
|
||||||
|
error = ctypes.get_last_error()
|
||||||
|
if handle != pipe.INVALID_HANDLE:
|
||||||
|
pipe._k32.CloseHandle(handle)
|
||||||
|
self.assertEqual((handle, error), (pipe.INVALID_HANDLE, pipe.ERROR_ACCESS_DENIED)) # ... not serve it
|
||||||
|
|
||||||
|
def test_access_list(self):
|
||||||
|
self.assertEqual(pipe_sddl("S-1-5-21-1-2-3-1001"),
|
||||||
|
"D:P(A;;GA;;;SY)(A;;GA;;;BA)(A;;0x12018b;;;S-1-5-21-1-2-3-1001)")
|
||||||
|
self.assertEqual(pipe_sddl(None), "D:P(A;;GA;;;SY)(A;;GA;;;BA)")
|
||||||
|
for bad in ("BU", "WD", "S-1-5-21-1-2-3-1001)(A;;GA;;;WD", ""):
|
||||||
|
with self.subTest(bad=bad):
|
||||||
|
with self.assertRaises(ValueError):
|
||||||
|
pipe_sddl(bad)
|
||||||
|
self.assertEqual(pipe.USER_ACCESS & 0x4, 0) # FILE_CREATE_PIPE_INSTANCE
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
Reference in new issue
Block a user