hunt: with the core's fix (the hidden desktop carries the interactive DACL and a Low label, no sandbox pref) and Firefox's own sandbox levels, whether the GPU process, the compositor and WebGL hold on the hidden Windows desktop and which process type reads c:\windows\fonts (measurement branch, not for main)

This commit is contained in:
feder-cr committed 2026-12-02 15:50:06 +01:00
1 parent 06cb753d9c
commit 2695ad5684
3 files changed
+1725

No files matched your search

+147
View File
@@ -0,0 +1,147 @@
# -----------------------------------------------------------------------------
# d72-sandbox-fix.yml - TEMPORARY MEASUREMENT, not a gate.
#
# What it asks. With the core's fix in place (the hidden Windows desktop made with the interactive desktop's DACL and a Low mandatory label,
# and no security.sandbox.* pref written by the core: patch scripts/hunt_d72_core_fix.patch, core commit de3e5156 on top of 20e5d50), and Firefox's
# own sandbox levels in force (content 9, GPU 2), does the browser on the hidden desktop keep a GPU process, a hardware compositor and WebGL, and
# does anything of it read c:/windows/fonts? The patch is NOT on GitHub as a commit: it is applied here to a checkout of oss-invisible/core at 20e5d50.
# One variant: InvisiblePlaywright(seed=1, headless=True), no extra_prefs. The script (scripts/hunt_d72_sandbox_fix.py) records about:support,
# the profile's prefs (user.js must hold no security.sandbox.* line), WebGL, three cross-origin navigations, every firefox.exe process with the
# integrity level of its token (the GPU process alive at the END is the evidence), crashes, the label of the desktops (GetSecurityInfo), and an
# ETW Kernel-File + process-creation-audit trace of the whole run (the recorder of the host oracle, scripts/ci_ab_host.py WindowsTrace, the method of
# RetailCaptures branch hunt/abhost-retail-hidden-desktop) to say which firefox.exe process type opened a path under c:/windows/fonts.
#
# The engine is the artifact asset-win-x86_64 of run 46792115974 of the series, sealed as before.
#
# It runs only on a push to the branch hunt/d72-sandbox-fix, and is deleted with that branch once the question is answered.
# -----------------------------------------------------------------------------
name: d72 sandbox fix hunt
on:
push:
branches: [hunt/d72-sandbox-fix]
permissions:
contents: read
env:
ENGINE_RUN: "46792115974"
ENGINE_REPO: oss-invisible/firefox_antidetect_patch
CORE_BASE_SHA: 20e5d50e1360deb043a4cc0a7980cd1283f04707
CORE_PATCH: scripts/hunt_d72_core_fix.patch
INVISIBLE_CORE_AUTOFIX: "off"
INVISIBLE_CORE_PIN: allow
jobs:
hunt:
name: d72 sandbox fix (windows)
runs-on: windows-2025
timeout-minutes: 30
# TEMP and TMP on D:\a\_temp, as e2e-hunt.yml does: the Firefox profiles land in TEMP and on C: they saturate the disk.
env:
TEMP: 'D:\a\_temp'
TMP: 'D:\a\_temp'
defaults:
run:
shell: bash
steps:
# LF in every checkout: the patch is LF and the core's files are LF, and `git apply` refuses a patch whose lines do not match byte for byte.
- name: LF in every checkout
run: git config --global core.autocrlf false
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with: { fetch-depth: 1 }
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
with:
repository: oss-invisible/core
ref: ${{ env.CORE_BASE_SHA }}
path: core-fix
fetch-depth: 1
persist-credentials: false
- uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5
with: { python-version: '3.11' }
- name: The engine (the artifact of the series' build run)
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: asset-win-x86_64
path: art
repository: ${{ env.ENGINE_REPO }}
run-id: ${{ env.ENGINE_RUN }}
github-token: ${{ github.token }}
- name: Extract and locate the engine
run: |
set -e
ls -la art
python - <<'PY'
import hashlib, os, sys, zipfile
from pathlib import Path
art, dest = Path("art"), Path("ff")
dest.mkdir(exist_ok=True)
zips = sorted(art.glob("firefox-*-stealth-win-x86_64.zip")) or sorted(art.glob("*.zip"))
if len(zips) > 1:
sys.exit("ERROR: expected one archive in art/, found: %s" % [str(z) for z in zips])
if zips:
h = hashlib.sha256(zips[0].read_bytes()).hexdigest()
print("archive", zips[0], h)
with zipfile.ZipFile(zips[0]) as z:
z.extractall(dest)
root = dest
else:
root = art # the artifact already holds the tree
exes = sorted(p for p in root.rglob("firefox.exe") if p.parent.name != "uninstall")
if len(exes) != 1:
sys.exit("ERROR: expected one firefox.exe, found: %s" % [str(p) for p in exes])
exe = exes[0].resolve()
print("firefox.exe", exe, hashlib.sha256(exe.read_bytes()).hexdigest())
with open(os.environ["GITHUB_ENV"], "a", encoding="utf-8", newline="\n") as f:
f.write("FF_EXE=%s\n" % exe)
PY
- name: The core's fix (the patch, applied to the checkout of the core at 20e5d50)
run: |
set -e
git -C core-fix rev-parse HEAD
test "$(git -C core-fix rev-parse HEAD)" = "$CORE_BASE_SHA"
sha256sum "$CORE_PATCH"
git -C core-fix apply --check "$(cygpath -w "$PWD/$CORE_PATCH")"
git -C core-fix apply --stat "$(cygpath -w "$PWD/$CORE_PATCH")"
git -C core-fix apply "$(cygpath -w "$PWD/$CORE_PATCH")"
echo "---- git diff --stat of the core now (the fix is in) ----"
git -C core-fix add -N .
git -C core-fix diff --stat
git -C core-fix status --short
grep -n "_label_the_hidden_desktop" core-fix/src/invisible_core/_headless.py
if grep -n "security.sandbox" core-fix/src/invisible_core/prefs.py; then echo "NOTE: security.sandbox still named in prefs.py (see lines above)"; fi
- name: Install the wrapper, then the core with the fix
run: |
python -m pip install --upgrade pip
python -m pip install .
python -m pip install "playwright==$(cat scripts/playwright_pin.txt)"
python -m pip install --no-deps --force-reinstall "$(cygpath -w "$PWD/core-fix")"
python -m pip list 2>/dev/null | grep -i -E "invisible|playwright|psutil"
python - <<'PY'
import invisible_core, invisible_core._headless as h
print("invisible_core from", invisible_core.__file__)
assert hasattr(h, "_label_the_hidden_desktop"), "the installed core does not hold the fix"
print("the installed core holds _label_the_hidden_desktop")
PY
- name: The security state (a fixed directory of the repository)
run: python scripts/ci_lab_security_state.py set --pin ci/security-state.pin.json
- name: The GeoIP database (made by the repository, same bytes every run)
run: python scripts/ci_lab_geoip.py build --pin ci/geoip.json
- name: Seal of the binary under test
run: |
python -m invisible_core seal --binary "$FF_EXE" --tag firefox-72-candidate -o "$(cygpath -w "$PWD/gate.seal.json")"
- name: The measurement (the wrapper's normal launch, headless=True, one variant, traced)
env:
PYTHONUNBUFFERED: "1"
run: |
export INVISIBLE_SEAL_FILE="$(cygpath -w "$PWD/gate.seal.json")" INVPW_BINARY_PATH="$FF_EXE" STEALTHFOX_E2E_BINARY="$FF_EXE"
mkdir -p evidence
python -u scripts/hunt_d72_sandbox_fix.py --binary "$FF_EXE" --out evidence
- name: Upload the record
if: always()
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: d72-sandbox-fix
path: evidence
if-no-files-found: warn
retention-days: 14
+679
View File
@@ -0,0 +1,679 @@
From de3e5156b06cdb99767bbd20884279c173ce78e2 Mon Sep 17 00:00:00 2001
From: feder-cr <85809106+feder-cr@users.noreply.github.com>
Date: Wed, 2 Dec 2026 15:41:12 +0100
Subject: [PATCH] Give the hidden desktop the interactive DACL and a Low label;
drop the two sandbox prefs
The core created its hidden desktop with a null security descriptor, which
carries no mandatory label and reads as Medium. At every GPU sandbox level of
1 or more Firefox's GPU process runs at Low integrity and inherits that
desktop (sandboxBroker.cpp:1347-1348), and the sandbox assumes the desktop
admits Low (broker_services.cc:685-700). Retail 159.0 on such a desktop lost
its GPU process 3 of 3 launches and read WebGL as null (RetailCaptures run
46903007316).
_headless._label_the_hidden_desktop now copies the DACL of the desktop the
thread is on (GetSecurityInfo/SetSecurityInfo, SE_WINDOW_OBJECT) and sets a
Low mandatory label (SDDL S:(ML;;NW;;;LW)), as Chromium's CreateAltDesktop and
alternate_desktop.cc do. A failure closes the new desktop and raises; it never
leaves a null descriptor. Every LocalAlloc block is freed.
With that, security.sandbox.gpu.level 0 (an unsandboxed GPU process) and
security.sandbox.content.level 4 (effectively 6, Windows' minimum) are no
longer needed: _WIN_VIRT_DESKTOP_WORKAROUNDS and _apply_platform_workarounds
are removed, and Firefox's own defaults (content 9, GPU 2) apply. The two
"measured on this exact setup" comments are replaced by what is true now.
Tests:
- new tests/test_the_hidden_desktop_admits_a_low_process.py (Windows only)
creates the desktop through _WindowsVirtualDesktop.start() and reads its
label and DACL back; on 20e5d50 it reads 0x2000 (Medium), not 0x1000.
- tests/test_prefs.py: test_virtual_display_workaround_applied_on_windows
asserted security.sandbox.gpu.level == 0 and the "absent when disabled"
test asserted the key missing; both are now one test asserting no
security.sandbox.* key on win32 with virtual_display True or False. The
old assertion is wrong because retail 159.0 needs its own levels and the
fix is the desktop's label, not the pref. VD3 (Linux) asserts the same.
- tests/test_prefs_sections.py: the parametrised test of the table's
setdefault is removed with the table; the order test now expects
_apply_extension_lists before the overlay.
- tests/test_canvas_2d_on_the_cpu.py and
tests/test_webgl_not_decided_by_host_blocklist.py asserted a pref is not in
the removed table; the webgl one now asserts the prefs of a hidden desktop
do not carry them, the canvas one is covered by the existing value test.
- docs/decisions/core-07 and core-10 say how it is now.
---
...refs-go-to-user-js-from-one-composition.md | 4 +-
...er-is-always-headed-on-a-hidden-surface.md | 8 +-
src/invisible_core/_headless.py | 130 +++++++++++++++++-
src/invisible_core/config.py | 6 +-
src/invisible_core/prefs.py | 78 +----------
tests/test_canvas_2d_on_the_cpu.py | 9 +-
tests/test_prefs.py | 33 ++---
tests/test_prefs_sections.py | 35 +----
...the_hidden_desktop_admits_a_low_process.py | 119 ++++++++++++++++
...est_webgl_not_decided_by_host_blocklist.py | 13 +-
10 files changed, 280 insertions(+), 155 deletions(-)
create mode 100644 tests/test_the_hidden_desktop_admits_a_low_process.py
diff --git a/docs/decisions/core-07-prefs-go-to-user-js-from-one-composition.md b/docs/decisions/core-07-prefs-go-to-user-js-from-one-composition.md
index fbb0c8e..50eb177 100644
--- a/docs/decisions/core-07-prefs-go-to-user-js-from-one-composition.md
+++ b/docs/decisions/core-07-prefs-go-to-user-js-from-one-composition.md
@@ -7,9 +7,9 @@
- `translate_profile_to_prefs` writes only the fingerprint, not the whole session. *Question:* Does `translate_profile_to_prefs` write only the fingerprint (file:line)?
- The core declares how each pref `translate_profile_to_prefs` emits varies across seeds, in `pref_classification.py`: a dimension, a derivation by a function the core holds, or an exclusion with its reason. A pref that varies across `SAMPLE_SEEDS` and is classified nowhere is red. *Question:* Is every pref that varies across seeds a member of a dimension, derived by the core's own function, or excluded with a reason (file:line, test)?
- The base prefs are in `_BASELINE` and are applied first. *Question:* Is `_BASELINE` applied first (file:line, test)?
-- On headless Windows the dicts of the helper and of the wrapper differ by `_WIN_VIRT_DESKTOP_WORKAROUNDS`; this is intended. Hiding the surface belongs to the caller. *Question:* Do the helper and wrapper dicts differ on headless Windows only by `_WIN_VIRT_DESKTOP_WORKAROUNDS` (test)?
+- On headless Windows the dicts of the helper and of the wrapper do not differ because of the hidden desktop: it writes no pref. Hiding the surface belongs to the caller. *Question:* Does the hidden desktop write no pref (`tests/test_prefs.py::test_the_hidden_desktop_writes_no_sandbox_pref_on_windows`)?
-**Enforced by.** `tests/test_launch.py::test_write_user_js_float_is_quoted`, `::test_write_user_js_writes_lf_bytes_in_insertion_order`, `::test_write_user_js_refuses_a_type_firefox_has_no_pref_for` and `::test_write_user_js_creates_dir_and_overwrites` fail when the file format, the key order, the type rule or the rewrite changes. `tests/test_prefs.py::test_no_pref_is_emitted_as_a_python_float` fails when a bare float reaches the prefs. `tests/test_prefs_composition.py::test_the_two_core_paths_compose_the_same_prefs` fails when the direct launch and the public helper compose different prefs. `tests/test_prefs_composition.py::test_extra_prefs_beat_the_crash_prefs_and_humanize_beats_extra_prefs` and `tests/test_prefs_sections.py::test_the_pipeline_runs_the_overlay_last` fail when the order of the layers changes. `tests/test_prefs_sections.py::test_the_platform_workarounds_never_take_a_choice_away` fails when a workaround overwrites a value an earlier layer chose. `tests/test_pref_types.py::test_every_declared_pref_has_the_type_the_engine_reads_and_a_reader` fails when a declared pref has a type the engine does not read. `tests/test_pref_classification.py::test_the_core_declares_how_every_varying_pref_varies` fails when a pref varies across the sample of seeds and is classified nowhere, and `::test_a_varying_pref_that_is_not_classified_is_red_naming_it`, `::test_a_derived_pref_with_two_values_for_one_dimension_value_is_red` and `::test_a_classified_pref_that_no_longer_varies_is_red` fail when the rule stops naming it.
+**Enforced by.** `tests/test_launch.py::test_write_user_js_float_is_quoted`, `::test_write_user_js_writes_lf_bytes_in_insertion_order`, `::test_write_user_js_refuses_a_type_firefox_has_no_pref_for` and `::test_write_user_js_creates_dir_and_overwrites` fail when the file format, the key order, the type rule or the rewrite changes. `tests/test_prefs.py::test_no_pref_is_emitted_as_a_python_float` fails when a bare float reaches the prefs. `tests/test_prefs_composition.py::test_the_two_core_paths_compose_the_same_prefs` fails when the direct launch and the public helper compose different prefs. `tests/test_prefs_composition.py::test_extra_prefs_beat_the_crash_prefs_and_humanize_beats_extra_prefs` and `tests/test_prefs_sections.py::test_the_pipeline_runs_the_overlay_last` fail when the order of the layers changes. `tests/test_pref_types.py::test_every_declared_pref_has_the_type_the_engine_reads_and_a_reader` fails when a declared pref has a type the engine does not read. `tests/test_pref_classification.py::test_the_core_declares_how_every_varying_pref_varies` fails when a pref varies across the sample of seeds and is classified nowhere, and `::test_a_varying_pref_that_is_not_classified_is_red_naming_it`, `::test_a_derived_pref_with_two_values_for_one_dimension_value_is_red` and `::test_a_classified_pref_that_no_longer_varies_is_red` fail when the rule stops naming it.
**Why.** Prefs set at run time give different results from one launch to the next, and `Browser.enable` does not accept prefs. The direct launch and the wrapper must produce the same prefs, and several layers write the same keys. A fixed order and one composer make the final value of each key deterministic, and the profile identical and checkable byte for byte at every launch.
diff --git a/docs/decisions/core-10-the-browser-is-always-headed-on-a-hidden-surface.md b/docs/decisions/core-10-the-browser-is-always-headed-on-a-hidden-surface.md
index ef6affb..4c8f781 100644
--- a/docs/decisions/core-10-the-browser-is-always-headed-on-a-hidden-surface.md
+++ b/docs/decisions/core-10-the-browser-is-always-headed-on-a-hidden-surface.md
@@ -3,15 +3,15 @@
**Rule.** The browser never runs in the native headless mode of Firefox, and it never opens a window on the desktop of the user. *Question:* Does the browser never run in the native headless mode of Firefox and never open a window on the desktop of the user (which test and which run show it)?
- On Windows it runs on a dedicated Win32 desktop made with `CreateDesktopW`. The name travels only in the launch environment as `INVPW_DESKTOP`, and the spawner sets it in `STARTUPINFO.lpDesktop` for the whole process tree. *Question:* On Windows, does the browser run on a `CreateDesktopW` desktop whose name travels only as `INVPW_DESKTOP` and is set in `STARTUPINFO.lpDesktop` (file:line, tests)?
- On Linux it runs on a private Xvfb with an auth cookie per session, a display chosen among the free ones, ready when it answers, and `-nolisten tcp`. *Question:* On Linux, does it run on a private Xvfb with a cookie per session, a free display, a readiness check and `-nolisten tcp` (tests)?
-- On a Windows virtual desktop with `virtual_display`, `security.sandbox.gpu.level` is 0 and `security.sandbox.content.level` is 4. The workarounds enter with `setdefault`, only with `virtual_display` on win32, and live in the Windows section of `prefs.py` (`_WIN_VIRT_DESKTOP_WORKAROUNDS`). *Question:* Are `security.sandbox.gpu.level` 0 and `security.sandbox.content.level` 4 set with `setdefault`, only with `virtual_display` on win32, in `_WIN_VIRT_DESKTOP_WORKAROUNDS` (file:line, test)?
+- The Windows desktop carries the DACL of the interactive desktop and a Low mandatory label (`_headless._label_the_hidden_desktop`), so the browser's own sandbox levels apply on it (content 9, GPU 2) and the core writes no `security.sandbox.*` pref. A failure to set either raises; it never leaves a desktop with a null descriptor. *Question:* Does the created desktop read back a Low label and the interactive desktop's DACL, and does the core write no `security.sandbox.*` key (file:line, `tests/test_the_hidden_desktop_admits_a_low_process.py`, `tests/test_prefs.py::test_the_hidden_desktop_writes_no_sandbox_pref_on_windows`)?
- Stopping the Xvfb leaves no descriptor and no TCP port. *Question:* After the Xvfb stops, is no descriptor and no TCP port left (test)?
-**Enforced by.** `tests/test_headless.py::test_the_desktop_variable_name_is_a_contract` and `::test_the_desktop_never_touches_the_process_environment` fail when the desktop name moves out of the launch environment. `tests/test_headless.py::test_two_sessions_never_share_a_desktop` fails when two sessions share a desktop. `tests/test_headless.py::test_the_display_is_not_on_the_network`, `::test_xvfb_is_started_off_the_network_and_with_access_control` and `::test_the_display_refuses_a_client_without_the_session_cookie` fail when the Xvfb listens on TCP or accepts a client without its cookie. `tests/test_headless.py::test_no_descriptor_outlives_start_and_stop` and `::test_stop_right_after_start_leaves_nothing_behind` fail when a stop leaves a descriptor or a process. `tests/test_prefs_sections.py::test_the_platform_workarounds_never_take_a_choice_away` fails when a workaround is assigned instead of defaulted.
+**Enforced by.** `tests/test_headless.py::test_the_desktop_variable_name_is_a_contract` and `::test_the_desktop_never_touches_the_process_environment` fail when the desktop name moves out of the launch environment. `tests/test_headless.py::test_two_sessions_never_share_a_desktop` fails when two sessions share a desktop. `tests/test_headless.py::test_the_display_is_not_on_the_network`, `::test_xvfb_is_started_off_the_network_and_with_access_control` and `::test_the_display_refuses_a_client_without_the_session_cookie` fail when the Xvfb listens on TCP or accepts a client without its cookie. `tests/test_headless.py::test_no_descriptor_outlives_start_and_stop` and `::test_stop_right_after_start_leaves_nothing_behind` fail when a stop leaves a descriptor or a process. `tests/test_the_hidden_desktop_admits_a_low_process.py` fails when the created desktop has no Low label or not the interactive desktop's DACL. `tests/test_prefs.py::test_the_hidden_desktop_writes_no_sandbox_pref_on_windows` fails when a `security.sandbox.*` key is written.
-**Why.** A native headless Firefox has a rendering pipeline a site can measure, and the browser must not open windows on the desktop of the user. The hidden surface is the dedicated desktop, not the headless mode of the engine. The GPU process cannot parent its window across desktops under the default GPU sandbox, so that level is lowered on the virtual desktop. Above content level 4 the content process would go to another window station and the navigation would fail, so the content sandbox must stay on the desktop of the browser.
+**Why.** A native headless Firefox has a rendering pipeline a site can measure, and the browser must not open windows on the desktop of the user. The hidden surface is the dedicated desktop, not the headless mode of the engine. At every GPU sandbox level of 1 or more the GPU process runs at Low integrity and inherits the desktop of its parent; the sandbox assumes that desktop admits a Low process. A desktop with no label counts as Medium, so the GPU process cannot create its window there (retail 159.0: the GPU process died 3 of 3 launches, WebGL null). The label and the DACL make the desktop one the browser's sandbox can use, so no level is lowered.
**Files.** `src/invisible_core/_headless.py`, `src/invisible_core/prefs.py`, `src/invisible_core/environment.py`, `invisible_playwright: src/invisible_playwright/_session.py`.
**Don't.**
- Use the native headless mode of Firefox, write `INVPW_DESKTOP` in `os.environ`, or rename the desktop on one side only. *Question:* Is the native headless mode used, `INVPW_DESKTOP` written in `os.environ`, or the desktop renamed on one side only (grep result)?
-- Apply `gpu.level` 0 outside the virtual desktop, raise `content.level` above 4, or assign the workarounds with `update` instead of `setdefault`. *Question:* Is `gpu.level` 0 applied outside the virtual desktop, `content.level` raised above 4, or a workaround assigned with `update` (grep result, test)?
+- Write a `security.sandbox.*` pref for the hidden desktop, or create the desktop with a null security descriptor. *Question:* Is a `security.sandbox.*` pref written for the desktop, or is the desktop created without the interactive DACL and the Low label (grep result, test)?
diff --git a/src/invisible_core/_headless.py b/src/invisible_core/_headless.py
index 5c2a7f6..a335d5c 100644
--- a/src/invisible_core/_headless.py
+++ b/src/invisible_core/_headless.py
@@ -442,6 +442,109 @@ class _LinuxVirtualDisplay:
self._auth_dir = None
+# Low integrity, no write-up, on the Low integrity level SID (``LW``).
+_LOW_LABEL_SDDL = "S:(ML;;NW;;;LW)"
+
+
+def _label_the_hidden_desktop(handle: int) -> None:
+ """Give a new desktop the interactive desktop's DACL and a Low label.
+
+ Chromium's alternate desktop does the same two things (``CreateAltDesktop``
+ copies the current desktop's DACL; ``alternate_desktop.cc`` lowers the
+ integrity label). Both are set on the open handle with ``SetSecurityInfo``
+ rather than through ``SECURITY_ATTRIBUTES`` at creation: the DACL is read
+ from the live desktop as a pointer into its own descriptor and the label
+ comes from a one-line SDDL, so each is one call that reports its own
+ error, with no absolute descriptor to assemble. Nothing runs on the
+ desktop before ``start()`` returns.
+
+ Any failure raises: a desktop left at the default (Medium) label breaks
+ the GPU process at every sandbox level of 1 or more, so it is never
+ ignored and never replaced by a null descriptor.
+ """
+ import ctypes
+ from ctypes import wintypes
+
+ se_window_object = 7
+ dacl_information = 0x4
+ label_information = 0x10
+ sddl_revision_1 = 1
+
+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ user32 = ctypes.WinDLL("user32", use_last_error=True)
+ advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)
+ pvoid = ctypes.c_void_p
+ kernel32.GetCurrentThreadId.restype = wintypes.DWORD
+ kernel32.LocalFree.argtypes = (pvoid,)
+ kernel32.LocalFree.restype = pvoid
+ user32.GetThreadDesktop.argtypes = (wintypes.DWORD,)
+ user32.GetThreadDesktop.restype = wintypes.HANDLE
+ advapi32.GetSecurityInfo.argtypes = (
+ wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD, pvoid, pvoid,
+ ctypes.POINTER(pvoid), ctypes.POINTER(pvoid), ctypes.POINTER(pvoid))
+ advapi32.GetSecurityInfo.restype = wintypes.DWORD
+ advapi32.SetSecurityInfo.argtypes = (
+ wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD, pvoid, pvoid, pvoid,
+ pvoid)
+ advapi32.SetSecurityInfo.restype = wintypes.DWORD
+ convert = advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW
+ convert.argtypes = (
+ wintypes.LPCWSTR, wintypes.DWORD, ctypes.POINTER(pvoid), pvoid)
+ convert.restype = wintypes.BOOL
+ advapi32.GetSecurityDescriptorSacl.argtypes = (
+ pvoid, ctypes.POINTER(wintypes.BOOL), ctypes.POINTER(pvoid),
+ ctypes.POINTER(wintypes.BOOL))
+ advapi32.GetSecurityDescriptorSacl.restype = wintypes.BOOL
+
+ def fail(what: str, err: int) -> RuntimeError:
+ return RuntimeError(
+ "invisible_playwright headless=True could not secure its hidden "
+ "desktop (%s failed, WinError %d). Without the interactive "
+ "desktop's access list and a Low integrity label the browser's "
+ "GPU process cannot create its window there; run from a "
+ "logged-on session." % (what, err))
+
+ held = [] # LocalAlloc blocks, freed whatever happens below
+ try:
+ # The desktop this thread is on (WinSta0\Default in a normal logon).
+ # The handle belongs to the thread and is not closed here.
+ current = user32.GetThreadDesktop(kernel32.GetCurrentThreadId())
+ if not current:
+ raise fail("GetThreadDesktop", ctypes.get_last_error())
+ dacl, sd = pvoid(), pvoid()
+ err = advapi32.GetSecurityInfo(
+ current, se_window_object, dacl_information, None, None,
+ ctypes.byref(dacl), None, ctypes.byref(sd))
+ if err:
+ raise fail("GetSecurityInfo(DACL)", err)
+ held.append(sd)
+ err = advapi32.SetSecurityInfo(
+ handle, se_window_object, dacl_information, None, None, dacl, None)
+ if err:
+ raise fail("SetSecurityInfo(DACL)", err)
+
+ label_sd = pvoid()
+ if not convert(_LOW_LABEL_SDDL, sddl_revision_1,
+ ctypes.byref(label_sd), None):
+ raise fail("ConvertStringSecurityDescriptorToSecurityDescriptorW",
+ ctypes.get_last_error())
+ held.append(label_sd)
+ present, defaulted, sacl = wintypes.BOOL(), wintypes.BOOL(), pvoid()
+ if (not advapi32.GetSecurityDescriptorSacl(
+ label_sd, ctypes.byref(present), ctypes.byref(sacl),
+ ctypes.byref(defaulted)) or not present.value or not sacl):
+ raise fail("GetSecurityDescriptorSacl", ctypes.get_last_error())
+ err = advapi32.SetSecurityInfo(
+ handle, se_window_object, label_information, None, None, None,
+ sacl)
+ if err:
+ raise fail("SetSecurityInfo(label)", err)
+ finally:
+ for block in held:
+ if block:
+ kernel32.LocalFree(block)
+
+
class _WindowsVirtualDesktop:
"""A Win32 desktop object nobody switches to, owned by this session.
@@ -454,13 +557,19 @@ class _WindowsVirtualDesktop:
the GPU is the real one; only ``SwitchDesktop`` would show it, and nothing
here ever calls that.
- Two facts about that desktop are consequences, not choices, and the prefs
- that follow from them live in ``prefs._WIN_VIRT_DESKTOP_WORKAROUNDS``:
- the GPU process cannot parent its compositor window across desktops under
- the default GPU sandbox, and content processes above sandbox level 4 are
- put on the sandbox's own window station. Both were measured on this exact
- setup in 2026-05 (`22-patch-port-history.md` §P16, `71-bug-archive.md`
- #18 Bug A) and are what ``virtual_display=True`` switches on.
+ The desktop is made to fit the browser's own sandbox, not to work around
+ it. At every GPU sandbox level of 1 or more the GPU process runs at Low
+ integrity and inherits the desktop its parent is on; the sandbox assumes
+ that desktop admits a Low process. A desktop made with a null security
+ descriptor has no mandatory label, which Windows reads as Medium, and a
+ Low process cannot create its compositor window there (retail 159.0
+ measured on such a desktop: the GPU process died 3 of 3 launches and
+ WebGL read null). So ``start()`` gives the desktop the access list of the
+ interactive desktop and a Low mandatory label, as Chromium does for its
+ alternate desktop (``CreateAltDesktop`` in sandbox/win/src/window.cc,
+ alternate_desktop.cc). The browser's own sandbox levels (content 9,
+ GPU 2) then apply on it unchanged, and the core writes no
+ ``security.sandbox.*`` pref.
⛔ ``SetThreadDesktop`` on the launching thread is NOT enough, and that is
the mistake this class replaces for the second time: with ``lpDesktop``
@@ -503,6 +612,13 @@ class _WindowsVirtualDesktop:
"no interactive window station - a service, a scheduled task "
"with no logon - cannot host a headed browser; run from a "
"logged-on session." % err)
+ try:
+ _label_the_hidden_desktop(int(handle))
+ except BaseException:
+ user32.CloseDesktop.argtypes = (wintypes.HANDLE,)
+ user32.CloseDesktop.restype = wintypes.BOOL
+ user32.CloseDesktop(handle)
+ raise
self._handle = int(handle)
self._name = name
diff --git a/src/invisible_core/config.py b/src/invisible_core/config.py
index 85df210..31c1a29 100644
--- a/src/invisible_core/config.py
+++ b/src/invisible_core/config.py
@@ -113,9 +113,9 @@ def get_default_stealth_prefs(
silently change behaviour for existing integrations; the choice
between a shared-shape trajectory and no trajectory at all is
yours, and it is a real one.
- virtual_display: When True on Windows, apply GPU-disabling prefs
- to prevent GPU process crashes on virtual desktops without
- D3D11 backend.
+ virtual_display: Accepted so that callers need not change; it adds
+ no pref (the hidden desktop is made to fit the browser's own
+ sandbox, see ``_headless``).
proxy: Optional endpoint dict. A SOCKS endpoint writes the
``network.proxy.*`` auth prefs the patched binary reads; an
HTTP/HTTPS one is Playwright's to apply, so pass it to
diff --git a/src/invisible_core/prefs.py b/src/invisible_core/prefs.py
index 1f58a7c..a050fcf 100644
--- a/src/invisible_core/prefs.py
+++ b/src/invisible_core/prefs.py
@@ -1038,59 +1038,6 @@ _BASELINE: Dict[str, Any] = {
}
-# ──────────────────────────────────────────────────────────────────────
-# Windows hidden-desktop workarounds - when headless=True on Windows,
-# Firefox is CREATED on a fresh Win32 desktop (`_headless._WindowsVirtualDesktop`,
-# named in `STARTUPINFO.lpDesktop` by the wrapper's spawner). Two of the
-# engine's sandboxes assume the parent lives on the interactive desktop, and
-# each of the two keys below closes one of those assumptions. They are
-# emitted only when `virtual_display=True`, i.e. only when that desktop was
-# actually created (B172: the REAL fact, never a guess from the platform).
-#
-# The path this replaced, for the record: from 2026-06-11 to 2026-09-20 the
-# window was hidden by a DWMWA_CLOAK inside the binary instead, on the normal
-# desktop, and these two keys were dead code. The owner chose a stock engine
-# on this surface and the desktop as the hiding place, which is also what
-# the mass-test harness had used since 2026-05.
-#
-# Rejected before either key, measured 2026-05-05 (`22-patch-port-history.md`
-# §P16): forcing WARP (`layers.d3d11.force-warp`, `webgl.angle.force-warp`)
-# gives "Microsoft Basic Render Driver" and WebGL fields still null under
-# load; `webgl.out-of-process=False` moves WebGL into the content sandbox,
-# where ANGLE crashes the content process.
-# ──────────────────────────────────────────────────────────────────────
-
-_WIN_VIRT_DESKTOP_WORKAROUNDS: Dict[str, Any] = {
- # FF150 regression vs FF146 on CreateDesktop alt-desktop:
- # The GPU process sandbox (level=1, default since FF110) tries to parent
- # its compositor window to the parent process's window. Our worker spawns
- # Firefox on a CreateDesktop-created alt desktop - parent and GPU process
- # do not share the same desktop/HWND namespace, so window parenting fails
- # silently. WebRender falls back to "Software D3D11" and OOP-WebGL never
- # publishes a hardware ANGLE renderer → getContext('webgl') returns a
- # context but extensions/parameters/$hash all come back null/empty (FF146
- # had a more permissive sandbox, so the same setup worked there).
- # Bugzilla refs: 1798091, 1524591, 1229829. Lowering the GPU sandbox to 0
- # restores hardware compositor + functional WebGL on alt desktops.
- "security.sandbox.gpu.level": 0,
- # Same root cause as above, content process side. Wrapper repo issue #18
- # (tab crash on cross-process navigation under headless=True). Sandbox
- # content level > 4 puts content processes on the sandbox's own
- # kAlternateWinstation (see security/sandbox/win/src/sandboxbroker/
- # sandboxBroker.cpp line 1113-1114:
- # `if (aSandboxLevel > 4) config->SetDesktop(kAlternateWinstation)`).
- # Combined with our CreateDesktop alt-desktop, that puts browser process
- # and content processes on DIFFERENT desktops. Cross-process navigation
- # then fails window parenting between parent and child, the content
- # process exits cleanly (exitCode=0, signal=null) and Playwright fires
- # page.on('crash') ~10s after page load. Lowering content sandbox to 4
- # keeps content processes on the same desktop as the browser process,
- # which is what we want here (still tight enough - level 4 blocks
- # file/registry write, network calls, hardware access).
- "security.sandbox.content.level": 4,
-}
-
-
# The language table and its application moved to `_locale.py` in 36.x, with
# the one decision that applies it (`decide_session_locale`): a table that
# lives beside its only caller cannot be applied a second time somewhere
@@ -1971,18 +1918,6 @@ def _apply_extension_lists(prefs: Dict[str, Any], persona) -> None:
prefs["zoom.stealth.webgl2.extensions"] = ""
-def _apply_platform_workarounds(prefs: Dict[str, Any], *, virtual_display: bool) -> None:
- """`setdefault`, deliberately: anything a section above chose already wins."""
- # No Linux table. It held `gfx.webrender.all=False`, the engine's own default, which does nothing: WebRender is mandatory in 159 and on
- # llvmpipe `gfx.webrender.reject-software-driver` (true on GTK) is what sends it to software WebRender. The reason it carried
- # ("`ConnectToCompositor` retries forever under Xvfb") named a function that is not in 159's gfx/ or widget/. A pref is declared once and only if it does something.
-
- # Windows virtual-desktop workarounds (headless=True on Windows).
- if virtual_display and sys.platform == "win32":
- for k, v in _WIN_VIRT_DESKTOP_WORKAROUNDS.items():
- prefs.setdefault(k, v)
-
-
def _apply_caller_overlay(prefs: Dict[str, Any],
extra_prefs: Optional[Dict[str, Any]]) -> None:
"""LAST, so users can override anything we set.
@@ -2025,14 +1960,14 @@ def translate_profile_to_prefs(
REQUIRED: a missing zone is refused, never left to
the host (see ``_apply_timezone``).
extra_prefs: Optional overlay applied LAST.
- virtual_display: When True on Windows, apply GPU-disabling workarounds
- to prevent the GPU process from crashing on virtual
- desktops that have no D3D11 backend.
+ virtual_display: Accepted so that callers need not change; it adds
+ no pref. The hidden desktop is made to fit the
+ browser's own sandbox (``_headless``), so no
+ ``security.sandbox.*`` pref is written for it.
The body is the ORDER, and the order is the contract: the caller overlay
- runs last so it can override or delete anything, and the platform
- workarounds `setdefault` so they never take a choice away from a section
- above them. Each step keeps the reasoning it was written with.
+ runs last so it can override or delete anything. Each step keeps the
+ reasoning it was written with.
"""
prefs: Dict[str, Any] = dict(_BASELINE)
@@ -2053,7 +1988,6 @@ def translate_profile_to_prefs(
_apply_timezone(prefs, timezone)
_apply_render_seed(prefs, profile)
_apply_extension_lists(prefs, persona)
- _apply_platform_workarounds(prefs, virtual_display=virtual_display)
_apply_caller_overlay(prefs, extra_prefs)
return prefs
diff --git a/tests/test_canvas_2d_on_the_cpu.py b/tests/test_canvas_2d_on_the_cpu.py
index a36b7df..117a7a8 100644
--- a/tests/test_canvas_2d_on_the_cpu.py
+++ b/tests/test_canvas_2d_on_the_cpu.py
@@ -14,10 +14,7 @@ import sys
import pytest
from invisible_core._fpforge import generate_profile
-from invisible_core.prefs import (
- _WIN_VIRT_DESKTOP_WORKAROUNDS,
- translate_profile_to_prefs,
-)
+from invisible_core.prefs import translate_profile_to_prefs
pytestmark = pytest.mark.unit
@@ -30,7 +27,3 @@ def test_canvas_is_not_accelerated_on_any_host(monkeypatch, platform, virtual_di
prefs = translate_profile_to_prefs(generate_profile(seed=seed), timezone="America/New_York",
virtual_display=virtual_display)
assert prefs["gfx.canvas.accelerated"] is False
-
-
-def test_declared_once_not_in_a_platform_table():
- assert "gfx.canvas.accelerated" not in _WIN_VIRT_DESKTOP_WORKAROUNDS
diff --git a/tests/test_prefs.py b/tests/test_prefs.py
index e833385..2bd2056 100644
--- a/tests/test_prefs.py
+++ b/tests/test_prefs.py
@@ -443,21 +443,17 @@ def test_xvfb_workarounds_absent_on_windows(monkeypatch):
@pytest.mark.unit
-def test_virtual_display_workaround_applied_on_windows(monkeypatch):
- # VD1
+@pytest.mark.parametrize("virtual_display", [False, True])
+def test_the_hidden_desktop_writes_no_sandbox_pref_on_windows(monkeypatch, virtual_display):
+ # VD1: the hidden desktop is made to fit the browser's own sandbox
+ # (``_headless._label_the_hidden_desktop``), so Firefox's own levels apply (content 9,
+ # GPU 2) and the core writes no ``security.sandbox.*`` key. Lowering them (GPU 0,
+ # content 4) was a workaround for a desktop with no Low label, where retail 159.0's
+ # GPU process died 3 of 3 launches.
monkeypatch.setattr(sys, "platform", "win32")
p = generate_profile(seed=42)
- prefs = translate_profile_to_prefs(p, virtual_display=True, timezone="America/New_York")
- assert prefs["security.sandbox.gpu.level"] == 0
-
-
-@pytest.mark.unit
-def test_virtual_display_workaround_absent_when_disabled(monkeypatch):
- # VD2
- monkeypatch.setattr(sys, "platform", "win32")
- p = generate_profile(seed=42)
- prefs = translate_profile_to_prefs(p, virtual_display=False, timezone="America/New_York")
- assert "security.sandbox.gpu.level" not in prefs
+ prefs = translate_profile_to_prefs(p, virtual_display=virtual_display, timezone="America/New_York")
+ assert [k for k in prefs if k.startswith("security.sandbox.")] == []
# ──────────────────────────────────────────────────────────────────────
@@ -536,7 +532,7 @@ def test_webgl_extensions_preserved_on_linux(monkeypatch):
@pytest.mark.unit
def test_xvfb_workarounds_applied_on_linux(monkeypatch):
- # XW1: there is no Linux table any more (it held one dead pref, see _apply_platform_workarounds):
+ # XW1: there is no Linux table any more (it held one dead pref):
# nothing of it reaches the prefs, and what a caller passes in ``extra_prefs`` still wins.
monkeypatch.setattr(sys, "platform", "linux")
p = generate_profile(seed=42)
@@ -563,14 +559,13 @@ def test_xvfb_workarounds_caller_can_override(monkeypatch):
@pytest.mark.unit
-def test_virtual_display_no_op_on_linux(monkeypatch):
- # VD3: ``virtual_display`` is a Windows-only concept (CreateDesktop
- # alt-desktop GPU sandbox workaround). Even when True, Linux must
- # not pick up ``security.sandbox.gpu.level``.
+def test_virtual_display_writes_no_sandbox_pref_on_linux(monkeypatch):
+ # VD3: Even when True, Linux writes no ``security.sandbox.*`` pref: Firefox's own
+ # defaults apply under Xvfb.
monkeypatch.setattr(sys, "platform", "linux")
p = generate_profile(seed=42)
prefs = translate_profile_to_prefs(p, virtual_display=True, timezone="America/New_York")
- assert "security.sandbox.gpu.level" not in prefs
+ assert [k for k in prefs if k.startswith("security.sandbox.")] == []
# ──────────────────────────────────────────────────────────────────────
diff --git a/tests/test_prefs_sections.py b/tests/test_prefs_sections.py
index 12e3e54..7704810 100644
--- a/tests/test_prefs_sections.py
+++ b/tests/test_prefs_sections.py
@@ -49,39 +49,6 @@ def test_the_caller_overlay_can_delete_a_pref_entirely(profile):
assert key not in got
-@pytest.mark.parametrize("platform,table", [
- ("win32", "_WIN_VIRT_DESKTOP_WORKAROUNDS"),
-])
-def test_the_platform_workarounds_never_take_a_choice_away(
- monkeypatch, platform, table):
- """`setdefault`, so a section above always wins. Anything else and a
- workaround silently overrides a sampled value on one platform only - a bug
- that reproduces on one developer's machine and nowhere else.
-
- BOTH branches, with the platform patched. The first version of this ran on
- the host platform only, and a mutation flipping the LINUX branch to plain
- assignment SURVIVED the whole suite on Windows - the exact "reproduces
- nowhere you are looking" shape the test is about. Measured: with
- `sys.platform` left alone, 1 of the 2 mutations was caught; patched, both.
- """
- monkeypatch.setattr(P.sys, "platform", platform)
- sentinel = object()
- prefs = {key: sentinel for key in getattr(P, table)}
- assert prefs, f"{table} is empty; this test would pass over nothing"
-
- P._apply_platform_workarounds(prefs, virtual_display=True)
-
- assert all(v is sentinel for v in prefs.values()), (
- f"a {platform} workaround overwrote a value the pipeline had already "
- f"chosen")
-
- # And it DOES apply them when nothing chose first, or the parametrisation
- # above would pass against a function that does nothing at all.
- fresh = {}
- P._apply_platform_workarounds(fresh, virtual_display=True)
- assert set(fresh) == set(getattr(P, table))
-
-
def test_the_pipeline_runs_the_overlay_last():
"""Read off the source, because the property is the ORDER and the order is
only visible as a sequence of calls."""
@@ -96,7 +63,7 @@ def test_the_pipeline_runs_the_overlay_last():
assert calls[-1] == "_apply_caller_overlay", (
f"the caller overlay is not last; the pipeline ends with {calls[-1]!r}, "
f"so a user override can be silently overwritten by whatever follows it")
- assert calls[-2] == "_apply_platform_workarounds"
+ assert calls[-2] == "_apply_extension_lists"
assert calls[0] == "_apply_gpu_persona", (
"the persona must be applied first: _apply_extension_lists is told "
"whether one was, and everything else may overwrite what it set")
diff --git a/tests/test_the_hidden_desktop_admits_a_low_process.py b/tests/test_the_hidden_desktop_admits_a_low_process.py
new file mode 100644
index 0000000..b25f12e
--- /dev/null
+++ b/tests/test_the_hidden_desktop_admits_a_low_process.py
@@ -0,0 +1,119 @@
+"""The hidden desktop must admit the browser's own sandboxed processes.
+
+At every GPU sandbox level of 1 or more Firefox's GPU process runs at Low integrity and inherits the desktop its parent is on
+(sandboxBroker.cpp:1347-1348); the sandbox assumes that desktop admits a Low process (broker_services.cc:685-700). A desktop made
+with a null security descriptor has no mandatory label, which Windows reads as Medium, and a Low process cannot create its
+compositor window on it: retail 159.0 on such a desktop lost its GPU process 3 of 3 launches and read WebGL as null
+(RetailCaptures run 46903007316). So the core creates the desktop with the DACL of the interactive desktop and a Low label, as
+Chromium does for its alternate desktop, and writes no ``security.sandbox.*`` pref.
+
+The test creates the desktop through the real ``_WindowsVirtualDesktop.start()`` and reads the label and the DACL back from the
+created object. Windows only: a desktop and a mandatory label exist nowhere else.
+"""
+from __future__ import annotations
+
+import sys
+
+import pytest
+
+from invisible_core._headless import _WindowsVirtualDesktop
+
+pytestmark = [
+ pytest.mark.unit,
+ pytest.mark.skipif(sys.platform != "win32",
+ reason="a Win32 desktop and its mandatory label exist only on Windows"),
+]
+
+SE_WINDOW_OBJECT = 7
+DACL_SECURITY_INFORMATION = 0x4
+LABEL_SECURITY_INFORMATION = 0x10
+SYSTEM_MANDATORY_LABEL_ACE_TYPE = 0x11
+SECURITY_MANDATORY_LOW_RID = 0x1000
+SECURITY_MANDATORY_MEDIUM_RID = 0x2000
+
+
+class _Win:
+ def __init__(self):
+ import ctypes
+ from ctypes import wintypes
+ self.ctypes, self.wintypes = ctypes, wintypes
+ self.kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
+ self.user32 = ctypes.WinDLL("user32", use_last_error=True)
+ self.advapi32 = ctypes.WinDLL("advapi32", use_last_error=True)
+ pv = ctypes.c_void_p
+ self.kernel32.GetCurrentThreadId.restype = wintypes.DWORD
+ self.kernel32.LocalFree.argtypes = (pv,)
+ self.kernel32.LocalFree.restype = pv
+ self.user32.GetThreadDesktop.argtypes = (wintypes.DWORD,)
+ self.user32.GetThreadDesktop.restype = wintypes.HANDLE
+ self.advapi32.GetSecurityInfo.argtypes = (
+ wintypes.HANDLE, wintypes.DWORD, wintypes.DWORD, pv, pv,
+ ctypes.POINTER(pv), ctypes.POINTER(pv), ctypes.POINTER(pv))
+ self.advapi32.GetSecurityInfo.restype = wintypes.DWORD
+ to_string = self.advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW
+ to_string.argtypes = (pv, wintypes.DWORD, wintypes.DWORD,
+ ctypes.POINTER(ctypes.c_void_p), pv)
+ to_string.restype = wintypes.BOOL
+
+ def label_rid(self, handle):
+ """The integrity RID of the object's mandatory label; Medium when it carries none (Windows' default)."""
+ ct = self.ctypes
+ sacl, sd = ct.c_void_p(), ct.c_void_p()
+ err = self.advapi32.GetSecurityInfo(
+ self.wintypes.HANDLE(handle), SE_WINDOW_OBJECT, LABEL_SECURITY_INFORMATION,
+ None, None, None, ct.byref(sacl), ct.byref(sd))
+ assert err == 0, "GetSecurityInfo(label) failed, WinError %d" % err
+ try:
+ if not sacl.value:
+ return SECURITY_MANDATORY_MEDIUM_RID
+ acl = ct.string_at(sacl.value, 8)
+ ace_count = int.from_bytes(acl[4:6], "little")
+ assert ace_count == 1, "the label ACL holds %d entries" % ace_count
+ ace = ct.string_at(sacl.value + 8, 8)
+ assert ace[0] == SYSTEM_MANDATORY_LABEL_ACE_TYPE, "the SACL entry is not a mandatory label"
+ sid_at = sacl.value + 8 + 8
+ sub_count = ct.string_at(sid_at + 1, 1)[0]
+ sub_authorities = ct.string_at(sid_at + 8, 4 * sub_count)
+ return int.from_bytes(sub_authorities[-4:], "little")
+ finally:
+ self.kernel32.LocalFree(sd)
+
+ def dacl_sddl(self, handle):
+ """The object's DACL as SDDL text, which spells every entry's SID and rights."""
+ ct = self.ctypes
+ sd = ct.c_void_p()
+ err = self.advapi32.GetSecurityInfo(
+ self.wintypes.HANDLE(handle), SE_WINDOW_OBJECT, DACL_SECURITY_INFORMATION,
+ None, None, None, None, ct.byref(sd))
+ assert err == 0, "GetSecurityInfo(DACL) failed, WinError %d" % err
+ text = ct.c_void_p()
+ try:
+ assert self.advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW(
+ sd, 1, DACL_SECURITY_INFORMATION, ct.byref(text), None)
+ try:
+ return ct.wstring_at(text.value)
+ finally:
+ self.kernel32.LocalFree(text)
+ finally:
+ self.kernel32.LocalFree(sd)
+
+ def interactive_desktop(self):
+ return self.user32.GetThreadDesktop(self.kernel32.GetCurrentThreadId())
+
+
+def test_the_hidden_desktop_is_labelled_low_and_carries_the_interactive_dacl():
+ win = _Win()
+ interactive = win.interactive_desktop()
+ assert interactive, "this thread is on no desktop"
+ vd = _WindowsVirtualDesktop()
+ vd.start()
+ try:
+ rid = win.label_rid(vd._handle)
+ assert rid == SECURITY_MANDATORY_LOW_RID, (
+ "the hidden desktop's integrity label is 0x%x, not Low (0x1000): the browser's Low-integrity GPU process "
+ "cannot create its window on it" % rid)
+ assert win.dacl_sddl(vd._handle) == win.dacl_sddl(interactive), (
+ "the hidden desktop does not carry the access list of the interactive desktop")
+ finally:
+ vd.stop()
+ assert vd._handle is None
diff --git a/tests/test_webgl_not_decided_by_host_blocklist.py b/tests/test_webgl_not_decided_by_host_blocklist.py
index d0a65ac..6f87aff 100644
--- a/tests/test_webgl_not_decided_by_host_blocklist.py
+++ b/tests/test_webgl_not_decided_by_host_blocklist.py
@@ -16,10 +16,7 @@ import sys
import pytest
from invisible_core._fpforge import generate_profile
-from invisible_core.prefs import (
- _WIN_VIRT_DESKTOP_WORKAROUNDS,
- translate_profile_to_prefs,
-)
+from invisible_core.prefs import translate_profile_to_prefs
pytestmark = pytest.mark.unit
@@ -43,6 +40,10 @@ def test_webgl_is_declared_ok_on_every_host(monkeypatch, platform, virtual_displ
assert "gfx.blacklist.webgl.angle" not in prefs
-def test_no_platform_table_brings_them_back():
+@pytest.mark.parametrize("platform", ["win32", "linux"])
+def test_a_hidden_desktop_does_not_bring_them_back(monkeypatch, platform):
+ monkeypatch.setattr(sys, "platform", platform)
+ prefs = translate_profile_to_prefs(generate_profile(seed=1), timezone="America/New_York",
+ virtual_display=True)
for name in ("webgl.force-enabled", "gfx.blacklist.webgl.angle"):
- assert name not in _WIN_VIRT_DESKTOP_WORKAROUNDS
+ assert name not in prefs
--
2.55.0.windows.5
+899
View File
@@ -0,0 +1,899 @@
r"""With the core's fix (interactive DACL and a Low label on the hidden desktop, no sandbox pref), what does the hidden Windows desktop do to the GPU process, the compositor, WebGL and c:\windows\fonts? (a measurement on a branch of its own, not a gate)
python scripts/hunt_d72_sandbox_fix.py --binary PATH_TO_FIREFOX_EXE --out evidence
The workflow installs the core with the fix (scripts/hunt_d72_core_fix.patch on oss-invisible/core 20e5d50) over the wrapper's own install, so the core makes
its hidden desktop with the interactive desktop's DACL and a Low mandatory label and writes no security.sandbox.* pref: Firefox's own levels apply (content 9,
GPU 2). One variant, "fix": InvisiblePlaywright(seed=1, headless=True), no extra_prefs.
evidence/fix.json records: about:support (the page's whole text), the prefs the browser reads from its profile (user.js and prefs.js; user.js must hold no
security.sandbox.* line), what a page on 127.0.0.1 reads from WebGL and WebGL2, three cross-origin navigations, every firefox.exe (and crashreporter.exe) process
with its command line, its type and the integrity level of its token (taken while the browser is open, with ctypes; the GPU process alive at the END is evidence),
any sign of a crash, the security descriptor of every desktop of the window station (the label and the DACL, read with GetSecurityInfo through ctypes while the
browser runs; the hidden desktop is the one that holds the windows of the browser), and a trace of the whole run for c:\windows\fonts.
The fonts trace is the recorder of the host oracle (scripts/ci_ab_host.py WindowsTrace: the process-creation audit, event 4688, and an ETW session on
Microsoft-Windows-Kernel-File Create, started BEFORE the launch and stopped after the close), the method of the retail footprint on the hidden desktop
(oss-invisible/RetailCaptures, branch hunt/abhost-retail-hidden-desktop, scripts/abhost_retail/hidden_desktop.py). Here the tree is read from the browser
parents found after the launch; each Create event of a path under \windows\fonts is given the process type of its pid (parent, gpu, tab, rdd, socket, utility...).
It sees opens by file name (a read through a file the process already holds, or a memory mapping a driver makes in the kernel, is not a Create event).
evidence/summary.json has the answer in one place ("result") and the assertions ("assertions"). The variant runs in a child process of its own, so a hang is cut
by a timeout and the processes it left are recorded and killed. Only Windows is meaningful; nothing here fails the run on one query that errors, the error is
the record. The exit code is 1 only when user.js holds a security.sandbox.* line (the core wrote a pref it must not write).
"""
from __future__ import annotations
import argparse
import hashlib
import http.server
import json
import os
import re
import shutil
import socketserver
import subprocess
import sys
import tempfile
import threading
import time
import traceback
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.dont_write_bytecode = True
sys.path.insert(0, str(HERE))
SEED = 1
VARIANTS = {
"fix": None, # no extra_prefs: the levels are Firefox's own
}
CHILD_TIMEOUT_S = 660
NAV_SETTLE_S = 3
LATE_CHECK_S = 12 # the content process of the wrapper's issue #18 died about 10 s after the load
INTEGRITY_NAMES = {0x0000: "Untrusted", 0x1000: "Low", 0x2000: "Medium", 0x2100: "MediumPlus", 0x3000: "High", 0x4000: "System", 0x5000: "Protected"}
# ---------------------------------------------------------------------------------------------------------------------------------------
# The pages
# ---------------------------------------------------------------------------------------------------------------------------------------
NAV_PAGE = (b"<!doctype html><meta charset=utf-8><title>start</title><body><span id=h></span>"
b"<script>window.__ran=true;document.title='ran:'+location.host;document.getElementById('h').textContent=location.host;</script></body>")
WEBGL_PAGE = b"""<!doctype html><meta charset=utf-8><title>webgl</title><body><script>
function probe(kind) {
var out = {context: false, renderer: null, vendor: null, error: null};
var gl = null;
try { gl = document.createElement('canvas').getContext(kind); } catch (e) { out.error = String(e); }
if (!gl) return out;
out.context = true;
try {
var ext = gl.getExtension('WEBGL_debug_renderer_info');
out.debug_info_extension = !!ext;
if (ext) {
out.renderer = gl.getParameter(ext.UNMASKED_RENDERER_WEBGL);
out.vendor = gl.getParameter(ext.UNMASKED_VENDOR_WEBGL);
}
} catch (e) { out.error = String(e); }
try {
out.masked_renderer = gl.getParameter(gl.RENDERER);
out.masked_vendor = gl.getParameter(gl.VENDOR);
out.version = gl.getParameter(gl.VERSION);
out.context_lost = gl.isContextLost();
} catch (e) { out.error2 = String(e); }
return out;
}
window.__webgl = {webgl: probe('webgl'), webgl2: probe('webgl2')};
window.__webgl_done = true;
</script></body>"""
class _Handler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
body = WEBGL_PAGE if self.path.startswith("/webgl") else NAV_PAGE
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(body)
def log_message(self, *args):
pass
class _Server(socketserver.ThreadingMixIn, http.server.HTTPServer):
daemon_threads = True
allow_reuse_address = True
def _serve(host: str) -> "_Server":
server = _Server((host, 0), _Handler)
threading.Thread(target=server.serve_forever, daemon=True).start()
return server
# ---------------------------------------------------------------------------------------------------------------------------------------
# The processes: command line, type, integrity level of the token
# ---------------------------------------------------------------------------------------------------------------------------------------
_win = {}
def _winapi():
"""The few Win32 calls, with their types declared (a 64-bit handle through the default int type is a wrong answer, not an error)."""
if _win:
return _win
import ctypes
from ctypes import wintypes
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
adv = ctypes.WinDLL("advapi32", use_last_error=True)
k32.OpenProcess.restype = wintypes.HANDLE
k32.OpenProcess.argtypes = (wintypes.DWORD, wintypes.BOOL, wintypes.DWORD)
k32.CloseHandle.argtypes = (wintypes.HANDLE,)
adv.OpenProcessToken.restype = wintypes.BOOL
adv.OpenProcessToken.argtypes = (wintypes.HANDLE, wintypes.DWORD, ctypes.POINTER(wintypes.HANDLE))
adv.GetTokenInformation.restype = wintypes.BOOL
adv.GetTokenInformation.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD))
adv.GetSidSubAuthorityCount.restype = ctypes.POINTER(ctypes.c_ubyte)
adv.GetSidSubAuthorityCount.argtypes = (ctypes.c_void_p,)
adv.GetSidSubAuthority.restype = ctypes.POINTER(wintypes.DWORD)
adv.GetSidSubAuthority.argtypes = (ctypes.c_void_p, wintypes.DWORD)
_win.update(ctypes=ctypes, wintypes=wintypes, k32=k32, adv=adv)
return _win
def integrity_of(pid: int) -> dict:
"""The integrity level of a process's token, or the error: OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION) + OpenProcessToken + GetTokenInformation."""
try:
w = _winapi()
ctypes, wintypes, k32, adv = w["ctypes"], w["wintypes"], w["k32"], w["adv"]
PROCESS_QUERY_LIMITED_INFORMATION, TOKEN_QUERY = 0x1000, 0x0008
TOKEN_INTEGRITY_LEVEL, TOKEN_IS_RESTRICTED = 25, 40
proc = k32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, int(pid))
if not proc:
return {"error": "OpenProcess failed, WinError %d" % ctypes.get_last_error()}
try:
token = wintypes.HANDLE()
if not adv.OpenProcessToken(proc, TOKEN_QUERY, ctypes.byref(token)):
return {"error": "OpenProcessToken failed, WinError %d" % ctypes.get_last_error()}
try:
out = {}
buf = ctypes.create_string_buffer(512)
need = wintypes.DWORD(0)
if not adv.GetTokenInformation(token, TOKEN_INTEGRITY_LEVEL, buf, len(buf), ctypes.byref(need)):
return {"error": "GetTokenInformation(TokenIntegrityLevel) failed, WinError %d" % ctypes.get_last_error()}
sid = ctypes.c_void_p.from_buffer(buf).value # TOKEN_MANDATORY_LABEL starts with the SID pointer
count = adv.GetSidSubAuthorityCount(sid)[0]
rid = int(adv.GetSidSubAuthority(sid, count - 1)[0])
out["rid"] = rid
out["rid_hex"] = "0x%04X" % rid
out["level"] = INTEGRITY_NAMES.get(rid, "Other(0x%04X)" % rid)
restricted = wintypes.DWORD(0)
if adv.GetTokenInformation(token, TOKEN_IS_RESTRICTED, ctypes.byref(restricted), ctypes.sizeof(restricted), ctypes.byref(need)):
out["token_is_restricted"] = bool(restricted.value)
return out
finally:
k32.CloseHandle(token)
finally:
k32.CloseHandle(proc)
except Exception as exc: # noqa: BLE001 - the error is the record
return {"error": repr(exc)}
def process_type(cmdline: "str | None") -> str:
"""parent for the browser process; for a child, the last word of its command line (tab, gpu, rdd, socket, utility, ...)."""
if not cmdline:
return "unknown"
if "-contentproc" not in cmdline:
return "parent"
words = cmdline.replace('"', " ").split()
return words[-1] if words else "unknown"
def profile_of(cmdline: "str | None") -> "str | None":
m = re.search(r'-profile\s+(?:"([^"]+)"|(\S+))', cmdline or "")
return (m.group(1) or m.group(2)) if m else None
def snapshot(label: str) -> dict:
"""Every firefox.exe and crashreporter.exe process now: pid, parent pid, command line (WMI), type, integrity. Never raises."""
snap = {"label": label, "at_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "processes": [], "crashreporters": [], "error": None}
script = ("Get-CimInstance Win32_Process -Filter \"Name='firefox.exe' OR Name='crashreporter.exe'\" | "
"Select-Object Name,ProcessId,ParentProcessId,CommandLine,ExecutablePath | ConvertTo-Json -Compress")
rows = None
for shell in ("powershell", "pwsh"):
try:
r = subprocess.run([shell, "-NoProfile", "-NonInteractive", "-Command", script], capture_output=True, text=True, timeout=90)
except (OSError, subprocess.SubprocessError) as exc:
snap["error"] = "%s: %r" % (shell, exc)
continue
if r.returncode != 0:
snap["error"] = "%s exit %d: %s" % (shell, r.returncode, (r.stderr or "")[-400:])
continue
text = (r.stdout or "").strip()
try:
rows = json.loads(text) if text else []
snap["error"] = None
except ValueError as exc:
snap["error"] = "%s output not JSON: %r %r" % (shell, exc, text[:200])
continue
break
if rows is None:
return snap
if isinstance(rows, dict):
rows = [rows]
for row in rows:
pid = row.get("ProcessId")
cmd = row.get("CommandLine")
if (row.get("Name") or "").lower() == "crashreporter.exe":
snap["crashreporters"].append({"pid": pid, "parent_pid": row.get("ParentProcessId"), "command_line": cmd})
continue
snap["processes"].append({
"pid": pid, "parent_pid": row.get("ParentProcessId"), "command_line": cmd, "executable": row.get("ExecutablePath"),
"type": process_type(cmd), "integrity": integrity_of(pid) if pid else {"error": "no pid"},
})
snap["processes"].sort(key=lambda p: (p["type"] != "parent", p["type"], p["pid"] or 0))
snap["gpu_process_exists"] = any(p["type"] == "gpu" for p in snap["processes"])
return snap
def kill_firefox() -> dict:
"""Close every firefox.exe with its whole tree and count again."""
for _ in range(3):
try:
subprocess.run(["taskkill", "/F", "/T", "/IM", "firefox.exe"], capture_output=True, text=True, timeout=60)
except (OSError, subprocess.SubprocessError):
pass
time.sleep(1)
if not snapshot("recount")["processes"]:
return {"left": 0}
return {"left": len(snapshot("recount")["processes"])}
# ---------------------------------------------------------------------------------------------------------------------------------------
# The desktops: the label and the DACL of every desktop of the window station (GetSecurityInfo, through ctypes)
# ---------------------------------------------------------------------------------------------------------------------------------------
_LABEL_RE = re.compile(r"\(ML;[^;]*;[^;]*;[^;]*;[^;]*;([A-Z0-9]+)\)")
LABEL_NAMES = {"LW": "Low", "ME": "Medium", "MP": "MediumPlus", "HI": "High", "SI": "System"}
READ_CONTROL, DESKTOP_READOBJECTS, DESKTOP_ENUMERATE = 0x20000, 0x0001, 0x0040
SE_WINDOW_OBJECT, SDDL_REVISION_1 = 7, 1
DACL_SECURITY_INFORMATION, LABEL_SECURITY_INFORMATION = 0x4, 0x10
def desktops_security(firefox_pids) -> dict:
"""The desktops of this process's window station, each with the mandatory label and the DACL as SDDL (GetSecurityInfo with LABEL_SECURITY_INFORMATION and
DACL_SECURITY_INFORMATION, access READ_CONTROL) and the top-level windows on it, those owned by a firefox.exe in `firefox_pids` counted apart. The hidden desktop is
the one that holds windows of the browser (`hosting_firefox`). A desktop that cannot be opened or read says why; nothing raises."""
out = {"at_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "window_station": None, "desktops": [], "hosting_firefox": [], "error": None}
if sys.platform != "win32":
out["error"] = "not Windows"
return out
pids = {int(p) for p in firefox_pids or [] if p}
try:
import ctypes
from ctypes import wintypes
user32 = ctypes.WinDLL("user32", use_last_error=True)
adv = ctypes.WinDLL("advapi32", use_last_error=True)
k32 = ctypes.WinDLL("kernel32", use_last_error=True)
enum_desktops = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.LPWSTR, wintypes.LPARAM)
enum_windows = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
user32.GetProcessWindowStation.restype = wintypes.HANDLE
user32.GetProcessWindowStation.argtypes = ()
user32.GetUserObjectInformationW.restype = wintypes.BOOL
user32.GetUserObjectInformationW.argtypes = (wintypes.HANDLE, ctypes.c_int, ctypes.c_void_p, wintypes.DWORD, ctypes.POINTER(wintypes.DWORD))
user32.EnumDesktopsW.restype = wintypes.BOOL
user32.EnumDesktopsW.argtypes = (wintypes.HANDLE, enum_desktops, wintypes.LPARAM)
user32.OpenDesktopW.restype = wintypes.HANDLE
user32.OpenDesktopW.argtypes = (wintypes.LPCWSTR, wintypes.DWORD, wintypes.BOOL, wintypes.DWORD)
user32.CloseDesktop.restype = wintypes.BOOL
user32.CloseDesktop.argtypes = (wintypes.HANDLE,)
user32.EnumDesktopWindows.restype = wintypes.BOOL
user32.EnumDesktopWindows.argtypes = (wintypes.HANDLE, enum_windows, wintypes.LPARAM)
user32.GetWindowThreadProcessId.argtypes = (wintypes.HWND, ctypes.POINTER(wintypes.DWORD))
user32.IsWindowVisible.argtypes = (wintypes.HWND,)
adv.GetSecurityInfo.restype = wintypes.DWORD
adv.GetSecurityInfo.argtypes = (wintypes.HANDLE, ctypes.c_int, wintypes.DWORD, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_void_p,
ctypes.POINTER(ctypes.c_void_p))
adv.ConvertSecurityDescriptorToStringSecurityDescriptorW.restype = wintypes.BOOL
adv.ConvertSecurityDescriptorToStringSecurityDescriptorW.argtypes = (ctypes.c_void_p, wintypes.DWORD, wintypes.DWORD, ctypes.POINTER(ctypes.c_void_p),
ctypes.c_void_p)
k32.LocalFree.restype = ctypes.c_void_p
k32.LocalFree.argtypes = (ctypes.c_void_p,)
def sddl_of(handle, info):
sd = ctypes.c_void_p()
err = adv.GetSecurityInfo(handle, SE_WINDOW_OBJECT, info, None, None, None, None, ctypes.byref(sd))
if err:
return None, "GetSecurityInfo failed, error %d" % err
try:
text = ctypes.c_void_p()
if not adv.ConvertSecurityDescriptorToStringSecurityDescriptorW(sd, SDDL_REVISION_1, info, ctypes.byref(text), None):
return None, "ConvertSecurityDescriptorToStringSecurityDescriptorW failed, WinError %d" % ctypes.get_last_error()
try:
return ctypes.wstring_at(text.value), None
finally:
k32.LocalFree(text)
finally:
k32.LocalFree(sd)
winsta = user32.GetProcessWindowStation()
name_buf = ctypes.create_unicode_buffer(256)
need = wintypes.DWORD(0)
if winsta and user32.GetUserObjectInformationW(winsta, 2, name_buf, ctypes.sizeof(name_buf), ctypes.byref(need)): # UOI_NAME
out["window_station"] = name_buf.value
names: list = []
def each_desktop(name, _lparam):
names.append(name)
return True
if not user32.EnumDesktopsW(winsta, enum_desktops(each_desktop), 0):
out["error"] = "EnumDesktopsW failed, WinError %d" % ctypes.get_last_error()
for name in names:
d = {"name": name, "label_sddl": None, "label_level": None, "label_is_low": None, "dacl_sddl": None, "windows_total": None,
"windows_owned_by_firefox": None, "errors": []}
out["desktops"].append(d)
handle = user32.OpenDesktopW(name, 0, False, READ_CONTROL | DESKTOP_READOBJECTS | DESKTOP_ENUMERATE)
can_enum = bool(handle)
if not handle:
d["errors"].append("OpenDesktopW(READ_CONTROL|ENUMERATE) failed, WinError %d" % ctypes.get_last_error())
handle = user32.OpenDesktopW(name, 0, False, READ_CONTROL)
if not handle:
d["errors"].append("OpenDesktopW(READ_CONTROL) failed, WinError %d" % ctypes.get_last_error())
continue
try:
d["label_sddl"], err = sddl_of(handle, LABEL_SECURITY_INFORMATION)
if err:
d["errors"].append("label: " + err)
elif d["label_sddl"] is not None:
m = _LABEL_RE.search(d["label_sddl"])
d["label_level"] = LABEL_NAMES.get(m.group(1), m.group(1)) if m else "none (no mandatory label: counts as Medium)"
d["label_is_low"] = bool(m) and m.group(1) == "LW"
d["dacl_sddl"], err = sddl_of(handle, DACL_SECURITY_INFORMATION)
if err:
d["errors"].append("dacl: " + err)
if can_enum:
owners: list = []
def each_window(hwnd, _lparam):
owner = wintypes.DWORD()
user32.GetWindowThreadProcessId(hwnd, ctypes.byref(owner))
owners.append(int(owner.value))
return True
if user32.EnumDesktopWindows(handle, enum_windows(each_window), 0):
d["windows_total"] = len(owners)
d["windows_owned_by_firefox"] = sum(1 for o in owners if o in pids)
else:
d["errors"].append("EnumDesktopWindows failed, WinError %d" % ctypes.get_last_error())
finally:
user32.CloseDesktop(handle)
out["hosting_firefox"] = [d["name"] for d in out["desktops"] if d.get("windows_owned_by_firefox")]
except Exception as exc: # noqa: BLE001 - the error is the record
out["error"] = "%r\n%s" % (exc, traceback.format_exc()[-1200:])
return out
# ---------------------------------------------------------------------------------------------------------------------------------------
# c:\windows\fonts: which process type opened a path under it (the Kernel-File trace of the host oracle's recorder)
# ---------------------------------------------------------------------------------------------------------------------------------------
_FONTS_RE = re.compile(r"(?:^|\\)windows\\fonts(?:\\|$)", re.I)
_USER_FONTS_RE = re.compile(r"\\microsoft\\windows\\fonts(?:\\|$)", re.I)
SAMPLE = 25
def _image_name(image: str) -> str:
return (image or "").replace("/", "\\").rsplit("\\", 1)[-1].lower()
def pid_types(tree: list) -> dict:
"""{pid: (image name, type)} of the 4688 events of the tree: for firefox.exe the type is the last word of a -contentproc command line (gpu, tab, rdd, socket, utility...)
or parent; for another image the type is its name. A pid born again is the later process."""
types = {}
for e in tree:
image = _image_name(e.get("image"))
types[e["pid"]] = (image, process_type(e.get("cmd")) if image == "firefox.exe" else image)
return types
def fonts_report(files, tree: list) -> dict:
"""What the trace says about c:\\windows\\fonts: every (pid, path) of a process of the tree whose path is the folder or under it, with the process's image and type;
the Create events of every type are counted too, so a type with 0 hits is a type that was seen recording."""
types = pid_types(tree)
per_type: dict = {}
created: dict = {}
for pid, name in files:
image, kind = types.get(pid, ("unknown pid", "unknown"))
key = "%s:%s" % (image, kind) if image != "firefox.exe" else kind
created[key] = created.get(key, 0) + 1
low = name.replace("/", "\\")
for prefix in ("\\??\\", "\\\\?\\"):
if low.lower().startswith(prefix):
low = low[len(prefix):]
if _FONTS_RE.search(low) and not _USER_FONTS_RE.search(low):
row = per_type.setdefault(key, {"image": image, "folder_opens": 0, "file_opens": 0, "pids": set(), "paths": set()})
row["folder_opens" if low.rstrip("\\").lower().endswith("\\windows\\fonts") else "file_opens"] += 1
row["pids"].add(pid)
row["paths"].add(low)
by_type = {k: {"image": v["image"], "folder_opens": v["folder_opens"], "file_opens": v["file_opens"], "pids": sorted(v["pids"]),
"paths_sample": sorted(v["paths"])[:SAMPLE], "paths_distinct": len(v["paths"])} for k, v in sorted(per_type.items())}
firefox_types = sorted(k for k, v in by_type.items() if v["image"] == "firefox.exe")
return {"measured": True, "fonts_read": bool(firefox_types), "fonts_read_by_process_type": firefox_types,
"hits_by_type": by_type, "create_events_by_type": dict(sorted(created.items())),
"folder_opened_by_type": sorted(k for k, v in by_type.items() if v["image"] == "firefox.exe" and v["folder_opens"]),
"files_opened_by_type": sorted(k for k, v in by_type.items() if v["image"] == "firefox.exe" and v["file_opens"]),
"path_pattern": "a path under (or equal to) \\windows\\fonts, the per-user \\microsoft\\windows\\fonts left out"}
# ---------------------------------------------------------------------------------------------------------------------------------------
# One variant, in a child process
# ---------------------------------------------------------------------------------------------------------------------------------------
def _sha256(path: str) -> str:
h = hashlib.sha256()
with open(path, "rb") as f:
for block in iter(lambda: f.read(1 << 20), b""):
h.update(block)
return h.hexdigest()
def _step(rec: dict, name: str, fn):
t0 = time.time()
try:
value = fn()
rec["steps"][name] = {"ok": True, "seconds": round(time.time() - t0, 2)}
return value
except Exception as exc: # noqa: BLE001 - one failed step never stops the others
rec["steps"][name] = {"ok": False, "seconds": round(time.time() - t0, 2), "error": repr(exc), "trace": traceback.format_exc()[-1800:]}
return None
_PREF_RE = re.compile(r"sandbox|gfx\.|webgl|layers\.|webrender|compositor|d3d11|angle|gpu|widget\.|dom\.ipc|fission", re.I)
def _read_profile(rec: dict, out: Path, variant: str, snaps: list) -> None:
"""The prefs the browser actually reads: user.js and prefs.js of the profile directory on the browser process's command line."""
path = None
for snap in reversed(snaps):
for p in snap.get("processes", []):
path = profile_of(p.get("command_line"))
if path:
break
if path:
break
prof = {"directory": path, "files": {}}
rec["profile"] = prof
if not path:
prof["note"] = "no firefox.exe command line carried -profile, so the profile directory is unknown"
return
for name in ("user.js", "prefs.js"):
f = Path(path) / name
try:
text = f.read_text(encoding="utf-8", errors="replace")
except OSError as exc:
prof["files"][name] = {"error": repr(exc)}
continue
(out / ("%s.%s" % (variant, name))).write_text(text, encoding="utf-8", newline="\n")
lines = text.splitlines()
prof["files"][name] = {"lines": len(lines), "bytes": len(text.encode("utf-8")),
"sandbox_lines": [ln for ln in lines if "security.sandbox" in ln],
"graphics_lines": [ln for ln in lines if _PREF_RE.search(ln)][:200]}
def _crash_files(profile: "str | None", since: float) -> dict:
found = {}
roots = []
if profile:
roots += [("profile/minidumps", Path(profile) / "minidumps"), ("profile/crashes", Path(profile) / "crashes")]
appdata = os.environ.get("APPDATA")
if appdata:
roots += [("appdata/Crash Reports", Path(appdata) / "Mozilla" / "Firefox" / "Crash Reports")]
for label, root in roots:
items = []
try:
for f in root.rglob("*"):
try:
if f.is_file() and f.stat().st_mtime >= since - 5:
# InstallTime<build id> and the like are written at every start; only a dump, its .extra and LastCrash are a crash
items.append({"path": str(f.relative_to(root)), "bytes": f.stat().st_size,
"crash_artifact": f.suffix.lower() in (".dmp", ".extra") or f.name == "LastCrash"})
except OSError:
pass
except OSError as exc:
items.append({"error": repr(exc)})
found[label] = items
return found
def run_variant(variant: str, binary: str, out: Path) -> int:
extra = VARIANTS[variant]
started = time.time()
rec = {"variant": variant, "seed": SEED, "extra_prefs": extra, "binary": binary, "binary_sha256": None,
"started_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(started)), "steps": {}, "snapshots": [], "events": [],
"about_support": None, "profile": None, "webgl": None, "navigations": [], "late_check": None, "servers": {}, "crash": {}, "launch": {},
"desktops": {}, "trace": {}, "fonts": None, "crashreporter_births": []}
out.mkdir(parents=True, exist_ok=True)
rec["binary_sha256"] = _step(rec, "sha256", lambda: _sha256(binary))
s1 = _serve("127.0.0.1")
s2 = _serve("127.0.0.1")
third_host, third_note = "127.0.0.2", None
try:
s3 = _serve("127.0.0.2")
except OSError as exc:
s3 = _serve("127.0.0.1")
third_host, third_note = "localhost", "binding 127.0.0.2 failed (%r): the third navigation is another port on localhost" % (exc,)
p1, p2, p3 = (s.server_address[1] for s in (s1, s2, s3))
base = {"webgl": "http://127.0.0.1:%d/webgl" % p1,
"navs": ["http://127.0.0.1:%d/" % p1, "http://localhost:%d/" % p2, "http://%s:%d/" % (third_host, p3)]}
rec["servers"] = {"urls": base, "third_note": third_note, "localhost_server_binds": "127.0.0.1"}
seen_parents: set = set() # every browser parent pid seen: the roots of the tree the trace reads
closing = {"v": False} # set just before the browser is closed: a "disconnected" after that is the close, not a crash
trace = {"obj": None, "dir": None, "started": False}
def snap(label):
s = snapshot(label)
rec["snapshots"].append(s)
seen_parents.update(p["pid"] for p in s.get("processes", []) if p["type"] == "parent" and p.get("pid"))
return s
def desktops(label):
pids = [p["pid"] for p in (rec["snapshots"][-1].get("processes", []) if rec["snapshots"] else []) if p.get("pid")]
rec["desktops"][label] = desktops_security(pids)
def save():
(out / ("%s.json" % variant)).write_text(json.dumps(rec, indent=1, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
def event(name):
rec["events"].append({"event": name, "t": round(time.time() - started, 2), "during_run": not closing["v"]})
def trace_start():
if sys.platform != "win32":
raise RuntimeError("the trace is for Windows")
import ci_ab_host as host # the recorder of the host oracle: scripts/ci_ab_host.py
trace["dir"] = Path(tempfile.mkdtemp(prefix="d72-fonts-"))
trace["obj"] = host.WindowsTrace(trace["dir"])
trace["obj"].start() # the audit on, the ETW session open, the canaries: BEFORE the launch
trace["started"] = True
def trace_finish():
roots = sorted(seen_parents)
if not roots:
raise RuntimeError("no browser parent (firefox.exe without -contentproc) was seen, so the tree has no root")
result = trace["obj"].finish(roots)
tree = result["tree"]
rec["trace"] = {"roots": roots, "problems": result["problems"], "events": result["events"], "exited": result["exited"], "exits_available": result["exits_available"],
"outside_processes": result["outside"], "tree_size": len(tree), "files_of_tree": len(result["files"]),
"tree": [{"pid": e["pid"], "ppid": e["ppid"], "image": e["image"], "type": pid_types([e])[e["pid"]][1], "time": e["time"], "cmd": (e["cmd"] or "")[:300]}
for e in tree]}
rec["fonts"] = fonts_report(result["files"], tree)
events = trace["obj"].audit_raw[0]
rec["crashreporter_births"] = [{"pid": e["pid"], "ppid": e["ppid"], "image": e["image"], "time": e["time"], "cmd": (e["cmd"] or "")[:300]}
for e in events if _image_name(e.get("image")) == "crashreporter.exe"]
_step(rec, "trace_start", trace_start)
try:
from invisible_playwright import InvisiblePlaywright
kwargs = {"seed": SEED, "binary_path": binary, "headless": True}
if extra:
kwargs["extra_prefs"] = dict(extra)
try:
ip = InvisiblePlaywright(**kwargs)
browser = ip.__enter__()
except Exception as exc: # noqa: BLE001
rec["launch"] = {"ok": False, "error": repr(exc), "trace": traceback.format_exc()[-2500:]}
snap("after_launch_failure")
return 0
rec["launch"] = {"ok": True, "seconds": round(time.time() - started, 2)}
try:
browser.on("disconnected", lambda *_: event("browser disconnected"))
ctx = browser.new_context()
page = ctx.new_page()
page.on("crash", lambda *_: event("page crash"))
page.on("close", lambda *_: event("page closed"))
snap("after_launch")
_step(rec, "desktops_after_launch", lambda: desktops("after_launch"))
# 1. about:support
def about_support():
a = {"ok": False, "error": None, "text": None}
rec["about_support"] = a
try:
page.goto("about:support", timeout=30_000)
except Exception as exc: # noqa: BLE001
a["error"] = "goto: %r" % (exc,)
return
try:
page.wait_for_function("document.body && document.body.innerText.indexOf('Compositing') >= 0", timeout=30_000)
except Exception as exc: # noqa: BLE001
a["wait_error"] = repr(exc)
time.sleep(2) # the Graphics and Sandbox tables fill in from separate providers
a["text"] = page.evaluate("document.body.innerText")
a["ok"] = True
(out / ("%s.about_support.txt" % variant)).write_text(a["text"] or "", encoding="utf-8", newline="\n")
_step(rec, "about_support", about_support)
snap("after_about_support")
# 2. WebGL and WebGL2 on 127.0.0.1
def webgl():
page.goto(base["webgl"], timeout=30_000)
page.wait_for_function("window.__webgl_done === true", timeout=30_000)
rec["webgl"] = page.evaluate("window.__webgl")
_step(rec, "webgl", webgl)
snap("after_webgl")
# 3. three cross-origin navigations
for url in base["navs"]:
n = {"url": url, "ok": False, "ran": None, "title": None, "href": None, "error": None}
rec["navigations"].append(n)
def nav(n=n, url=url):
page.goto(url, timeout=30_000, wait_until="load")
time.sleep(NAV_SETTLE_S)
n["ran"] = page.evaluate("window.__ran === true")
n["title"] = page.title()
n["href"] = page.url
n["ok"] = bool(n["ran"]) and n["href"] == url
try:
nav()
except Exception as exc: # noqa: BLE001
n["error"] = repr(exc)
n["page_closed"] = page.is_closed()
# a delayed check: the content process of a cross-process navigation died about 10 s after the load
time.sleep(LATE_CHECK_S)
late = {"page_closed": page.is_closed(), "ran": None, "error": None}
try:
late["ran"] = page.evaluate("window.__ran === true")
except Exception as exc: # noqa: BLE001
late["error"] = repr(exc)
rec["late_check"] = late
# 4. the processes and the desktops, while the browser is open: the GPU process alive at the END is the evidence
snap("end")
_step(rec, "desktops_end", lambda: desktops("end"))
_step(rec, "profile", lambda: _read_profile(rec, out, variant, rec["snapshots"]))
rec["crash"]["while_open"] = _crash_files((rec.get("profile") or {}).get("directory"), started)
finally:
closing["v"] = True
try:
ip.__exit__(None, None, None)
except Exception as exc: # noqa: BLE001
rec["events"].append({"event": "close error", "error": repr(exc), "during_run": False})
rec["crash"]["after_close"] = _crash_files((rec.get("profile") or {}).get("directory"), started)
except Exception as exc: # noqa: BLE001
rec["fatal"] = {"error": repr(exc), "trace": traceback.format_exc()[-2500:]}
finally:
# the browser is closed (or never started): end whatever is left, then read the trace
rec["left_after_close"] = kill_firefox()
if trace["started"]:
_step(rec, "trace_finish", trace_finish)
if trace["obj"] is not None:
try:
trace["obj"].cleanup() # the session closed and gone, the audit as it was
except Exception as exc: # noqa: BLE001
rec["steps"]["trace_cleanup"] = {"ok": False, "error": repr(exc)}
if trace["dir"] is not None:
shutil.rmtree(trace["dir"], ignore_errors=True)
rec["seconds"] = round(time.time() - started, 2)
save()
for s in (s1, s2, s3):
try:
s.shutdown()
except Exception: # noqa: BLE001
pass
return 0
# ---------------------------------------------------------------------------------------------------------------------------------------
# The summary
# ---------------------------------------------------------------------------------------------------------------------------------------
def _find_row(lines: list, pattern: str) -> "dict | None":
"""The about:support row whose label matches `pattern`: {"label", "value"}; the value is the rest of the line after a tab (or two spaces), else the next line."""
rx = re.compile(pattern, re.I)
for i, ln in enumerate(lines):
parts = re.split(r"\t+| {2,}", ln.strip(), maxsplit=1)
if rx.search(parts[0]):
value = parts[1].strip() if len(parts) > 1 else next((n.strip() for n in lines[i + 1:i + 3] if n.strip()), None)
return {"label": parts[0].strip(), "value": value}
return None
_COMPOSITING_RE = re.compile(r"composit|webrender|d3d|direct3d|software|hardware|acceler|angle|gpuprocess|renderer|adapter|window protocol|basic", re.I)
def summarize_variant(rec: "dict | None") -> dict:
if rec is None:
return {"error": "no record"}
s = {"extra_prefs": rec.get("extra_prefs"), "launch": rec.get("launch"), "fatal": rec.get("fatal"), "events": rec.get("events"),
"child_timeout": rec.get("child_timeout", False)}
a = rec.get("about_support") or {}
text = a.get("text") or ""
lines = text.splitlines()
s["about_support"] = {"ok": a.get("ok"), "error": a.get("error"), "wait_error": a.get("wait_error")}
s["sandbox_rows"] = {
"effective_content_process_sandbox_level": _find_row(lines, r"^effective content process sandbox level"),
"content_process_sandbox_level": _find_row(lines, r"^content process sandbox level"),
"gpu_sandbox_level": _find_row(lines, r"gpu.*sandbox|sandbox.*gpu"),
"win32k_lockdown": _find_row(lines, r"win32k"),
}
s["sandbox_lines"] = [ln for ln in lines if re.search(r"sandbox|win32k", ln, re.I)]
s["compositing_exact"] = [ln for ln in lines if ln.strip().lower().startswith("compositing")]
s["compositing_lines"] = [ln for ln in lines if _COMPOSITING_RE.search(ln)][:150]
prof = (rec.get("profile") or {}).get("files", {})
s["prefs_in_profile"] = {name: (info.get("sandbox_lines") if isinstance(info, dict) else None) for name, info in prof.items()}
w = rec.get("webgl") or {}
s["webgl"] = {"webgl": w.get("webgl"), "webgl2": w.get("webgl2"), "page_error": (rec.get("steps", {}).get("webgl") or {}).get("error")}
snaps = rec.get("snapshots") or []
end = next((x for x in reversed(snaps) if x.get("label") == "end"), None)
s["gpu_process_by_snapshot"] = {x.get("label"): bool(x.get("gpu_process_exists")) for x in snaps}
by_type = {}
for p in (end or {}).get("processes", []):
by_type.setdefault(p["type"], []).append({"pid": p["pid"], "integrity": p["integrity"].get("level") or p["integrity"].get("error"),
"restricted": p["integrity"].get("token_is_restricted")})
s["processes_at_end"] = by_type
s["snapshot_error"] = (end or {}).get("error")
s["navigations"] = [{"url": n["url"], "ok": n["ok"], "ran": n["ran"], "href": n["href"], "error": n["error"], "page_closed": n.get("page_closed")}
for n in rec.get("navigations", [])]
s["late_check"] = rec.get("late_check")
s["steps_failed"] = {k: v.get("error") for k, v in rec.get("steps", {}).items() if not v.get("ok")}
# crashes: any sign of one, in one place
crash_files = {}
for when, folders in (rec.get("crash") or {}).items():
for label, items in (folders or {}).items():
real = [i for i in items if i.get("crash_artifact")]
if real:
crash_files["%s %s" % (when, label)] = real
reporters = sorted({c["pid"] for x in snaps for c in x.get("crashreporters", [])})
births = rec.get("crashreporter_births") or []
run_events = [e for e in rec.get("events", []) if e.get("during_run") and ("crash" in e.get("event", "") or "disconnected" in e.get("event", ""))]
s["crash"] = {"events_during_run": run_events, "crashreporter_pids_in_snapshots": reporters, "crashreporter_births_in_audit": births,
"minidump_or_crash_files": crash_files, "fatal": rec.get("fatal"),
"seen": bool(run_events or reporters or births or crash_files or rec.get("fatal"))}
# the desktops: the one that holds the windows of the browser, with its label
hosting = None
for label in ("end", "after_launch"):
d = (rec.get("desktops") or {}).get(label) or {}
for row in d.get("desktops", []):
if row["name"] in d.get("hosting_firefox", []):
hosting = dict(row, read_at=label, window_station=d.get("window_station"))
break
if hosting:
break
s["hidden_desktop"] = hosting
s["desktops"] = {label: [{"name": r["name"], "label_sddl": r["label_sddl"], "label_level": r["label_level"], "windows_owned_by_firefox": r["windows_owned_by_firefox"],
"errors": r["errors"]} for r in (d or {}).get("desktops", [])] for label, d in (rec.get("desktops") or {}).items()}
fonts = rec.get("fonts") or {}
s["fonts"] = {k: fonts.get(k) for k in ("measured", "fonts_read", "fonts_read_by_process_type", "folder_opened_by_type", "files_opened_by_type", "hits_by_type",
"create_events_by_type")} if fonts else {"measured": False, "error": (rec.get("steps", {}).get("trace_finish") or rec.get("steps", {}).get("trace_start") or {}).get("error")}
s["trace"] = {k: (rec.get("trace") or {}).get(k) for k in ("roots", "problems", "events", "exited", "tree_size", "files_of_tree")}
return s
def _level(value: "str | None") -> "str | None":
m = re.search(r"-?\d+", value or "")
return m.group(0) if m else value
def result_of(v: dict) -> dict:
"""The answer, in one place."""
rows = v.get("sandbox_rows") or {}
eff = rows.get("effective_content_process_sandbox_level") or rows.get("content_process_sandbox_level")
comp = (v.get("compositing_exact") or [None])[0]
w = v.get("webgl") or {}
gl, gl2 = w.get("webgl") or {}, w.get("webgl2") or {}
by_type = v.get("processes_at_end") or {}
gpu = (by_type.get("gpu") or [None])[0]
fonts = v.get("fonts") or {}
files = v.get("prefs_in_profile") or {}
user_js = files.get("user.js")
hd = v.get("hidden_desktop") or {}
snaps = v.get("gpu_process_by_snapshot") or {}
alive_at_end = snaps.get("end") if "end" in snaps else None
return {
"effective_content_level": {"row": eff, "level": _level((eff or {}).get("value"))},
"gpu_sandbox_level_row": rows.get("gpu_sandbox_level"),
"compositing": re.sub(r"\t+", ": ", comp.strip()) if comp else None,
"webgl_renderer": gl.get("renderer"),
"webgl2_renderer": gl2.get("renderer"),
"gpu_process_alive_at_end": alive_at_end,
"gpu_process_integrity_at_end": (gpu or {}).get("integrity") if gpu else None,
"gpu_process_by_snapshot": snaps,
"fonts_read": fonts.get("fonts_read") if fonts.get("measured") else None,
"fonts_read_by_process_type": fonts.get("fonts_read_by_process_type") if fonts.get("measured") else None,
"fonts_measured": bool(fonts.get("measured")),
"navigations": [{"url": n["url"], "ok": n["ok"], "error": n["error"]} for n in v.get("navigations", [])],
"crashes_seen": (v.get("crash") or {}).get("seen"),
"crash_detail": v.get("crash"),
"hidden_desktop_name": hd.get("name"),
"hidden_desktop_label": hd.get("label_sddl"),
"hidden_desktop_label_level": hd.get("label_level"),
"user_js_security_sandbox_lines": user_js,
}
def assertions_of(result: dict) -> dict:
"""True / False / None (not measured) for each thing the fix promises."""
user_js = result.get("user_js_security_sandbox_lines")
return {
"user_js_has_no_security_sandbox_line": (len(user_js) == 0) if isinstance(user_js, list) else None,
"hidden_desktop_label_is_low": (result.get("hidden_desktop_label_level") == "Low") if result.get("hidden_desktop_label") is not None else None,
"gpu_process_alive_at_end": result.get("gpu_process_alive_at_end"),
"three_navigations_ok": (len(result.get("navigations", [])) == 3 and all(n["ok"] for n in result["navigations"])) if result.get("navigations") else None,
"no_crash_seen": (not result["crashes_seen"]) if result.get("crashes_seen") is not None else None,
}
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--binary", required=True)
ap.add_argument("--out", type=Path, required=True)
ap.add_argument("--child", choices=sorted(VARIANTS), help="internal: run one variant in this process")
args = ap.parse_args()
if args.child:
return run_variant(args.child, args.binary, args.out)
args.out.mkdir(parents=True, exist_ok=True)
summary = {"seed": SEED, "binary": args.binary, "variants": {}}
for variant in VARIANTS:
print("== variant %s ==" % variant, flush=True)
cmd = [sys.executable, "-u", str(Path(__file__).resolve()), "--child", variant, "--binary", args.binary, "--out", str(args.out)]
child = subprocess.Popen(cmd)
timed_out = False
try:
child.wait(timeout=CHILD_TIMEOUT_S)
except subprocess.TimeoutExpired:
timed_out = True
print("variant %s: child timed out after %d s" % (variant, CHILD_TIMEOUT_S), flush=True)
stuck = snapshot("child_timeout")
subprocess.run(["taskkill", "/F", "/T", "/PID", str(child.pid)], capture_output=True, timeout=60)
path = args.out / ("%s.json" % variant)
try:
rec = json.loads(path.read_text(encoding="utf-8"))
except (OSError, ValueError):
rec = None
if timed_out:
rec = rec or {"variant": variant}
rec["child_timeout"] = True
rec.setdefault("snapshots", []).append(stuck)
path.write_text(json.dumps(rec, indent=1, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
elif rec is None:
rec = {"variant": variant, "child_exit": child.returncode, "snapshots": []}
path.write_text(json.dumps(rec, indent=1, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
v = summarize_variant(rec)
v["child_exit"] = child.returncode
v["firefox_left_after"] = kill_firefox()
summary["variants"][variant] = v
only = summary["variants"][next(iter(VARIANTS))]
summary["result"] = result_of(only)
summary["assertions"] = assertions_of(summary["result"])
r = summary["result"]
print("content level: %s | gpu row: %s | compositing: %s | webgl: %s / %s | gpu alive at end: %s (%s) | fonts read: %s %s | navigations ok: %s | crashes: %s | desktop label: %s"
% (r["effective_content_level"]["level"], (r["gpu_sandbox_level_row"] or {}).get("value"), r["compositing"], r["webgl_renderer"], r["webgl2_renderer"],
r["gpu_process_alive_at_end"], r["gpu_process_integrity_at_end"], r["fonts_read"], r["fonts_read_by_process_type"], [n["ok"] for n in r["navigations"]],
r["crashes_seen"], r["hidden_desktop_label"]), flush=True)
print("assertions: %s" % json.dumps(summary["assertions"]), flush=True)
(args.out / "summary.json").write_text(json.dumps(summary, indent=1, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
# the one thing that fails the run: the core wrote a security.sandbox.* pref
return 1 if summary["assertions"]["user_js_has_no_security_sandbox_line"] is False else 0
if __name__ == "__main__":
raise SystemExit(main())