Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-driver): accept verbatim and junctioned Windows browser installs (#4467)

Francesco Bonacci07f2bfce9039
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/browser_installation_path.rs b/libs/cua-driver/rust/crates/platform-windows/src/browser_installation_path.rs
new file mode 100644
index 0000000000..23d1e18923
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-windows/src/browser_installation_path.rs
@@ -0,0 +1,749 @@
+//! Path normalization and reparse-point resolution for the Windows isolated
+//! browser installation check.
+//!
+//! A trusted browser candidate such as
+//! `C:\Program Files\Google\Chrome\Application\chrome.exe` may reach its files
+//! through directory junctions or symbolic links, for example when an
+//! administrator relocates `Application` to another volume. Rejecting every
+//! redirect refuses such installs as "not installed"; following redirects
+//! without checking them would let a writable link target replace the browser.
+//!
+//! [`resolve_installation`] walks the candidate one component at a time. Each
+//! link must keep the candidate's relative layout: a link reached at
+//! `<root>\Google\Chrome\Application` must point to some
+//! `<other root>\Google\Chrome\Application`. The walk returns the final real
+//! executable and every object whose modification could change what that
+//! path opens: each link object itself, each real directory and the
+//! executable, and each new root a link moves to. The caller requires the
+//! browser launch token to be denied write access to all of them, then
+//! cross-checks the result against the operating system's own resolution.
+//!
+//! The module is pure. Filesystem access goes through [`InstallationFs`], so
+//! the unit tests run on any host.
+
+/// Upper bound on links followed for one candidate.
+pub(crate) const MAX_REPARSE_HOPS: usize = 8;
+
+/// Convert a Windows path to its plain Win32 form.
+///
+/// `\\?\C:\x` becomes `C:\x`, `\\?\UNC\server\share\x` becomes
+/// `\\server\share\x`, and the NT form `\??\C:\x` stored in junction data
+/// becomes `C:\x`. A path without a verbatim prefix is returned unchanged.
+/// Verbatim forms with no plain equivalent, such as `\\?\Volume{...}\` or
+/// `\\?\GLOBALROOT\`, return `None` so callers fail closed.
+pub(crate) fn plain_windows_path(path: &str) -> Option<String> {
+ let verbatim = path
+ .strip_prefix(r"\\?\")
+ .or_else(|| path.strip_prefix(r"\??\"));
+ let Some(rest) = verbatim else {
+ return Some(path.to_owned());
+ };
+ // Verbatim paths are passed to the filesystem without normalization, so
+ // `/` is an ordinary character there; such a path has no plain form.
+ if rest.contains('/') {
+ return None;
+ }
+ if let Some(unc) = strip_prefix_ignore_ascii_case(rest, r"UNC\") {
+ let mut parts = unc.splitn(3, '\\');
+ let server = parts.next().unwrap_or_default();
+ let share = parts.next().unwrap_or_default();
+ if server.is_empty() || share.is_empty() {
+ return None;
+ }
+ return Some(format!(r"\\{unc}"));
+ }
+ let bytes = rest.as_bytes();
+ let is_drive = bytes.len() >= 2
+ && bytes[0].is_ascii_alphabetic()
+ && bytes[1] == b':'
+ && (bytes.len() == 2 || bytes[2] == b'\\');
+ is_drive.then(|| rest.to_owned())
+}
+
+fn strip_prefix_ignore_ascii_case<'a>(value: &'a str, prefix: &str) -> Option<&'a str> {
+ let head = value.get(..prefix.len())?;
+ head.eq_ignore_ascii_case(prefix)
+ .then(|| &value[prefix.len()..])
+}
+
+/// Split an absolute local drive path into `["C:", component, ...]`.
+///
+/// Network, device, volume-GUID, relative, and drive-relative paths return
+/// `None`, as do paths with `.` or `..` components, so a redirect can never
+/// leave the local drive namespace or escape its claimed layout.
+fn drive_components(path: &str) -> Option<Vec<String>> {
+ let plain = plain_windows_path(path)?;
+ let bytes = plain.as_bytes();
+ if bytes.len() < 3
+ || !bytes[0].is_ascii_alphabetic()
+ || bytes[1] != b':'
+ || !matches!(bytes[2], b'\\' | b'/')
+ {
+ return None;
+ }
+ let mut components = vec![plain[..2].to_ascii_uppercase()];
+ let mut parts = plain[3..].split(['\\', '/']).peekable();
+ while let Some(part) = parts.next() {
+ if part.is_empty() {
+ // Only a single trailing separator is tolerated.
+ if parts.peek().is_none() {
+ break;
+ }
+ return None;
+ }
+ if part == "." || part == ".." {
+ return None;
+ }
+ components.push(part.to_owned());
+ }
+ Some(components)
+}
+
+fn join_components(components: &[String]) -> String {
+ match components {
+ [] => String::new(),
+ [drive] => format!(r"{drive}\"),
+ [drive, rest @ ..] => format!(r"{drive}\{}", rest.join(r"\")),
+ }
+}
+
+fn same_component(left: &str, right: &str) -> bool {
+ left == right || left.to_lowercase() == right.to_lowercase()
+}
+
+fn same_components(left: &[String], right: &[String]) -> bool {
+ left.len() == right.len()
+ && left
+ .iter()
+ .zip(right)
+ .all(|(left, right)| same_component(left, right))
+}
+
+/// What a path names, without following a link at its final component.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum InstallationEntry {
+ Missing,
+ File,
+ Directory,
+ /// A junction or symbolic link and its stored target.
+ Link(String),
+}
+
+/// Filesystem queries the resolution needs.
+pub(crate) trait InstallationFs {
+ /// Classify `path` without following a link at its final component.
+ fn entry(&self, path: &str) -> Result<InstallationEntry, String>;
+ /// Fully resolve `path` as the operating system would open it.
+ fn canonical(&self, path: &str) -> Result<String, String>;
+}
+
+/// One object whose write access the launch token must be denied.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct ProbeTarget {
+ pub path: String,
+ pub directory: bool,
+ /// Probe the link object itself rather than its target.
+ pub link: bool,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) struct ResolvedInstallation {
+ /// The real executable path in plain drive form.
+ pub executable: String,
+ /// Objects to probe, in walk order.
+ pub probes: Vec<ProbeTarget>,
+}
+
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub(crate) enum InstallationResolution {
+ /// The candidate does not exist.
+ Missing,
+ /// The candidate exists but cannot be proven to be a protected
+ /// installation; the reason explains why.
+ Untrusted(String),
+ Resolved(ResolvedInstallation),
+}
+
+/// Resolve `executable` below `trusted_root`, following each link only when
+/// it keeps the executable's relative layout. See the module documentation.
+pub(crate) fn resolve_installation(
+ executable: &str,
+ trusted_root: &str,
+ fs: &impl InstallationFs,
+) -> InstallationResolution {
+ use InstallationResolution::{Missing, Resolved, Untrusted};
+
+ let Some(root) = drive_components(trusted_root) else {
+ return Untrusted(format!(
+ "trusted installation root {trusted_root} is not a local drive path"
+ ));
+ };
+ let Some(candidate) = drive_components(executable) else {
+ return Untrusted(format!("{executable} is not a local drive path"));
+ };
+ if candidate.len() <= root.len() || !same_components(&candidate[..root.len()], &root) {
+ return Untrusted(format!("{executable} is outside {trusted_root}"));
+ }
+ let tail = &candidate[root.len()..];
+
+ // `base` is the real directory that currently stands in for the trusted
+ // root; the path being examined is `base` plus the first `depth` tail
+ // components.
+ let mut base = root;
+ let mut probes = Vec::new();
+ let mut hops = 0;
+ for depth in 0..=tail.len() {
+ let directory = depth < tail.len();
+ loop {
+ let mut current = base.clone();
+ current.extend_from_slice(&tail[..depth]);
+ let current_path = join_components(&current);
+ let entry = match fs.entry(&current_path) {
+ Ok(entry) => entry,
+ Err(error) => {
+ return Untrusted(format!("could not inspect {current_path}: {error}"))
+ }
+ };
+ match entry {
+ InstallationEntry::Missing => return Missing,
+ InstallationEntry::Directory if directory => {
+ probes.push(ProbeTarget {
+ path: current_path,
+ directory: true,
+ link: false,
+ });
+ break;
+ }
+ InstallationEntry::File if !directory => {
+ probes.push(ProbeTarget {
+ path: current_path,
+ directory: false,
+ link: false,
+ });
+ break;
+ }
+ // A file where a directory belongs, or a directory where the
+ // executable belongs: the candidate is not installed.
+ InstallationEntry::File | InstallationEntry::Directory => return Missing,
+ InstallationEntry::Link(target) => {
+ hops += 1;
+ if hops > MAX_REPARSE_HOPS {
+ return Untrusted(format!(
+ "{executable} passes through more than {MAX_REPARSE_HOPS} links"
+ ));
+ }
+ probes.push(ProbeTarget {
+ path: current_path.clone(),
+ directory,
+ link: true,
+ });
+ let Some(target_components) = drive_components(&target) else {
+ return Untrusted(format!(
+ "{current_path} links to {target}, which is not an absolute local \
+ drive path"
+ ));
+ };
+ let kept = &tail[..depth];
+ let split = target_components.len().saturating_sub(kept.len());
+ if split == 0 || !same_components(&target_components[split..], kept) {
+ return Untrusted(format!(
+ "{current_path} links to {target}, which does not keep the \
+ installation layout below {trusted_root}"
+ ));
+ }
+ base = target_components[..split].to_vec();
+ // The new root and the directories between it and the
+ // link target are part of the real installation chain.
+ for prefix in 0..depth {
+ let mut ancestor = base.clone();
+ ancestor.extend_from_slice(&tail[..prefix]);
+ probes.push(ProbeTarget {
+ path: join_components(&ancestor),
+ directory: true,
+ link: false,
+ });
+ }
+ // Re-examine the target itself, which may be another link.
+ }
+ }
+ }
+ }
+
+ let mut resolved = base;
+ resolved.extend_from_slice(tail);
+ let resolved_path = join_components(&resolved);
+ // The walk sees links only at the components it visits. A link anywhere
+ // else (above the trusted root or above a link's new root) would make the
+ // operating system open a different file, so require both views to agree.
+ match fs.canonical(executable).map(|path| drive_components(&path)) {
+ Ok(Some(canonical)) if same_components(&canonical, &resolved) => {
+ Resolved(ResolvedInstallation {
+ executable: resolved_path,
+ probes,
+ })
+ }
+ Ok(_) => Untrusted(format!(
+ "{executable} resolves somewhere other than {resolved_path}"
+ )),
+ Err(error) => Untrusted(format!("could not resolve {executable}: {error}")),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::collections::HashMap;
+
+ #[test]
+ fn plain_windows_path_strips_verbatim_prefixes() {
+ assert_eq!(
+ plain_windows_path(r"\\?\C:\Program Files\Google\Chrome\Application\chrome.exe")
+ .as_deref(),
+ Some(r"C:\Program Files\Google\Chrome\Application\chrome.exe")
+ );
+ assert_eq!(
+ plain_windows_path(r"\\?\UNC\server\share\Chrome\chrome.exe").as_deref(),
+ Some(r"\\server\share\Chrome\chrome.exe")
+ );
+ assert_eq!(
+ plain_windows_path(r"\\?\unc\server\share").as_deref(),
+ Some(r"\\server\share")
+ );
+ assert_eq!(
+ plain_windows_path(r"\??\E:\Program Files\Google").as_deref(),
+ Some(r"E:\Program Files\Google")
+ );
+ assert_eq!(plain_windows_path(r"\\?\D:").as_deref(), Some(r"D:"));
+ assert_eq!(
+ plain_windows_path(r"C:\Program Files").as_deref(),
+ Some(r"C:\Program Files")
+ );
+ }
+
+ #[test]
+ fn plain_windows_path_refuses_verbatim_forms_without_a_plain_equivalent() {
+ for path in [
+ r"\\?\Volume{0b1f7c33-5a3c-4c1e-9d7a-3f1d2a6b8c11}\Program Files",
+ r"\\?\GLOBALROOT\Device\HarddiskVolume3\Program Files",
+ r"\\?\UNC\server",
+ r"\\?\UNC\\share",
+ r"\\?\C:/Program Files",
+ r"\\?\CC:\x",
+ ] {
+ assert_eq!(plain_windows_path(path), None, "{path}");
+ }
+ }
+
+ #[test]
+ fn drive_components_accepts_only_absolute_local_drive_paths() {
+ assert_eq!(
+ drive_components(r"\\?\c:\Program Files\"),
+ Some(vec!["C:".to_owned(), "Program Files".to_owned()])
+ );
+ assert_eq!(
+ drive_components(r"E:/Program Files/Google"),
+ Some(vec![
+ "E:".to_owned(),
+ "Program Files".to_owned(),
+ "Google".to_owned()
+ ])
+ );
+ for path in [
+ r"\\server\share\Program Files",
+ r"\\?\UNC\server\share\Program Files",
+ r"Program Files\Google",
+ r"C:Program Files",
+ r"C:\Program Files\..\Users",
+ r"C:\Program Files\.\Google",
+ r"C:\Program Files\\Google",
+ r"\\.\C:\Program Files",
+ ] {
+ assert_eq!(drive_components(path), None, "{path}");
+ }
+ }
+
+ /// In-memory filesystem: lowercase path -> entry. `canonical` follows the
+ /// links the same way the operating system does, at every component.
+ #[derive(Default)]
+ struct FakeFs {
+ entries: HashMap<String, InstallationEntry>,
+ }
+
+ impl FakeFs {
+ fn dir(mut self, path: &str) -> Self {
+ self.entries
+ .insert(path.to_lowercase(), InstallationEntry::Directory);
+ self
+ }
+ fn file(mut self, path: &str) -> Self {
+ self.entries
+ .insert(path.to_lowercase(), InstallationEntry::File);
+ self
+ }
+ fn link(mut self, path: &str, target: &str) -> Self {
+ self.entries.insert(
+ path.to_lowercase(),
+ InstallationEntry::Link(target.to_owned()),
+ );
+ self
+ }
+ /// Directories for `path` and each of its ancestors.
+ fn tree(mut self, path: &str) -> Self {
+ let components = drive_components(path).unwrap();
+ for end in 1..=components.len() {
+ self = self.dir(&join_components(&components[..end]));
+ }
+ self
+ }
+ }
+
+ impl InstallationFs for FakeFs {
+ fn entry(&self, path: &str) -> Result<InstallationEntry, String> {
+ // Resolve links in the parent, as a real lookup would.
+ let components = drive_components(path).ok_or("bad path")?;
+ if components.len() > 1 {
+ let parent = join_components(&components[..components.len() - 1]);
+ let parent = plain_windows_path(&self.canonical(&parent)?).ok_or("bad parent")?;
+ let real = format!(
+ r"{}\{}",
+ parent.trim_end_matches('\\'),
+ components.last().unwrap()
+ );
+ if real.to_lowercase() != path.to_lowercase() {
+ return self.entry(&real);
+ }
+ }
+ Ok(self
+ .entries
+ .get(&path.to_lowercase())
+ .cloned()
+ .unwrap_or(InstallationEntry::Missing))
+ }
+
+ fn canonical(&self, path: &str) -> Result<String, String> {
+ self.resolve(path, 0)
+ .map(|resolved| format!(r"\\?\{resolved}"))
+ }
+ }
+
+ impl FakeFs {
+ /// Follow links at every component, including inside link targets.
+ fn resolve(&self, path: &str, depth: usize) -> Result<String, String> {
+ if depth > 32 {
+ return Err("link loop".to_owned());
+ }
+ let components = drive_components(path).ok_or("bad path")?;
+ let mut resolved = vec![components[0].clone()];
+ for component in &components[1..] {
+ resolved.push(component.clone());
+ if let Some(InstallationEntry::Link(target)) =
+ self.entries.get(&join_components(&resolved).to_lowercase())
+ {
+ let target = self.resolve(target, depth + 1)?;
+ resolved = drive_components(&target).ok_or("bad target")?;
+ }
+ }
+ Ok(join_components(&resolved))
+ }
+ }
+
+ const ROOT: &str = r"C:\Program Files";
+ const CHROME: &str = r"C:\Program Files\Google\Chrome\Application\chrome.exe";
+
+ fn resolved(resolution: InstallationResolution) -> ResolvedInstallation {
+ match resolution {
+ InstallationResolution::Resolved(resolved) => resolved,
+ other => panic!("expected a resolved installation, got {other:?}"),
+ }
+ }
+
+ fn untrusted_reason(resolution: InstallationResolution) -> String {
+ match resolution {
+ InstallationResolution::Untrusted(reason) => reason,
+ other => panic!("expected an untrusted installation, got {other:?}"),
+ }
+ }
+
+ fn probe(path: &str, directory: bool, link: bool) -> ProbeTarget {
+ ProbeTarget {
+ path: path.to_owned(),
+ directory,
+ link,
+ }
+ }
+
+ #[test]
+ fn plain_installation_probes_the_executable_and_each_directory_up_to_the_root() {
+ let fs = FakeFs::default()
+ .tree(r"C:\Program Files\Google\Chrome\Application")
+ .file(CHROME);
+ let resolved = resolved(resolve_installation(CHROME, ROOT, &fs));
+ assert_eq!(resolved.executable, CHROME);
+ assert_eq!(
+ resolved.probes,
+ vec![
+ probe(r"C:\Program Files", true, false),
+ probe(r"C:\Program Files\Google", true, false),
+ probe(r"C:\Program Files\Google\Chrome", true, false),
+ probe(r"C:\Program Files\Google\Chrome\Application", true, false),
+ probe(CHROME, false, false),
+ ]
+ );
+ }
+
+ #[test]
+ fn verbatim_paths_resolve_to_plain_drive_paths() {
+ let fs = FakeFs::default()
+ .tree(r"C:\Program Files\Google\Chrome\Application")
+ .file(CHROME);
+ let resolved = resolved(resolve_installation(
+ &format!(r"\\?\{CHROME}"),
+ &format!(r"\\?\{ROOT}"),
+ &fs,
+ ));
+ assert_eq!(resolved.executable, CHROME);
+ assert!(resolved
+ .probes
+ .iter()
+ .all(|probe| !probe.path.starts_with(r"\\")));
+ }
+
+ #[test]
+ fn in_tree_junction_resolves_to_the_relocated_installation() {
+ let fs = FakeFs::default()
+ .tree(r"C:\Program Files\Google\Chrome")
+ .link(
+ r"C:\Program Files\Google\Chrome\Application",
+ r"\\?\E:\Program Files\Google\Chrome\Application",
+ )
+ .tree(r"E:\Program Files\Google\Chrome\Application")
+ .file(r"E:\Program Files\Google\Chrome\Application\chrome.exe");
+ let resolved = resolved(resolve_installation(CHROME, ROOT, &fs));
+ assert_eq!(
+ resolved.executable,
+ r"E:\Program Files\Google\Chrome\Application\chrome.exe"
+ );
+ assert_eq!(
+ resolved.probes,
+ vec![
+ probe(r"C:\Program Files", true, false),
+ probe(r"C:\Program Files\Google", true, false),
+ probe(r"C:\Program Files\Google\Chrome", true, false),
+ // The junction object itself, then the real chain it reaches.
+ probe(r"C:\Program Files\Google\Chrome\Application", true, true),
+ probe(r"E:\Program Files", true, false),
+ probe(r"E:\Program Files\Google", true, false),
+ probe(r"E:\Program Files\Google\Chrome", true, false),
+ probe(r"E:\Program Files\Google\Chrome\Application", true, false),
+ probe(
+ r"E:\Program Files\Google\Chrome\Application\chrome.exe",
+ false,
+ false
+ ),
+ ]
+ );
+ }
+
+ #[test]
+ fn every_link_in_a_chain_and_each_new_root_are_probed() {
+ let fs = FakeFs::default()
+ .tree(r"C:\Program Files\Google")
+ .link(
+ r"C:\Program Files\Google\Chrome",
+ r"\??\E:\Apps\Google\Chrome",
+ )
+ .tree(r"E:\Apps\Google")
+ .link(r"E:\Apps\Google\Chrome", r"F:\Program Files\Google\Chrome")
+ .tree(r"F:\Program Files\Google\Chrome\Application")
+ .link(
+ r"F:\Program Files\Google\Chrome\Application\chrome.exe",
+ r"G:\Program Files\Google\Chrome\Application\chrome.exe",
+ )
+ .tree(r"G:\Program Files\Google\Chrome\Application")
+ .file(r"G:\Program Files\Google\Chrome\Application\chrome.exe");
+ let resolved = resolved(resolve_installation(CHROME, ROOT, &fs));
+ assert_eq!(
+ resolved.executable,
+ r"G:\Program Files\Google\Chrome\Application\chrome.exe"
+ );
+ let links: Vec<_> = resolved
+ .probes
+ .iter()
+ .filter(|probe| probe.link)
+ .map(|probe| probe.path.as_str())
+ .collect();
+ assert_eq!(
+ links,
+ [
+ r"C:\Program Files\Google\Chrome",
+ r"E:\Apps\Google\Chrome",
+ r"F:\Program Files\Google\Chrome\Application\chrome.exe",
+ ]
+ );
+ for directory in [
+ r"E:\Apps",
+ r"E:\Apps\Google",
+ r"F:\Program Files",
+ r"F:\Program Files\Google",
+ r"G:\Program Files\Google\Chrome\Application",
+ ] {
+ assert!(
+ resolved.probes.contains(&probe(directory, true, false)),
+ "{directory} must be probed: {:?}",
+ resolved.probes
+ );
+ }
+ // The file link is probed as a file object.
+ assert!(resolved.probes.contains(&probe(
+ r"F:\Program Files\Google\Chrome\Application\chrome.exe",
+ false,
+ true
+ )));
+ }
+
+ #[test]
+ fn junctioned_trusted_root_resolves_with_its_target_probed() {
+ let fs = FakeFs::default()
+ .tree(r"C:\")
+ .link(r"C:\Program Files", r"\??\E:\Program Files")
+ .tree(r"E:\Program Files\Google\Chrome\Application")
+ .file(r"E:\Program Files\Google\Chrome\Application\chrome.exe");
+ let resolved = resolved(resolve_installation(CHROME, ROOT, &fs));
+ assert_eq!(resolved.probes[0], probe(r"C:\Program Files", true, true));
+ assert_eq!(resolved.probes[1], probe(r"E:\Program Files", true, false));
+ }
+
+ #[test]
+ fn link_that_changes_the_installation_layout_is_untrusted() {
+ let fs = FakeFs::default()
+ .tree(r"C:\Program Files\Google\Chrome")
+ .link(
+ r"C:\Program Files\Google\Chrome\Application",
+ r"\??\C:\Users\Public\Downloads",
+ )
+ .tree(r"C:\Users\Public\Downloads")
+ .file(r"C:\Users\Public\Downloads\chrome.exe");
+ let reason = untrusted_reason(resolve_installation(CHROME, ROOT, &fs));
+ assert!(
+ reason.contains("does not keep the installation layout"),
+ "{reason}"
+ );
+
+ // The file name itself must be kept too.
+ let fs = FakeFs::default()
+ .tree(r"C:\Program Files\Google\Chrome\Application")
+ .link(
+ CHROME,
+ r"C:\Program Files\Google\Chrome\Application\other.exe",
+ )
+ .file(r"C:\Program Files\Google\Chrome\Application\other.exe");
+ untrusted_reason(resolve_installation(CHROME, ROOT, &fs));
+ }
+
+ #[test]
+ fn link_to_a_drive_root_keeps_the_writable_root_in_the_probe_set() {
+ let fs = FakeFs::default()
+ .tree(r"C:\Program Files")
+ .link(r"C:\Program Files\Google", r"\??\D:\Google")
+ .tree(r"D:\Google\Chrome\Application")
+ .file(r"D:\Google\Chrome\Application\chrome.exe");
+ let resolved = resolved(resolve_installation(CHROME, ROOT, &fs));
+ assert!(resolved.probes.contains(&probe(r"D:\", true, false)));
+ }
+
+ #[test]
+ fn link_to_a_network_volume_or_relative_target_is_untrusted() {
+ for target in [
+ r"\\?\UNC\server\share\Google\Chrome\Application",
+ r"\\server\share\Google\Chrome\Application",
+ r"\??\Volume{0b1f7c33-5a3c-4c1e-9d7a-3f1d2a6b8c11}\Google\Chrome\Application",
+ r"..\..\..\Elsewhere\Google\Chrome\Application",
+ r"Google\Chrome\Application",
+ ] {
+ let fs = FakeFs::default()
+ .tree(r"C:\Program Files\Google\Chrome")
+ .link(r"C:\Program Files\Google\Chrome\Application", target);
+ let reason = untrusted_reason(resolve_installation(CHROME, ROOT, &fs));
+ assert!(
+ reason.contains("not an absolute local drive path"),
+ "{target}: {reason}"
+ );
+ }
+ }
+
+ #[test]
+ fn link_loops_are_bounded() {
+ let fs = FakeFs::default()
+ .tree(r"C:\Program Files\Google\Chrome")
+ .link(
+ r"C:\Program Files\Google\Chrome\Application",
+ r"D:\Program Files\Google\Chrome\Application",
+ )
+ .tree(r"D:\Program Files\Google\Chrome")
+ .link(
+ r"D:\Program Files\Google\Chrome\Application",
+ r"C:\Program Files\Google\Chrome\Application",
+ );
+ let reason = untrusted_reason(resolve_installation(CHROME, ROOT, &fs));
+ assert!(reason.contains("more than"), "{reason}");
+ }
+
+ #[test]
+ fn unseen_link_above_a_root_is_caught_by_the_canonical_cross_check() {
+ // `E:\Program Files` is itself a junction. The walk only visits the
+ // components below the new root, so the operating system's
+ // resolution must veto the result.
+ let fs = FakeFs::default()
+ .tree(r"C:\Program Files\Google\Chrome")
+ .link(
+ r"C:\Program Files\Google\Chrome\Application",
+ r"E:\Program Files\Google\Chrome\Application",
+ )
+ .tree(r"E:\")
+ .link(r"E:\Program Files", r"F:\Writable")
+ .tree(r"F:\Writable\Google\Chrome\Application")
+ .file(r"F:\Writable\Google\Chrome\Application\chrome.exe");
+ let reason = untrusted_reason(resolve_installation(CHROME, ROOT, &fs));
+ assert!(reason.contains("resolves somewhere other than"), "{reason}");
+ }
+
+ #[test]
+ fn candidate_outside_the_trusted_root_is_untrusted_and_absent_one_is_missing() {
+ let fs = FakeFs::default()
+ .tree(r"D:\UserControlled")
+ .file(r"D:\UserControlled\chrome.exe");
+ untrusted_reason(resolve_installation(
+ r"D:\UserControlled\chrome.exe",
+ ROOT,
+ &fs,
+ ));
+ untrusted_reason(resolve_installation(ROOT, ROOT, &fs));
+
+ let fs = FakeFs::default().tree(r"C:\Program Files\Google");
+ assert_eq!(
+ resolve_installation(CHROME, ROOT, &fs),
+ InstallationResolution::Missing
+ );
+ let fs = FakeFs::default()
+ .tree(r"C:\Program Files\Google\Chrome\Application")
+ .tree(CHROME);
+ assert_eq!(
+ resolve_installation(CHROME, ROOT, &fs),
+ InstallationResolution::Missing
+ );
+ }
+
+ #[test]
+ fn inspection_errors_fail_closed() {
+ struct Failing;
+ impl InstallationFs for Failing {
+ fn entry(&self, _: &str) -> Result<InstallationEntry, String> {
+ Err("access denied".to_owned())
+ }
+ fn canonical(&self, _: &str) -> Result<String, String> {
+ Err("access denied".to_owned())
+ }
+ }
+ untrusted_reason(resolve_installation(CHROME, ROOT, &Failing));
+ }
+}
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.rs
index 7dc284b7d1..a7d70f29fd 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,10 +11,9 @@ use std::time::Duration;
use async_trait::async_trait;
use cua_driver_core::browser::platform::{
- select_isolated_browser_executable, BrowserConsentOutcome, BrowserConsentRequest,
- BrowserPlatform, BrowserVisualAction, BrowserVisualActionKind, ExistingProfileSetupOutcome,
- ExistingProfileSetupRequest, IsolatedBrowserProcess, PrepareAction, PrepareOutcome,
- PrepareRequest,
+ BrowserConsentOutcome, BrowserConsentRequest, BrowserPlatform, BrowserVisualAction,
+ BrowserVisualActionKind, ExistingProfileSetupOutcome, ExistingProfileSetupRequest,
+ IsolatedBrowserProcess, PrepareAction, PrepareOutcome, PrepareRequest,
};
use cua_driver_core::browser::refusal::{BrowserRefusal, BrowserRefusalCode};
use cua_driver_core::browser::types::{
@@ -27,6 +26,10 @@ use cua_driver_core::browser::{
};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
+use crate::browser_installation_path::{
+ plain_windows_path, resolve_installation, InstallationEntry, InstallationFs,
+ InstallationResolution,
+};
use crate::browser_isolated_selection::{
decide_isolated_browser, InstallationWriteAccess, IsolatedBrowserDecision,
IsolatedCandidateFacts, NO_PROTECTED_BROWSER_MESSAGE,
@@ -46,9 +49,9 @@ use windows::Win32::NetworkManagement::IpHelper::{
use windows::Win32::Networking::WinSock::{AF_INET, AF_INET6};
use windows::Win32::Storage::FileSystem::{
CreateFileW, DELETE, FILE_ADD_FILE, FILE_ADD_SUBDIRECTORY, FILE_APPEND_DATA, FILE_DELETE_CHILD,
- FILE_FLAGS_AND_ATTRIBUTES, FILE_FLAG_BACKUP_SEMANTICS, FILE_SHARE_DELETE, FILE_SHARE_READ,
- FILE_SHARE_WRITE, FILE_WRITE_ATTRIBUTES, FILE_WRITE_DATA, FILE_WRITE_EA, OPEN_EXISTING,
- WRITE_DAC, WRITE_OWNER,
+ FILE_FLAGS_AND_ATTRIBUTES, FILE_FLAG_BACKUP_SEMANTICS, FILE_FLAG_OPEN_REPARSE_POINT,
+ FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE, FILE_WRITE_ATTRIBUTES, FILE_WRITE_DATA,
+ FILE_WRITE_EA, OPEN_EXISTING, WRITE_DAC, WRITE_OWNER,
};
use windows::Win32::System::Com::CoTaskMemFree;
use windows::Win32::System::SystemInformation::GetSystemDirectoryW;
@@ -364,6 +367,18 @@ fn has_trusted_authenticode_identity(
}
fn authenticode_output(executable: &std::path::Path) -> std::io::Result<std::process::Output> {
+ // Some Windows PowerShell 5.1 builds cannot resolve a `\\?\` verbatim
+ // path through `-LiteralPath` ("A drive named '\?\C' does not exist"),
+ // which would make every candidate look unsigned. Pass the plain path.
+ let executable = executable
+ .to_str()
+ .and_then(plain_windows_path)
+ .ok_or_else(|| {
+ std::io::Error::other(format!(
+ "browser executable {} has no plain Win32 path",
+ executable.display()
+ ))
+ })?;
let Ok(system32) = system_directory_path() else {
return Err(std::io::Error::other(
"could not resolve the Windows system directory",
@@ -381,7 +396,7 @@ fn authenticode_output(executable: &std::path::Path) -> std::io::Result<std::pro
// The static command imports Security beside the trusted System32
// PowerShell, ignoring an incompatible inherited PSModulePath. Pass the
// browser path as data so PowerShell never parses it as command text.
- .env("CUA_BROWSER_ATTEST_PATH", executable)
+ .env("CUA_BROWSER_ATTEST_PATH", &executable)
.stdin(Stdio::null())
.output()
}
@@ -395,14 +410,17 @@ enum WriteProbe {
}
fn current_token_write_denial_reason(path: &std::path::Path, directory: bool) -> Option<String> {
- match current_token_write_probe(path, directory) {
+ match current_token_write_probe(path, directory, false) {
WriteProbe::Denied => None,
WriteProbe::Granted(name) => Some(format!("current token was granted {name}")),
WriteProbe::Failed(reason) => Some(reason),
}
}
-fn current_token_write_probe(path: &std::path::Path, directory: bool) -> WriteProbe {
+/// Probe `path` for write-class rights. With `link`, the junction or symbolic
+/// link object itself is opened rather than its target, because rewriting or
+/// replacing a link redirects every path through it.
+fn current_token_write_probe(path: &std::path::Path, directory: bool, link: bool) -> WriteProbe {
use std::os::windows::ffi::OsStrExt;
// This launch boundary keeps the token that runs the browser (the
@@ -439,11 +457,14 @@ fn current_token_write_probe(path: &std::path::Path, directory: bool) -> WritePr
("write_owner", WRITE_OWNER.0),
]
};
- let flags = if directory {
+ let mut flags = if directory {
FILE_FLAG_BACKUP_SEMANTICS
} else {
FILE_FLAGS_AND_ATTRIBUTES(0)
};
+ if link {
+ flags |= FILE_FLAG_OPEN_REPARSE_POINT;
+ }
for &(name, right) in rights {
match unsafe {
CreateFileW(
@@ -469,31 +490,141 @@ fn current_token_write_probe(path: &std::path::Path, directory: bool) -> WritePr
WriteProbe::Denied
}
+/// Outcome of resolving and probing one isolated-launch candidate.
+#[derive(Debug, PartialEq, Eq)]
+struct CandidateInstallation {
+ installed: bool,
+ /// The real executable in plain drive form, when it resolved.
+ executable: Option<String>,
+ write_access: InstallationWriteAccess,
+ /// Why the candidate is not `Protected`, for the refusal detail.
+ reason: Option<String>,
+}
+
+/// The real filesystem, as seen by the calling thread's effective token.
+struct WindowsInstallationFs;
+
+impl InstallationFs for WindowsInstallationFs {
+ fn entry(&self, path: &str) -> Result<InstallationEntry, String> {
+ match std::fs::symlink_metadata(path) {
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
+ Ok(InstallationEntry::Missing)
+ }
+ Err(error) => Err(error.to_string()),
+ // std reports name-surrogate reparse points (junctions and
+ // symbolic links) as symlinks.
+ Ok(metadata) if metadata.file_type().is_symlink() => std::fs::read_link(path)
+ .map(|target| InstallationEntry::Link(target.to_string_lossy().into_owned()))
+ .map_err(|error| format!("could not read link target: {error}")),
+ Ok(metadata) if metadata.is_dir() => Ok(InstallationEntry::Directory),
+ Ok(_) => Ok(InstallationEntry::File),
+ }
+ }
+
+ fn canonical(&self, path: &str) -> Result<String, String> {
+ std::fs::canonicalize(path)
+ .map(|path| path.to_string_lossy().into_owned())
+ .map_err(|error| error.to_string())
+ }
+}
+
+/// Resolve the candidate below `trusted_root`, following junctions and
+/// symbolic links only when they keep the installation layout, and require
+/// every object on the resolved chain (each link object, each real directory
+/// up to each root, and the executable) to deny write access to the calling
+/// thread's token. The first non-denied probe decides the rejection kind: a
+/// granted right is `WritableByLaunchToken`, a failed probe is `Untrusted`
+/// (fail closed).
+fn windows_installation_write_access_with(
+ executable: &std::path::Path,
+ trusted_root: &std::path::Path,
+ fs: &impl InstallationFs,
+ mut probe: impl FnMut(&std::path::Path, bool, bool) -> WriteProbe,
+) -> CandidateInstallation {
+ let untrusted = |reason: String| CandidateInstallation {
+ installed: true,
+ executable: None,
+ write_access: InstallationWriteAccess::Untrusted,
+ reason: Some(reason),
+ };
+ let (Some(executable_text), Some(root_text)) = (executable.to_str(), trusted_root.to_str())
+ else {
+ return untrusted("installation path is not valid Unicode".to_owned());
+ };
+ let resolved = match resolve_installation(executable_text, root_text, fs) {
+ InstallationResolution::Missing => {
+ return CandidateInstallation {
+ installed: false,
+ executable: None,
+ write_access: InstallationWriteAccess::Untrusted,
+ reason: None,
+ }
+ }
+ InstallationResolution::Untrusted(reason) => return untrusted(reason),
+ InstallationResolution::Resolved(resolved) => resolved,
+ };
+ let mut write_access = InstallationWriteAccess::Protected;
+ let mut reason = None;
+ for target in &resolved.probes {
+ let path = std::path::Path::new(&target.path);
+ match probe(path, target.directory, target.link) {
+ WriteProbe::Denied => continue,
+ WriteProbe::Granted(right) => {
+ write_access = InstallationWriteAccess::WritableByLaunchToken;
+ reason = Some(format!(
+ "launch token was granted {right} on {}",
+ target.path
+ ));
+ }
+ WriteProbe::Failed(error) => {
+ write_access = InstallationWriteAccess::Untrusted;
+ reason = Some(format!("{}: {error}", target.path));
+ }
+ }
+ break;
+ }
+ CandidateInstallation {
+ installed: true,
+ executable: Some(resolved.executable),
+ write_access,
+ reason,
+ }
+}
+
fn windows_installation_write_access(
executable: &std::path::Path,
trusted_root: &std::path::Path,
-) -> InstallationWriteAccess {
- windows_installation_write_access_with_probe(
+) -> CandidateInstallation {
+ windows_installation_write_access_with(
executable,
trusted_root,
+ &WindowsInstallationFs,
current_token_write_probe,
)
}
-/// 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).
+/// Resolve and probe the installation for the token that will run the
+/// browser. For a standard-user launch the whole check 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 {
+) -> CandidateInstallation {
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),
+ .unwrap_or_else(|error| CandidateInstallation {
+ installed: true,
+ executable: None,
+ write_access: InstallationWriteAccess::Untrusted,
+ reason: Some(format!(
+ "could not impersonate the standard-user launch token: {error}"
+ )),
+ }),
}
}
@@ -502,58 +633,10 @@ fn trusted_windows_installation(
executable: &std::path::Path,
trusted_root: &std::path::Path,
) -> bool {
- windows_installation_write_access(executable, trusted_root)
+ windows_installation_write_access(executable, trusted_root).write_access
== InstallationWriteAccess::Protected
}
-#[cfg(test)]
-fn trusted_windows_installation_with_probe(
- executable: &std::path::Path,
- trusted_root: &std::path::Path,
- mut cannot_write: impl FnMut(&std::path::Path, bool) -> bool,
-) -> bool {
- windows_installation_write_access_with_probe(executable, trusted_root, |path, directory| {
- if cannot_write(path, directory) {
- WriteProbe::Denied
- } else {
- WriteProbe::Granted("test_write")
- }
- }) == InstallationWriteAccess::Protected
-}
-
-/// 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 `WritableByLaunchToken`, a failed probe
-/// is `Untrusted` (fail closed).
-fn windows_installation_write_access_with_probe(
- executable: &std::path::Path,
- trusted_root: &std::path::Path,
- mut probe: impl FnMut(&std::path::Path, bool) -> WriteProbe,
-) -> InstallationWriteAccess {
- let rejection = |result: WriteProbe| match result {
- WriteProbe::Denied => None,
- WriteProbe::Granted(_) => Some(InstallationWriteAccess::WritableByLaunchToken),
- WriteProbe::Failed(_) => Some(InstallationWriteAccess::Untrusted),
- };
- if !executable.starts_with(trusted_root) {
- return InstallationWriteAccess::Untrusted;
- }
- if let Some(rejected) = rejection(probe(executable, false)) {
- return rejected;
- }
- let mut current = executable.parent();
- while let Some(directory) = current {
- if let Some(rejected) = rejection(probe(directory, true)) {
- return rejected;
- }
- if directory == trusted_root {
- return InstallationWriteAccess::Protected;
- }
- current = directory.parent();
- }
- InstallationWriteAccess::Untrusted
-}
-
fn isolated_browser_product_name(executable: &std::path::Path) -> &'static str {
match browser_product(&executable.to_string_lossy()) {
BrowserProduct::MicrosoftEdge => "Edge",
@@ -1665,15 +1748,35 @@ impl BrowserPlatform for WindowsBrowserPlatform {
let context = browser_launch_context()?;
let mut facts = Vec::new();
let mut executables = Vec::new();
+ let mut diagnostics = Vec::new();
for (candidate, trusted_root, expected_cn, expected_org) in isolated_browser_candidates()? {
let product = isolated_browser_product_name(&candidate);
- let Ok(executable) = select_isolated_browser_executable([candidate.clone()]) else {
- facts.push(IsolatedCandidateFacts::missing(product));
+ // Resolves junctions and symbolic links that keep the installation
+ // layout and probes every object on the resolved chain, so the
+ // executable is the real file in plain drive form.
+ let installation =
+ launch_token_installation_write_access(&context, &candidate, &trusted_root);
+ let Some(executable) = installation.executable.filter(|_| installation.installed)
+ else {
+ diagnostics.push(serde_json::json!({
+ "candidate": candidate.display().to_string(),
+ "installed": installation.installed,
+ "reason": installation.reason,
+ }));
+ facts.push(if installation.installed {
+ IsolatedCandidateFacts {
+ product,
+ installed: true,
+ write_access: InstallationWriteAccess::Untrusted,
+ vendor_signed: false,
+ }
+ } else {
+ IsolatedCandidateFacts::missing(product)
+ });
executables.push(None);
continue;
};
- let write_access =
- launch_token_installation_write_access(&context, &candidate, &trusted_root);
+ let write_access = installation.write_access;
// 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
@@ -1682,6 +1785,13 @@ impl BrowserPlatform for WindowsBrowserPlatform {
expected_cn,
expected_org,
);
+ diagnostics.push(serde_json::json!({
+ "candidate": candidate.display().to_string(),
+ "installed": true,
+ "resolved": executable,
+ "vendor_signed": vendor_signed,
+ "reason": installation.reason,
+ }));
let fact = IsolatedCandidateFacts {
product,
installed: true,
@@ -1705,7 +1815,8 @@ impl BrowserPlatform for WindowsBrowserPlatform {
IsolatedBrowserDecision::Refuse(message) => Err(refusal(
BrowserRefusalCode::BrowserRouteUnavailable,
message,
- )),
+ )
+ .with_detail(serde_json::json!({ "candidates": diagnostics }))),
}
}
@@ -2581,72 +2692,108 @@ mod tests {
assert!(!trusted_windows_installation(&executable, root.path()));
}
- #[test]
- fn installation_trust_walk_requires_every_probe_to_deny_write() {
- let root = std::path::Path::new(r"C:\Program Files");
- let executable = root.join(r"Google\Chrome\Application\chrome.exe");
+ /// A link-free installation tree: `.exe` paths are files, the rest are
+ /// directories, and every path is already canonical.
+ struct PlainTreeFs;
- assert!(trusted_windows_installation_with_probe(
- &executable,
- root,
- |_, _| true,
- ));
- assert!(!trusted_windows_installation_with_probe(
- &executable,
- root,
- |path, directory| !(directory && path.ends_with(r"Google\Chrome")),
- ));
- assert!(!trusted_windows_installation_with_probe(
- &executable,
- root,
- |path, directory| !(directory && path == root),
- ));
- assert!(!trusted_windows_installation_with_probe(
- &std::path::PathBuf::from(r"D:\UserControlled\chrome.exe"),
+ impl InstallationFs for PlainTreeFs {
+ fn entry(&self, path: &str) -> Result<InstallationEntry, String> {
+ Ok(if path.ends_with(".exe") {
+ InstallationEntry::File
+ } else {
+ InstallationEntry::Directory
+ })
+ }
+ fn canonical(&self, path: &str) -> Result<String, String> {
+ Ok(format!(r"\\?\{path}"))
+ }
+ }
+
+ /// A tree whose `Application` directory is a junction to `target`.
+ struct JunctionedTreeFs {
+ target: &'static str,
+ }
+
+ impl InstallationFs for JunctionedTreeFs {
+ fn entry(&self, path: &str) -> Result<InstallationEntry, String> {
+ if path.eq_ignore_ascii_case(r"C:\Program Files\Google\Chrome\Application") {
+ return Ok(InstallationEntry::Link(format!(r"\\?\{}", self.target)));
+ }
+ PlainTreeFs.entry(path)
+ }
+ fn canonical(&self, path: &str) -> Result<String, String> {
+ let relocated = path.replacen(
+ r"C:\Program Files\Google\Chrome\Application",
+ self.target,
+ 1,
+ );
+ Ok(format!(r"\\?\{relocated}"))
+ }
+ }
+
+ fn write_access_with_probe(
+ fs: &impl InstallationFs,
+ probe: impl FnMut(&std::path::Path, bool, bool) -> WriteProbe,
+ ) -> CandidateInstallation {
+ let root = std::path::Path::new(r"C:\Program Files");
+ windows_installation_write_access_with(
+ &root.join(r"Google\Chrome\Application\chrome.exe"),
root,
- |_, _| true,
- ));
+ fs,
+ probe,
+ )
}
#[test]
- fn installation_write_access_distinguishes_granted_from_failed_probes() {
+ fn installation_trust_walk_requires_every_probe_to_deny_write() {
let root = std::path::Path::new(r"C:\Program Files");
- let executable = root.join(r"Google\Chrome\Application\chrome.exe");
-
+ let protected = write_access_with_probe(&PlainTreeFs, |_, _, _| WriteProbe::Denied);
+ assert_eq!(protected.write_access, InstallationWriteAccess::Protected);
assert_eq!(
- windows_installation_write_access_with_probe(&executable, root, |_, _| {
- WriteProbe::Denied
- }),
- InstallationWriteAccess::Protected
+ protected.executable.as_deref(),
+ Some(r"C:\Program Files\Google\Chrome\Application\chrome.exe")
);
- assert_eq!(
- windows_installation_write_access_with_probe(&executable, root, |path, directory| {
- if directory && path == root {
+ for writable in [r"C:\Program Files\Google\Chrome", r"C:\Program Files"] {
+ let result = write_access_with_probe(&PlainTreeFs, |path, directory, _| {
+ if directory && path == std::path::Path::new(writable) {
WriteProbe::Granted("add_file")
} else {
WriteProbe::Denied
}
- }),
- InstallationWriteAccess::WritableByLaunchToken
- );
- assert_eq!(
- windows_installation_write_access_with_probe(&executable, root, |_, directory| {
- if directory {
- WriteProbe::Denied
- } else {
- WriteProbe::Failed("write_data probe failed closed".to_owned())
- }
- }),
- InstallationWriteAccess::Untrusted
- );
- assert_eq!(
- windows_installation_write_access_with_probe(
- std::path::Path::new(r"D:\UserControlled\chrome.exe"),
- root,
- |_, _| WriteProbe::Denied,
- ),
- InstallationWriteAccess::Untrusted
+ });
+ assert_eq!(
+ result.write_access,
+ InstallationWriteAccess::WritableByLaunchToken,
+ "{writable}"
+ );
+ }
+ let outside = windows_installation_write_access_with(
+ std::path::Path::new(r"D:\UserControlled\chrome.exe"),
+ root,
+ &PlainTreeFs,
+ |_, _, _| WriteProbe::Denied,
);
+ assert!(outside.installed);
+ assert_eq!(outside.executable, None);
+ assert_eq!(outside.write_access, InstallationWriteAccess::Untrusted);
+ }
+
+ #[test]
+ fn installation_write_access_distinguishes_granted_from_failed_probes() {
+ let root = std::path::Path::new(r"C:\Program Files");
+ let executable = root.join(r"Google\Chrome\Application\chrome.exe");
+ let failed = write_access_with_probe(&PlainTreeFs, |_, directory, _| {
+ if directory {
+ WriteProbe::Denied
+ } else {
+ WriteProbe::Failed("write_data probe failed closed".to_owned())
+ }
+ });
+ assert_eq!(failed.write_access, InstallationWriteAccess::Untrusted);
+ assert!(failed
+ .reason
+ .as_deref()
+ .is_some_and(|reason| reason.contains("write_data probe failed closed")));
assert_eq!(isolated_browser_product_name(&executable), "Chrome");
assert_eq!(
isolated_browser_product_name(&root.join(r"Microsoft\Edge\Application\msedge.exe")),
@@ -2654,6 +2801,61 @@ mod tests {
);
}
+ #[test]
+ fn junctioned_installation_is_accepted_only_when_the_whole_chain_is_protected() {
+ let fs = JunctionedTreeFs {
+ target: r"E:\Program Files\Google\Chrome\Application",
+ };
+ let mut probed = Vec::new();
+ let protected = write_access_with_probe(&fs, |path, directory, link| {
+ probed.push((path.to_path_buf(), directory, link));
+ WriteProbe::Denied
+ });
+ assert_eq!(protected.write_access, InstallationWriteAccess::Protected);
+ assert_eq!(
+ protected.executable.as_deref(),
+ Some(r"E:\Program Files\Google\Chrome\Application\chrome.exe")
+ );
+ assert!(probed.contains(&(
+ PathBuf::from(r"C:\Program Files\Google\Chrome\Application"),
+ true,
+ true
+ )));
+
+ // The junction itself, each real directory, and the real root must
+ // all deny write access.
+ for writable in [
+ r"C:\Program Files\Google\Chrome\Application",
+ r"E:\Program Files",
+ r"E:\Program Files\Google\Chrome\Application",
+ r"E:\Program Files\Google\Chrome\Application\chrome.exe",
+ ] {
+ let result = write_access_with_probe(&fs, |path, _, _| {
+ if path == std::path::Path::new(writable) {
+ WriteProbe::Granted("write_dac")
+ } else {
+ WriteProbe::Denied
+ }
+ });
+ assert_eq!(
+ result.write_access,
+ InstallationWriteAccess::WritableByLaunchToken,
+ "{writable}"
+ );
+ assert!(result.reason.unwrap().contains(writable));
+ }
+
+ // A junction that leaves the installation layout is never followed.
+ let escaped = write_access_with_probe(
+ &JunctionedTreeFs {
+ target: r"C:\Users\Public\Chrome",
+ },
+ |_, _, _| WriteProbe::Denied,
+ );
+ assert_eq!(escaped.write_access, InstallationWriteAccess::Untrusted);
+ assert_eq!(escaped.executable, None);
+ }
+
#[test]
fn installed_vendor_browser_tree_is_accepted_only_for_a_nonwritable_token() {
let candidates = isolated_browser_candidates().expect("trusted Known Folder roots");
@@ -2697,7 +2899,8 @@ mod tests {
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),
+ launch_token_installation_write_access(&context, &installed.0, &installed.1)
+ .write_access,
InstallationWriteAccess::Protected,
"the standard-user launch token must not be able to modify {}",
installed.0.display()
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/lib.rs b/libs/cua-driver/rust/crates/platform-windows/src/lib.rs
index 87b9d9d036..b38d1633df 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/lib.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/lib.rs
@@ -84,6 +84,12 @@ pub mod browser_platform;
#[cfg(any(target_os = "windows", test))]
mod browser_isolated_selection;
+// Pure path normalization and reparse-point resolution for the isolated
+// browser installation check; cfg-independent so its unit tests run on any
+// host.
+#[cfg(any(target_os = "windows", test))]
+mod browser_installation_path;
+
// 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))]