Privilege split 7/11: launch the LLM servers as plain child processes

- kurgan/ai/launcher.py: the app is unelevated now, so the servers are
  started with CreateProcessW, still suspended into their own kill-on-close
  job object and with an explicit handle list (only the log and NUL are
  inherited). Gone: the copy of Explorer's token (CreateProcessWithTokenW),
  the Safer "normal user" token and CreateProcessAsUserW, and with them the
  AI service's wait for the desktop at logon.
- launch() refuses (PermissionError) if The Kurgan itself is elevated, rather
  than pass admin rights on to a model server; this also covers opening the
  browser.
- Tests: the handle list is checked for real (an inheritable, unlisted handle
  doesn't reach the child; a control run without the list leaks it), and an
  elevated app starts nothing. The launch tests skip when the suite itself
  runs elevated.
- The UI's server token label and the README's launcher paragraph follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
paulandClaude Opus 5.5 committed 2026-12-05 19:44:47 +13:00
1 parent eb771656fb
commit e583e25346
5 files changed
+76 -168

No files matched your search

+39 -159
View File
@@ -1,22 +1,14 @@
"""Start the AI servers as ordinary, non-elevated processes, even though The Kurgan runs elevated.
"""Start the AI servers as ordinary child processes, each in its own job object.
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.
The Kurgan runs without admin rights (only the hardware service, kurgan.hw, is elevated), so
its children are what any program the user starts would be: medium integrity, not elevated,
in the desktop's logon session. launch() refuses to start anything if The Kurgan itself has
been run elevated, rather than hand a model server admin rights.
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.
orphan holding VRAM or a port. stdout/stderr go to a log file, and an explicit handle list
means the log and NUL handles are all the child inherits.
"""
from __future__ import annotations
@@ -33,13 +25,8 @@ 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
@@ -61,9 +48,6 @@ 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):
@@ -105,18 +89,6 @@ class ExtendedLimits(ctypes.Structure):
("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]
@@ -125,11 +97,6 @@ _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,
@@ -158,18 +125,10 @@ _k32.UpdateProcThreadAttribute.argtypes = [ctypes.c_void_p, wt.DWORD, ctypes.c_s
_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
_k32.CreateProcessW.argtypes = [wt.LPCWSTR, wt.LPWSTR, wt.LPVOID, wt.LPVOID, wt.BOOL, wt.DWORD, wt.LPVOID,
wt.LPCWSTR, ctypes.c_void_p, ctypes.POINTER(ProcessInformation)]
_k32.CreateProcessW.restype = wt.BOOL
_launch_lock = threading.Lock()
@@ -180,31 +139,6 @@ def _check(ok, what: str):
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))
@@ -241,46 +175,6 @@ def elevated() -> bool:
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)
@@ -360,15 +254,17 @@ class ChildProcess:
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).
"""Start argv 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)."""
the returned handle (used to open the browser). OSError if this process is elevated."""
if elevated():
raise PermissionError("The Kurgan is running with admin rights, so it starts nothing (its children "
"would get them too); run it from its logon task, which setup.ps1 registers "
"without them")
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:
@@ -384,41 +280,26 @@ def launch(argv: list[str], cwd: str, log_path: str | None, env: dict[str, str]
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
flags = (CREATE_SUSPENDED | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT | CREATE_NEW_PROCESS_GROUP
| EXTENDED_STARTUPINFO_PRESENT)
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]}")
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) # all the child inherits
_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(_k32.CreateProcessW(None, command, None, None, True, flags, 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)
@@ -429,20 +310,19 @@ def launch(argv: list[str], cwd: str, log_path: str | None, env: dict[str, str]
_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 "")
log.info("Started %s (pid %s, %s integrity%s)", os.path.basename(argv[0]), child.pid,
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):
for handle in (out, nul, job):
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."""
"""Open a web page in the default browser (never elevated: launch() refuses if we are)."""
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)
-6
View File
@@ -121,7 +121,6 @@ class AiService:
self.action: str | None = None # "Loading model..." while a load/unload request runs
self.message: str | None = None
self._stop: threading.Event | None = None
self._born = time.monotonic()
def set_public_url(self, url: str) -> None:
"""The Kurgan's web server, which the links in the UI point to."""
@@ -356,11 +355,6 @@ class AiService:
return
if time.monotonic() < slot.hold_until:
return
# At logon The Kurgan can be up before Explorer; give the desktop up to 2 minutes so the
# server gets the desktop's own token (see launcher.py) rather than the fallback.
if time.monotonic() - self._born < 120 and not launcher.desktop_ready():
self.transition = f"Waiting for the desktop to start {slot.backend.label}"
return
problem = slot.backend.check_files()
if problem:
slot.error = problem
+1 -1
View File
@@ -763,7 +763,7 @@ function renderActive(ai) {
const st = b.model.state;
const adminLevel = b.token && ["high", "system"].includes(b.token.integrity);
const token = !b.token ? null : adminLevel ? `admin rights, ${b.token.integrity} integrity (unexpected)`
: `${b.token.elevated ? "restricted token" : "normal user"}, ${b.token.integrity} integrity`;
: `normal user, ${b.token.integrity} integrity`;
const kv = el("dl", { class: "kv" },
el("dt", { text: "Model" }), el("dd", { text: b.model.id ?? b.model_label }),
b.model.context ? [el("dt", { text: "Context" }), el("dd", { text: `${fmt.n0(b.model.context)} tokens` })] : null,