Fix #3488: a reused PID in a child marker without a start time no longer blocks every load; the engine hash check reads twice before refusing

This commit is contained in:
Niko1221 committed 2026-10-20 23:53:07 +02:00
1 parent 1e7bcb8b6e
commit 53752401f2
5 files changed
+98 -5

No files matched your search

+22 -2
View File
@@ -41,6 +41,7 @@ from __future__ import annotations
import hashlib
import json
import os
import time
import re
import shutil
import subprocess
@@ -382,6 +383,22 @@ def _sha256(path: Path) -> str:
return digest.hexdigest()
def _hash_settled(path: Path, digest: str) -> str | None:
"""The file's SHA-256, read again once when the first read fails or differs: a file that was just unpacked or is
being scanned by a virus checker can read short or locked for a moment, and a failure must not be kept (#3488)."""
actual = None
for attempt in range(2):
try:
actual = _sha256(path)
except OSError:
actual = None
if actual == digest:
break
if attempt == 0:
time.sleep(0.5)
return actual
def verify(component: EngineComponent, *, full: bool = False) -> None:
"""Raise IntegrityProblem unless the files are what the manifest says. `full` hashes every file; without it only
the entrypoint is hashed (sizes are always checked)."""
@@ -401,8 +418,11 @@ def verify(component: EngineComponent, *, full: bool = False) -> None:
raise IntegrityProblem(f"{rel} resolves outside the component folder")
if info.st_size != size:
raise IntegrityProblem(f"{rel} is {info.st_size} bytes, the manifest says {size}")
if (full or rel == component.entrypoint) and _sha256(target) != digest:
raise IntegrityProblem(f"{rel} does not match its recorded SHA-256")
if full or rel == component.entrypoint:
actual = _hash_settled(target, digest)
if actual != digest:
raise IntegrityProblem(f"{rel} does not match its recorded SHA-256 (expected {digest[:12]}, "
f"found {actual[:12] if actual else 'unreadable'})")
if os.name != "nt" and not os.access(component.exe, os.X_OK):
raise IntegrityProblem(f"{component.entrypoint} is not executable")
+21 -3
View File
@@ -254,6 +254,22 @@ def _pid_exists(pid: int, started: int | None = None) -> bool:
return True
def _child_present(child: dict) -> bool:
"""Whether the child recorded in an owner marker is still there. A marker without a creation time (Windows could not
read it when the child started) cannot tell the recorded server from a later process that reused the number, so
a live process that is not a Python or Strata executable is a reused number: the child is gone (#3488)."""
started = child.get("started") if type(child.get("started")) is int else None
if not _pid_exists(child["pid"], started):
return False
if WINDOWS and started is None:
image = winproc.process_image(child["pid"])
if image is not None:
name = os.path.basename(image).lower()
if "python" not in name and "strata" not in name:
return False
return True
def _host_lease_active(name: str) -> bool:
path, _, _ = _paths(name)
descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
@@ -291,10 +307,9 @@ def _recover_stale(name: str, *, wait: float) -> bool:
child.get("phase") != "owned" or type(child.get("pid")) is not int or child["pid"] <= 0:
raise ProfileError("lost host child launch is unverified; inspect before recovery", 6)
deadline = time.monotonic() + min(45.0, max(5.0, wait))
started = child.get("started") if type(child.get("started")) is int else None
while _pid_exists(child["pid"], started) and time.monotonic() < deadline:
while _child_present(child) and time.monotonic() < deadline:
time.sleep(0.1)
if _pid_exists(child["pid"], started):
if _child_present(child):
raise ProfileError("lost host child is still present; retry after it exits", 6)
if not isinstance(child.get("ready"), str):
raise ProfileError("lost host ready path is invalid; inspect before recovery", 6)
@@ -715,6 +730,9 @@ class Host:
payload.update(pid=pid, ready=str(ready))
if WINDOWS:
started = winproc.process_started(pid)
if started is None:
time.sleep(0.05)
started = winproc.process_started(pid) # one more try: the child may not be queryable yet
if started is not None:
payload["started"] = started # tells this process from a later one with the same number
profiles._atomic(_child_marker(self.name, self.token), (json.dumps(payload) + "\n").encode())
+23
View File
@@ -45,6 +45,10 @@ if WINDOWS:
_k32.GetProcessTimes.argtypes = [wintypes.HANDLE] + [ctypes.POINTER(wintypes.FILETIME)] * 4
_k32.GetProcessTimes.restype = wintypes.BOOL
_k32.QueryFullProcessImageNameW.argtypes = [wintypes.HANDLE, wintypes.DWORD, wintypes.LPWSTR,
ctypes.POINTER(wintypes.DWORD)]
_k32.QueryFullProcessImageNameW.restype = wintypes.BOOL
_LOCKFILE_FAIL_IMMEDIATELY = 0x1
_LOCKFILE_EXCLUSIVE_LOCK = 0x2
_ERROR_LOCK_VIOLATION = 33
@@ -93,6 +97,22 @@ if WINDOWS:
finally:
_k32.CloseHandle(handle)
def process_image(pid: int) -> str | None:
"""The executable path of a running process, or None when it cannot be read."""
if type(pid) is not int or pid <= 0:
return None
handle = _k32.OpenProcess(_PROCESS_QUERY_LIMITED_INFORMATION, False, pid)
if not handle:
return None
try:
size = wintypes.DWORD(32768)
buffer = ctypes.create_unicode_buffer(size.value)
if not _k32.QueryFullProcessImageNameW(handle, 0, buffer, ctypes.byref(size)):
return None
return buffer.value
finally:
_k32.CloseHandle(handle)
def pid_alive(pid: int, started: int | None = None) -> bool:
"""Whether `pid` is a running process, and, when `started` is given, the one created at that time."""
if type(pid) is not int or pid <= 0:
@@ -116,5 +136,8 @@ else:
def process_started(pid: int) -> int | None:
return None
def process_image(pid: int) -> str | None:
return None
def pid_alive(pid: int, started: int | None = None) -> bool:
raise OSError("Windows only")
+17
View File
@@ -388,5 +388,22 @@ class Issue3302AdministratorAlias(unittest.TestCase):
self.assertFalse(pf.is_unshared("x"))
class Issue3488IntegrityRetry(unittest.TestCase):
"""A hash that reads wrong once (file just unpacked, or held by a virus scanner) must not stick."""
def test_second_read_decides(self):
from unittest import mock
from strata_control import engine_component as ec
path = Path("x")
with mock.patch.object(ec, "_sha256", side_effect=["bad", "good"]) as sha, mock.patch.object(ec.time, "sleep"):
self.assertEqual(ec._hash_settled(path, "good"), "good")
self.assertEqual(sha.call_count, 2)
with mock.patch.object(ec, "_sha256", side_effect=[PermissionError(), "good"]), mock.patch.object(ec.time, "sleep"):
self.assertEqual(ec._hash_settled(path, "good"), "good")
with mock.patch.object(ec, "_sha256", return_value="bad"), mock.patch.object(ec.time, "sleep"):
self.assertEqual(ec._hash_settled(path, "good"), "bad") # still wrong after the retry: refuse
if __name__ == "__main__":
unittest.main()
+15
View File
@@ -1144,6 +1144,21 @@ class RuntimeTests(unittest.TestCase):
victim.kill()
victim.wait(timeout=10)
def test_marker_without_creation_time_ignores_a_reused_pid_of_a_foreign_program(self):
# #3488: the marker had no `started`, the number was reused by another program, every load said "still present".
child = {"pid": 38552}
with mock.patch.object(runtime, "WINDOWS", True), \
mock.patch.object(runtime, "_pid_exists", return_value=True), \
mock.patch.object(runtime.winproc, "process_image", create=True) as image:
image.return_value = r"C:\Windows\System32\svchost.exe"
self.assertFalse(runtime._child_present(child))
image.return_value = r"C:\Users\a\AppData\Local\Strata\python\python.exe"
self.assertTrue(runtime._child_present(child))
image.return_value = None # unreadable: keep refusing, never guess
self.assertTrue(runtime._child_present(child))
image.return_value = r"C:\Windows\System32\svchost.exe"
self.assertTrue(runtime._child_present({"pid": 1, "started": 5})) # a creation time decides by itself
@unittest.skipUnless(WINDOWS, "os.kill(pid, 0) ends a process on Windows; liveness is a handle query")
def test_liveness_check_does_not_end_the_process_it_asks_about(self):
victim = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(120)"])