diff --git a/crates/engine/src/automation/file_access.rs b/crates/engine/src/automation/file_access.rs index 249d3483c..934c62ad9 100644 --- a/crates/engine/src/automation/file_access.rs +++ b/crates/engine/src/automation/file_access.rs @@ -127,6 +127,10 @@ const MAX_LINKS: u8 = 40; /// on the share of one of `roots` goes on to the usual check. A path that can't be made absolute /// is refused as well, rather than left to what comes next. fn refused_unresolved(path: &Path, roots: &[PathBuf]) -> Option { + // Win32 lookups trim a trailing period or space from a name, but not always from one in the middle of a path: refused as given. + if has_trimmed_name(path) { + return Some(Unresolved::Linked); + } // Made absolute without looking at the disk (on Windows `GetFullPathNameW`, which also turns a // bare device name such as `NUL` into `\\.\NUL`, as opening it would). Like opening, it takes // `..` by name, so `link\..\x` is `x` and never goes through the link. @@ -180,6 +184,10 @@ fn nothing_there(e: &std::io::Error) -> bool { /// the way is opened in turn while the path is resolved, and the device behind a name such as /// `LPT1` can be a printer on another computer. fn refused_spelling(p: &str, roots: &[PathBuf]) -> Option { + // A native NT name (`\Device\Mup\server\share`) has no prefix for `std` or `craft_docpath`, yet the system follows it to wherever it names. + if is_native_name(Path::new(p)) { + return Some(Refused::Device); + } match craft_docpath::resolve(p, None) { // With a root passed as the document path (what a link would be relative to), a path on // that root's share is allowed. @@ -199,7 +207,11 @@ fn is_volume(p: &str) -> bool { let (Some(""), Some(""), Some("?" | "."), Some(volume)) = (names.next(), names.next(), names.next(), names.next()) else { return false; }; - volume.get(..7).is_some_and(|v| v.eq_ignore_ascii_case("Volume{")) && volume.ends_with('}') + let bytes = volume.as_bytes(); + bytes.len() == 44 + && volume.get(..7).is_some_and(|v| v.eq_ignore_ascii_case("Volume{")) + && volume.ends_with('}') + && bytes[7..43].iter().enumerate().all(|(i, b)| if matches!(i, 8 | 13 | 18 | 23) { *b == b'-' } else { b.is_ascii_hexdigit() }) } /// Whether a link on the way to `abs` (an absolute path) leads to a path [`refused_spelling`] @@ -224,6 +236,11 @@ fn link_refused(abs: &Path, roots: &[PathBuf], links: u8, look: &dyn Fn(&Path) - Entry::Link(target) => target, }; let (Some(links), Some(target)) = (links.checked_sub(1), target) else { return true }; + // Judged as written too: joined onto the link's folder, a rooted target such as `\Device\Mup\x` would keep that folder's drive, + // and Win32 trims a trailing period or space that the kernel follows as it is. + if refused_spelling(&target.to_string_lossy(), roots).is_some() || is_rooted_without_drive(&target) || has_trimmed_name(&target) { + return true; + } // A relative target is relative to the link's folder; an absolute one replaces it. let next = lexical(&at.parent().unwrap_or(&at).join(target).join(rest.as_path())); return refused_spelling(&next.to_string_lossy(), roots).is_some() || link_refused(&next, roots, links, look); @@ -231,6 +248,26 @@ fn link_refused(abs: &Path, roots: &[PathBuf], links: u8, look: &dyn Fn(&Path) - false } +/// Whether `path` is a native NT name (`\Device\…`, `\DosDevices\…`, `\GLOBAL??\…`, `\??\…`, `\Sessions\…`, `\GLOBALROOT\…`), which a link +/// may hold: no prefix for `std`, yet the system follows it to wherever it names. +fn is_native_name(path: &Path) -> bool { + let bytes = path.as_os_str().as_encoded_bytes(); + [&br"\Device\"[..], &br"\DosDevices\"[..], &br"\GLOBAL??\"[..], &br"\??\"[..], &br"\Sessions\"[..], &br"\GLOBALROOT\"[..]].iter().any(|p| { + bytes.get(..p.len() - 1).is_some_and(|b| b.eq_ignore_ascii_case(&p[..p.len() - 1])) && matches!(bytes.get(p.len() - 1), None | Some(b'\\')) + }) +} + +/// Whether a link's target starts with one separator and no drive (`\RPC Control\x`, `\BaseNamedObjects\x`, `\work`): `std` sees no +/// prefix in it, yet the system reads it in its own object namespace or on the link's drive, and may follow it to wherever it names. +fn is_rooted_without_drive(path: &Path) -> bool { + matches!(path.as_os_str().as_encoded_bytes(), [b'\\', rest @ ..] if rest.first() != Some(&b'\\')) +} + +/// Whether any plain name in `path` ends in a period or a space, which Win32 path handling trims before it looks the name up. +fn has_trimmed_name(path: &Path) -> bool { + path.components().any(|c| matches!(c, Component::Normal(n) if n.as_encoded_bytes().last().is_some_and(|b| matches!(b, b'.' | b' ')))) +} + /// `p` with its `.` and `..` taken by name, as Windows takes them. fn lexical(p: &Path) -> PathBuf { let mut out = PathBuf::new(); @@ -273,9 +310,24 @@ pub(crate) fn within_app_folder(path: &Path, folder: &Path) -> bool { matches!((std::fs::canonicalize(path), std::fs::canonicalize(folder)), (Ok(p), Ok(f)) if p.starts_with(&f)) } +/// Whether `a` and `b` are the same file. Comparing opens both, so while roots confine this thread a +/// path that resolving would not be allowed to open (on another computer, or a device: see +/// [`refused_unresolved`]) is never opened. Whether it is the same file can't then be told, and the +/// callers guard against overwriting a file through another name for it, so it counts as the same: +/// the guard keeps asking (a path like that can't be written anyway). A local path outside the +/// roots is compared. pub fn same_file(a: impl AsRef, b: impl AsRef) -> bool { let (a, b) = (a.as_ref(), b.as_ref()); - a == b || same_file::is_same_file(a, b).unwrap_or(false) + if a == b { + return true; + } + if let Some(scope) = current() { + let roots = [scope.read.as_slice(), scope.write.as_slice()].concat(); + if cfg!(windows) && [a, b].into_iter().any(|p| refused_unresolved(p, &roots).is_some()) { + return true; + } + } + same_file::is_same_file(a, b).unwrap_or(false) } /// `p` without Windows' `\\?\` prefix, for messages. diff --git a/crates/engine/src/automation/file_access/tests.rs b/crates/engine/src/automation/file_access/tests.rs index d642befb1..57dd48c6f 100644 --- a/crates/engine/src/automation/file_access/tests.rs +++ b/crates/engine/src/automation/file_access/tests.rs @@ -229,6 +229,8 @@ fn spellings_of_other_computers_and_devices_are_refused() { r"C:\work\LPT³\x.png", r"C:\work\conout$", r"C:\work\aux:stream", + // A volume name that is not a GUID could be an alias of anything. + r"\\?\Volume{remote}\x.png", // After a name `craft_docpath` refuses for another reason. r"C:\work\a:b\prn.png", ]; @@ -402,6 +404,34 @@ fn a_parent_after_a_link_is_taken_by_name() { assert_eq!(std::fs::read(&through).unwrap(), b"in", "Windows opens the file in the root"); } +/// Comparing two files opens both, so a path the roots don't allow is not compared: it is not the +/// same file as one inside, even when it is another name for it (a hard link outside the roots). +#[test] +fn same_file_does_not_open_a_path_outside_the_roots() { + let f = Fixture::new("same-file"); + let inside = f.p("root/in.txt"); + let outside = f.p("outside/linked.txt"); + if std::fs::hard_link(&inside, &outside).is_err() { + eprintln!("skipped: hard links can't be made here"); + return; + } + assert!(super::same_file(&inside, &outside), "unconfined, another name for a file is the same file"); + let roots = Arc::new(f.rw()); + confined(Some(&roots), || { + assert!(super::same_file(&inside, &outside), "a local path outside the roots is compared, and a hard link to a file inside is that file"); + if cfg!(windows) { + assert!( + super::same_file(&inside, r"\\192.0.2.1\share\x"), + "a path on another computer is never opened, and counts as the same so that the guard keeps asking" + ); + } + assert!(super::same_file(&inside, &inside), "a path is the same file as itself"); + let other = f.p("root/sub/other.txt"); + std::fs::write(&other, b"other").unwrap(); + assert!(!super::same_file(&inside, &other), "two files inside are compared, and differ"); + }); +} + /// A path on another computer and a device path are refused before anything is opened: resolving /// them made Windows contact the server, which may send it the signed-in user's credentials /// (#1094). Each is refused with a message that only the check before resolving gives: had the @@ -468,6 +498,59 @@ fn links_to_other_computers_are_refused_before_they_are_followed() { assert!(r.check(Path::new(&f.p("root/alias/x.png")), Access::Write).is_ok()); } +/// A native NT name is told with or without the separator after its first name: a link to `\Device` alone, with the +/// rest of the path after it, reaches `\Device\Mup\...`. +#[test] +fn native_names_are_told_with_or_without_the_closing_separator() { + for p in + [r"\Device", r"\Device\Mup\203.0.113.5\s", r"\device\mup", r"\DosDevices", r"\GLOBAL??", r"\??", r"\??\UNC\x\y", r"\Sessions", r"\GLOBALROOT"] + { + assert!(super::is_native_name(Path::new(p)), "{p}"); + } + for p in [r"\Devices", r"\Devicex\y", r"Device", r"\work\Device", r"\\server\share", r"\"] { + assert!(!super::is_native_name(Path::new(p)), "{p}"); + } +} + +/// A link target that starts with one separator and no drive names a root the system reads in its own object namespace or on the +/// link's drive, whichever directory it names. +#[test] +fn rooted_link_targets_without_a_drive_are_refused() { + for p in [r"\Device\Mup\203.0.113.5\s", r"\RPC Control\remote", r"\BaseNamedObjects\x", r"\??\UNC\x\y", r"\work", r"\"] { + assert!(super::is_rooted_without_drive(Path::new(p)), "{p}"); + } + for p in [r"Device", r"work\x", r"C:\x", r"\\server\share", r"\\?\C:\x", ""] { + assert!(!super::is_rooted_without_drive(Path::new(p)), "{p}"); + } +} + +/// A link whose text is a native NT name (`\Device\Mup\server\share`) or ends in a period, and a path with a name that ends in a +/// space, are refused as written: joined onto the link's folder the first would keep that folder's drive, and Windows trims the +/// others where it looks a name up but not where the kernel follows a link. +#[test] +#[cfg(windows)] +fn native_names_and_names_windows_trims_are_refused_as_written() { + let f = Fixture::new("native-trimmed"); + let r = f.rw(); + if !symlink_dir(Path::new(r"\Device\Mup\192.0.2.1\share"), &f.0.join("root/native")) + || !symlink_dir(Path::new("remote."), &f.0.join("root/trimmed")) + { + eprintln!("skipped: this system doesn't let tests make symbolic links"); + return; + } + let standard = |p: &str| format!("automation path rejected: {p} is outside the folders that may be"); + // However the system stores the native name, the link is refused. + let native = f.p("root/native/x.png"); + assert!(r.check(Path::new(&native), Access::Read).is_err(), "{native}"); + let p = f.p("root/trimmed/x.png"); + let e = r.check(Path::new(&p), Access::Read).expect_err(&p); + assert!(e.starts_with(&standard(&p)), "{p}: {e}"); + let p = f.p("root/remote /x.png"); + let e = r.check(Path::new(&p), Access::Write).expect_err(&p); + assert!(e.starts_with(&standard(&p)), "{p}: {e}"); + assert_eq!(super::refused_spelling(r"\??\UNC\192.0.2.1\share\x", &[]), Some(craft_docpath::Refused::Device)); +} + #[test] fn a_scope_confines_the_thread_and_ends_with_it() { let f = Fixture::new("scope"); diff --git a/docs/mcp.md b/docs/mcp.md index 9b44a0c55..700d1d48a 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -94,8 +94,14 @@ Each may be given more than once, as `--flag DIR` or `--flag=DIR`: (writing through it would create its target, wherever that is). A path outside the roots gets the same refusal whatever exists there, so a refusal doesn't tell what is outside. Folders are compared by whole names: `/work2/x` is not inside `/work`. On Windows the case comes from the disk (`C:\WORK\x` is - inside `C:\work`), `\\?\` and UNC (`\\server\share\…`) paths are resolved like drive-letter ones, - and new names that are devices (`CON`, `NUL`, `COM1`…) or streams (`a.png:x`) are refused. + inside `C:\work`), `\\?\C:\…` paths are resolved like drive-letter ones, and + new names that are devices (`CON`, `NUL`, `COM1`…) or streams (`a.png:x`) are refused. + A path on another computer (`\\server\share\…`, `\\?\UNC\…`, WebDAV's `\\host@SSL\share\…`) or a device + path (`\\.\pipe\…`, `\\?\GLOBALROOT\…`) is refused by its spelling before anything looks it up, since looking + it up would contact that host, unless a root is on the same share; a link whose target is one of those is + refused too. A local volume's `\\?\Volume{…}\` path is let through. A link whose text is a native NT name + (`\Device\…`, `\??\…`, `\GLOBAL??\…`) is refused as a device path, and so is a name that ends in a period or a space, in a + path or as a link's target, since Windows trims it where it looks a name up. - **The network:** a confined call reaches no FigCraft or plugin server, so it can't send a document anywhere through one. Hosting, joining, publishing and sharing a file (`collab.host`, `collab.join`, `collab.publish`, `collab.share` …), team libraries on a server (`library.check`