diff --git a/crates/cloud-local/README.md b/crates/cloud-local/README.md new file mode 100644 index 000000000..d8f7cb3a7 --- /dev/null +++ b/crates/cloud-local/README.md @@ -0,0 +1,21 @@ +# craft-cloud-local + +A reference `CloudBackend` over one folder on disk, proving that `craft-cloud`'s contract needs +no specific provider behind it. + +## No-escape policy + +Every path this crate is handed, a `Job::List`/`Read`/`Write` path or a `Job::Create` name, is +confined to the configured root before anything touches a filesystem. + +A path's segments, and a `Create` name on its own, are accepted only when each one parses as a +single `Component::Normal`: no `..`, no `.`, no empty segment, no absolute form, and no Windows +drive letter, UNC path or backslash. That last group is refused on every platform this crate +builds for, not only on Windows, because a name reaches this backend from whatever platform the +UI runs on. + +Once a candidate path is built from nothing but checked names, it is still confirmed against a +symlink or (on Windows) a directory junction placed somewhere under the root: the nearest +ancestor that already exists is canonicalised and must stay under the canonicalised root. A path +that reaches outside the root this way is refused before any read, write, listing or creation +touches it. diff --git a/crates/cloud-local/src/lib.rs b/crates/cloud-local/src/lib.rs index c974a295e..c0caf5d45 100644 --- a/crates/cloud-local/src/lib.rs +++ b/crates/cloud-local/src/lib.rs @@ -23,7 +23,7 @@ use std::fs; use std::io::Write as _; -use std::path::{Path, PathBuf}; +use std::path::{Component, Path, PathBuf}; use craft_cloud::{Capability, Entry, EntryKind}; use craft_ui::cloud::{Account, CloudBackend, Event, Fault, Job, Post}; @@ -33,8 +33,16 @@ use craft_ui::cloud::{Account, CloudBackend, Event, Fault, Job, Post}; /// `Entry::id` and `Entry::path` are the same slash-separated path relative to /// `root`, always starting with `/` below the root itself (the root's own /// path is the empty string, matching [`Job::List`]'s contract). Neither is -/// an OS path; both go through [`resolve`] before anything touches a -/// filesystem, so a name containing `..` can never walk out of `root`. +/// an OS path; both go through [`resolve`] and then [`confine_to_root`] +/// before anything touches a filesystem. A [`Job::Create`] name is not a +/// path at all; it goes through the same per-segment check [`resolve`] uses, +/// [`confine_segment`], on its own. Together the two refuse `..`, an +/// absolute form, a Windows drive letter or UNC prefix, and a backslash, +/// regardless of which platform this crate is built for, since a name +/// reaches this backend from whatever platform the UI runs on. No-escape +/// through a symlink or a Windows junction is a separate policy, stated on +/// [`confine_to_root`] itself, and every one of [`list`], [`read`], +/// [`write`] and [`create`] applies it. pub struct LocalBackend { root: PathBuf, /// Shown in the account badge. Nothing else reads it. @@ -111,25 +119,81 @@ fn account(display: String) -> Account { } /// Turns a [`Job`]'s slash-separated path into a real filesystem path under -/// `root`, refusing anything that would walk back out of it. +/// `root`, refusing anything that is not a run of ordinary names. /// -/// `..` is the only way out, so `..` is the only segment refused. `.` and -/// repeated or leading slashes are just an empty segment and are skipped, -/// the same way a browser's address bar collapses them. +/// `.` and repeated or leading slashes are just an empty segment and are +/// skipped, the same way a browser's address bar collapses them. Every other +/// segment goes through [`confine_segment`], which is what actually refuses +/// `..`, an absolute form, a backslash or a drive letter, or anything else +/// that is not one ordinary name. This function never touches disk, so it +/// cannot see a symlink or a junction; [`confine_to_root`] is the other half +/// of the promise, and every caller of `resolve` runs both. fn resolve(root: &Path, path: &str) -> Result { let mut real = root.to_path_buf(); for segment in path.split('/') { if segment.is_empty() || segment == "." { continue; } - if segment == ".." { - return Err(Fault::Refused(format!("{path} reaches outside this folder"))); - } - real.push(segment); + real.push(confine_segment(segment)?); } Ok(real) } +/// Confines one path segment, or a whole [`Job::Create`] name, to a single +/// ordinary file or folder name. +/// +/// Accepted only when `segment` parses as exactly one [`Component::Normal`] +/// equal to `segment` itself: no empty name, no `.` or `..`, no absolute +/// form, and nothing left over for a second component to hide in. A +/// `std::path::Component` parse alone does not catch every one of those on +/// every platform; a Unix build's parser does not know what `C:` or +/// `\\server\share` mean, so it would wave a Windows drive letter or a UNC +/// prefix straight through as one ordinary name. A `:` or a `\` is refused +/// outright first, on every platform, for exactly that reason: a name +/// reaches this backend's public [`CloudBackend::submit`] from whatever +/// platform the UI happens to run on, and a Windows-shaped escape must not +/// slip past a Linux build's narrower native parser, or the reverse. +fn confine_segment(segment: &str) -> Result<&str, Fault> { + if segment.contains('\\') || segment.contains(':') { + return Err(Fault::Refused(format!("{segment} is not a plain file name"))); + } + let mut components = Path::new(segment).components(); + match (components.next(), components.next()) { + (Some(Component::Normal(name)), None) if name == std::ffi::OsStr::new(segment) => Ok(segment), + _ => Err(Fault::Refused(format!("{segment} is not a plain file name"))), + } +} + +/// Confirms a path already built from nothing but [`confine_segment`]-checked +/// names still cannot have reached outside `root` through a symlink or, on +/// Windows, a directory junction. +/// +/// The no-escape policy: `candidate` need not exist yet, since [`write`] and +/// [`create`] both route a path that may still be about to be created +/// through here. Starting at `candidate` and walking up through its +/// ancestors, the first one that does exist is canonicalised and compared +/// against the canonicalised `root`. Nothing below that ancestor exists +/// either, so a link cannot sit on any of the remaining components, and +/// every one of them is already known to be ordinary `Component::Normal` +/// text, never `..` or an absolute form, because [`confine_segment`] is what +/// built them. A canonical path that lands outside `root` is refused; +/// nothing here ever opens, reads or writes through it. +fn confine_to_root(root: &Path, candidate: &Path) -> Result { + let real_root = fs::canonicalize(root).map_err(|error| io_fault(&error))?; + let mut probe = candidate; + loop { + match fs::canonicalize(probe) { + Ok(real) if real == real_root || real.starts_with(&real_root) => return Ok(candidate.to_path_buf()), + Ok(_) => return Err(Fault::Refused("that path leaves this folder".to_owned())), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => match probe.parent() { + Some(parent) => probe = parent, + None => return Err(io_fault(&error)), + }, + Err(error) => return Err(io_fault(&error)), + } + } +} + /// The path a listed child gets, given the folder it was found in. fn child_path(folder: &str, name: &str) -> String { format!("{}/{name}", folder.trim_end_matches('/')) @@ -155,7 +219,7 @@ fn io_fault(error: &std::io::Error) -> Fault { } fn list(root: &Path, path: &str) -> Result, Fault> { - let dir = resolve(root, path)?; + let dir = confine_to_root(root, &resolve(root, path)?)?; let read = fs::read_dir(&dir).map_err(|error| io_fault(&error))?; let mut entries = Vec::new(); for item in read { @@ -189,7 +253,7 @@ fn list(root: &Path, path: &str) -> Result, Fault> { /// carry the old etag into the reloaded document, so the very next save would /// conflict again on a copy that is actually current. fn read(root: &Path, entry: &Entry) -> Result<(Entry, Vec), Fault> { - let file = resolve(root, &entry.id)?; + let file = confine_to_root(root, &resolve(root, &entry.id)?)?; let bytes = fs::read(&file).map_err(|error| io_fault(&error))?; let meta = fs::metadata(&file).map_err(|error| io_fault(&error))?; let fresh = Entry { size: Some(meta.len()), etag: Some(etag_of(&meta)), ..entry.clone() }; @@ -200,7 +264,7 @@ fn read(root: &Path, entry: &Entry) -> Result<(Entry, Vec), Fault> { /// `entry.etag` was read. A file that no longer exists has nothing to /// conflict with, the same way a provider treats a deleted document. fn write(root: &Path, entry: &Entry, bytes: &[u8]) -> Result { - let file = resolve(root, &entry.id)?; + let file = confine_to_root(root, &resolve(root, &entry.id)?)?; if let Ok(meta) = fs::metadata(&file) && Some(etag_of(&meta)) != entry.etag { @@ -215,7 +279,11 @@ fn write(root: &Path, entry: &Entry, bytes: &[u8]) -> Result { } fn create(root: &Path, folder: &str, name: &str, bytes: &[u8]) -> Result { - let dir = resolve(root, folder)?; + // `name` is never a path: it is one [`Job::Create`] field that names the + // new file, so it goes through `confine_segment` directly rather than + // through `resolve`, which only ever splits and confines a slash path. + let name = confine_segment(name)?; + let dir = confine_to_root(root, &resolve(root, folder)?)?; fs::create_dir_all(&dir).map_err(|error| io_fault(&error))?; let file = dir.join(name); // Exclusive creation, not an `exists` check ahead of a separate write: two @@ -267,6 +335,51 @@ mod tests { assert_eq!(resolve(&root, "").unwrap(), root); } + #[test] + fn confine_segment_accepts_only_a_single_ordinary_name() { + for ordinary in ["Minutes.txt", "Archive", "2026", "a name with spaces.docx"] { + assert!(confine_segment(ordinary).is_ok(), "{ordinary} is an ordinary name"); + } + } + + #[test] + fn confine_segment_refuses_empty_dot_and_dot_dot() { + for bad in ["", ".", ".."] { + assert!(confine_segment(bad).is_err(), "{bad:?} is not a single ordinary name"); + } + } + + #[test] + fn confine_segment_refuses_a_slash_hidden_inside_a_create_name() { + assert!(confine_segment("folder/evil").is_err()); + assert!(confine_segment("../outside.txt").is_err()); + assert!(confine_segment("/outside.txt").is_err()); + } + + #[test] + fn confine_segment_refuses_windows_separators_and_prefixes_on_every_platform() { + for bad in ["..\\outside.txt", "C:\\x", "C:evil", "\\\\server\\share\\x"] { + assert!(confine_segment(bad).is_err(), "{bad:?} must be refused on every platform, not only on Windows"); + } + } + + #[test] + fn confine_to_root_accepts_a_path_that_does_not_exist_yet_under_an_existing_root() { + let root = tempfile::tempdir().unwrap(); + let candidate = root.path().join("not-written-yet.txt"); + assert!(confine_to_root(root.path(), &candidate).is_ok()); + } + + #[test] + fn confine_to_root_refuses_a_candidate_that_canonicalises_outside_root() { + let root = tempfile::tempdir().unwrap(); + let elsewhere = tempfile::tempdir().unwrap(); + // Built from a path that never went through `confine_segment` (this + // helper is tested on its own merits), standing in for whatever a + // symlink or junction would otherwise have redirected into `root`. + assert!(confine_to_root(root.path(), elsewhere.path()).is_err()); + } + #[test] fn a_folder_announces_no_capability_this_backend_cannot_honour() { let reported = account("Local disk".to_owned()).capabilities; diff --git a/crates/cloud-local/tests/confinement_regressions.rs b/crates/cloud-local/tests/confinement_regressions.rs new file mode 100644 index 000000000..d4bebd038 --- /dev/null +++ b/crates/cloud-local/tests/confinement_regressions.rs @@ -0,0 +1,289 @@ +//! The P1 from FredApps' re-review of #160: `resolve` only split on `/` and rejected a segment +//! equal to `..`; it did not constrain a Windows backslash, a drive letter or UNC prefix, or a +//! filesystem link, and `create` joined `name` onto the resolved folder with no validation of +//! `name` at all. Driven through `craft_ui::cloud`'s public functions the way an application +//! does, with a sentinel file and directory kept as a sibling of the configured root: every test +//! here must leave both untouched and unread. + +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; + +use craft_cloud::{Entry, EntryKind}; +use craft_cloud_local::LocalBackend; +use craft_ui::cloud::{self, CloudApp, CloudFiles, Destination, DocumentKind, Job}; + +const NOTE: DocumentKind = DocumentKind { extensions: &["txt"], mimes: &["text/plain"], noun: "note", default_extension: "txt" }; + +/// A document the harness was told to open: its name and its bytes. +type OpenedDocs = Arc)>>>; + +struct Harness { + cloud: CloudFiles, + share: craft_ui::share::ShareDialog, + presence: craft_ui::presence::PresenceBar, + opened: OpenedDocs, + said: Arc>>, +} + +impl Harness { + fn new() -> Harness { + Harness { + cloud: CloudFiles::new(), + share: craft_ui::share::ShareDialog::new(), + presence: craft_ui::presence::PresenceBar::new(), + opened: Arc::new(Mutex::new(Vec::new())), + said: Arc::new(Mutex::new(Vec::new())), + } + } +} + +impl CloudApp for Harness { + fn cloud(&self) -> &CloudFiles { + &self.cloud + } + fn cloud_mut(&mut self) -> &mut CloudFiles { + &mut self.cloud + } + fn kind(&self) -> DocumentKind { + NOTE + } + fn active(&self) -> Option { + None + } + fn title(&self, _uid: u64) -> String { + String::new() + } + fn open_bytes(&mut self, name: &str, bytes: Vec) -> Result, String> { + self.opened.lock().unwrap().push((name.to_owned(), bytes)); + Ok(Some(1)) + } + fn encode(&mut self, _uid: u64, _into: Destination<'_>) -> Result, String> { + Ok(Vec::new()) + } + fn close(&mut self, _uid: u64) {} + fn sharing(&mut self) -> &mut craft_ui::share::ShareDialog { + &mut self.share + } + fn presence(&mut self) -> &mut craft_ui::presence::PresenceBar { + &mut self.presence + } + fn paint_icon(&self, _painter: &egui::Painter, _rect: egui::Rect, _kind: EntryKind, _colour: egui::Color32) {} + fn open_url(&self, _url: &str) {} + fn say(&mut self, text: String) { + self.said.lock().unwrap().push(text); + } + fn app_name(&self) -> &str { + "Harness" + } +} + +fn wired(root: PathBuf) -> (Harness, egui::Context) { + let mut app = Harness::new(); + app.cloud.connect(LocalBackend::new(root)); + (app, egui::Context::default()) +} + +/// Drains whatever the backend's worker threads have sent so far, until `done` says the state +/// the test is waiting for arrived or five seconds pass. Five seconds is far more than a thread +/// doing local file IO ever needs; it only guards against a real bug leaving the test to hang. +fn settle(app: &mut Harness, ctx: &egui::Context, mut done: impl FnMut(&Harness) -> bool) { + let start = Instant::now(); + loop { + ctx.begin_pass(Default::default()); + cloud::pump(app, ctx); + ctx.end_pass().textures_delta.clear(); + if done(app) { + return; + } + assert!(start.elapsed() < Duration::from_secs(5), "timed out waiting for the backend's worker thread"); + std::thread::sleep(Duration::from_millis(5)); + } +} + +fn said(app: &mut Harness, ctx: &egui::Context) -> Vec { + settle(app, ctx, |app| !app.said.lock().unwrap().is_empty()); + app.said.lock().unwrap().clone() +} + +/// A tempdir holding the cloud root, plus a sentinel file and a sentinel directory that sit +/// beside it rather than inside it. Every test below must leave both exactly as they start. +struct Sentinels { + // Kept only so the tempdir outlives every test that borrows the paths below; nothing reads + // it back once the paths it was built from are in hand. + _arena: tempfile::TempDir, + root: PathBuf, + sentinel_file: PathBuf, + sentinel_dir: PathBuf, +} + +fn sentinels() -> Sentinels { + let arena = tempfile::tempdir().unwrap(); + let root = arena.path().join("root"); + std::fs::create_dir(&root).unwrap(); + let sentinel_file = arena.path().join("sentinel.txt"); + std::fs::write(&sentinel_file, b"a sibling file this backend must never read or write").unwrap(); + let sentinel_dir = arena.path().join("sentinel-dir"); + std::fs::create_dir(&sentinel_dir).unwrap(); + std::fs::write(sentinel_dir.join("secret.txt"), b"a sibling directory this backend must never list").unwrap(); + Sentinels { _arena: arena, root, sentinel_file, sentinel_dir } +} + +fn assert_sentinels_untouched(sentinels: &Sentinels) { + assert_eq!( + std::fs::read(&sentinels.sentinel_file).unwrap(), + b"a sibling file this backend must never read or write", + "the sentinel file outside the root was changed" + ); + assert_eq!( + std::fs::read(sentinels.sentinel_dir.join("secret.txt")).unwrap(), + b"a sibling directory this backend must never list", + "the sentinel directory's file outside the root was changed" + ); +} + +/// Every one of these is a [`Job::Create`] `name` that must be refused before any byte reaches +/// disk: the review's own examples (a parent segment, an absolute path, and the three +/// Windows-shaped forms), none of which a Unix build's native parser alone would catch, and a +/// name that already is nothing but a Windows separator or drive prefix on top of that. +fn malicious_create_names() -> Vec<&'static str> { + vec!["../sentinel.txt", "/sentinel.txt", "..\\sentinel.txt", "C:\\x", "C:evil", "\\\\server\\share\\x"] +} + +#[test] +fn create_refuses_every_escaping_name_and_the_sentinels_stay_untouched() { + for name in malicious_create_names() { + let sentinels = sentinels(); + let (mut app, ctx) = wired(sentinels.root.clone()); + + cloud::submit(&app, Job::Create { uid: 1, folder: String::new(), name: name.to_owned(), bytes: b"pwned".to_vec() }); + let messages = said(&mut app, &ctx); + + assert!(cloud::origin(&app).is_none(), "{name:?} must not be reported as created"); + assert!(!messages.is_empty(), "{name:?} must be refused, not silently dropped"); + assert_sentinels_untouched(&sentinels); + } +} + +/// A folder path for `Job::List` can carry the same Windows-shaped escape a `Create` name can; +/// `resolve` must refuse it through the identical [`confine_segment`] check, not a weaker one. +#[test] +fn listing_a_windows_shaped_folder_path_is_refused_on_every_platform() { + let sentinels = sentinels(); + let (mut app, ctx) = wired(sentinels.root.clone()); + + cloud::browse(&mut app, "..\\sentinel-dir"); + settle(&mut app, &ctx, |app| app.cloud().mine.loaded); + + assert!(app.cloud().mine.error.is_some(), "a backslash-separated folder path must be refused"); + assert!(app.cloud().mine.entries.is_empty()); + assert_sentinels_untouched(&sentinels); +} + +// ------------------------------------------------------------------- link-based escapes +// +// `escape(&sentinels)` places one link named `escape` inside the cloud root, pointing out to +// `sentinels.sentinel_dir`: a symlink on Unix, a directory junction on Windows, which needs no +// elevated privilege, unlike a Windows symlink. The Linux gate runs the symlink half of every +// test below; CI's windows-latest lanes run the junction half. Either way `root/escape/secret.txt` +// is the same sentinel file reached through the link. + +/// Nothing to clean up on Unix: `tempfile`'s own recursive removal of the arena directory +/// removes a plain symlink entry without following it. This exists only so `escape` returns the +/// same shape of RAII handle on every platform, rather than a bare `()` some lint would flag. +#[cfg(unix)] +struct Linked; + +#[cfg(unix)] +fn escape(sentinels: &Sentinels) -> Linked { + std::os::unix::fs::symlink(&sentinels.sentinel_dir, sentinels.root.join("escape")).unwrap(); + Linked +} + +/// A directory junction, removed on drop before the tempdir it sits beside is cleaned up. +#[cfg(windows)] +struct Junction(PathBuf); + +#[cfg(windows)] +impl Drop for Junction { + fn drop(&mut self) { + let _ = std::fs::remove_dir(&self.0); + } +} + +#[cfg(windows)] +fn escape(sentinels: &Sentinels) -> Junction { + use std::os::windows::process::CommandExt as _; + let link = sentinels.root.join("escape"); + let target = &sentinels.sentinel_dir; + assert!(link.is_absolute() && target.is_absolute()); + let output = std::process::Command::new("cmd") + .args(["/C", "mklink", "/J"]) + .arg(&link) + .arg(target) + .creation_flags(0x0800_0000) // CREATE_NO_WINDOW + .output() + .unwrap(); + assert!(output.status.success(), "{}", String::from_utf8_lossy(&output.stderr)); + Junction(link) +} + +#[cfg(any(unix, windows))] +fn leaked_entry() -> Entry { + Entry { + id: "/escape/secret.txt".to_owned(), + room: "local:/escape/secret.txt".to_owned(), + name: "secret.txt".to_owned(), + path: "/escape/secret.txt".to_owned(), + kind: EntryKind::File, + size: None, + modified: None, + mime: None, + etag: None, + writable: true, + shared_by: None, + } +} + +#[cfg(any(unix, windows))] +#[test] +fn listing_a_linked_folder_cannot_see_outside_the_root() { + let sentinels = sentinels(); + let (mut app, ctx) = wired(sentinels.root.clone()); + let _escape = escape(&sentinels); + + cloud::browse(&mut app, "escape"); + settle(&mut app, &ctx, |app| app.cloud().mine.loaded); + + assert!(app.cloud().mine.error.is_some(), "listing through a symlink or junction out of the root must be refused"); + assert!(app.cloud().mine.entries.is_empty()); + assert_sentinels_untouched(&sentinels); +} + +#[cfg(any(unix, windows))] +#[test] +fn reading_through_a_linked_folder_cannot_return_bytes_from_outside_the_root() { + let sentinels = sentinels(); + let (mut app, ctx) = wired(sentinels.root.clone()); + let _escape = escape(&sentinels); + + cloud::submit(&app, Job::Read { entry: leaked_entry(), into: None }); + said(&mut app, &ctx); + + assert!(app.opened.lock().unwrap().is_empty(), "a read through a symlink or junction out of the root must not deliver bytes"); + assert_sentinels_untouched(&sentinels); +} + +#[cfg(any(unix, windows))] +#[test] +fn writing_through_a_linked_folder_cannot_change_a_file_outside_the_root() { + let sentinels = sentinels(); + let (mut app, ctx) = wired(sentinels.root.clone()); + let _escape = escape(&sentinels); + + cloud::submit(&app, Job::Write { uid: 1, entry: leaked_entry(), bytes: b"pwned".to_vec() }); + said(&mut app, &ctx); + + assert!(app.cloud().conflict.is_none(), "this must be refused outright, not treated as a stale-version conflict"); + assert_sentinels_untouched(&sentinels); +}