Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cua-driver): launch isolated browsers de-elevated from an elevated Windows Driver (#4234)
Francesco Bonacci6650ac56c591
diff --git a/.github/workflows/e2e-rust-standalone-browsers.yml b/.github/workflows/e2e-rust-standalone-browsers.ymlindex e338eb5642..e0399a6e0e 100644--- a/.github/workflows/e2e-rust-standalone-browsers.yml+++ b/.github/workflows/e2e-rust-standalone-browsers.yml@@ -72,7 +72,10 @@ jobs:CUA_E2E_BROWSER_STDERR: "1"CUA_E2E_BROWSER_PRODUCTS: ${{ matrix.products }}CUA_TEST_REQUIRE_PROTECTED_WINDOWS_BROWSER: ${{ matrix.label == 'Windows' && '1' || '0' }}- CUA_E2E_WINDOWS_BROWSER_LIMITATION: ${{ matrix.label == 'Windows' && 'hosted_runner_token' || '0' }}+ # GitHub-hosted Windows runs the job, and so the Driver, with an+ # elevated administrator token. The isolated-launch case must prove the+ # Driver launches its browser with a derived standard-user token.+ CUA_E2E_EXPECT_ELEVATED_DRIVER: ${{ matrix.label == 'Windows' && '1' || '0' }}RUST_BACKTRACE: "1"steps:- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4@@ -128,15 +131,15 @@ jobs:}Write-Host "[browser-trust] verified vendor-signed candidate: $($browser.Executable)"}- - name: Run standalone browsers on Windows with hosted-token limitation+ - name: Run standalone browsers on Windows from an elevated Driverif: runner.os == 'Windows'shell: pwshrun: |$ErrorActionPreference = 'Stop'$artifactDir = Join-Path $PWD 'artifacts\cua-driver\standalone-browser'$scriptPath = Join-Path $PWD 'scripts\ci\windows\run-rust-standalone-browser-e2e.ps1'- # Hosted Windows does not expose a restricted token. The suite records- # the driver's typed refusal and proves it has no setup side effects.+ # The elevated Driver launches isolated browsers with a derived+ # standard-user token; the suite verifies that token independently.$env:CUA_E2E_ARTIFACT_DIR = $artifactDir& $scriptPath -NoBuildif ($LASTEXITCODE -ne 0) { throw "standalone-browser E2E failed with exit code $LASTEXITCODE" }diff --git a/docs/content/docs/how-to-guides/driver/jev-use.mdx b/docs/content/docs/how-to-guides/driver/jev-use.mdxindex c4771239b5..2de2869566 100644--- a/docs/content/docs/how-to-guides/driver/jev-use.mdx+++ b/docs/content/docs/how-to-guides/driver/jev-use.mdx@@ -67,18 +67,20 @@ if either grant is missing.</Tab><Tab value="Windows">-Use a normal, non-administrator PowerShell terminal in your logged-in desktop-session. Install Google Chrome or Microsoft Edge as a system application.-Run Driver without elevation too: automatic browser discovery requires an-installation the running account's token cannot modify.--An elevated or administrator token can modify `Program Files`, so Driver-refuses its signed Chrome and Edge. `browser_prepare` then fails with-`browser_route_unavailable` and a message that says the installed browser is-writable by the current elevated or administrator token. Some cloud Windows-images make the first user the built-in Administrator account (SID ending in-`-500`). That account always runs elevated, even with UAC enabled. Sign in as-a standard user instead, or run Driver from a non-elevated session.+Use a PowerShell terminal in your logged-in desktop session. Install Google+Chrome or Microsoft Edge as a system application. Automatic browser discovery+requires an installation that the token running the browser cannot modify.++Driver can run elevated, as the installer's autostart does on an administrator+account. An elevated token can modify `Program Files`, so an elevated Driver+never runs the isolated browser with its own token. It launches Chrome or Edge+with a standard-user token derived from its own: the same account and desktop,+with administrator rights removed. This also covers the built-in Administrator+account that some cloud Windows images create as the first user, and+administrator accounts with UAC turned off. If Windows cannot provide a+verified standard-user token, `browser_prepare` fails with+`browser_route_unavailable` and explains why. Driver never falls back to an+elevated browser.```powershellcua-driver --version@@ -256,7 +258,7 @@ shell call until it finishes. The command manages the test server itself.| Problem | What to check || --- | --- || Driver not running or permissions missing | Follow the [Driver setup guide](/how-to-guides/driver/install). |-| Browser cannot launch | Check the browser installation and desktop-session requirements in your platform tab. On Windows, avoid an elevated Driver process. |+| Browser cannot launch | Check the browser installation and desktop-session requirements in your platform tab. On Windows, read the `browser_prepare` refusal message; it names the installation or token check that failed. || `browser_prepare` requires a `pid` | Update an older Driver installation before using this example. || `uv` not found | Finish the uv installation and open a new terminal with its installation directory on `PATH`. || API authentication or quota error | Check your TypeSafe key and account access. The connection check can pass even when live access fails. |diff --git a/libs/cua-driver/examples/jev-use/README.md b/libs/cua-driver/examples/jev-use/README.mdindex 0b4b16b6ef..b3e6b4088d 100644--- a/libs/cua-driver/examples/jev-use/README.md+++ b/libs/cua-driver/examples/jev-use/README.md@@ -86,10 +86,11 @@ export npm_config_cache="$PWD/.venv/npm-cache"npm ci```-On Windows, use a non-administrator desktop session and `npm.cmd ci` in-PowerShell. An elevated session, including the built-in Administrator account-that some cloud images create as the first user, makes Driver refuse the-installed browser as writable by the current token. The managed verifier starts TypeScript through `node --import tsx`,+On Windows, use your logged-in desktop session and `npm.cmd ci` in+PowerShell. An elevated Driver, such as the installer's autostart on an+administrator account or the built-in Administrator account that some cloud+images create as the first user, launches the isolated browser with a derived+standard-user token. The managed verifier starts TypeScript through `node --import tsx`,not an npm shell shim. On Linux, use a supported system browser and a desktopsession accessible to the same user as Driver; native Wayland has separatecompositor-specific requirements.diff --git a/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md b/libs/cua-driver/rust/Skills/cua-driver/BROWSER.mdindex f71f7a39b3..166c268952 100644--- a/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md+++ b/libs/cua-driver/rust/Skills/cua-driver/BROWSER.md@@ -135,11 +135,14 @@ order: Google Chrome, then Microsoft Edge. On Linux it accepts exactroot-owned, non-group/world-writable package payloads in this order: GoogleChrome, Chromium, then Microsoft Edge. User application directories, `PATH`entries, redirected paths, and unsigned or mismatched products fail closed.-On Windows, the installation must also be unmodifiable by the Driver's token.-An elevated or built-in Administrator token can write `Program Files`, so the-refusal then says the installed Chrome/Edge is writable by the current-elevated or administrator token. Run Driver from a non-administrator session-in that case; the browser is not missing or unsigned.+On Windows, the installation must also be unmodifiable by the token that runs+the browser. A non-elevated Driver runs the browser with its own token. An+elevated Driver, including the built-in Administrator and administrators with+UAC off, runs it with a derived standard-user token (administrator rights+removed, Medium integrity) and proves the installation protected from that+token. If that token cannot be derived and verified, or can still modify the+installation, the refusal says so; the browser is not missing or unsigned, and+Driver never falls back to an elevated browser.Supply a Chromium-family browser pid when the isolated launch must use thatprocess's exact executable, including Chromium on macOS or Windows. The pidremains required for existing-profile attachment.diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mod.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mod.rsindex 8462884713..070d6c0734 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mod.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/mod.rs@@ -65,8 +65,9 @@ pub use engine::BrowserEngine;pub use platform::{BrowserConsentOutcome, BrowserConsentRequest, BrowserPlatform, BrowserVisualAction,BrowserVisualActionKind, ExistingProfileSetupOutcome, ExistingProfileSetupRequest,- PrepareAction, PrepareAttachment, PrepareAttachmentKind, PrepareOutcome, PrepareProfile,- PrepareProfileMode, PrepareRequest, PrepareSideEffects, PrepareStrategy,+ IsolatedBrowserProcess, PrepareAction, PrepareAttachment, PrepareAttachmentKind,+ PrepareOutcome, PrepareProfile, PrepareProfileMode, PrepareRequest, PrepareSideEffects,+ PrepareStrategy,};pub use refusal::{BrowserRefusal, BrowserRefusalCode};pub use setup_descriptor::{diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/platform.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/platform.rsindex bf0912f4b5..37385d9a3e 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/platform.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/platform.rs@@ -10,13 +10,57 @@use async_trait::async_trait;use serde::{Deserialize, Serialize};-use std::path::PathBuf;+use std::path::{Path, PathBuf};+use std::process::{Child, Command, ExitStatus};use super::refusal::BrowserRefusal;use super::types::{BrowserClassification, BrowserProduct, NativeWindowInfo, OwnedEndpoint, ProcessFingerprint,};+/// Root process of a driver-owned isolated browser that core launched.+///+/// Core keeps this handle for the browser's lifetime to observe launcher+/// exit, reap the process tree, and remove the driver-owned profile. The+/// default implementation is [`std::process::Child`]. A platform that runs+/// the browser under a different token than the Driver supplies its own+/// handle so that filesystem work inside the browser-writable profile uses+/// the browser's authority rather than the Driver's.+pub trait IsolatedBrowserProcess: Send {+ fn id(&self) -> u32;+ fn try_wait(&mut self) -> std::io::Result<Option<ExitStatus>>;+ fn kill(&mut self) -> std::io::Result<()>;+ fn wait(&mut self) -> std::io::Result<ExitStatus>;++ /// Run `work` with the authority of the browser's token. The browser can+ /// write its profile directory, so a more privileged Driver must not+ /// follow browser-planted links there with its own rights. When the+ /// browser runs with the Driver's token, `work` runs directly. An error+ /// means `work` did not run; callers must then skip the file operation.+ fn with_browser_file_authority(&self, work: &mut dyn FnMut()) -> std::io::Result<()> {+ work();+ Ok(())+ }+}++impl IsolatedBrowserProcess for Child {+ fn id(&self) -> u32 {+ Child::id(self)+ }++ fn try_wait(&mut self) -> std::io::Result<Option<ExitStatus>> {+ Child::try_wait(self)+ }++ fn kill(&mut self) -> std::io::Result<()> {+ Child::kill(self)+ }++ fn wait(&mut self) -> std::io::Result<ExitStatus> {+ Child::wait(self)+ }+}+/// Select the first installed, non-redirected candidate and return its/// canonical path. Native adapters must supply only trusted installation/// locations in public product-preference order. Rejecting redirects prevents@@ -279,6 +323,28 @@ pub trait BrowserPlatform: Send + Sync {))}+ /// Spawn the driver-owned isolated browser that core fully configured in+ /// `command` for the private profile at `profile`. The default launches+ /// it with the Driver's own token. A platform may instead launch it with+ /// a less privileged token; it must then keep every trust check made by+ /// [`Self::isolated_browser_executable`] valid for that token and refuse+ /// rather than fall back to the Driver's token.+ fn spawn_isolated_browser(+ &self,+ mut command: Command,+ _profile: &Path,+ ) -> Result<Box<dyn IsolatedBrowserProcess>, BrowserRefusal> {+ command+ .spawn()+ .map(|child| Box::new(child) as Box<dyn IsolatedBrowserProcess>)+ .map_err(|error| {+ BrowserRefusal::new(+ super::refusal::BrowserRefusalCode::BrowserRouteUnavailable,+ format!("could not launch an isolated browser process: {error}"),+ )+ })+ }+/// Explain why a trusted CDP Input route cannot preserve background/// posture for a standalone browser on this platform. Embedded Chromium/// routes are independently proven and do not consult this capability.diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rsindex 1d10b31955..ac51344496 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/browser/prepare.rs@@ -5,7 +5,7 @@ use std::future::Future;use std::io::Write;use std::path::{Path, PathBuf};use std::pin::Pin;-use std::process::{Child, Command, ExitStatus, Stdio};+use std::process::{Command, ExitStatus, Stdio};use std::sync::{Arc, Mutex};use std::time::{Duration, Instant};@@ -14,9 +14,9 @@ use serde::{Deserialize, Serialize};use super::engine::unsupported_engine_refusal;use super::platform::{BrowserConsentOutcome, BrowserConsentRequest, ExistingProfileSetupOutcome,- ExistingProfileSetupRequest, PrepareAction, PrepareAttachment, PrepareAttachmentKind,- PrepareOutcome, PrepareProfile, PrepareProfileMode, PrepareRequest, PrepareSideEffects,- PrepareStrategy,+ ExistingProfileSetupRequest, IsolatedBrowserProcess, PrepareAction, PrepareAttachment,+ PrepareAttachmentKind, PrepareOutcome, PrepareProfile, PrepareProfileMode, PrepareRequest,+ PrepareSideEffects, PrepareStrategy,};use super::refusal::{BrowserRefusal, BrowserRefusalCode};use super::types::{@@ -226,7 +226,7 @@ struct PreparedProfile {}pub(crate) struct ManagedBrowser {- child: Child,+ child: Box<dyn IsolatedBrowserProcess>,owned_pid: i64,profile: PathBuf,delete_profile: bool,@@ -258,8 +258,8 @@ impl Drop for ManagedBrowser {}let _ = self.child.kill();let _ = self.child.wait();- if self.delete_profile && profile_matches_marker(&self.profile, &self.marker) {- let _ = fs::remove_dir_all(&self.profile);+ if self.delete_profile {+ remove_owned_profile_as_browser(self.child.as_ref(), &self.profile, &self.marker);}}}@@ -327,6 +327,32 @@ fn cleanup_created_profile(profile: &PreparedProfile) {}}+/// Remove a driver-owned profile after its browser ran. The browser could+/// write the profile, so the marker proof and the recursive removal both use+/// the browser's authority; a failure to assume it leaves the profile behind.+fn remove_owned_profile_as_browser(+ browser: &dyn IsolatedBrowserProcess,+ path: &Path,+ marker: &ProfileMarker,+) {+ let _ = browser.with_browser_file_authority(&mut || {+ if profile_matches_marker(path, marker) {+ let _ = fs::remove_dir_all(path);+ }+ });+}++fn cleanup_created_profile_as_browser(+ browser: &mut dyn IsolatedBrowserProcess,+ profile: &PreparedProfile,+) {+ let _ = browser.kill();+ let _ = browser.wait();+ if profile.delete_on_cleanup {+ remove_owned_profile_as_browser(browser, &profile.path, &profile.marker);+ }+}+#[cfg(target_os = "linux")]fn configure_linux_isolated_browser_command(command: &mut Command,@@ -521,7 +547,7 @@ fn prepare_profile(profile: &PrepareProfile) -> Result<PreparedProfile, BrowserR}async fn wait_for_spawned_endpoint(- child: &mut Child,+ child: &mut dyn IsolatedBrowserProcess,profile: &Path,) -> Result<OwnedEndpoint, BrowserRefusal> {let deadline = Instant::now() + Duration::from_secs(20);@@ -547,7 +573,20 @@ async fn wait_for_spawned_endpoint());}}- if let Ok(text) = fs::read_to_string(&port_file) {+ let mut port_file_text = None;+ child+ .with_browser_file_authority(&mut || {+ port_file_text = fs::read_to_string(&port_file).ok();+ })+ .map_err(|error| {+ refusal(+ BrowserRefusalCode::BrowserRouteUnavailable,+ format!(+ "could not read the isolated browser profile with the browser's token: {error}"+ ),+ )+ })?;+ if let Some(text) = port_file_text {let mut lines = text.lines();if let (Some(port), Some(path)) = (lines.next(), lines.next()) {if let Ok(port) = port.parse::<u16>() {@@ -727,30 +766,24 @@ impl BrowserEngine {self.platform.isolated_browser_executable()?};let prepared_profile = prepare_profile(profile_request)?;- let mut command = isolated_browser_command(&executable, &prepared_profile.path);- let mut child = command.spawn().map_err(|error| {- cleanup_created_profile(&prepared_profile);- refusal(- BrowserRefusalCode::BrowserRouteUnavailable,- format!("could not launch an isolated browser process: {error}"),- )- })?;- let endpoint = match wait_for_spawned_endpoint(&mut child, &prepared_profile.path).await {+ let command = isolated_browser_command(&executable, &prepared_profile.path);+ let mut child = self+ .platform+ .spawn_isolated_browser(command, &prepared_profile.path)+ .inspect_err(|_| cleanup_created_profile(&prepared_profile))?;+ let endpoint = match wait_for_spawned_endpoint(child.as_mut(), &prepared_profile.path).await+ {Ok(endpoint) => {match attest_spawned_endpoint(self, i64::from(child.id()), endpoint).await {Ok(endpoint) => endpoint,Err(error) => {- let _ = child.kill();- let _ = child.wait();- cleanup_created_profile(&prepared_profile);+ cleanup_created_profile_as_browser(child.as_mut(), &prepared_profile);return Err(error);}}}Err(error) => {- let _ = child.kill();- let _ = child.wait();- cleanup_created_profile(&prepared_profile);+ cleanup_created_profile_as_browser(child.as_mut(), &prepared_profile);return Err(error);}};diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/Cargo.toml b/libs/cua-driver/rust/crates/cua-driver-e2e/Cargo.tomlindex 832cf0108b..3932c32aa6 100644--- a/libs/cua-driver/rust/crates/cua-driver-e2e/Cargo.toml+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/Cargo.toml@@ -59,5 +59,7 @@ core-foundation = "0.10"platform-windows = { path = "../platform-windows" }windows = { version = "0.61", features = ["Win32_Foundation",+ "Win32_Security",+ "Win32_System_Threading","Win32_UI_WindowsAndMessaging",] }diff --git a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/standalone_browser_behavior_test.rs b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/standalone_browser_behavior_test.rsindex 2b1e192db9..8b902bb949 100644--- a/libs/cua-driver/rust/crates/cua-driver-e2e/tests/standalone_browser_behavior_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver-e2e/tests/standalone_browser_behavior_test.rs@@ -1501,14 +1501,149 @@ fn case(browser: &str, action: &str) -> CaseSpec {}fn prepare_isolated_case(browser: &str) -> CaseSpec {- let case = case(browser, "browser_prepare_isolated_launch");- if cfg!(target_os = "windows")- && std::env::var("CUA_E2E_WINDOWS_BROWSER_LIMITATION").as_deref()- == Ok("hosted_runner_token")- {- case.expecting_refusal(vec![RefusalCode::BrowserRouteUnavailable])- } else {- case+ case(browser, "browser_prepare_isolated_launch")+}++/// Independent oracle for the Windows isolated-browser token boundary. The+/// ephemeral test daemon inherits this test process's token, so the test+/// token stands in for the Driver's. An elevated Driver must run the browser+/// with a standard-user token: Administrators not enabled and Medium (or+/// lower) integrity below the Driver's.+#[cfg(target_os = "windows")]+fn assert_windows_isolated_browser_token(browser_pid: u32) {+ let driver = windows_token_oracle::posture(None).expect("read the Driver token");+ let browser =+ windows_token_oracle::posture(Some(browser_pid)).expect("read the isolated browser token");+ eprintln!("[isolated-browser-token] driver={driver:?} browser={browser:?}");+ if std::env::var("CUA_E2E_EXPECT_ELEVATED_DRIVER").as_deref() == Ok("1") {+ assert!(+ driver.privileged(),+ "this job must run the Driver elevated to prove the standard-user browser launch: {driver:?}"+ );+ }+ // `elevated` is only logged: a standard-user token derived from an+ // elevated token inherits Windows' TokenElevation flag, which grants no+ // access; Administrators and integrity decide access.+ assert!(+ !browser.administrators_enabled && browser.integrity_rid <= 0x2000,+ "the isolated browser must run with a standard-user token: {browser:?}"+ );+ if driver.privileged() {+ assert!(+ browser.integrity_rid < driver.integrity_rid,+ "the isolated browser must run below the elevated Driver's integrity: driver={driver:?} browser={browser:?}"+ );+ }+}++#[cfg(target_os = "windows")]+mod windows_token_oracle {+ use windows::Win32::Foundation::{CloseHandle, HANDLE};+ use windows::Win32::Security::{+ CreateWellKnownSid, EqualSid, GetSidSubAuthority, GetSidSubAuthorityCount,+ GetTokenInformation, TokenElevation, TokenGroups, TokenIntegrityLevel,+ WinBuiltinAdministratorsSid, PSID, SID_AND_ATTRIBUTES, TOKEN_ELEVATION, TOKEN_GROUPS,+ TOKEN_INFORMATION_CLASS, TOKEN_MANDATORY_LABEL, TOKEN_QUERY,+ };+ use windows::Win32::System::Threading::{+ GetCurrentProcess, OpenProcess, OpenProcessToken, PROCESS_QUERY_LIMITED_INFORMATION,+ };++ const SE_GROUP_ENABLED: u32 = 0x4;+ const SE_GROUP_USE_FOR_DENY_ONLY: u32 = 0x10;++ #[derive(Debug)]+ pub(super) struct Posture {+ pub elevated: bool,+ pub administrators_enabled: bool,+ pub integrity_rid: u32,+ }++ impl Posture {+ pub fn privileged(&self) -> bool {+ self.elevated || self.administrators_enabled || self.integrity_rid >= 0x3000+ }+ }++ struct Handle(HANDLE);+ impl Drop for Handle {+ fn drop(&mut self) {+ let _ = unsafe { CloseHandle(self.0) };+ }+ }++ fn information(token: HANDLE, class: TOKEN_INFORMATION_CLASS) -> Result<Vec<u64>, String> {+ let mut needed = 0u32;+ let _ = unsafe { GetTokenInformation(token, class, None, 0, &mut needed) };+ let mut buffer = vec![0u64; (needed as usize).div_ceil(8).max(1)];+ unsafe {+ GetTokenInformation(+ token,+ class,+ Some(buffer.as_mut_ptr().cast()),+ needed,+ &mut needed,+ )+ }+ .map_err(|error| format!("GetTokenInformation({}): {error}", class.0))?;+ Ok(buffer)+ }++ /// Token posture of `pid`, or of this process for `None`.+ pub(super) fn posture(pid: Option<u32>) -> Result<Posture, String> {+ let process = match pid {+ Some(pid) => Some(Handle(+ unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) }+ .map_err(|error| format!("OpenProcess({pid}): {error}"))?,+ )),+ None => None,+ };+ let process_handle = process+ .as_ref()+ .map_or_else(|| unsafe { GetCurrentProcess() }, |handle| handle.0);+ let mut token = HANDLE::default();+ unsafe { OpenProcessToken(process_handle, TOKEN_QUERY, &mut token) }+ .map_err(|error| format!("OpenProcessToken: {error}"))?;+ let token = Handle(token);++ let elevation = information(token.0, TokenElevation)?;+ let elevated =+ unsafe { (*elevation.as_ptr().cast::<TOKEN_ELEVATION>()).TokenIsElevated } != 0;++ let label = information(token.0, TokenIntegrityLevel)?;+ let sid = unsafe { (*label.as_ptr().cast::<TOKEN_MANDATORY_LABEL>()).Label.Sid };+ let integrity_rid = unsafe {+ let count = *GetSidSubAuthorityCount(sid);+ *GetSidSubAuthority(sid, u32::from(count) - 1)+ };++ let mut sid_buffer = [0u64; 12];+ let mut sid_size = std::mem::size_of_val(&sid_buffer) as u32;+ let administrators = PSID(sid_buffer.as_mut_ptr().cast());+ unsafe {+ CreateWellKnownSid(+ WinBuiltinAdministratorsSid,+ None,+ Some(administrators),+ &mut sid_size,+ )+ }+ .map_err(|error| format!("CreateWellKnownSid: {error}"))?;+ let groups = information(token.0, TokenGroups)?;+ let header = groups.as_ptr().cast::<TOKEN_GROUPS>();+ let count = unsafe { (*header).GroupCount } as usize;+ let first = unsafe { std::ptr::addr_of!((*header).Groups).cast::<SID_AND_ATTRIBUTES>() };+ let administrators_enabled = (0..count).any(|index| {+ let group = unsafe { *first.add(index) };+ unsafe { EqualSid(group.Sid, administrators) }.is_ok()+ && group.Attributes & SE_GROUP_USE_FOR_DENY_ONLY == 0+ && group.Attributes & SE_GROUP_ENABLED != 0+ });+ Ok(Posture {+ elevated,+ administrators_enabled,+ integrity_rid,+ })}}@@ -2268,176 +2403,125 @@ fn run_prepare_isolated_launch(spec: &BrowserSpec) {assert!(!started.is_error(), "start_session failed: {}", started.raw);driver.start_behavior_recording();- if cfg!(target_os = "windows")- && std::env::var("CUA_E2E_WINDOWS_BROWSER_LIMITATION").as_deref()- == Ok("hosted_runner_token")- {- let sentinel = ForegroundSentinel::launch(&mut driver);- let (prepared, passed) = sentinel- .observe_desktop(|| {- driver.call(- "browser_prepare",- serde_json::json!({- "session": session,- "allow_launch": true,- "profile": {"mode": "isolated_new"},- }),- )- })- .expect("observe hosted Windows browser limitation");- assert_eq!(- prepared.structured()["status"],- "refused",- "{}",- prepared.raw- );- assert_eq!(- prepared.structured()["refusal"]["code"],- "browser_route_unavailable",- "{}",- prepared.raw- );- assert!(- prepared.structured()["action"].is_null()- && prepared.structured()["prepared_pid"].is_null()- && prepared.structured()["side_effects"].is_null(),- "hosted Windows refusal must precede browser setup: {}",- prepared.raw- );- assert_eq!(- profile_entries(&driver_profiles),- profiles_before,- "hosted Windows refusal must not create an isolated profile"- );- let ended = driver.call("end_session", serde_json::json!({ "session": session }));- assert!(!ended.is_error(), "end_session failed: {}", ended.raw);- let mut observation = Observation::refused(- RefusalCode::BrowserRouteUnavailable,- vec![OracleKind::FixtureState],- prepared.text(),- Evidence::default(),- );- observation.passed_oracles.extend(passed);- observation- } else {- let prepared = driver.call(- "browser_prepare",- serde_json::json!({- "session": session,- "allow_launch": true,- "profile": {"mode": "isolated_new"},- }),- );- assert_eq!(prepared.structured()["status"], "ok", "{}", prepared.raw);- assert_eq!(- prepared.structured()["action"],- "launched_isolated_browser",- "{}",- prepared.raw- );- assert_eq!(- prepared.structured()["side_effects"]["launched_browser"],- true- );- assert_eq!(- prepared.structured()["side_effects"]["created_profile"],- true- );- let prepared_json = prepared.raw.to_string();- assert!(- !prepared_json.contains(&driver_profiles.display().to_string()),- "browser_prepare disclosed its private profile path: {}",- prepared.raw- );-- let prepared_pid = prepared.structured()["prepared_pid"]- .as_u64()- .expect("prepared browser pid") as u32;- let (prepared_window_id, state) =- wait_for_exact_browser_binding(&mut driver, prepared_pid, &session)- .expect("isolated browser did not expose an exactly bindable window");- let target = state.structured()["target_id"]- .as_str()- .expect("prepared target id")- .to_owned();- let tab = state.structured()["tabs"]- .as_array()- .and_then(|tabs| tabs.iter().find(|tab| tab["active"] == true))- .and_then(|tab| tab["tab_id"].as_str())- .expect("prepared active tab")- .to_owned();- let navigated = driver.call(- "browser_navigate",- serde_json::json!({- "target_id": target,- "tab_id": tab,- "url": target_server.page_url(),- "session": session,- }),- );- assert_eq!(navigated.structured()["status"], "ok", "{}", navigated.raw);- wait_for_observed(&target_server, "WEB_HARNESS_MARKER_v1");+ let prepared = driver.call(+ "browser_prepare",+ serde_json::json!({+ "session": session,+ "allow_launch": true,+ "profile": {"mode": "isolated_new"},+ }),+ );+ assert_eq!(prepared.structured()["status"], "ok", "{}", prepared.raw);+ assert_eq!(+ prepared.structured()["action"],+ "launched_isolated_browser",+ "{}",+ prepared.raw+ );+ assert_eq!(+ prepared.structured()["side_effects"]["launched_browser"],+ true+ );+ assert_eq!(+ prepared.structured()["side_effects"]["created_profile"],+ true+ );+ let prepared_json = prepared.raw.to_string();+ assert!(+ !prepared_json.contains(&driver_profiles.display().to_string()),+ "browser_prepare disclosed its private profile path: {}",+ prepared.raw+ );- let target_window = TargetWindow {- pid: prepared_pid,- native_id: prepared_window_id,- };- let sentinel = ForegroundSentinel::launch(&mut driver);- sentinel- .assert_background_posture(target_window)- .expect("establish isolated browser background posture");- sentinel- .prepare_background_observation(&mut driver, target_window)- .expect("restore isolated browser background posture");- let (mut observation, passed) = sentinel- .observe_background(target_window, || {- let snapshot = driver.call(- "get_browser_state",- serde_json::json!({- "target_id": target,- "tab_id": tab,- "session": session,- }),- );- let click_ref = ref_by_label(&snapshot, "id=btn-increment");- let clicked = driver.call(- "browser_click",- serde_json::json!({- "target_id": target,- "tab_id": tab,- "ref": click_ref,- "input_route": "dom_event",- "session": session,- }),- );- assert_eq!(- clicked.action_effect(),- Some("unverifiable"),- "{}",- clicked.raw- );- wait_for_text(&target_server, "lbl-counter", "counter=1");- Observation::delivered(vec![OracleKind::FixtureState], Evidence::default())- })- .expect("observe isolated browser desktop effects");- observation.passed_oracles.extend(passed);+ let prepared_pid = prepared.structured()["prepared_pid"]+ .as_u64()+ .expect("prepared browser pid") as u32;+ #[cfg(target_os = "windows")]+ assert_windows_isolated_browser_token(prepared_pid);+ let (prepared_window_id, state) =+ wait_for_exact_browser_binding(&mut driver, prepared_pid, &session)+ .expect("isolated browser did not expose an exactly bindable window");+ let target = state.structured()["target_id"]+ .as_str()+ .expect("prepared target id")+ .to_owned();+ let tab = state.structured()["tabs"]+ .as_array()+ .and_then(|tabs| tabs.iter().find(|tab| tab["active"] == true))+ .and_then(|tab| tab["tab_id"].as_str())+ .expect("prepared active tab")+ .to_owned();+ let navigated = driver.call(+ "browser_navigate",+ serde_json::json!({+ "target_id": target,+ "tab_id": tab,+ "url": target_server.page_url(),+ "session": session,+ }),+ );+ assert_eq!(navigated.structured()["status"], "ok", "{}", navigated.raw);+ wait_for_observed(&target_server, "WEB_HARNESS_MARKER_v1");- let ended = driver.call("end_session", serde_json::json!({ "session": session }));- assert!(!ended.is_error(), "end_session failed: {}", ended.raw);- wait_for_pid_windows_to_close(&mut driver, prepared_pid);- let profile_deadline = Instant::now() + Duration::from_secs(5);- loop {- if profile_entries(&driver_profiles) == profiles_before {- break;- }- assert!(- Instant::now() < profile_deadline,- "isolated_new profile remained after end_session"+ let target_window = TargetWindow {+ pid: prepared_pid,+ native_id: prepared_window_id,+ };+ let sentinel = ForegroundSentinel::launch(&mut driver);+ sentinel+ .assert_background_posture(target_window)+ .expect("establish isolated browser background posture");+ sentinel+ .prepare_background_observation(&mut driver, target_window)+ .expect("restore isolated browser background posture");+ let (mut observation, passed) = sentinel+ .observe_background(target_window, || {+ let snapshot = driver.call(+ "get_browser_state",+ serde_json::json!({+ "target_id": target,+ "tab_id": tab,+ "session": session,+ }),);- thread::sleep(Duration::from_millis(100));+ let click_ref = ref_by_label(&snapshot, "id=btn-increment");+ let clicked = driver.call(+ "browser_click",+ serde_json::json!({+ "target_id": target,+ "tab_id": tab,+ "ref": click_ref,+ "input_route": "dom_event",+ "session": session,+ }),+ );+ assert_eq!(+ clicked.action_effect(),+ Some("unverifiable"),+ "{}",+ clicked.raw+ );+ wait_for_text(&target_server, "lbl-counter", "counter=1");+ Observation::delivered(vec![OracleKind::FixtureState], Evidence::default())+ })+ .expect("observe isolated browser desktop effects");+ observation.passed_oracles.extend(passed);++ let ended = driver.call("end_session", serde_json::json!({ "session": session }));+ assert!(!ended.is_error(), "end_session failed: {}", ended.raw);+ wait_for_pid_windows_to_close(&mut driver, prepared_pid);+ let profile_deadline = Instant::now() + Duration::from_secs(5);+ loop {+ if profile_entries(&driver_profiles) == profiles_before {+ break;}- observation+ assert!(+ Instant::now() < profile_deadline,+ "isolated_new profile remained after end_session"+ );+ thread::sleep(Duration::from_millis(100));}+ observation});}diff --git a/libs/cua-driver/rust/crates/platform-windows/Cargo.toml b/libs/cua-driver/rust/crates/platform-windows/Cargo.tomlindex 4da06bdcce..1821d5ba74 100644--- a/libs/cua-driver/rust/crates/platform-windows/Cargo.toml+++ b/libs/cua-driver/rust/crates/platform-windows/Cargo.toml@@ -47,6 +47,9 @@ windows = { version = "0.58", features = ["Win32_System_LibraryLoader","Win32_Graphics_OpenGL","Win32_Security",+ # SaferCreateLevel / SaferComputeTokenFromLevel: derive the standard-user+ # token an elevated Driver uses to run isolated browsers.+ "Win32_Security_AppLocker","Win32_System_Com","Win32_Storage_Xps","Win32_Storage_FileSystem",diff --git a/libs/cua-driver/rust/crates/platform-windows/src/browser_isolated_selection.rs b/libs/cua-driver/rust/crates/platform-windows/src/browser_isolated_selection.rsindex 80400e1e84..e034749093 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/browser_isolated_selection.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/browser_isolated_selection.rs@@ -1,27 +1,32 @@//! Pure decision logic for choosing the Windows isolated-launch browser.//!//! The Windows adapter gathers facts about each trusted Chrome and Edge-//! installation (present, write access for the current token, vendor-//! signature) and this module turns them into either a launch choice or a-//! refusal message. It has no Win32 dependencies so its unit tests run on any-//! host.+//! installation (present, write access for the token that will run the+//! browser, vendor signature) and this module turns them into either a launch+//! choice or a refusal message. It has no Win32 dependencies so its unit+//! tests run on any host.//!-//! The security rule is unchanged by the diagnostic: a candidate launches only-//! when it is installed, protected from the current token, and vendor-signed.-//! The distinct message exists because an elevated or built-in Administrator-//! token can write `Program Files`, so correctly signed browsers are refused-//! for that token. Reporting that case as "no vendor-signed executable"-//! wrongly implies the browser is missing or unsigned.--/// Whether the current token can modify a candidate's installation tree.+//! The security rule: a candidate launches only when it is installed,+//! vendor-signed, and protected from the token that runs the browser. For a+//! non-elevated Driver that is the Driver's own token. An elevated Driver+//! runs the browser with a derived standard-user token instead (see+//! `browser_launch_token`), so protection is proven for that token. A signed+//! candidate that the launch token can still write gets a distinct message,+//! because "no vendor-signed executable" would wrongly imply the browser is+//! missing or unsigned.++use crate::browser_launch_token::BrowserLaunchToken;++/// Whether the browser launch token can modify a candidate's installation+/// tree.#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub(crate) enum InstallationWriteAccess {/// The executable and every ancestor up to the trusted root deny write- /// access to the current token.+ /// access to the launch token.Protected,- /// The current token was granted a write-class right on the executable or- /// an ancestor (typical for elevated and built-in Administrator tokens).- WritableByCurrentToken,+ /// The launch token was granted a write-class right on the executable or+ /// an ancestor.+ WritableByLaunchToken,/// The path is outside the trusted root or a write probe failed closed.Untrusted,}@@ -36,7 +41,7 @@ pub(crate) struct IsolatedCandidateFacts {pub write_access: InstallationWriteAccess,/// The executable carries the expected vendor Authenticode identity. The/// adapter evaluates this only for installed candidates whose write access- /// is `Protected` or `WritableByCurrentToken`; otherwise it is `false`.+ /// is `Protected` or `WritableByLaunchToken`; otherwise it is `false`.pub vendor_signed: bool,}@@ -72,6 +77,7 @@ pub(crate) const NO_PROTECTED_BROWSER_MESSAGE: &str =/// Choose the first launchable candidate, or explain why none qualifies.pub(crate) fn decide_isolated_browser(candidates: &[IsolatedCandidateFacts],+ launch_token: BrowserLaunchToken,) -> IsolatedBrowserDecision {if let Some(index) = candidates.iter()@@ -83,7 +89,7 @@ pub(crate) fn decide_isolated_browser(for candidate in candidates {if candidate.installed&& candidate.vendor_signed- && candidate.write_access == InstallationWriteAccess::WritableByCurrentToken+ && candidate.write_access == InstallationWriteAccess::WritableByLaunchToken&& !writable_products.contains(&candidate.product){writable_products.push(candidate.product);@@ -92,13 +98,20 @@ pub(crate) fn decide_isolated_browser(if writable_products.is_empty() {return IsolatedBrowserDecision::Refuse(NO_PROTECTED_BROWSER_MESSAGE.to_owned());}- IsolatedBrowserDecision::Refuse(format!(- "installed vendor-signed {} is writable by the current elevated or administrator token, \- so Cua Driver refuses to launch it for an isolated browser; run Cua Driver from a \- non-administrator, non-elevated session (the built-in Administrator account is always \- elevated)",- writable_products.join("/"),- ))+ let products = writable_products.join("/");+ IsolatedBrowserDecision::Refuse(match launch_token {+ BrowserLaunchToken::Driver => format!(+ "installed vendor-signed {products} is writable by the current non-elevated token, \+ so Cua Driver refuses to launch it for an isolated browser; restore the browser \+ installation's default permissions so that standard users cannot modify it"+ ),+ BrowserLaunchToken::StandardUser => format!(+ "installed vendor-signed {products} is writable even by the standard-user token that \+ the elevated Cua Driver uses for isolated browsers, so Cua Driver refuses to launch \+ it; restore the browser installation's default permissions so that standard users \+ cannot modify it"+ ),+ })}#[cfg(test)]@@ -118,6 +131,10 @@ mod tests {}}+ fn decide(candidates: &[IsolatedCandidateFacts]) -> IsolatedBrowserDecision {+ decide_isolated_browser(candidates, BrowserLaunchToken::Driver)+ }+fn refusal_message(decision: IsolatedBrowserDecision) -> String {match decision {IsolatedBrowserDecision::Refuse(message) => message,@@ -132,13 +149,10 @@ mod tests {IsolatedCandidateFacts::missing("Edge"),];assert_eq!(- refusal_message(decide_isolated_browser(&facts)),- NO_PROTECTED_BROWSER_MESSAGE- );- assert_eq!(- refusal_message(decide_isolated_browser(&[])),+ refusal_message(decide(&facts)),NO_PROTECTED_BROWSER_MESSAGE);+ assert_eq!(refusal_message(decide(&[])), NO_PROTECTED_BROWSER_MESSAGE);}#[test]@@ -147,12 +161,12 @@ mod tests {candidate("Chrome", InstallationWriteAccess::Protected, false),candidate("Edge",- InstallationWriteAccess::WritableByCurrentToken,+ InstallationWriteAccess::WritableByLaunchToken,false,),];assert_eq!(- refusal_message(decide_isolated_browser(&facts)),+ refusal_message(decide(&facts)),NO_PROTECTED_BROWSER_MESSAGE);}@@ -165,7 +179,7 @@ mod tests {false,)];assert_eq!(- refusal_message(decide_isolated_browser(&facts)),+ refusal_message(decide(&facts)),NO_PROTECTED_BROWSER_MESSAGE);}@@ -175,39 +189,49 @@ mod tests {let facts = [candidate("Chrome",- InstallationWriteAccess::WritableByCurrentToken,+ InstallationWriteAccess::WritableByLaunchToken,true,),IsolatedCandidateFacts::missing("Chrome"),- candidate(- "Edge",- InstallationWriteAccess::WritableByCurrentToken,- true,- ),- candidate(- "Edge",- InstallationWriteAccess::WritableByCurrentToken,- true,- ),+ candidate("Edge", InstallationWriteAccess::WritableByLaunchToken, true),+ candidate("Edge", InstallationWriteAccess::WritableByLaunchToken, true),];- let message = refusal_message(decide_isolated_browser(&facts));+ let message = refusal_message(decide(&facts));assert_ne!(message, NO_PROTECTED_BROWSER_MESSAGE);assert!(message.starts_with("installed vendor-signed Chrome/Edge is writable"));- assert!(message.contains("elevated or administrator token"));- assert!(message.contains("non-administrator"));+ assert!(message.contains("current non-elevated token"));+ assert!(message.contains("default permissions"));++ let message = refusal_message(decide_isolated_browser(+ &facts,+ BrowserLaunchToken::StandardUser,+ ));+ assert!(message.starts_with("installed vendor-signed Chrome/Edge is writable"));+ assert!(message.contains("even by the standard-user token"));+ assert!(message.contains("default permissions"));+ }++ #[test]+ fn launch_token_does_not_change_which_candidate_is_launchable() {+ let facts = [+ IsolatedCandidateFacts::missing("Chrome"),+ candidate("Edge", InstallationWriteAccess::Protected, true),+ ];+ for token in [BrowserLaunchToken::Driver, BrowserLaunchToken::StandardUser] {+ assert_eq!(+ decide_isolated_browser(&facts, token),+ IsolatedBrowserDecision::Launch(1)+ );+ }}#[test]fn writable_message_names_only_signed_writable_products() {let facts = [candidate("Chrome", InstallationWriteAccess::Protected, false),- candidate(- "Edge",- InstallationWriteAccess::WritableByCurrentToken,- true,- ),+ candidate("Edge", InstallationWriteAccess::WritableByLaunchToken, true),];- let message = refusal_message(decide_isolated_browser(&facts));+ let message = refusal_message(decide(&facts));assert!(message.starts_with("installed vendor-signed Edge is writable"));}@@ -216,17 +240,14 @@ mod tests {let facts = [candidate("Chrome",- InstallationWriteAccess::WritableByCurrentToken,+ InstallationWriteAccess::WritableByLaunchToken,true,),IsolatedCandidateFacts::missing("Chrome"),candidate("Edge", InstallationWriteAccess::Protected, true),candidate("Edge", InstallationWriteAccess::Protected, true),];- assert_eq!(- decide_isolated_browser(&facts),- IsolatedBrowserDecision::Launch(2)- );+ assert_eq!(decide(&facts), IsolatedBrowserDecision::Launch(2));}#[test]@@ -235,7 +256,7 @@ mod tests {assert!(!candidate("Chrome", InstallationWriteAccess::Protected, false).launchable());assert!(!candidate("Chrome",- InstallationWriteAccess::WritableByCurrentToken,+ InstallationWriteAccess::WritableByLaunchToken,true).launchable());diff --git a/libs/cua-driver/rust/crates/platform-windows/src/browser_launch_token.rs b/libs/cua-driver/rust/crates/platform-windows/src/browser_launch_token.rsnew file mode 100644index 0000000000..b8d738b074--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/browser_launch_token.rs@@ -0,0 +1,512 @@+//! Pure decision logic for the token that runs a Windows isolated browser.+//!+//! Cua Driver launches an isolated Chrome or Edge only from a vendor-signed+//! installation that the token running the browser cannot modify. An+//! elevated token (an elevated administrator, the built-in Administrator, or+//! any administrator when UAC is off) can modify `Program Files`, so such a+//! Driver never runs the browser with its own token. It derives a standard+//! user token from its own token instead: the same user, logon session, and+//! desktop, with `BUILTIN\Administrators` and the other groups that+//! `runas /trustlevel:0x20000` disables set to deny-only, administrative+//! privileges removed, and Medium integrity. Every protection check is then+//! made for that derived token, and the browser runs with it.+//!+//! Verification checks the properties Windows uses for access decisions:+//! group membership, privileges, and integrity level. It does not require+//! `TokenElevation` to be false. Windows keeps reporting that flag from the+//! elevated source token, and the flag grants no access by itself.+//!+//! The Win32 adapter gathers token facts and this module decides. It has no+//! Win32 dependencies so its unit tests run on any host.++/// Mandatory integrity level RIDs (`SECURITY_MANDATORY_*_RID`).+pub(crate) const MEDIUM_INTEGRITY_RID: u32 = 0x2000;+pub(crate) const HIGH_INTEGRITY_RID: u32 = 0x3000;++/// How a token holds `BUILTIN\Administrators` (S-1-5-32-544).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum AdministratorsMembership {+ Absent,+ /// Present only for deny access control entries, as in a UAC-filtered or+ /// standard-user token.+ DenyOnly,+ /// Present and usable for allow access control entries.+ Enabled,+}++/// Security-relevant facts about one access token.+#[derive(Clone, Debug, PartialEq, Eq)]+pub(crate) struct TokenFacts {+ /// `TokenElevation` reported the token as elevated. Used to decide+ /// whether the Driver is elevated; a derived token inherits this flag from+ /// its source token, so it is not a verification criterion for one.+ pub elevated: bool,+ pub integrity_rid: u32,+ pub administrators: AdministratorsMembership,+ /// Every privilege present in the token, enabled or not, by name.+ pub privileges: Vec<String>,+}++/// The token that runs a driver-owned isolated browser.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) enum BrowserLaunchToken {+ /// The Driver's own token. Used whenever the Driver is not elevated, so+ /// that configuration behaves exactly as before.+ Driver,+ /// A standard-user token derived from the elevated Driver's token.+ StandardUser,+}++/// Privileges an ordinary standard-user token holds. A derived token that+/// keeps any other privilege is refused.+pub(crate) const STANDARD_USER_PRIVILEGES: &[&str] = &[+ "SeChangeNotifyPrivilege",+ "SeShutdownPrivilege",+ "SeUndockPrivilege",+ "SeIncreaseWorkingSetPrivilege",+ "SeTimeZonePrivilege",+];++/// Choose the browser token for a Driver with these token facts.+pub(crate) fn browser_launch_token(driver: &TokenFacts) -> BrowserLaunchToken {+ if driver.elevated+ || driver.administrators == AdministratorsMembership::Enabled+ || driver.integrity_rid >= HIGH_INTEGRITY_RID+ {+ BrowserLaunchToken::StandardUser+ } else {+ BrowserLaunchToken::Driver+ }+}++/// Privileges present in a derived token that a standard user does not hold.+pub(crate) fn privileges_beyond_standard_user(privileges: &[String]) -> Vec<&str> {+ privileges+ .iter()+ .map(String::as_str)+ .filter(|name| !STANDARD_USER_PRIVILEGES.contains(name))+ .collect()+}++/// Require the derived browser token to be a standard-user token that sits+/// below the Driver. Integrity ordering matters: Windows forbids a lower+/// integrity process from writing to a higher integrity process, so the+/// browser cannot tamper with the elevated Driver process. `derived.elevated`+/// is deliberately ignored (see the module documentation).+pub(crate) fn validate_standard_user_token(+ driver: &TokenFacts,+ derived: &TokenFacts,+) -> Result<(), String> {+ if derived.administrators == AdministratorsMembership::Enabled {+ return Err("the derived token still has BUILTIN\\Administrators enabled".to_owned());+ }+ if derived.integrity_rid > MEDIUM_INTEGRITY_RID {+ return Err(format!(+ "the derived token has integrity level 0x{:04x}, above Medium",+ derived.integrity_rid+ ));+ }+ if derived.integrity_rid >= driver.integrity_rid {+ return Err(format!(+ "the derived token integrity level 0x{:04x} is not below the Driver's 0x{:04x}, so \+ Windows would not stop the browser from writing to the Driver process",+ derived.integrity_rid, driver.integrity_rid+ ));+ }+ let extra = privileges_beyond_standard_user(&derived.privileges);+ if !extra.is_empty() {+ return Err(format!(+ "the derived token keeps privileges a standard user does not hold: {}",+ extra.join(", ")+ ));+ }+ Ok(())+}++/// Refusal for an elevated Driver that cannot produce a verified+/// standard-user token. The Driver never falls back to its elevated token.+pub(crate) fn standard_user_token_unavailable_message(reason: &str) -> String {+ format!(+ "Cua Driver is running elevated and could not prepare a verified standard-user token \+ for the isolated browser ({reason}); it refuses to run the browser with its elevated \+ token. Run Cua Driver from a non-elevated session to use isolated browsers"+ )+}++const BACKSLASH: u16 = b'\\' as u16;+const QUOTE: u16 = b'"' as u16;++/// Build a `CreateProcess` command line whose `CommandLineToArgvW` parse is+/// exactly `program` followed by `args`. Works on UTF-16 so no path is lossily+/// converted. The program is always quoted and must not contain a quote.+pub(crate) fn windows_command_line(program: &[u16], args: &[Vec<u16>]) -> Result<Vec<u16>, String> {+ if program.is_empty() || program.contains("E) {+ return Err("the browser executable path cannot be quoted safely".to_owned());+ }+ let mut line = Vec::with_capacity(program.len() + 2);+ line.push(QUOTE);+ line.extend_from_slice(program);+ line.push(QUOTE);+ for arg in args {+ if arg.contains(&0) {+ return Err("a browser argument contains a NUL character".to_owned());+ }+ line.push(b' ' as u16);+ append_quoted_argument(&mut line, arg);+ }+ Ok(line)+}++fn append_quoted_argument(line: &mut Vec<u16>, arg: &[u16]) {+ let needs_quotes = arg.is_empty()+ || arg+ .iter()+ .any(|&unit| matches!(unit, 0x20 | 0x09 | 0x0a | 0x0b) || unit == QUOTE);+ if needs_quotes {+ line.push(QUOTE);+ }+ let mut backslashes = 0usize;+ for &unit in arg {+ if unit == BACKSLASH {+ backslashes += 1;+ } else {+ if unit == QUOTE {+ // Double the preceding backslashes and escape the quote.+ line.extend(std::iter::repeat_n(BACKSLASH, backslashes + 1));+ }+ backslashes = 0;+ }+ line.push(unit);+ }+ if needs_quotes {+ // Trailing backslashes before the closing quote must be doubled.+ line.extend(std::iter::repeat_n(BACKSLASH, backslashes));+ line.push(QUOTE);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn facts(+ elevated: bool,+ integrity_rid: u32,+ administrators: AdministratorsMembership,+ privileges: &[&str],+ ) -> TokenFacts {+ TokenFacts {+ elevated,+ integrity_rid,+ administrators,+ privileges: privileges.iter().map(|name| (*name).to_owned()).collect(),+ }+ }++ fn elevated_admin() -> TokenFacts {+ facts(+ true,+ HIGH_INTEGRITY_RID,+ AdministratorsMembership::Enabled,+ &[+ "SeChangeNotifyPrivilege",+ "SeDebugPrivilege",+ "SeBackupPrivilege",+ "SeImpersonatePrivilege",+ ],+ )+ }++ fn standard_user() -> TokenFacts {+ facts(+ false,+ MEDIUM_INTEGRITY_RID,+ AdministratorsMembership::DenyOnly,+ &["SeChangeNotifyPrivilege", "SeShutdownPrivilege"],+ )+ }++ #[test]+ fn non_elevated_driver_keeps_its_own_token() {+ // A standard user, and an administrator's UAC-filtered token.+ for driver in [+ facts(+ false,+ MEDIUM_INTEGRITY_RID,+ AdministratorsMembership::Absent,+ &["SeChangeNotifyPrivilege"],+ ),+ standard_user(),+ ] {+ assert_eq!(browser_launch_token(&driver), BrowserLaunchToken::Driver);+ }+ }++ #[test]+ fn elevated_driver_uses_a_standard_user_token() {+ // Elevated administrator with UAC on.+ assert_eq!(+ browser_launch_token(&elevated_admin()),+ BrowserLaunchToken::StandardUser+ );+ // Built-in Administrator or UAC off: Administrators enabled even if+ // TokenElevation were to report false.+ let uac_off = facts(+ false,+ HIGH_INTEGRITY_RID,+ AdministratorsMembership::Enabled,+ &[],+ );+ assert_eq!(+ browser_launch_token(&uac_off),+ BrowserLaunchToken::StandardUser+ );+ // Each signal alone is enough.+ let admins_only = facts(+ false,+ MEDIUM_INTEGRITY_RID,+ AdministratorsMembership::Enabled,+ &[],+ );+ assert_eq!(+ browser_launch_token(&admins_only),+ BrowserLaunchToken::StandardUser+ );+ let high_only = facts(+ false,+ HIGH_INTEGRITY_RID,+ AdministratorsMembership::DenyOnly,+ &[],+ );+ assert_eq!(+ browser_launch_token(&high_only),+ BrowserLaunchToken::StandardUser+ );+ let system = facts(false, 0x4000, AdministratorsMembership::DenyOnly, &[]);+ assert_eq!(+ browser_launch_token(&system),+ BrowserLaunchToken::StandardUser+ );+ let elevated_only = facts(+ true,+ MEDIUM_INTEGRITY_RID,+ AdministratorsMembership::DenyOnly,+ &[],+ );+ assert_eq!(+ browser_launch_token(&elevated_only),+ BrowserLaunchToken::StandardUser+ );+ }++ #[test]+ fn verified_standard_user_token_is_accepted() {+ assert_eq!(+ validate_standard_user_token(&elevated_admin(), &standard_user()),+ Ok(())+ );+ let mut absent = standard_user();+ absent.administrators = AdministratorsMembership::Absent;+ assert_eq!(+ validate_standard_user_token(&elevated_admin(), &absent),+ Ok(())+ );+ let all_standard = facts(+ false,+ MEDIUM_INTEGRITY_RID,+ AdministratorsMembership::DenyOnly,+ STANDARD_USER_PRIVILEGES,+ );+ assert_eq!(+ validate_standard_user_token(&elevated_admin(), &all_standard),+ Ok(())+ );+ }++ #[test]+ fn derived_token_is_judged_by_groups_not_the_inherited_elevation_flag() {+ // A SAFER token derived from an elevated token keeps TokenElevation+ // set; with Administrators deny-only, standard privileges, and Medium+ // integrity it is still a standard-user token.+ let mut inherited_flag = standard_user();+ inherited_flag.elevated = true;+ assert_eq!(+ validate_standard_user_token(&elevated_admin(), &inherited_flag),+ Ok(())+ );+ let mut admin = standard_user();+ admin.administrators = AdministratorsMembership::Enabled;+ assert!(validate_standard_user_token(&elevated_admin(), &admin)+ .unwrap_err()+ .contains("Administrators enabled"));+ }++ #[test]+ fn derived_token_must_be_medium_or_lower_and_below_the_driver() {+ let mut high = standard_user();+ high.integrity_rid = HIGH_INTEGRITY_RID;+ assert!(validate_standard_user_token(&elevated_admin(), &high)+ .unwrap_err()+ .contains("above Medium"));+ let mut medium_plus = standard_user();+ medium_plus.integrity_rid = 0x2100;+ assert!(validate_standard_user_token(&elevated_admin(), &medium_plus).is_err());+ // An elevated-by-group Driver at Medium integrity cannot be protected+ // from a Medium browser by integrity ordering.+ let medium_admin_driver = facts(+ false,+ MEDIUM_INTEGRITY_RID,+ AdministratorsMembership::Enabled,+ &[],+ );+ assert!(+ validate_standard_user_token(&medium_admin_driver, &standard_user())+ .unwrap_err()+ .contains("not below the Driver")+ );+ }++ #[test]+ fn derived_token_must_not_keep_administrative_privileges() {+ for privilege in [+ "SeDebugPrivilege",+ "SeBackupPrivilege",+ "SeRestorePrivilege",+ "SeTakeOwnershipPrivilege",+ "SeImpersonatePrivilege",+ "SeCreateGlobalPrivilege",+ "SeLoadDriverPrivilege",+ ] {+ let mut derived = standard_user();+ derived.privileges.push(privilege.to_owned());+ let error = validate_standard_user_token(&elevated_admin(), &derived).unwrap_err();+ assert!(error.contains(privilege), "{error}");+ }+ assert_eq!(+ privileges_beyond_standard_user(&elevated_admin().privileges),+ vec![+ "SeDebugPrivilege",+ "SeBackupPrivilege",+ "SeImpersonatePrivilege"+ ]+ );+ }++ #[test]+ fn unavailable_token_message_refuses_the_elevated_fallback() {+ let message = standard_user_token_unavailable_message("SaferCreateLevel failed");+ assert!(message.contains("running elevated"));+ assert!(message.contains("SaferCreateLevel failed"));+ assert!(message.contains("refuses to run the browser with its elevated token"));+ }++ fn wide(text: &str) -> Vec<u16> {+ text.encode_utf16().collect()+ }++ fn command_line(program: &str, args: &[&str]) -> Result<String, String> {+ let args = args.iter().map(|arg| wide(arg)).collect::<Vec<_>>();+ windows_command_line(&wide(program), &args).map(|line| String::from_utf16(&line).unwrap())+ }++ /// Reference `CommandLineToArgvW` argument parser (post-2008 rules) used+ /// to prove the quoting round-trips.+ fn parse_arguments(line: &str) -> Vec<String> {+ let chars = line.chars().collect::<Vec<_>>();+ let mut index = 0;+ // Program name: quoted or up to whitespace; no escape processing.+ if chars.first() == Some(&'"') {+ index = 1;+ while index < chars.len() && chars[index] != '"' {+ index += 1;+ }+ index += 1;+ } else {+ while index < chars.len() && chars[index] != ' ' && chars[index] != '\t' {+ index += 1;+ }+ }+ let mut arguments = Vec::new();+ loop {+ while index < chars.len() && (chars[index] == ' ' || chars[index] == '\t') {+ index += 1;+ }+ if index >= chars.len() {+ return arguments;+ }+ let mut current = String::new();+ let mut quoted = false;+ while index < chars.len() {+ let ch = chars[index];+ if ch == '\\' {+ let start = index;+ while index < chars.len() && chars[index] == '\\' {+ index += 1;+ }+ let count = index - start;+ if index < chars.len() && chars[index] == '"' {+ current.extend(std::iter::repeat_n('\\', count / 2));+ if count % 2 == 1 {+ current.push('"');+ index += 1;+ }+ } else {+ current.extend(std::iter::repeat_n('\\', count));+ }+ continue;+ }+ if ch == '"' {+ if quoted && chars.get(index + 1) == Some(&'"') {+ current.push('"');+ index += 2;+ continue;+ }+ quoted = !quoted;+ index += 1;+ continue;+ }+ if !quoted && (ch == ' ' || ch == '\t') {+ break;+ }+ current.push(ch);+ index += 1;+ }+ arguments.push(current);+ }+ }++ #[test]+ fn command_line_round_trips_browser_arguments() {+ let program = r"C:\Program Files\Google\Chrome\Application\chrome.exe";+ let args = [+ "--remote-debugging-port=0",+ r"--user-data-dir=C:\Users\Jane Doe\AppData\Local\CuaDriver\BrowserProfiles\isolated-1",+ "",+ r"trailing\",+ r"spaced trailing\\",+ r#"quote"inside"#,+ r#"back\"slash"#,+ "tab\there",+ "about:blank",+ ];+ let line = command_line(program, &args).expect("quotable");+ assert!(line.starts_with(&format!("\"{program}\" ")));+ assert_eq!(parse_arguments(&line), args);+ }++ #[test]+ fn simple_arguments_stay_unquoted() {+ assert_eq!(+ command_line(r"C:\b.exe", &["--no-first-run", r"C:\p\q"]).unwrap(),+ r#""C:\b.exe" --no-first-run C:\p\q"#+ );+ }++ #[test]+ fn command_line_rejects_unquotable_input() {+ assert!(command_line(r#"C:\bad"name.exe"#, &[]).is_err());+ assert!(command_line("", &[]).is_err());+ let nul = vec![wide("a\0b")];+ assert!(windows_command_line(&wide(r"C:\b.exe"), &nul).is_err());+ }+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/browser_platform.rs b/libs/cua-driver/rust/crates/platform-windows/src/browser_platform.rsindex 18449713e0..ab31d7ea59 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/browser_platform.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/browser_platform.rs@@ -11,7 +11,8 @@ use async_trait::async_trait;use cua_driver_core::browser::platform::{select_isolated_browser_executable, BrowserConsentOutcome, BrowserConsentRequest,BrowserPlatform, BrowserVisualAction, BrowserVisualActionKind, ExistingProfileSetupOutcome,- ExistingProfileSetupRequest, PrepareAction, PrepareOutcome, PrepareRequest,+ ExistingProfileSetupRequest, IsolatedBrowserProcess, PrepareAction, PrepareOutcome,+ PrepareRequest,};use cua_driver_core::browser::refusal::{BrowserRefusal, BrowserRefusalCode};use cua_driver_core::browser::types::{@@ -28,6 +29,10 @@ use crate::browser_isolated_selection::{decide_isolated_browser, InstallationWriteAccess, IsolatedBrowserDecision,IsolatedCandidateFacts, NO_PROTECTED_BROWSER_MESSAGE,};+use crate::browser_standard_user::{+ browser_launch_context, require_profile_writable, spawn_with_token, with_impersonation,+ BrowserLaunchContext,+};use windows::core::PCWSTR;use windows::Win32::Foundation::{CloseHandle, E_ACCESSDENIED, FILETIME, HWND, RECT};use windows::Win32::Storage::FileSystem::{@@ -220,7 +225,8 @@ fn authenticode_output(executable: &std::path::Path) -> std::io::Result<std::pro.output()}-/// Result of probing one path for write-class rights held by the current token.+/// Result of probing one path for write-class rights held by the calling+/// thread's effective token.enum WriteProbe {Denied,Granted(&'static str),@@ -238,9 +244,13 @@ fn current_token_write_denial_reason(path: &std::path::Path, directory: bool) ->fn current_token_write_probe(path: &std::path::Path, directory: bool) -> WriteProbe {use std::os::windows::ffi::OsStrExt;- // This launch boundary protects the current agent token from executing a- // browser tree that it can modify. Other principals that can replace an- // installed browser are outside this runtime authorization boundary.+ // This launch boundary keeps the token that runs the browser (the+ // Driver's own token, or the standard-user token an elevated Driver+ // derives) from executing a browser tree that it can modify. The probe+ // uses the calling thread's effective token, so a caller impersonating+ // the standard-user token probes for that token. Principals more+ // privileged than the launch token that can replace an installed browser+ // are outside this runtime authorization boundary.let wide = path.as_os_str().encode_wide()@@ -309,6 +319,23 @@ fn windows_installation_write_access()}+/// Probe the installation for the token that will run the browser. For a+/// standard-user launch every probe runs while impersonating that token; if+/// impersonation fails the candidate is `Untrusted` (fail closed).+fn launch_token_installation_write_access(+ context: &BrowserLaunchContext,+ executable: &std::path::Path,+ trusted_root: &std::path::Path,+) -> InstallationWriteAccess {+ match context {+ BrowserLaunchContext::Driver => windows_installation_write_access(executable, trusted_root),+ BrowserLaunchContext::StandardUser(token) => with_impersonation(token, || {+ windows_installation_write_access(executable, trusted_root)+ })+ .unwrap_or(InstallationWriteAccess::Untrusted),+ }+}+#[cfg(test)]fn trusted_windows_installation(executable: &std::path::Path,@@ -335,7 +362,7 @@ fn trusted_windows_installation_with_probe(/// Walk the executable and every ancestor up to `trusted_root`, requiring/// each probe to deny write access. The first non-denied probe decides the-/// rejection kind: a granted right is `WritableByCurrentToken`, a failed probe+/// rejection kind: a granted right is `WritableByLaunchToken`, a failed probe/// is `Untrusted` (fail closed).fn windows_installation_write_access_with_probe(executable: &std::path::Path,@@ -344,7 +371,7 @@ fn windows_installation_write_access_with_probe() -> InstallationWriteAccess {let rejection = |result: WriteProbe| match result {WriteProbe::Denied => None,- WriteProbe::Granted(_) => Some(InstallationWriteAccess::WritableByCurrentToken),+ WriteProbe::Granted(_) => Some(InstallationWriteAccess::WritableByLaunchToken),WriteProbe::Failed(_) => Some(InstallationWriteAccess::Untrusted),};if !executable.starts_with(trusted_root) {@@ -1301,6 +1328,9 @@ where#[async_trait]impl BrowserPlatform for WindowsBrowserPlatform {fn isolated_browser_executable(&self) -> Result<String, BrowserRefusal> {+ // An elevated Driver runs the browser with a derived standard-user+ // token, so installation protection is proven for that token.+ let context = browser_launch_context()?;let mut facts = Vec::new();let mut executables = Vec::new();for (candidate, trusted_root, expected_cn, expected_org) in isolated_browser_candidates()? {@@ -1310,7 +1340,8 @@ impl BrowserPlatform for WindowsBrowserPlatform {executables.push(None);continue;};- let write_access = windows_installation_write_access(&candidate, &trusted_root);+ let write_access =+ launch_token_installation_write_access(&context, &candidate, &trusted_root);// The signature of a writable candidate is read only to explain// the refusal; such a candidate is never launched.let vendor_signed = write_access != InstallationWriteAccess::Untrusted@@ -1332,7 +1363,7 @@ impl BrowserPlatform for WindowsBrowserPlatform {break;}}- match decide_isolated_browser(&facts) {+ match decide_isolated_browser(&facts, context.kind()) {IsolatedBrowserDecision::Launch(index) => executables[index].take().ok_or_else(|| {refusal(BrowserRefusalCode::BrowserRouteUnavailable,@@ -1346,6 +1377,42 @@ impl BrowserPlatform for WindowsBrowserPlatform {}}+ fn spawn_isolated_browser(+ &self,+ mut command: std::process::Command,+ profile: &std::path::Path,+ ) -> Result<Box<dyn IsolatedBrowserProcess>, BrowserRefusal> {+ match browser_launch_context()? {+ BrowserLaunchContext::Driver => command+ .spawn()+ .map(|child| Box::new(child) as Box<dyn IsolatedBrowserProcess>)+ .map_err(|error| {+ refusal(+ BrowserRefusalCode::BrowserRouteUnavailable,+ format!("could not launch an isolated browser process: {error}"),+ )+ }),+ BrowserLaunchContext::StandardUser(token) => {+ require_profile_writable(&token, profile)?;+ tracing::info!(+ "launching the isolated browser with a standard-user token derived from the \+ elevated Driver token"+ );+ spawn_with_token(token, &command)+ .map(|child| Box::new(child) as Box<dyn IsolatedBrowserProcess>)+ .map_err(|error| {+ refusal(+ BrowserRefusalCode::BrowserRouteUnavailable,+ format!(+ "could not launch the isolated browser with the standard-user \+ token: {error}"+ ),+ )+ })+ }+ }+ }+async fn visualize_browser_action(&self, action: BrowserVisualAction) {if action.session.is_empty()|| action.cdp_target_id.is_empty()@@ -2117,7 +2184,7 @@ mod tests {WriteProbe::Denied}}),- InstallationWriteAccess::WritableByCurrentToken+ InstallationWriteAccess::WritableByLaunchToken);assert_eq!(windows_installation_write_access_with_probe(&executable, root, |_, directory| {@@ -2181,6 +2248,31 @@ mod tests {);};+ // An elevated host (GitHub-hosted Windows runs tests elevated) must+ // prove the vendor tree protected from the derived standard-user+ // token and select it end to end, instead of refusing.+ let context = browser_launch_context().expect("browser launch context");+ if matches!(context, BrowserLaunchContext::StandardUser(_)) {+ assert_eq!(+ launch_token_installation_write_access(&context, &installed.0, &installed.1),+ InstallationWriteAccess::Protected,+ "the standard-user launch token must not be able to modify {}",+ installed.0.display()+ );+ let selected = WindowsBrowserPlatform::default()+ .isolated_browser_executable()+ .expect(+ "an elevated Driver selects a protected browser for its standard-user token",+ );+ let selected_path = selected.strip_prefix(r"\\?\").unwrap_or(&selected);+ assert!(+ candidates.iter().any(|(candidate, _, _, _)| selected_path+ .eq_ignore_ascii_case(&candidate.to_string_lossy())),+ "selected executable must be a trusted candidate: {selected}"+ );+ return;+ }+if !trusted_windows_installation(&installed.0, &installed.1) {let mut diagnostics = vec![("executable".to_string(),diff --git a/libs/cua-driver/rust/crates/platform-windows/src/browser_standard_user.rs b/libs/cua-driver/rust/crates/platform-windows/src/browser_standard_user.rsnew file mode 100644index 0000000000..cab7691ce3--- /dev/null+++ b/libs/cua-driver/rust/crates/platform-windows/src/browser_standard_user.rs@@ -0,0 +1,727 @@+//! Win32 side of the standard-user launch for isolated browsers.+//!+//! An elevated Driver derives a standard-user token from its own process token+//! with the SAFER "Normal User" level (the level `runas /trustlevel:0x20000`+//! uses): `BUILTIN\Administrators` and the other administrative groups become+//! deny-only and administrative privileges are removed. The Driver then lowers+//! the token to Medium integrity, removes any remaining privilege a standard+//! user does not hold, and verifies the result before use. The browser is+//! created with that token, the installation protection probes run while+//! impersonating it, and file work inside the browser-writable profile runs+//! while impersonating it. The Driver never falls back to its own elevated+//! token. Decision rules live in `browser_launch_token`.+//!+//! A restricted token from `CreateRestrictedToken` (with or without+//! `LUA_TOKEN`/`DISABLE_MAX_PRIVILEGE`) is deliberately not used: Chrome's+//! sandbox cannot launch its GPU and renderer processes under one.++use std::ffi::c_void;+use std::os::windows::ffi::OsStrExt;+use std::os::windows::process::ExitStatusExt;+use std::path::Path;+use std::process::{Command, ExitStatus};+use std::sync::{Arc, Mutex};++use cua_driver_core::browser::refusal::{BrowserRefusal, BrowserRefusalCode};+use cua_driver_core::browser::IsolatedBrowserProcess;+use windows::core::{PCWSTR, PWSTR};+use windows::Win32::Foundation::{+ CloseHandle, GetLastError, ERROR_NOT_ALL_ASSIGNED, E_ACCESSDENIED, HANDLE, LUID, WAIT_OBJECT_0,+ WAIT_TIMEOUT,+};+use windows::Win32::Security::AppLocker::{+ SaferCloseLevel, SaferComputeTokenFromLevel, SaferCreateLevel,+ SAFER_COMPUTE_TOKEN_FROM_LEVEL_FLAGS, SAFER_LEVELID_NORMALUSER, SAFER_LEVEL_OPEN,+ SAFER_SCOPEID_USER,+};+use windows::Win32::Security::{+ AdjustTokenPrivileges, CreateWellKnownSid, EqualSid, GetLengthSid, GetSidSubAuthority,+ GetSidSubAuthorityCount, GetTokenInformation, ImpersonateLoggedOnUser, LookupPrivilegeNameW,+ RevertToSelf, SecurityImpersonation, SetTokenInformation, TokenElevation, TokenGroups,+ TokenImpersonationLevel, TokenIntegrityLevel, TokenPrivileges, WinBuiltinAdministratorsSid,+ WinMediumLabelSid, LUID_AND_ATTRIBUTES, PSID, SAFER_LEVEL_HANDLE, SECURITY_IMPERSONATION_LEVEL,+ SE_PRIVILEGE_REMOVED, SID_AND_ATTRIBUTES, TOKEN_ACCESS_MASK, TOKEN_ASSIGN_PRIMARY,+ TOKEN_DUPLICATE, TOKEN_ELEVATION, TOKEN_GROUPS, TOKEN_INFORMATION_CLASS, TOKEN_MANDATORY_LABEL,+ TOKEN_PRIVILEGES, TOKEN_QUERY,+};+use windows::Win32::Storage::FileSystem::{+ CreateFileW, FILE_ADD_FILE, FILE_ADD_SUBDIRECTORY, FILE_DELETE_CHILD,+ FILE_FLAG_BACKUP_SEMANTICS, FILE_LIST_DIRECTORY, FILE_SHARE_DELETE, FILE_SHARE_READ,+ FILE_SHARE_WRITE, FILE_TRAVERSE, OPEN_EXISTING,+};+use windows::Win32::System::Threading::{+ CreateProcessAsUserW, GetCurrentProcess, GetCurrentThread, GetExitCodeProcess,+ OpenProcessToken, OpenThreadToken, TerminateProcess, WaitForSingleObject, INFINITE,+ PROCESS_CREATION_FLAGS, PROCESS_INFORMATION, STARTUPINFOW,+};++use crate::browser_launch_token::{+ browser_launch_token, privileges_beyond_standard_user, standard_user_token_unavailable_message,+ validate_standard_user_token, windows_command_line, AdministratorsMembership,+ BrowserLaunchToken, TokenFacts, MEDIUM_INTEGRITY_RID,+};++// `SE_GROUP_*` attribute bits from winnt.h.+const SE_GROUP_ENABLED: u32 = 0x0000_0004;+const SE_GROUP_USE_FOR_DENY_ONLY: u32 = 0x0000_0010;+const SE_GROUP_INTEGRITY: u32 = 0x0000_0020;++/// An owned kernel handle closed on drop.+pub(crate) struct OwnedHandle(HANDLE);++// SAFETY: a kernel handle value is process-wide and may be used and closed+// from any thread. The wrapper never hands out the handle for closing.+unsafe impl Send for OwnedHandle {}+unsafe impl Sync for OwnedHandle {}++impl OwnedHandle {+ pub(crate) fn raw(&self) -> HANDLE {+ self.0+ }+}++impl Drop for OwnedHandle {+ fn drop(&mut self) {+ if !self.0.is_invalid() {+ let _ = unsafe { CloseHandle(self.0) };+ }+ }+}++/// The token that will run the isolated browser.+#[derive(Clone)]+pub(crate) enum BrowserLaunchContext {+ /// The Driver is not elevated; the browser runs with the Driver's token.+ Driver,+ /// A verified standard-user token derived from the elevated Driver token.+ StandardUser(Arc<OwnedHandle>),+}++impl BrowserLaunchContext {+ pub(crate) fn kind(&self) -> BrowserLaunchToken {+ match self {+ Self::Driver => BrowserLaunchToken::Driver,+ Self::StandardUser(_) => BrowserLaunchToken::StandardUser,+ }+ }+}++/// A process token cannot change after process start, so one verified+/// standard-user token serves every isolated launch. Failures are not cached.+static STANDARD_USER_TOKEN: Mutex<Option<Arc<OwnedHandle>>> = Mutex::new(None);++fn refusal(message: impl Into<String>) -> BrowserRefusal {+ BrowserRefusal::new(BrowserRefusalCode::BrowserRouteUnavailable, message)+}++/// Decide which token runs the isolated browser and, for an elevated Driver,+/// produce the verified standard-user token. Never returns the Driver's+/// elevated token for the browser.+pub(crate) fn browser_launch_context() -> Result<BrowserLaunchContext, BrowserRefusal> {+ let driver_token = current_process_token(TOKEN_QUERY)+ .map_err(|error| refusal(format!("could not open the Driver process token: {error}")))?;+ let driver = token_facts(driver_token.raw()).map_err(|error| {+ refusal(format!(+ "could not inspect the Driver process token: {error}"+ ))+ })?;+ if browser_launch_token(&driver) == BrowserLaunchToken::Driver {+ return Ok(BrowserLaunchContext::Driver);+ }+ let mut cached = STANDARD_USER_TOKEN+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ if let Some(token) = cached.as_ref() {+ return Ok(BrowserLaunchContext::StandardUser(token.clone()));+ }+ let token = derive_verified_standard_user_token(&driver)+ .map(Arc::new)+ .map_err(|reason| refusal(standard_user_token_unavailable_message(&reason)))?;+ *cached = Some(token.clone());+ Ok(BrowserLaunchContext::StandardUser(token))+}++fn current_process_token(access: TOKEN_ACCESS_MASK) -> Result<OwnedHandle, String> {+ let mut token = HANDLE::default();+ unsafe { OpenProcessToken(GetCurrentProcess(), access, &mut token) }+ .map_err(|error| format!("OpenProcessToken failed: {error}"))?;+ Ok(OwnedHandle(token))+}++/// Derive, harden, and verify the standard-user token for `driver`.+fn derive_verified_standard_user_token(driver: &TokenFacts) -> Result<OwnedHandle, String> {+ let driver_token = current_process_token(TOKEN_QUERY | TOKEN_DUPLICATE | TOKEN_ASSIGN_PRIMARY)?;+ let derived = safer_normal_user_token(driver_token.raw())?;+ let facts = token_facts(derived.raw())?;+ if facts.integrity_rid > MEDIUM_INTEGRITY_RID {+ set_medium_integrity(derived.raw())?;+ }+ remove_privileges(derived.raw(), &facts)?;+ let verified = token_facts(derived.raw())?;+ validate_standard_user_token(driver, &verified).map_err(|reason| {+ format!(+ "{reason}; derived token: integrity=0x{:04x}, administrators={:?}, privileges=[{}]",+ verified.integrity_rid,+ verified.administrators,+ verified.privileges.join(", ")+ )+ })?;+ Ok(derived)+}++fn safer_normal_user_token(driver_token: HANDLE) -> Result<OwnedHandle, String> {+ let mut level = SAFER_LEVEL_HANDLE::default();+ unsafe {+ SaferCreateLevel(+ SAFER_SCOPEID_USER,+ SAFER_LEVELID_NORMALUSER,+ SAFER_LEVEL_OPEN,+ &mut level,+ None,+ )+ }+ .map_err(|error| format!("SaferCreateLevel failed: {error}"))?;+ let mut derived = HANDLE::default();+ let computed = unsafe {+ SaferComputeTokenFromLevel(+ level,+ driver_token,+ &mut derived,+ SAFER_COMPUTE_TOKEN_FROM_LEVEL_FLAGS(0),+ None,+ )+ };+ let _ = unsafe { SaferCloseLevel(level) };+ computed.map_err(|error| format!("SaferComputeTokenFromLevel failed: {error}"))?;+ Ok(OwnedHandle(derived))+}++fn set_medium_integrity(token: HANDLE) -> Result<(), String> {+ // SECURITY_MAX_SID_SIZE is 68 bytes; use u64 storage for alignment.+ let mut sid_buffer = [0u64; 12];+ let mut sid_size = std::mem::size_of_val(&sid_buffer) as u32;+ let sid = PSID(sid_buffer.as_mut_ptr().cast());+ unsafe { CreateWellKnownSid(WinMediumLabelSid, PSID::default(), sid, &mut sid_size) }+ .map_err(|error| format!("could not build the Medium integrity SID: {error}"))?;+ let label = TOKEN_MANDATORY_LABEL {+ Label: SID_AND_ATTRIBUTES {+ Sid: sid,+ Attributes: SE_GROUP_INTEGRITY,+ },+ };+ let size = std::mem::size_of::<TOKEN_MANDATORY_LABEL>() as u32 + unsafe { GetLengthSid(sid) };+ unsafe {+ SetTokenInformation(+ token,+ TokenIntegrityLevel,+ std::ptr::from_ref(&label).cast(),+ size,+ )+ }+ .map_err(|error| format!("could not lower the token to Medium integrity: {error}"))+}++fn remove_privileges(token: HANDLE, facts: &TokenFacts) -> Result<(), String> {+ let extra = privileges_beyond_standard_user(&facts.privileges);+ if extra.is_empty() {+ return Ok(());+ }+ for (name, luid) in token_privileges(token)? {+ if !extra.contains(&name.as_str()) {+ continue;+ }+ let state = TOKEN_PRIVILEGES {+ PrivilegeCount: 1,+ Privileges: [LUID_AND_ATTRIBUTES {+ Luid: luid,+ Attributes: SE_PRIVILEGE_REMOVED,+ }],+ };+ unsafe { AdjustTokenPrivileges(token, false, Some(&state), 0, None, None) }+ .map_err(|error| format!("could not remove {name}: {error}"))?;+ if unsafe { GetLastError() } == ERROR_NOT_ALL_ASSIGNED {+ return Err(format!(+ "could not remove {name}: not all privileges assigned"+ ));+ }+ }+ Ok(())+}++/// Read one variable-length token information class into aligned storage.+fn token_information(token: HANDLE, class: TOKEN_INFORMATION_CLASS) -> Result<Vec<u64>, String> {+ let mut needed = 0u32;+ let _ = unsafe { GetTokenInformation(token, class, None, 0, &mut needed) };+ if needed == 0 {+ return Err(format!("GetTokenInformation({}) reported no data", class.0));+ }+ let mut buffer = vec![0u64; (needed as usize).div_ceil(8)];+ unsafe {+ GetTokenInformation(+ token,+ class,+ Some(buffer.as_mut_ptr().cast()),+ needed,+ &mut needed,+ )+ }+ .map_err(|error| format!("GetTokenInformation({}) failed: {error}", class.0))?;+ Ok(buffer)+}++fn sid_last_rid(sid: PSID) -> Option<u32> {+ unsafe {+ let count = GetSidSubAuthorityCount(sid);+ if count.is_null() || *count == 0 {+ return None;+ }+ let rid = GetSidSubAuthority(sid, u32::from(*count - 1));+ (!rid.is_null()).then(|| *rid)+ }+}++fn token_privileges(token: HANDLE) -> Result<Vec<(String, LUID)>, String> {+ let buffer = token_information(token, TokenPrivileges)?;+ let header = buffer.as_ptr().cast::<TOKEN_PRIVILEGES>();+ let count = unsafe { (*header).PrivilegeCount } as usize;+ let first = unsafe { std::ptr::addr_of!((*header).Privileges).cast::<LUID_AND_ATTRIBUTES>() };+ let mut privileges = Vec::with_capacity(count);+ for index in 0..count {+ let luid = unsafe { (*first.add(index)).Luid };+ let mut name = [0u16; 128];+ let mut length = name.len() as u32;+ let resolved = unsafe {+ LookupPrivilegeNameW(PCWSTR::null(), &luid, PWSTR(name.as_mut_ptr()), &mut length)+ };+ // An unresolvable privilege keeps a synthetic name, which is never on+ // the standard-user allow list, so validation fails closed.+ let name = match resolved {+ Ok(()) => String::from_utf16_lossy(&name[..length as usize]),+ Err(_) => format!("LUID({:#x}:{:#x})", luid.HighPart, luid.LowPart),+ };+ privileges.push((name, luid));+ }+ Ok(privileges)+}++fn administrators_membership(token: HANDLE) -> Result<AdministratorsMembership, String> {+ let mut sid_buffer = [0u64; 12];+ let mut sid_size = std::mem::size_of_val(&sid_buffer) as u32;+ let administrators = PSID(sid_buffer.as_mut_ptr().cast());+ unsafe {+ CreateWellKnownSid(+ WinBuiltinAdministratorsSid,+ PSID::default(),+ administrators,+ &mut sid_size,+ )+ }+ .map_err(|error| format!("could not build the Administrators SID: {error}"))?;+ let buffer = token_information(token, TokenGroups)?;+ let header = buffer.as_ptr().cast::<TOKEN_GROUPS>();+ let count = unsafe { (*header).GroupCount } as usize;+ let first = unsafe { std::ptr::addr_of!((*header).Groups).cast::<SID_AND_ATTRIBUTES>() };+ for index in 0..count {+ let group = unsafe { *first.add(index) };+ if unsafe { EqualSid(group.Sid, administrators) }.is_ok() {+ let attributes = group.Attributes;+ return Ok(if attributes & SE_GROUP_USE_FOR_DENY_ONLY != 0 {+ AdministratorsMembership::DenyOnly+ } else if attributes & SE_GROUP_ENABLED != 0 {+ AdministratorsMembership::Enabled+ } else {+ // A present, disabled, allow-capable group can be re-enabled+ // by the token holder, so treat it as enabled.+ AdministratorsMembership::Enabled+ });+ }+ }+ Ok(AdministratorsMembership::Absent)+}++/// Gather the security-relevant facts of `token`.+pub(crate) fn token_facts(token: HANDLE) -> Result<TokenFacts, String> {+ let mut elevation = TOKEN_ELEVATION::default();+ let mut returned = 0u32;+ unsafe {+ GetTokenInformation(+ token,+ TokenElevation,+ Some(std::ptr::from_mut(&mut elevation).cast::<c_void>()),+ std::mem::size_of::<TOKEN_ELEVATION>() as u32,+ &mut returned,+ )+ }+ .map_err(|error| format!("GetTokenInformation(TokenElevation) failed: {error}"))?;+ let label = token_information(token, TokenIntegrityLevel)?;+ let label = label.as_ptr().cast::<TOKEN_MANDATORY_LABEL>();+ let integrity_rid = sid_last_rid(unsafe { (*label).Label.Sid })+ .ok_or_else(|| "the token integrity label has no RID".to_owned())?;+ Ok(TokenFacts {+ elevated: elevation.TokenIsElevated != 0,+ integrity_rid,+ administrators: administrators_membership(token)?,+ privileges: token_privileges(token)?+ .into_iter()+ .map(|(name, _)| name)+ .collect(),+ })+}++/// Reverts the calling thread's impersonation when dropped, including on+/// unwind, so a thread never keeps a borrowed token.+struct ImpersonationGuard;++impl Drop for ImpersonationGuard {+ fn drop(&mut self) {+ if unsafe { RevertToSelf() }.is_err() {+ // Continuing on a thread with an unknown security context would+ // make later Driver work unpredictable.+ std::process::abort();+ }+ }+}++/// Run `work` on the current thread while impersonating `token`. Windows+/// silently downgrades a disallowed impersonation to Identification level,+/// which would make file access fail, so the level is verified first.+pub(crate) fn with_impersonation<R>(+ token: &OwnedHandle,+ work: impl FnOnce() -> R,+) -> std::io::Result<R> {+ unsafe { ImpersonateLoggedOnUser(token.raw()) }.map_err(std::io::Error::other)?;+ let guard = ImpersonationGuard;+ let mut thread_token = HANDLE::default();+ unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, true, &mut thread_token) }+ .map_err(std::io::Error::other)?;+ let thread_token = OwnedHandle(thread_token);+ let mut level = SECURITY_IMPERSONATION_LEVEL::default();+ let mut returned = 0u32;+ unsafe {+ GetTokenInformation(+ thread_token.raw(),+ TokenImpersonationLevel,+ Some(std::ptr::from_mut(&mut level).cast::<c_void>()),+ std::mem::size_of::<SECURITY_IMPERSONATION_LEVEL>() as u32,+ &mut returned,+ )+ }+ .map_err(std::io::Error::other)?;+ if level.0 < SecurityImpersonation.0 {+ return Err(std::io::Error::other(format!(+ "Windows granted impersonation level {} instead of SecurityImpersonation",+ level.0+ )));+ }+ let result = work();+ drop(guard);+ Ok(result)+}++/// Require the standard-user token to be able to create, list, and delete+/// entries in the isolated profile directory the Driver prepared.+pub(crate) fn require_profile_writable(+ token: &OwnedHandle,+ profile: &Path,+) -> Result<(), BrowserRefusal> {+ let wide = profile+ .as_os_str()+ .encode_wide()+ .chain(std::iter::once(0))+ .collect::<Vec<_>>();+ let access = FILE_LIST_DIRECTORY.0+ | FILE_TRAVERSE.0+ | FILE_ADD_FILE.0+ | FILE_ADD_SUBDIRECTORY.0+ | FILE_DELETE_CHILD.0;+ let opened = with_impersonation(token, || unsafe {+ CreateFileW(+ PCWSTR(wide.as_ptr()),+ access,+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,+ None,+ OPEN_EXISTING,+ FILE_FLAG_BACKUP_SEMANTICS,+ None,+ )+ })+ .map_err(|error| {+ refusal(format!(+ "could not assume the standard-user browser token to check the isolated profile: {error}"+ ))+ })?;+ match opened {+ Ok(handle) => {+ drop(OwnedHandle(handle));+ Ok(())+ }+ Err(error) if error.code() == E_ACCESSDENIED => Err(refusal(+ "the standard-user token that runs the isolated browser cannot write its driver-owned \+ profile directory; remove the custom permissions from the Cua Driver browser profile \+ root",+ )),+ Err(error) => Err(refusal(format!(+ "could not verify the isolated profile for the standard-user browser token: {error}"+ ))),+ }+}++/// The root process of an isolated browser created with a standard-user+/// token. File work in its profile runs while impersonating that token.+pub(crate) struct StandardUserBrowserProcess {+ process: OwnedHandle,+ pid: u32,+ token: Arc<OwnedHandle>,+}++impl StandardUserBrowserProcess {+ fn exit_status(&self) -> std::io::Result<ExitStatus> {+ let mut code = 0u32;+ unsafe { GetExitCodeProcess(self.process.raw(), &mut code) }+ .map_err(std::io::Error::other)?;+ Ok(ExitStatus::from_raw(code))+ }++ #[cfg(test)]+ pub(crate) fn process_handle(&self) -> HANDLE {+ self.process.raw()+ }+}++impl IsolatedBrowserProcess for StandardUserBrowserProcess {+ fn id(&self) -> u32 {+ self.pid+ }++ fn try_wait(&mut self) -> std::io::Result<Option<ExitStatus>> {+ let waited = unsafe { WaitForSingleObject(self.process.raw(), 0) };+ if waited == WAIT_OBJECT_0 {+ self.exit_status().map(Some)+ } else if waited == WAIT_TIMEOUT {+ Ok(None)+ } else {+ Err(std::io::Error::last_os_error())+ }+ }++ fn kill(&mut self) -> std::io::Result<()> {+ if self.try_wait()?.is_some() {+ return Ok(());+ }+ unsafe { TerminateProcess(self.process.raw(), 1) }.map_err(std::io::Error::other)+ }++ fn wait(&mut self) -> std::io::Result<ExitStatus> {+ if unsafe { WaitForSingleObject(self.process.raw(), INFINITE) } != WAIT_OBJECT_0 {+ return Err(std::io::Error::last_os_error());+ }+ self.exit_status()+ }++ fn with_browser_file_authority(&self, work: &mut dyn FnMut()) -> std::io::Result<()> {+ with_impersonation(&self.token, work)+ }+}++/// Create the process described by `command` with `token`. Only the program+/// and arguments are used: the child inherits no handles (so no elevated+/// handle crosses the boundary), the Driver's environment, and the Driver's+/// window station and desktop.+pub(crate) fn spawn_with_token(+ token: Arc<OwnedHandle>,+ command: &Command,+) -> Result<StandardUserBrowserProcess, String> {+ if command.get_envs().next().is_some() || command.get_current_dir().is_some() {+ return Err(+ "the isolated browser command sets an environment or working directory that the \+ standard-user launch does not forward"+ .to_owned(),+ );+ }+ let program = command.get_program().encode_wide().collect::<Vec<_>>();+ let args = command+ .get_args()+ .map(|arg| arg.encode_wide().collect::<Vec<_>>())+ .collect::<Vec<_>>();+ let mut command_line = windows_command_line(&program, &args)?;+ command_line.push(0);+ let application = program+ .into_iter()+ .chain(std::iter::once(0))+ .collect::<Vec<_>>();+ let startup = STARTUPINFOW {+ cb: std::mem::size_of::<STARTUPINFOW>() as u32,+ ..Default::default()+ };+ let mut information = PROCESS_INFORMATION::default();+ unsafe {+ CreateProcessAsUserW(+ token.raw(),+ PCWSTR(application.as_ptr()),+ PWSTR(command_line.as_mut_ptr()),+ None,+ None,+ false,+ PROCESS_CREATION_FLAGS(0),+ None,+ PCWSTR::null(),+ &startup,+ &mut information,+ )+ }+ .map_err(|error| format!("CreateProcessAsUserW failed: {error}"))?;+ drop(OwnedHandle(information.hThread));+ Ok(StandardUserBrowserProcess {+ process: OwnedHandle(information.hProcess),+ pid: information.dwProcessId,+ token,+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::browser_launch_token::HIGH_INTEGRITY_RID;++ fn process_token_facts(process: HANDLE) -> TokenFacts {+ let mut token = HANDLE::default();+ unsafe { OpenProcessToken(process, TOKEN_QUERY, &mut token) }+ .expect("open child process token");+ let token = OwnedHandle(token);+ token_facts(token.raw()).expect("child token facts")+ }++ fn system32() -> std::path::PathBuf {+ std::path::PathBuf::from(std::env::var_os("SystemRoot").expect("SystemRoot"))+ .join("System32")+ }++ #[test]+ fn driver_token_facts_are_readable_and_consistent() {+ let token = current_process_token(TOKEN_QUERY).expect("process token");+ let facts = token_facts(token.raw()).expect("token facts");+ assert!(facts.integrity_rid >= MEDIUM_INTEGRITY_RID, "{facts:?}");+ assert!(+ facts+ .privileges+ .iter()+ .any(|name| name == "SeChangeNotifyPrivilege"),+ "{facts:?}"+ );+ if facts.integrity_rid >= HIGH_INTEGRITY_RID {+ assert_eq!(+ browser_launch_token(&facts),+ BrowserLaunchToken::StandardUser+ );+ }+ }++ /// On an elevated host (GitHub-hosted Windows runs tests elevated), derive+ /// the real standard-user token, prove its posture, prove impersonation+ /// cannot write Program Files, and prove the created process runs with it.+ #[test]+ fn elevated_driver_launches_children_with_a_verified_standard_user_token() {+ let driver_token = current_process_token(TOKEN_QUERY).expect("process token");+ let driver = token_facts(driver_token.raw()).expect("driver facts");+ let context = browser_launch_context().expect("launch context");+ let BrowserLaunchContext::StandardUser(token) = context else {+ assert_eq!(browser_launch_token(&driver), BrowserLaunchToken::Driver);+ eprintln!("host token is not elevated; standard-user derivation is not exercised");+ return;+ };+ let derived = token_facts(token.raw()).expect("derived facts");+ assert_eq!(validate_standard_user_token(&driver, &derived), Ok(()));+ assert_ne!(+ derived.administrators,+ AdministratorsMembership::Enabled,+ "{derived:?}"+ );+ assert!(derived.integrity_rid <= MEDIUM_INTEGRITY_RID, "{derived:?}");++ // Impersonation reaches file access checks: the derived token cannot+ // add files to System32 even though the elevated Driver can.+ let system = system32()+ .as_os_str()+ .encode_wide()+ .chain(std::iter::once(0))+ .collect::<Vec<_>>();+ let denied = with_impersonation(&token, || unsafe {+ CreateFileW(+ PCWSTR(system.as_ptr()),+ FILE_ADD_FILE.0,+ FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE,+ None,+ OPEN_EXISTING,+ FILE_FLAG_BACKUP_SEMANTICS,+ None,+ )+ })+ .expect("impersonate the standard-user token");+ match denied {+ Ok(handle) => {+ drop(OwnedHandle(handle));+ panic!("the standard-user token must not be able to write System32");+ }+ Err(error) => assert_eq!(error.code(), E_ACCESSDENIED, "{error}"),+ }++ // The derived token cannot open the elevated Driver process to write+ // its memory or inject a thread.+ let driver_pid = unsafe { windows::Win32::System::Threading::GetCurrentProcessId() };+ let opened = with_impersonation(&token, || unsafe {+ windows::Win32::System::Threading::OpenProcess(+ windows::Win32::System::Threading::PROCESS_VM_WRITE+ | windows::Win32::System::Threading::PROCESS_CREATE_THREAD,+ false,+ driver_pid,+ )+ })+ .expect("impersonate the standard-user token");+ match opened {+ Ok(handle) => {+ drop(OwnedHandle(handle));+ panic!("the standard-user token must not be able to write the Driver process");+ }+ Err(error) => assert_eq!(error.code(), E_ACCESSDENIED, "{error}"),+ }++ // The thread is back on the Driver's token afterwards.+ let mut thread_token = HANDLE::default();+ assert!(+ unsafe { OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, true, &mut thread_token) }+ .is_err(),+ "impersonation must be reverted"+ );++ let mut command = Command::new(system32().join("PING.EXE"));+ command.args(["-n", "30", "127.0.0.1"]);+ let mut child = spawn_with_token(token.clone(), &command).expect("spawn with token");+ let child_facts = process_token_facts(child.process_handle());+ assert_eq!(+ validate_standard_user_token(&driver, &child_facts),+ Ok(()),+ "{child_facts:?}"+ );+ assert!(child.try_wait().expect("try_wait").is_none());+ child.kill().expect("terminate child");+ let status = child.wait().expect("wait child");+ assert_eq!(status.code(), Some(1));+ child.kill().expect("killing an exited child is a no-op");++ let mut command = Command::new(system32().join("cmd.exe"));+ command.args(["/d", "/c", "exit 7"]);+ let mut child = spawn_with_token(token, &command).expect("spawn with token");+ assert_eq!(child.wait().expect("wait").code(), Some(7));+ }++ #[test]+ fn standard_user_launch_refuses_unforwarded_command_state() {+ let token = Arc::new(current_process_token(TOKEN_QUERY).expect("token"));+ let mut command = Command::new(system32().join("cmd.exe"));+ command.env("CUA_TEST", "1");+ assert!(spawn_with_token(token.clone(), &command).is_err());+ let mut command = Command::new(system32().join("cmd.exe"));+ command.current_dir(system32());+ assert!(spawn_with_token(token, &command).is_err());+ }+}diff --git a/libs/cua-driver/rust/crates/platform-windows/src/lib.rs b/libs/cua-driver/rust/crates/platform-windows/src/lib.rsindex 0563c366f9..8b1d223ebb 100644--- a/libs/cua-driver/rust/crates/platform-windows/src/lib.rs+++ b/libs/cua-driver/rust/crates/platform-windows/src/lib.rs@@ -57,6 +57,14 @@ pub mod browser_platform;#[cfg(any(target_os = "windows", test))]mod browser_isolated_selection;+// Pure launch-token decision and command-line quoting for isolated browsers;+// cfg-independent so its unit tests run on any host.+#[cfg(any(target_os = "windows", test))]+mod browser_launch_token;++#[cfg(target_os = "windows")]+mod browser_standard_user;+#[cfg(target_os = "windows")]mod browser_consent_ui;#[cfg(target_os = "windows")]