"""Start the AI servers as ordinary, non-elevated processes, even though The Kurgan runs elevated. The Kurgan needs admin rights for PawnIO (CPU sensors, top fans, RAM lighting), but the LLM servers never did: they ran from non-elevated tasks before. How a server is started: - The Kurgan elevated (the normal case): with a copy of the desktop shell's (Explorer's) own token, through CreateProcessWithTokenW. The server is then exactly what Explorer would have started: medium integrity, not elevated, in the desktop's logon session. - No desktop shell yet (just after logon; see desktop_ready) or The Kurgan not elevated (tests, --demo): a "normal user" token from the Safer API (Administrators made deny-only, admin privileges removed, medium integrity). Windows still counts that token as part of the elevated logon session, so the shell's token is preferred. Each server gets its own job object that kills everything in it when The Kurgan closes the job, including the model processes the server starts itself; a crashed Kurgan leaves no orphan holding VRAM or a port. stdout/stderr go to a log file. The Safer path passes an explicit handle list, so only the log and NUL handles are inherited. CreateProcessWithTokenW can't take one; Python makes its handles non-inheritable, and launches are serialised, so in practice the same two are all the child gets. """ from __future__ import annotations import ctypes import ctypes.wintypes as wt import logging import os import subprocess import threading log = logging.getLogger(__name__) _k32 = ctypes.WinDLL("kernel32", use_last_error=True) _adv = ctypes.WinDLL("advapi32", use_last_error=True) SAFER_SCOPEID_USER = 2 SAFER_LEVELID_NORMALUSER = 0x20000 SAFER_LEVEL_OPEN = 1 TOKEN_INTEGRITY_LEVEL = 25 TOKEN_ELEVATION = 20 SE_GROUP_INTEGRITY = 0x20 MEDIUM_INTEGRITY_SID = "S-1-16-8192" CREATE_SUSPENDED = 0x4 CREATE_NEW_PROCESS_GROUP = 0x200 CREATE_UNICODE_ENVIRONMENT = 0x400 EXTENDED_STARTUPINFO_PRESENT = 0x80000 CREATE_NO_WINDOW = 0x08000000 STARTF_USESHOWWINDOW, STARTF_USESTDHANDLES = 0x1, 0x100 SW_HIDE = 0 PROC_THREAD_ATTRIBUTE_HANDLE_LIST = 0x20002 JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000 JOB_OBJECT_EXTENDED_LIMIT_INFORMATION = 9 GENERIC_READ, GENERIC_WRITE = 0x80000000, 0x40000000 FILE_APPEND_DATA = 0x4 SYNCHRONIZE = 0x100000 FILE_SHARE_ALL = 0x7 OPEN_EXISTING, OPEN_ALWAYS = 3, 4 INVALID_HANDLE = wt.HANDLE(-1).value WAIT_OBJECT_0, WAIT_TIMEOUT = 0, 0x102 STILL_ACTIVE = 259 PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 TOKEN_QUERY = 0x8 TOKEN_ASSIGN_PRIMARY, TOKEN_DUPLICATE, TOKEN_ADJUST_DEFAULT, TOKEN_ADJUST_SESSIONID = 0x1, 0x2, 0x80, 0x100 SECURITY_IMPERSONATION, TOKEN_PRIMARY = 2, 1 ERROR_INVALID_PARAMETER = 87 class SecurityAttributes(ctypes.Structure): _fields_ = [("nLength", wt.DWORD), ("lpSecurityDescriptor", wt.LPVOID), ("bInheritHandle", wt.BOOL)] class StartupInfo(ctypes.Structure): _fields_ = [("cb", wt.DWORD), ("lpReserved", wt.LPWSTR), ("lpDesktop", wt.LPWSTR), ("lpTitle", wt.LPWSTR), ("dwX", wt.DWORD), ("dwY", wt.DWORD), ("dwXSize", wt.DWORD), ("dwYSize", wt.DWORD), ("dwXCountChars", wt.DWORD), ("dwYCountChars", wt.DWORD), ("dwFillAttribute", wt.DWORD), ("dwFlags", wt.DWORD), ("wShowWindow", wt.WORD), ("cbReserved2", wt.WORD), ("lpReserved2", ctypes.c_void_p), ("hStdInput", wt.HANDLE), ("hStdOutput", wt.HANDLE), ("hStdError", wt.HANDLE)] class StartupInfoEx(ctypes.Structure): _fields_ = [("StartupInfo", StartupInfo), ("lpAttributeList", ctypes.c_void_p)] class ProcessInformation(ctypes.Structure): _fields_ = [("hProcess", wt.HANDLE), ("hThread", wt.HANDLE), ("dwProcessId", wt.DWORD), ("dwThreadId", wt.DWORD)] class SidAndAttributes(ctypes.Structure): _fields_ = [("Sid", ctypes.c_void_p), ("Attributes", wt.DWORD)] class BasicLimits(ctypes.Structure): _fields_ = [("PerProcessUserTimeLimit", ctypes.c_int64), ("PerJobUserTimeLimit", ctypes.c_int64), ("LimitFlags", wt.DWORD), ("MinimumWorkingSetSize", ctypes.c_size_t), ("MaximumWorkingSetSize", ctypes.c_size_t), ("ActiveProcessLimit", wt.DWORD), ("Affinity", ctypes.c_size_t), ("PriorityClass", wt.DWORD), ("SchedulingClass", wt.DWORD)] class ExtendedLimits(ctypes.Structure): _fields_ = [("BasicLimitInformation", BasicLimits), ("IoInfo", ctypes.c_uint64 * 6), ("ProcessMemoryLimit", ctypes.c_size_t), ("JobMemoryLimit", ctypes.c_size_t), ("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", ctypes.c_size_t)] _adv.SaferCreateLevel.argtypes = [wt.DWORD, wt.DWORD, wt.DWORD, ctypes.POINTER(wt.HANDLE), wt.LPVOID] _adv.SaferCreateLevel.restype = wt.BOOL _adv.SaferComputeTokenFromLevel.argtypes = [wt.HANDLE, wt.HANDLE, ctypes.POINTER(wt.HANDLE), wt.DWORD, wt.LPVOID] _adv.SaferComputeTokenFromLevel.restype = wt.BOOL _adv.SaferCloseLevel.argtypes = [wt.HANDLE] _adv.SaferCloseLevel.restype = wt.BOOL _adv.ConvertStringSidToSidW.argtypes = [wt.LPCWSTR, ctypes.POINTER(ctypes.c_void_p)] _adv.ConvertStringSidToSidW.restype = wt.BOOL _adv.GetLengthSid.argtypes = [ctypes.c_void_p] _adv.GetLengthSid.restype = wt.DWORD _adv.SetTokenInformation.argtypes = [wt.HANDLE, ctypes.c_int, wt.LPVOID, wt.DWORD] _adv.SetTokenInformation.restype = wt.BOOL _adv.GetTokenInformation.argtypes = [wt.HANDLE, ctypes.c_int, wt.LPVOID, wt.DWORD, ctypes.POINTER(wt.DWORD)] _adv.GetTokenInformation.restype = wt.BOOL _adv.GetSidSubAuthorityCount.argtypes = [ctypes.c_void_p] _adv.GetSidSubAuthorityCount.restype = ctypes.POINTER(ctypes.c_ubyte) _adv.GetSidSubAuthority.argtypes = [ctypes.c_void_p, wt.DWORD] _adv.GetSidSubAuthority.restype = ctypes.POINTER(wt.DWORD) _adv.OpenProcessToken.argtypes = [wt.HANDLE, wt.DWORD, ctypes.POINTER(wt.HANDLE)] _adv.OpenProcessToken.restype = wt.BOOL _adv.CreateProcessAsUserW.argtypes = [wt.HANDLE, wt.LPCWSTR, wt.LPWSTR, wt.LPVOID, wt.LPVOID, wt.BOOL, wt.DWORD, wt.LPVOID, wt.LPCWSTR, ctypes.c_void_p, ctypes.POINTER(ProcessInformation)] _adv.CreateProcessAsUserW.restype = wt.BOOL _k32.LocalFree.argtypes = [wt.HLOCAL] _k32.LocalFree.restype = wt.HLOCAL _k32.CloseHandle.argtypes = [wt.HANDLE] _k32.CloseHandle.restype = wt.BOOL _k32.CreateFileW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.POINTER(SecurityAttributes), wt.DWORD, wt.DWORD, wt.HANDLE] _k32.CreateFileW.restype = wt.HANDLE _k32.CreateJobObjectW.argtypes = [wt.LPVOID, wt.LPCWSTR] _k32.CreateJobObjectW.restype = wt.HANDLE _k32.SetInformationJobObject.argtypes = [wt.HANDLE, ctypes.c_int, wt.LPVOID, wt.DWORD] _k32.SetInformationJobObject.restype = wt.BOOL _k32.AssignProcessToJobObject.argtypes = [wt.HANDLE, wt.HANDLE] _k32.AssignProcessToJobObject.restype = wt.BOOL _k32.TerminateJobObject.argtypes = [wt.HANDLE, wt.UINT] _k32.TerminateJobObject.restype = wt.BOOL _k32.TerminateProcess.argtypes = [wt.HANDLE, wt.UINT] _k32.TerminateProcess.restype = wt.BOOL _k32.ResumeThread.argtypes = [wt.HANDLE] _k32.ResumeThread.restype = wt.DWORD _k32.WaitForSingleObject.argtypes = [wt.HANDLE, wt.DWORD] _k32.WaitForSingleObject.restype = wt.DWORD _k32.GetExitCodeProcess.argtypes = [wt.HANDLE, ctypes.POINTER(wt.DWORD)] _k32.GetExitCodeProcess.restype = wt.BOOL _k32.InitializeProcThreadAttributeList.argtypes = [ctypes.c_void_p, wt.DWORD, wt.DWORD, ctypes.POINTER(ctypes.c_size_t)] _k32.InitializeProcThreadAttributeList.restype = wt.BOOL _k32.UpdateProcThreadAttribute.argtypes = [ctypes.c_void_p, wt.DWORD, ctypes.c_size_t, wt.LPVOID, ctypes.c_size_t, wt.LPVOID, wt.LPVOID] _k32.UpdateProcThreadAttribute.restype = wt.BOOL _k32.DeleteProcThreadAttributeList.argtypes = [ctypes.c_void_p] _k32.DeleteProcThreadAttributeList.restype = None _k32.OpenProcess.argtypes = [wt.DWORD, wt.BOOL, wt.DWORD] _k32.OpenProcess.restype = wt.HANDLE _k32.GetCurrentProcess.restype = wt.HANDLE _adv.DuplicateTokenEx.argtypes = [wt.HANDLE, wt.DWORD, wt.LPVOID, ctypes.c_int, ctypes.c_int, ctypes.POINTER(wt.HANDLE)] _adv.DuplicateTokenEx.restype = wt.BOOL _adv.CreateProcessWithTokenW.argtypes = [wt.HANDLE, wt.DWORD, wt.LPCWSTR, wt.LPWSTR, wt.DWORD, wt.LPVOID, wt.LPCWSTR, ctypes.c_void_p, ctypes.POINTER(ProcessInformation)] _adv.CreateProcessWithTokenW.restype = wt.BOOL _u32 = ctypes.WinDLL("user32", use_last_error=True) _u32.GetShellWindow.restype = wt.HWND _u32.GetWindowThreadProcessId.argtypes = [wt.HWND, ctypes.POINTER(wt.DWORD)] _u32.GetWindowThreadProcessId.restype = wt.DWORD _launch_lock = threading.Lock() def _check(ok, what: str): if not ok: raise ctypes.WinError(ctypes.get_last_error(), f"{what} failed") return ok def _normal_user_token() -> wt.HANDLE: """A primary token like this process's, minus admin rights, at medium integrity.""" level, token = wt.HANDLE(), wt.HANDLE() _check(_adv.SaferCreateLevel(SAFER_SCOPEID_USER, SAFER_LEVELID_NORMALUSER, SAFER_LEVEL_OPEN, ctypes.byref(level), None), "SaferCreateLevel") try: _check(_adv.SaferComputeTokenFromLevel(level, None, ctypes.byref(token), 0, None), "SaferComputeTokenFromLevel") finally: _adv.SaferCloseLevel(level) sid = ctypes.c_void_p() try: _check(_adv.ConvertStringSidToSidW(MEDIUM_INTEGRITY_SID, ctypes.byref(sid)), "ConvertStringSidToSid") label = SidAndAttributes(sid, SE_GROUP_INTEGRITY) _check(_adv.SetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, ctypes.byref(label), ctypes.sizeof(label) + _adv.GetLengthSid(sid)), "SetTokenInformation") except OSError: _k32.CloseHandle(token) raise finally: if sid: _k32.LocalFree(sid) return token def _describe_token(token: wt.HANDLE) -> dict: size = wt.DWORD() _adv.GetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, None, 0, ctypes.byref(size)) buf = ctypes.create_string_buffer(size.value) _check(_adv.GetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, buf, size, ctypes.byref(size)), "GetTokenInformation(IntegrityLevel)") sid = SidAndAttributes.from_buffer(buf).Sid rid = _adv.GetSidSubAuthority(sid, _adv.GetSidSubAuthorityCount(sid)[0] - 1)[0] elevated = wt.DWORD() _check(_adv.GetTokenInformation(token, TOKEN_ELEVATION, ctypes.byref(elevated), 4, ctypes.byref(size)), "GetTokenInformation(Elevation)") names = {0x1000: "low", 0x2000: "medium", 0x2100: "medium-plus", 0x3000: "high", 0x4000: "system"} return {"integrity": names.get(rid, hex(rid)), "elevated": bool(elevated.value)} def token_info(process_handle=None) -> dict: """{"integrity": "medium"|"high"|..., "elevated": bool} for a process (default: this one).""" token = wt.HANDLE() handle = process_handle if process_handle is not None else _k32.GetCurrentProcess() _check(_adv.OpenProcessToken(handle, TOKEN_QUERY, ctypes.byref(token)), "OpenProcessToken") try: return _describe_token(token) finally: _k32.CloseHandle(token) _ELEVATED: bool | None = None def elevated() -> bool: global _ELEVATED if _ELEVATED is None: _ELEVATED = token_info()["elevated"] return _ELEVATED def _desktop_token() -> wt.HANDLE | None: """A primary copy of the desktop shell's token, or None if there is no (non-elevated) shell.""" hwnd = _u32.GetShellWindow() if not hwnd: return None pid = wt.DWORD() _u32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid)) process = _k32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid.value) if not process: return None shell, token = wt.HANDLE(), wt.HANDLE() try: if not _adv.OpenProcessToken(process, TOKEN_DUPLICATE | TOKEN_QUERY, ctypes.byref(shell)): return None try: _check(_adv.DuplicateTokenEx(shell, TOKEN_QUERY | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID, None, SECURITY_IMPERSONATION, TOKEN_PRIMARY, ctypes.byref(token)), "DuplicateTokenEx") finally: _k32.CloseHandle(shell) finally: _k32.CloseHandle(process) if _describe_token(token)["elevated"]: # someone runs Explorer elevated: no better than our own _k32.CloseHandle(token) return None return token def desktop_ready() -> bool: """True once servers can be started with the desktop's own token (always true when not elevated).""" if not elevated(): return True token = _desktop_token() if token is None: return False _k32.CloseHandle(token) return True def _inheritable(path: str, access: int, disposition: int) -> wt.HANDLE: sa = SecurityAttributes(ctypes.sizeof(SecurityAttributes), None, True) handle = _k32.CreateFileW(path, access, FILE_SHARE_ALL, ctypes.byref(sa), disposition, 0x80, None) if handle == INVALID_HANDLE or not handle: raise ctypes.WinError(ctypes.get_last_error(), f"Opening {path} failed") return handle def _environment_block(env: dict[str, str]) -> ctypes.Array: items = sorted(env.items(), key=lambda kv: kv[0].upper()) text = "".join(f"{k}={v}\0" for k, v in items) + "\0" return ctypes.create_unicode_buffer(text, len(text)) def child_environment(extra: dict[str, str] | None = None) -> dict[str, str]: env = dict(os.environ) # The Kurgan pins OpenBLAS to one thread for itself (see kurgan/__init__.py); the servers get the default. if env.get("KURGAN_PINNED_OPENBLAS") == "1": env.pop("OPENBLAS_NUM_THREADS", None) env.pop("KURGAN_PINNED_OPENBLAS", None) env.update(extra or {}) return env class ChildProcess: """A launched server: poll/wait/kill like subprocess.Popen, plus the job it runs in.""" def __init__(self, pid: int, process: wt.HANDLE, job: wt.HANDLE, argv: list[str]): self.pid = pid self.argv = argv self._process = process self._job = job self.returncode: int | None = None try: self.token = token_info(process) except OSError as e: log.warning("Could not read the token of process %s: %s", pid, e) self.token = {"integrity": "unknown", "elevated": None} def poll(self) -> int | None: return self.wait(0) def wait(self, timeout: float | None = None) -> int | None: if self.returncode is not None: return self.returncode if self._process is None: return None ms = 0xFFFFFFFF if timeout is None else max(0, int(timeout * 1000)) if _k32.WaitForSingleObject(self._process, ms) != WAIT_OBJECT_0: return None code = wt.DWORD() _check(_k32.GetExitCodeProcess(self._process, ctypes.byref(code)), "GetExitCodeProcess") self.returncode = code.value return self.returncode def kill(self) -> None: """End the server and everything it started.""" if self._job: _k32.TerminateJobObject(self._job, 1) elif self._process: _k32.TerminateProcess(self._process, 1) def close(self) -> None: """Release the handles; closing the job also kills anything still in it.""" for name in ("_process", "_job"): handle = getattr(self, name) if handle: _k32.CloseHandle(handle) setattr(self, name, None) def __del__(self): try: self.close() except Exception: pass def launch(argv: list[str], cwd: str, log_path: str | None, env: dict[str, str] | None = None, contained: bool = True) -> ChildProcess: """Start argv as a normal user, windowless, with stdout/stderr appended to log_path (None: discarded). contained: put it in its own kill-on-close job (servers). Without it the process outlives the returned handle (used to open the browser).""" if log_path is not None: os.makedirs(os.path.dirname(log_path), exist_ok=True) with _launch_lock: desktop = _desktop_token() if elevated() else None token = desktop or _normal_user_token() job = out = nul = None attributes = None try: if contained: job = _check(_k32.CreateJobObjectW(None, None), "CreateJobObject") limits = ExtendedLimits() limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE _check(_k32.SetInformationJobObject(job, JOB_OBJECT_EXTENDED_LIMIT_INFORMATION, ctypes.byref(limits), ctypes.sizeof(limits)), "SetInformationJobObject") out = (_inheritable(log_path, FILE_APPEND_DATA | SYNCHRONIZE, OPEN_ALWAYS) if log_path is not None else _inheritable("NUL", GENERIC_WRITE, OPEN_EXISTING)) nul = _inheritable("NUL", GENERIC_READ, OPEN_EXISTING) command = ctypes.create_unicode_buffer(subprocess.list2cmdline(argv)) block = _environment_block(env if env is not None else child_environment()) flags = CREATE_SUSPENDED | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT | CREATE_NEW_PROCESS_GROUP pi = ProcessInformation() if desktop: info = StartupInfo() info.cb = ctypes.sizeof(StartupInfo) info.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW info.wShowWindow = SW_HIDE info.hStdInput, info.hStdOutput, info.hStdError = nul, out, out ok = _adv.CreateProcessWithTokenW(token, 0, None, command, flags, block, cwd, ctypes.byref(info), ctypes.byref(pi)) if not ok and ctypes.get_last_error() == ERROR_INVALID_PARAMETER: # Not every creation flag is accepted here; SW_HIDE still hides a console window. ok = _adv.CreateProcessWithTokenW(token, 0, None, command, flags & ~CREATE_NO_WINDOW, block, cwd, ctypes.byref(info), ctypes.byref(pi)) _check(ok, f"Starting {argv[0]}") else: size = ctypes.c_size_t() _k32.InitializeProcThreadAttributeList(None, 1, 0, ctypes.byref(size)) attributes = ctypes.create_string_buffer(size.value) _check(_k32.InitializeProcThreadAttributeList(attributes, 1, 0, ctypes.byref(size)), "InitializeProcThreadAttributeList") handles = (wt.HANDLE * 2)(out, nul) _check(_k32.UpdateProcThreadAttribute(attributes, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, handles, ctypes.sizeof(handles), None, None), "UpdateProcThreadAttribute") info = StartupInfoEx() info.StartupInfo.cb = ctypes.sizeof(StartupInfoEx) info.StartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW info.StartupInfo.wShowWindow = SW_HIDE info.StartupInfo.hStdInput, info.StartupInfo.hStdOutput, info.StartupInfo.hStdError = nul, out, out info.lpAttributeList = ctypes.cast(attributes, ctypes.c_void_p) _check(_adv.CreateProcessAsUserW(token, None, command, None, None, True, flags | EXTENDED_STARTUPINFO_PRESENT, block, cwd, ctypes.byref(info), ctypes.byref(pi)), f"Starting {argv[0]}") if job and not _k32.AssignProcessToJobObject(job, pi.hProcess): error = ctypes.WinError(ctypes.get_last_error(), "AssignProcessToJobObject failed") _k32.TerminateProcess(pi.hProcess, 1) _k32.CloseHandle(pi.hThread) _k32.CloseHandle(pi.hProcess) raise error _k32.ResumeThread(pi.hThread) _k32.CloseHandle(pi.hThread) child = ChildProcess(pi.dwProcessId, pi.hProcess, job, argv) job = None # owned by the child object now log.info("Started %s (pid %s, %s token, %s integrity%s)", os.path.basename(argv[0]), child.pid, "desktop" if desktop else "restricted", child.token["integrity"], ", ELEVATED" if child.token["elevated"] else "") return child finally: if attributes is not None: _k32.DeleteProcThreadAttributeList(attributes) for handle in (out, nul, job, token): if handle: _k32.CloseHandle(handle) def open_url(url: str) -> None: """Open a web page in the default browser as the normal user, never elevated.""" rundll = os.path.join(os.environ.get("SystemRoot", r"C:\Windows"), "System32", "rundll32.exe") child = launch([rundll, "url.dll,FileProtocolHandler", url], cwd=os.path.dirname(rundll), log_path=None, contained=False) child.close()