Privilege split 9/11: setup installs the hardware service and moves its settings

- kurgan/hw/install.py (run elevated by setup.ps1): checks the base
  interpreter can run hw_service.py, creates %ProgramData%\Kurgan or resets
  its owner and access (Administrators own it; SYSTEM and Administrators full
  control, users read), moves the fan and RAM settings there, then creates or
  updates KurganHw through the service manager API (pywin32; sc.exe's quoting
  from Windows PowerShell 5.1 isn't reliable): LocalSystem, automatic start,
  restart after 5 s, 10 s and 60 s, the user's SID for the pipe. A running
  service is stopped first; then it's started and must reach "running".
- kurgan/hw/migrate.py: "copy" (elevated) creates hw-settings.json from the
  user's cooling and lighting.memory, never overwriting an existing file;
  "strip" (as the user) removes them from settings.json once hw-settings.json
  exists, keeping a dated backup. An invalid file on either side stops it.
- setup.ps1: creates the .venv if needed (the service runs from it), passes
  the base interpreter, the user's SID and settings path to the elevated part,
  which installs the service; then strips settings.json, registers and starts
  the app's task, and prints the service's status.
- uninstall.ps1: also stops and deletes the service.
- python -m kurgan.hw.client prints the service's status (setup runs it).
- The pipe's "isn't running", "refused this user" and "closed the
  connection" errors no longer repeat the Windows error text.
- Tests: migration (move, re-run, defaults, invalid files) and the install
  module's parts that don't need admin rights.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
paulandClaude Opus 5.5 committed 2026-12-05 19:51:42 +13:00
1 parent a7ebf42838
commit 8f91a38695
8 files changed
+492 -22

No files matched your search

+28
View File
@@ -299,3 +299,31 @@ class RamLighting:
def set_mode(self, mode: str) -> None:
self.client.set_ram_lighting(mode)
def main() -> int:
"""python -m kurgan.hw.client: is the hardware service reachable, and what is it doing?"""
logging.basicConfig(level=logging.ERROR, format="%(message)s")
client = HardwareClient()
client.poll()
if client.error is not None:
print(f"Hardware service unavailable: {client.error}")
return 1
service, cooling, cpu, ram = client.snapshot(), client.cooling(), client.cpu(), client.ram_lighting()
print(f"The Kurgan hardware {service['version']} (pid {service['pid']}, up {service['uptime']} s)")
if cooling["groups"]:
top = f", top {cooling['top']['duty']}%" if cooling["top"] else ""
groups = ", ".join(f"{g['name']} {g['duty']}%" for g in cooling["groups"])
print(f"Fans: {cooling['profile']} profile; {groups}{top}")
if cooling["note"]:
print(f"Fans: {cooling['note']}")
fmt = lambda v, unit: "--" if v is None else f"{v:.0f} {unit}"
print(f"CPU: {fmt(cpu['temp'], 'C')}, {fmt(cpu['power'], 'W')}" + (f" ({cpu['error']})" if cpu["error"] else ""))
print(f"RAM lighting: {ram['mode']} ({ram['status']})")
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
+162
View File
@@ -0,0 +1,162 @@
"""Install or update the hardware service; setup.ps1 runs this elevated (Decision 0002).
python -m kurgan.hw.install --python BASE_PYTHON --user-sid SID --user-settings PATH
1. checks that BASE_PYTHON can run the service (hw_service.py --check);
2. creates %ProgramData%\\Kurgan, or resets its access (Administrators own it; SYSTEM and
Administrators full control, users read), and moves the fan and RAM lighting settings into
hw-settings.json there, once (kurgan.hw.migrate);
3. creates the "KurganHw" service, or updates it after stopping it: LocalSystem, automatic start,
restart after 5 s, 10 s and 60 s on failure, and the user whose app may use its pipe;
4. starts it and waits until it runs.
The service runs the base interpreter, not the venv's python.exe (a redirector that starts the
base interpreter as a child, which the service manager wouldn't be talking to):
"BASE_PYTHON" -I -S -B "<repo>\\hw_service.py"
uninstall.ps1 removes the service with sc.exe; nothing else is needed for that.
"""
from __future__ import annotations
import argparse
import os
import subprocess
import sys
import time
from kurgan import paths
from kurgan.hw import main as hw_main
from kurgan.hw.pipe import valid_sid
SCRIPT = os.path.join(paths.PROJECT_DIR, "hw_service.py")
DESCRIPTION = ("The Kurgan's hardware control: case and top fan curves with their fail-safes, and the RAM "
"lighting. Stopping it leaves the case fans at 100% and the top fans on the BIOS curve.")
RESTARTS_MS = (5000, 10000, 60000)
RESET_SECONDS = 24 * 3600 # the failure count starts again after a day without one
# The data folder, owner included (kurgan.hw.settings.DATA_DIR_SDDL is the access list).
DATA_DIR_OWNER_SDDL = "O:BAG:SY"
def image_path(python: str, script: str = SCRIPT) -> str:
return f'"{python}" -I -S -B "{script}"'
def failure_actions() -> dict:
import win32service
return {"ResetPeriod": RESET_SECONDS, "RebootMsg": None, "Command": None,
"Actions": [(win32service.SC_ACTION_RESTART, ms) for ms in RESTARTS_MS]}
def check(python: str) -> str:
"""hw_service.py --check under the service's interpreter and flags; RuntimeError if it fails."""
try:
result = subprocess.run([python, "-I", "-S", "-B", SCRIPT, "--check"], capture_output=True, text=True,
timeout=120, cwd=paths.PROJECT_DIR)
except (OSError, subprocess.TimeoutExpired) as e:
raise RuntimeError(f"{python} can't run the hardware service: {e}") from None
if result.returncode != 0:
detail = (result.stderr or result.stdout).strip().splitlines()
raise RuntimeError(f"{python} can't run the hardware service: {detail[-1] if detail else result.returncode}")
return result.stdout.strip()
def reset_data_dir(path: str = paths.HW_DATA_DIR) -> None:
"""Create the data folder, or give an existing one exactly the intended owner and access."""
import win32security
from kurgan.hw import settings as hw_settings
hw_settings.ensure_data_dir(path)
sd = win32security.ConvertStringSecurityDescriptorToSecurityDescriptor(
DATA_DIR_OWNER_SDDL + hw_settings.DATA_DIR_SDDL, win32security.SDDL_REVISION_1)
win32security.SetNamedSecurityInfo( # also passes the inheritable entries on to the files inside
path, win32security.SE_FILE_OBJECT,
win32security.OWNER_SECURITY_INFORMATION | win32security.DACL_SECURITY_INFORMATION
| win32security.PROTECTED_DACL_SECURITY_INFORMATION,
sd.GetSecurityDescriptorOwner(), None, sd.GetSecurityDescriptorDacl(), None)
def _wait(service, state: int, seconds: float) -> int:
import win32service
deadline = time.monotonic() + seconds
while True:
current = win32service.QueryServiceStatus(service)[1]
if current == state or time.monotonic() > deadline:
return current
time.sleep(0.5)
def install(python: str, user_sid: str) -> None:
"""Create or update the service (stopping it first if it runs), then start it."""
import pywintypes
import win32service
import winerror
import winreg
manager = win32service.OpenSCManager(None, None, win32service.SC_MANAGER_ALL_ACCESS)
try:
args = (win32service.SERVICE_WIN32_OWN_PROCESS, win32service.SERVICE_AUTO_START,
win32service.SERVICE_ERROR_NORMAL, image_path(python), None, False, None)
try:
service = win32service.OpenService(manager, hw_main.SERVICE_NAME, win32service.SERVICE_ALL_ACCESS)
except pywintypes.error as e:
if e.winerror != winerror.ERROR_SERVICE_DOES_NOT_EXIST:
raise
service = win32service.CreateService(manager, hw_main.SERVICE_NAME, hw_main.SERVICE_DISPLAY_NAME,
win32service.SERVICE_ALL_ACCESS, *args, None, None)
print(f"Created the {hw_main.SERVICE_DISPLAY_NAME!r} service ({hw_main.SERVICE_NAME})")
else:
if win32service.QueryServiceStatus(service)[1] != win32service.SERVICE_STOPPED:
print("Stopping the running hardware service (case fans to 100% meanwhile)...")
win32service.ControlService(service, win32service.SERVICE_CONTROL_STOP)
if _wait(service, win32service.SERVICE_STOPPED, hw_main.STOP_SECONDS + 10) != win32service.SERVICE_STOPPED:
raise RuntimeError("the hardware service didn't stop; try again, or reboot")
win32service.ChangeServiceConfig(service, *args, "LocalSystem", None, hw_main.SERVICE_DISPLAY_NAME)
print(f"Updated the {hw_main.SERVICE_DISPLAY_NAME!r} service ({hw_main.SERVICE_NAME})")
try:
win32service.ChangeServiceConfig2(service, win32service.SERVICE_CONFIG_DESCRIPTION, DESCRIPTION)
win32service.ChangeServiceConfig2(service, win32service.SERVICE_CONFIG_FAILURE_ACTIONS, failure_actions())
win32service.ChangeServiceConfig2(service, win32service.SERVICE_CONFIG_FAILURE_ACTIONS_FLAG, True)
with winreg.CreateKeyEx(winreg.HKEY_LOCAL_MACHINE, hw_main.PARAMETERS_KEY, 0, winreg.KEY_SET_VALUE) as key:
winreg.SetValueEx(key, "UserSid", 0, winreg.REG_SZ, user_sid)
win32service.StartService(service, None)
state = _wait(service, win32service.SERVICE_RUNNING, 30)
if state != win32service.SERVICE_RUNNING:
raise RuntimeError(f"the hardware service didn't start (state {state}); see {paths.HW_LOG_PATH}")
print(f"The hardware service is running. Log: {paths.HW_LOG_PATH}")
finally:
win32service.CloseServiceHandle(service)
finally:
win32service.CloseServiceHandle(manager)
def main(argv: list[str] | None = None) -> int:
from kurgan.hw import migrate
ap = argparse.ArgumentParser(prog="python -m kurgan.hw.install", description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--python", required=True, help="the base interpreter's python.exe (not the venv's)")
ap.add_argument("--user-sid", required=True, help="the user whose app may use the pipe")
ap.add_argument("--user-settings", required=True, help="that user's settings.json, to move settings from")
args = ap.parse_args(argv)
if not valid_sid(args.user_sid):
ap.error(f"not a SID: {args.user_sid!r}")
if not os.path.isfile(args.python):
ap.error(f"no such interpreter: {args.python}")
try:
print(check(args.python))
reset_data_dir()
print(migrate.copy(args.user_settings))
install(args.python, args.user_sid)
except Exception as e: # setup.ps1 shows this and stops
print(f"error: {type(e).__name__}: {e}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+113
View File
@@ -0,0 +1,113 @@
"""Moving the fan and RAM lighting settings from the user's settings.json to hw-settings.json.
setup.ps1 runs both halves, once per install; each is safe to run again:
python -m kurgan.hw.migrate copy USER_SETTINGS elevated: create hw-settings.json from the user's
`cooling` and `lighting.memory`, unless it exists
python -m kurgan.hw.migrate strip as the user: once hw-settings.json exists, remove
them from settings.json, keeping a dated backup
An invalid file on either side stops the move (and setup) rather than lose a setting.
"""
from __future__ import annotations
import argparse
import copy as _copy
import json
import os
import shutil
import sys
import time
from kurgan import paths
from kurgan.hw import settings as hw_settings
from kurgan.settings import SettingsError, validate, write_json_atomic
def _read_json(path: str) -> dict | None:
"""The file's contents, or None if it doesn't exist; SettingsError if it isn't valid JSON."""
try:
with open(path, encoding="utf-8") as stream:
return json.load(stream)
except FileNotFoundError:
return None
except ValueError as e:
raise SettingsError(f"{path}: {e}") from None
def hardware_sections(user: dict) -> dict:
"""The parts of a user settings.json that belong to the hardware service."""
out: dict = {}
if isinstance(user.get("cooling"), dict):
out["cooling"] = dict(user["cooling"])
lighting = user.get("lighting")
if isinstance(lighting, dict) and "memory" in lighting:
out["lighting"] = {"memory": lighting["memory"]}
return out
def copy(user_path: str, hw_path: str = paths.HW_SETTINGS_PATH) -> str:
"""Create hw-settings.json from the user's settings, unless it exists. Returns what it did."""
if os.path.exists(hw_path):
return f"{hw_path} already exists; left as it is"
raw = _read_json(user_path)
sections = {}
if raw is not None:
try:
sections = hardware_sections(validate(raw))
except SettingsError as e:
raise SettingsError(f"{user_path}: {e}") from None
try:
data = hw_settings.validate(sections)
except SettingsError as e:
raise SettingsError(f"{user_path}'s fan or RAM settings can't move: {e}") from None
write_json_atomic(hw_path, data)
moved = [name for name, present in (("cooling", "cooling" in sections),
("lighting.memory", "lighting" in sections)) if present]
return f"Created {hw_path}" + (f" with {' and '.join(moved)} from {user_path}" if moved else " with the defaults")
def strip(user_path: str = paths.SETTINGS_PATH, hw_path: str = paths.HW_SETTINGS_PATH, now: float | None = None) -> str:
"""Remove the hardware sections from the user's settings.json, once hw-settings.json exists."""
if not os.path.exists(hw_path):
return f"{hw_path} doesn't exist yet; settings.json left as it is"
raw = _read_json(user_path)
if raw is None or not hardware_sections(raw):
return f"Nothing to move out of {user_path}"
stripped = _copy.deepcopy(raw)
stripped.pop("cooling", None)
if isinstance(stripped.get("lighting"), dict):
stripped["lighting"].pop("memory", None)
try:
data = validate(stripped)
except SettingsError as e:
raise SettingsError(f"{user_path}: {e}") from None
stamp = time.strftime("%Y%m%d-%H%M%S", time.localtime(now))
backup = f"{user_path}.{stamp}.bak"
shutil.copy2(user_path, backup)
write_json_atomic(user_path, data)
return f"Removed the fan and RAM lighting settings from {user_path} (now in {hw_path}); backup: {backup}"
def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(prog="python -m kurgan.hw.migrate", description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="action", required=True)
sub.add_parser("copy", help="create hw-settings.json (elevated)").add_argument("user_settings")
sub.add_parser("strip", help="tidy the user's settings.json (as the user)")
args = ap.parse_args(argv)
try:
if args.action == "copy":
hw_settings.ensure_data_dir()
print(copy(args.user_settings))
else:
print(strip())
except (OSError, SettingsError) as e:
print(f"error: {e}", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
+3 -3
View File
@@ -430,9 +430,9 @@ class PipeClient:
_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)
raise PipeError("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 PipeError("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()
@@ -460,7 +460,7 @@ class PipeClient:
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)
raise PipeError("the hardware service closed the connection", ERROR_BROKEN_PIPE)
self._lines += self._buffer.feed(chunk)
return self._lines.pop(0)