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:
1 parent
eb771656fb
commit
e583e25346
5 files changed
+76
-168
No files matched your search
@@ -45,8 +45,10 @@ Admin rights are needed for these readings and controls:
|
|||||||
- The RAM lighting
|
- The RAM lighting
|
||||||
|
|
||||||
Without admin rights those show `--` or stay idle, and everything else works. The LLM servers
|
Without admin rights those show `--` or stay idle, and everything else works. The LLM servers
|
||||||
always run as a normal user at medium integrity, never elevated, even though The Kurgan itself
|
are ordinary child processes of The Kurgan, each in a job object, at medium integrity: The
|
||||||
is elevated (see `kurgan/ai/launcher.py`). The web UI shows each server's integrity level.
|
Kurgan itself runs without admin rights, and if it is ever started elevated it refuses to start
|
||||||
|
them rather than pass admin rights on (see `kurgan/ai/launcher.py`). The web UI shows each
|
||||||
|
server's integrity level.
|
||||||
|
|
||||||
## Web UI
|
## Web UI
|
||||||
|
|
||||||
|
|||||||
+39
-159
@@ -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
|
The Kurgan runs without admin rights (only the hardware service, kurgan.hw, is elevated), so
|
||||||
servers never did: they ran from non-elevated tasks before. How a server is started:
|
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
|
||||||
- The Kurgan elevated (the normal case): with a copy of the desktop shell's (Explorer's) own
|
been run elevated, rather than hand a model server admin rights.
|
||||||
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
|
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
|
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
|
orphan holding VRAM or a port. stdout/stderr go to a log file, and an explicit handle list
|
||||||
handle list, so only the log and NUL handles are inherited. CreateProcessWithTokenW can't take
|
means the log and NUL handles are all the child inherits.
|
||||||
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
|
from __future__ import annotations
|
||||||
@@ -33,13 +25,8 @@ log = logging.getLogger(__name__)
|
|||||||
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
_k32 = ctypes.WinDLL("kernel32", use_last_error=True)
|
||||||
_adv = ctypes.WinDLL("advapi32", 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_INTEGRITY_LEVEL = 25
|
||||||
TOKEN_ELEVATION = 20
|
TOKEN_ELEVATION = 20
|
||||||
SE_GROUP_INTEGRITY = 0x20
|
|
||||||
MEDIUM_INTEGRITY_SID = "S-1-16-8192"
|
|
||||||
|
|
||||||
CREATE_SUSPENDED = 0x4
|
CREATE_SUSPENDED = 0x4
|
||||||
CREATE_NEW_PROCESS_GROUP = 0x200
|
CREATE_NEW_PROCESS_GROUP = 0x200
|
||||||
@@ -61,9 +48,6 @@ WAIT_OBJECT_0, WAIT_TIMEOUT = 0, 0x102
|
|||||||
STILL_ACTIVE = 259
|
STILL_ACTIVE = 259
|
||||||
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
|
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
|
||||||
TOKEN_QUERY = 0x8
|
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):
|
class SecurityAttributes(ctypes.Structure):
|
||||||
@@ -105,18 +89,6 @@ class ExtendedLimits(ctypes.Structure):
|
|||||||
("PeakProcessMemoryUsed", ctypes.c_size_t), ("PeakJobMemoryUsed", 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.argtypes = [wt.HANDLE, ctypes.c_int, wt.LPVOID, wt.DWORD, ctypes.POINTER(wt.DWORD)]
|
||||||
_adv.GetTokenInformation.restype = wt.BOOL
|
_adv.GetTokenInformation.restype = wt.BOOL
|
||||||
_adv.GetSidSubAuthorityCount.argtypes = [ctypes.c_void_p]
|
_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.GetSidSubAuthority.restype = ctypes.POINTER(wt.DWORD)
|
||||||
_adv.OpenProcessToken.argtypes = [wt.HANDLE, wt.DWORD, ctypes.POINTER(wt.HANDLE)]
|
_adv.OpenProcessToken.argtypes = [wt.HANDLE, wt.DWORD, ctypes.POINTER(wt.HANDLE)]
|
||||||
_adv.OpenProcessToken.restype = wt.BOOL
|
_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.argtypes = [wt.HANDLE]
|
||||||
_k32.CloseHandle.restype = wt.BOOL
|
_k32.CloseHandle.restype = wt.BOOL
|
||||||
_k32.CreateFileW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ctypes.POINTER(SecurityAttributes), wt.DWORD,
|
_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.UpdateProcThreadAttribute.restype = wt.BOOL
|
||||||
_k32.DeleteProcThreadAttributeList.argtypes = [ctypes.c_void_p]
|
_k32.DeleteProcThreadAttributeList.argtypes = [ctypes.c_void_p]
|
||||||
_k32.DeleteProcThreadAttributeList.restype = None
|
_k32.DeleteProcThreadAttributeList.restype = None
|
||||||
_k32.OpenProcess.argtypes = [wt.DWORD, wt.BOOL, wt.DWORD]
|
|
||||||
_k32.OpenProcess.restype = wt.HANDLE
|
|
||||||
_k32.GetCurrentProcess.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)]
|
_k32.CreateProcessW.argtypes = [wt.LPCWSTR, wt.LPWSTR, wt.LPVOID, wt.LPVOID, wt.BOOL, wt.DWORD, wt.LPVOID,
|
||||||
_adv.DuplicateTokenEx.restype = wt.BOOL
|
wt.LPCWSTR, ctypes.c_void_p, ctypes.POINTER(ProcessInformation)]
|
||||||
_adv.CreateProcessWithTokenW.argtypes = [wt.HANDLE, wt.DWORD, wt.LPCWSTR, wt.LPWSTR, wt.DWORD, wt.LPVOID, wt.LPCWSTR,
|
_k32.CreateProcessW.restype = wt.BOOL
|
||||||
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()
|
_launch_lock = threading.Lock()
|
||||||
|
|
||||||
@@ -180,31 +139,6 @@ def _check(ok, what: str):
|
|||||||
return ok
|
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:
|
def _describe_token(token: wt.HANDLE) -> dict:
|
||||||
size = wt.DWORD()
|
size = wt.DWORD()
|
||||||
_adv.GetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, None, 0, ctypes.byref(size))
|
_adv.GetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, None, 0, ctypes.byref(size))
|
||||||
@@ -241,46 +175,6 @@ def elevated() -> bool:
|
|||||||
return _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:
|
def _inheritable(path: str, access: int, disposition: int) -> wt.HANDLE:
|
||||||
sa = SecurityAttributes(ctypes.sizeof(SecurityAttributes), None, True)
|
sa = SecurityAttributes(ctypes.sizeof(SecurityAttributes), None, True)
|
||||||
handle = _k32.CreateFileW(path, access, FILE_SHARE_ALL, ctypes.byref(sa), disposition, 0x80, None)
|
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,
|
def launch(argv: list[str], cwd: str, log_path: str | None, env: dict[str, str] | None = None,
|
||||||
contained: bool = True) -> ChildProcess:
|
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
|
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:
|
if log_path is not None:
|
||||||
os.makedirs(os.path.dirname(log_path), exist_ok=True)
|
os.makedirs(os.path.dirname(log_path), exist_ok=True)
|
||||||
with _launch_lock:
|
with _launch_lock:
|
||||||
desktop = _desktop_token() if elevated() else None
|
|
||||||
token = desktop or _normal_user_token()
|
|
||||||
job = out = nul = None
|
job = out = nul = None
|
||||||
attributes = None
|
attributes = None
|
||||||
try:
|
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)
|
nul = _inheritable("NUL", GENERIC_READ, OPEN_EXISTING)
|
||||||
command = ctypes.create_unicode_buffer(subprocess.list2cmdline(argv))
|
command = ctypes.create_unicode_buffer(subprocess.list2cmdline(argv))
|
||||||
block = _environment_block(env if env is not None else child_environment())
|
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()
|
pi = ProcessInformation()
|
||||||
|
size = ctypes.c_size_t()
|
||||||
if desktop:
|
_k32.InitializeProcThreadAttributeList(None, 1, 0, ctypes.byref(size))
|
||||||
info = StartupInfo()
|
attributes = ctypes.create_string_buffer(size.value)
|
||||||
info.cb = ctypes.sizeof(StartupInfo)
|
_check(_k32.InitializeProcThreadAttributeList(attributes, 1, 0, ctypes.byref(size)),
|
||||||
info.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW
|
"InitializeProcThreadAttributeList")
|
||||||
info.wShowWindow = SW_HIDE
|
handles = (wt.HANDLE * 2)(out, nul) # all the child inherits
|
||||||
info.hStdInput, info.hStdOutput, info.hStdError = nul, out, out
|
_check(_k32.UpdateProcThreadAttribute(attributes, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, handles,
|
||||||
ok = _adv.CreateProcessWithTokenW(token, 0, None, command, flags, block, cwd,
|
ctypes.sizeof(handles), None, None),
|
||||||
ctypes.byref(info), ctypes.byref(pi))
|
"UpdateProcThreadAttribute")
|
||||||
if not ok and ctypes.get_last_error() == ERROR_INVALID_PARAMETER:
|
info = StartupInfoEx()
|
||||||
# Not every creation flag is accepted here; SW_HIDE still hides a console window.
|
info.StartupInfo.cb = ctypes.sizeof(StartupInfoEx)
|
||||||
ok = _adv.CreateProcessWithTokenW(token, 0, None, command, flags & ~CREATE_NO_WINDOW, block,
|
info.StartupInfo.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW
|
||||||
cwd, ctypes.byref(info), ctypes.byref(pi))
|
info.StartupInfo.wShowWindow = SW_HIDE
|
||||||
_check(ok, f"Starting {argv[0]}")
|
info.StartupInfo.hStdInput, info.StartupInfo.hStdOutput, info.StartupInfo.hStdError = nul, out, out
|
||||||
else:
|
info.lpAttributeList = ctypes.cast(attributes, ctypes.c_void_p)
|
||||||
size = ctypes.c_size_t()
|
_check(_k32.CreateProcessW(None, command, None, None, True, flags, block, cwd,
|
||||||
_k32.InitializeProcThreadAttributeList(None, 1, 0, ctypes.byref(size))
|
ctypes.byref(info), ctypes.byref(pi)), f"Starting {argv[0]}")
|
||||||
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):
|
if job and not _k32.AssignProcessToJobObject(job, pi.hProcess):
|
||||||
error = ctypes.WinError(ctypes.get_last_error(), "AssignProcessToJobObject failed")
|
error = ctypes.WinError(ctypes.get_last_error(), "AssignProcessToJobObject failed")
|
||||||
_k32.TerminateProcess(pi.hProcess, 1)
|
_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)
|
_k32.CloseHandle(pi.hThread)
|
||||||
child = ChildProcess(pi.dwProcessId, pi.hProcess, job, argv)
|
child = ChildProcess(pi.dwProcessId, pi.hProcess, job, argv)
|
||||||
job = None # owned by the child object now
|
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,
|
log.info("Started %s (pid %s, %s integrity%s)", os.path.basename(argv[0]), child.pid,
|
||||||
"desktop" if desktop else "restricted", child.token["integrity"],
|
child.token["integrity"], ", ELEVATED" if child.token["elevated"] else "")
|
||||||
", ELEVATED" if child.token["elevated"] else "")
|
|
||||||
return child
|
return child
|
||||||
finally:
|
finally:
|
||||||
if attributes is not None:
|
if attributes is not None:
|
||||||
_k32.DeleteProcThreadAttributeList(attributes)
|
_k32.DeleteProcThreadAttributeList(attributes)
|
||||||
for handle in (out, nul, job, token):
|
for handle in (out, nul, job):
|
||||||
if handle:
|
if handle:
|
||||||
_k32.CloseHandle(handle)
|
_k32.CloseHandle(handle)
|
||||||
|
|
||||||
|
|
||||||
def open_url(url: str) -> None:
|
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")
|
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,
|
child = launch([rundll, "url.dll,FileProtocolHandler", url], cwd=os.path.dirname(rundll), log_path=None,
|
||||||
contained=False)
|
contained=False)
|
||||||
|
|||||||
@@ -121,7 +121,6 @@ class AiService:
|
|||||||
self.action: str | None = None # "Loading model..." while a load/unload request runs
|
self.action: str | None = None # "Loading model..." while a load/unload request runs
|
||||||
self.message: str | None = None
|
self.message: str | None = None
|
||||||
self._stop: threading.Event | None = None
|
self._stop: threading.Event | None = None
|
||||||
self._born = time.monotonic()
|
|
||||||
|
|
||||||
def set_public_url(self, url: str) -> None:
|
def set_public_url(self, url: str) -> None:
|
||||||
"""The Kurgan's web server, which the links in the UI point to."""
|
"""The Kurgan's web server, which the links in the UI point to."""
|
||||||
@@ -356,11 +355,6 @@ class AiService:
|
|||||||
return
|
return
|
||||||
if time.monotonic() < slot.hold_until:
|
if time.monotonic() < slot.hold_until:
|
||||||
return
|
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()
|
problem = slot.backend.check_files()
|
||||||
if problem:
|
if problem:
|
||||||
slot.error = problem
|
slot.error = problem
|
||||||
|
|||||||
@@ -763,7 +763,7 @@ function renderActive(ai) {
|
|||||||
const st = b.model.state;
|
const st = b.model.state;
|
||||||
const adminLevel = b.token && ["high", "system"].includes(b.token.integrity);
|
const adminLevel = b.token && ["high", "system"].includes(b.token.integrity);
|
||||||
const token = !b.token ? null : adminLevel ? `admin rights, ${b.token.integrity} integrity (unexpected)`
|
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" },
|
const kv = el("dl", { class: "kv" },
|
||||||
el("dt", { text: "Model" }), el("dd", { text: b.model.id ?? b.model_label }),
|
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,
|
b.model.context ? [el("dt", { text: "Context" }), el("dd", { text: `${fmt.n0(b.model.context)} tokens` })] : null,
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
|
import msvcrt
|
||||||
import os
|
import os
|
||||||
|
import sys
|
||||||
import tempfile
|
import tempfile
|
||||||
import threading
|
import threading
|
||||||
import unittest
|
import unittest
|
||||||
@@ -382,7 +384,11 @@ class StrataLogRotationTest(unittest.TestCase):
|
|||||||
self.assertEqual(log.read(), "previous run")
|
self.assertEqual(log.read(), "previous run")
|
||||||
|
|
||||||
|
|
||||||
|
ELEVATED = launcher.token_info()["elevated"]
|
||||||
|
|
||||||
|
|
||||||
class LauncherTest(unittest.TestCase):
|
class LauncherTest(unittest.TestCase):
|
||||||
|
@unittest.skipIf(ELEVATED, "the launcher refuses to run elevated")
|
||||||
def test_child_runs_as_a_normal_user_with_its_output_logged(self):
|
def test_child_runs_as_a_normal_user_with_its_output_logged(self):
|
||||||
with tempfile.TemporaryDirectory() as directory:
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
log_path = os.path.join(directory, "logs", "child.log")
|
log_path = os.path.join(directory, "logs", "child.log")
|
||||||
@@ -395,6 +401,32 @@ class LauncherTest(unittest.TestCase):
|
|||||||
with open(log_path, encoding="utf-8", errors="replace") as f:
|
with open(log_path, encoding="utf-8", errors="replace") as f:
|
||||||
self.assertIn("hello from the child", f.read())
|
self.assertIn("hello from the child", f.read())
|
||||||
|
|
||||||
|
@unittest.skipIf(ELEVATED, "the launcher refuses to run elevated")
|
||||||
|
def test_only_the_log_and_nul_are_inherited(self):
|
||||||
|
# The child names the file behind a handle number of ours that is inheritable but not listed.
|
||||||
|
script = ("import ctypes, sys; b = ctypes.create_unicode_buffer(1024); "
|
||||||
|
"n = ctypes.windll.kernel32.GetFinalPathNameByHandleW(ctypes.c_void_p(int(sys.argv[1])), b, 1024, 0); "
|
||||||
|
"print(b.value if n else 'no such handle')")
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
log_path = os.path.join(directory, "child.log")
|
||||||
|
with open(os.path.join(directory, "secret.txt"), "w") as f:
|
||||||
|
handle = msvcrt.get_osfhandle(f.fileno())
|
||||||
|
os.set_handle_inheritable(handle, True)
|
||||||
|
child = launcher.launch([sys._base_executable, "-I", "-c", script, str(handle)], directory, log_path)
|
||||||
|
try:
|
||||||
|
self.assertEqual(child.wait(30), 0)
|
||||||
|
finally:
|
||||||
|
child.close()
|
||||||
|
with open(log_path, encoding="utf-8") as f:
|
||||||
|
self.assertNotIn("secret.txt", f.read())
|
||||||
|
|
||||||
|
def test_an_elevated_kurgan_starts_nothing(self):
|
||||||
|
with patch.object(launcher, "elevated", return_value=True), tempfile.TemporaryDirectory() as directory:
|
||||||
|
with self.assertRaises(PermissionError) as raised:
|
||||||
|
launcher.launch(["cmd.exe", "/d", "/c", "exit 0"], directory, None)
|
||||||
|
self.assertIn("admin rights", str(raised.exception))
|
||||||
|
|
||||||
|
@unittest.skipIf(ELEVATED, "the launcher refuses to run elevated")
|
||||||
def test_kill_ends_the_whole_job(self):
|
def test_kill_ends_the_whole_job(self):
|
||||||
with tempfile.TemporaryDirectory() as directory:
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
child = launcher.launch(["cmd.exe", "/d", "/c", "ping -n 30 127.0.0.1"], directory, None)
|
child = launcher.launch(["cmd.exe", "/d", "/c", "ping -n 30 127.0.0.1"], directory, None)
|
||||||
|
|||||||
Reference in new issue
Block a user