From f519832af17b413e93d7993a083d28dbbfd93de1 Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 18:06:25 +0000 Subject: [PATCH 1/5] fix(portal): confine file operations beneath the granted directory The portal normalised a request path to check it against the granted directories, but then operated on the raw path. A link inside a granted directory, followed by '..', therefore reached files outside it. Links pointing outside were followed too. Each granted directory is now opened once. Every request is resolved beneath that descriptor with openat2(RESOLVE_BENEATH | NO_MAGICLINKS), so the kernel keeps the operation inside the directory even when links are replaced while it runs. Paths with '.' or '..' components are refused. Other changes: - Writes replace the file atomically and no longer create directories. - Files are limited to 16 MiB, listings to 10,000 entries, request lines to the size of a full write, and the portal to 4 concurrent connections. - The runtime no longer passes the portal's socket path to components, which cannot reach it. --- Cargo.lock | 1 + README.md | 2 +- crates/weft-file-portal/Cargo.toml | 3 + crates/weft-file-portal/src/main.rs | 703 ++++++++++++++++++---------- crates/weft-runtime/src/main.rs | 4 - docs/architecture.md | 4 +- docs/security.md | 2 +- 7 files changed, 457 insertions(+), 262 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 20cbbdf..d5a03ee 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -10511,6 +10511,7 @@ version = "0.1.0" dependencies = [ "anyhow", "base64 0.22.1", + "rustix 1.1.4", "serde", "serde_json", ] diff --git a/README.md b/README.md index 022b3d0..8b38ead 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ WEFT OS is a Wayland compositor and application runtime where every app is a Web **Package management** — `weft-pack` handles check, sign, verify, install, uninstall, list, build-image (EROFS dm-verity), and info. Validates capability strings at check time. App data is stored apart from packages and survives uninstall. -**File portal** — `weft-file-portal` is a per-session file proxy with a path allowlist and `..` blocking. +**File portal** — `weft-file-portal` is a per-session file proxy for the session's directory grants, with every operation confined beneath the granted directory by the kernel. **Mount helper** — `weft-mount-helper` is a setuid helper for EROFS dm-verity mount/umount via `veritysetup`. diff --git a/crates/weft-file-portal/Cargo.toml b/crates/weft-file-portal/Cargo.toml index 5e8c337..1b6ecbc 100644 --- a/crates/weft-file-portal/Cargo.toml +++ b/crates/weft-file-portal/Cargo.toml @@ -13,3 +13,6 @@ anyhow = "1.0" serde = { version = "1", features = ["derive"] } serde_json = "1" base64 = "0.22" + +[target.'cfg(target_os = "linux")'.dependencies] +rustix = { version = "1", features = ["fs"] } diff --git a/crates/weft-file-portal/src/main.rs b/crates/weft-file-portal/src/main.rs index 822e535..8b4815f 100644 --- a/crates/weft-file-portal/src/main.rs +++ b/crates/weft-file-portal/src/main.rs @@ -1,17 +1,31 @@ -#[cfg(unix)] -use std::io::{BufRead, BufReader, Write}; -use std::path::{Path, PathBuf}; +//! A per-session file proxy for the directories a session is granted. +//! +//! Requests name absolute host paths inside a granted directory. Each +//! granted directory is opened once at startup, and every operation resolves +//! the rest of the path relative to that descriptor with `openat2` and +//! `RESOLVE_BENEATH`, so the kernel keeps it inside the directory while it +//! runs: `..`, absolute symbolic links, links that point outside and links +//! replaced during the operation cannot leave it. Paths must name their +//! location directly, without `.` or `..` components. Writes replace a file +//! atomically and never create directories. + +#[cfg(target_os = "linux")] +use std::io::{BufRead, BufReader, Read, Write}; +use std::path::{Component, Path, PathBuf}; use serde::{Deserialize, Serialize}; -#[cfg(unix)] -use std::sync::Arc; - -#[cfg(unix)] -use anyhow::Context; - -#[cfg(unix)] -use std::os::unix::net::{UnixListener, UnixStream}; +/// The largest file read or written, in bytes. +const MAX_FILE: usize = 16 * 1024 * 1024; +/// The longest request line: a write of the largest file, base64-encoded, +/// with room for its path. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +const MAX_LINE: usize = MAX_FILE / 3 * 4 + 64 * 1024; +/// The most entries one listing returns. +const MAX_ENTRIES: usize = 10_000; +/// The most connections served at once. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +const MAX_CONNECTIONS: usize = 4; #[derive(Deserialize)] #[serde(tag = "op", rename_all = "snake_case")] @@ -38,8 +52,13 @@ impl Response { } } -#[cfg(unix)] +#[cfg(target_os = "linux")] fn main() -> anyhow::Result<()> { + use anyhow::Context; + use std::os::unix::net::UnixListener; + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + let args: Vec = std::env::args().collect(); if args.len() < 2 { eprintln!( @@ -49,32 +68,49 @@ fn main() -> anyhow::Result<()> { } let socket_path = &args[1]; - let allowed = Arc::new(parse_allowed(&args[2..])); + let mut roots = Vec::new(); + for grant in parse_allowed(&args[2..]) { + match Root::open(grant) { + Ok(root) => roots.push(root), + Err((path, e)) => eprintln!("cannot open granted directory {}: {e}", path.display()), + } + } + let roots = Arc::new(roots); if Path::new(socket_path).exists() { std::fs::remove_file(socket_path) .with_context(|| format!("remove stale socket {socket_path}"))?; } - let listener = UnixListener::bind(socket_path).with_context(|| format!("bind {socket_path}"))?; + let active = Arc::new(AtomicUsize::new(0)); for stream in listener.incoming() { - match stream { - Ok(s) => { - let allowed = Arc::clone(&allowed); - std::thread::spawn(move || handle_connection(s, &allowed)); + let mut stream = match stream { + Ok(s) => s, + Err(e) => { + eprintln!("accept error: {e}"); + continue; } - Err(e) => eprintln!("accept error: {e}"), + }; + if active.fetch_add(1, Ordering::SeqCst) >= MAX_CONNECTIONS { + active.fetch_sub(1, Ordering::SeqCst); + let _ = stream.write_all(b"{\"error\":\"too many connections\"}\n"); + continue; } + let roots = Arc::clone(&roots); + let active = Arc::clone(&active); + std::thread::spawn(move || { + handle_connection(stream, &roots); + active.fetch_sub(1, Ordering::SeqCst); + }); } - Ok(()) } -#[cfg(not(unix))] +#[cfg(not(target_os = "linux"))] fn main() -> anyhow::Result<()> { - anyhow::bail!("weft-file-portal requires a Unix platform") + anyhow::bail!("weft-file-portal requires Linux") } /// A directory the session may use: `--allow` grants reading and writing, @@ -85,7 +121,6 @@ struct Allowed { writable: bool, } -#[cfg_attr(not(any(unix, test)), allow(dead_code))] fn parse_allowed(args: &[String]) -> Vec { let mut allowed = Vec::new(); let mut i = 0; @@ -109,33 +144,84 @@ fn parse_allowed(args: &[String]) -> Vec { allowed } -#[cfg_attr(not(any(unix, test)), allow(dead_code))] -fn normalize_path(path: &Path) -> PathBuf { - use std::path::Component; - let mut out = PathBuf::new(); - for c in path.components() { - match c { - Component::ParentDir => { - out.pop(); - } - Component::CurDir => {} - other => out.push(other), +/// The part of `path` inside the granted directory `root`, if `path` lies +/// in it and names its location directly: only plain components, no `.`, +/// `..` or repeated root. +fn relative_to<'a>(path: &'a Path, root: &Path) -> Option<&'a Path> { + let rest = path.strip_prefix(root).ok()?; + rest.components() + .all(|c| matches!(c, Component::Normal(_))) + .then_some(rest) +} + +/// A granted directory, held open for the life of the portal. +#[cfg(target_os = "linux")] +struct Root { + path: PathBuf, + dir: rustix::fd::OwnedFd, + writable: bool, +} + +#[cfg(target_os = "linux")] +impl Root { + fn open(grant: Allowed) -> Result { + use rustix::fs::{Mode, OFlags}; + match rustix::fs::open( + &grant.root, + OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, + Mode::empty(), + ) { + Ok(dir) => Ok(Self { + path: grant.root, + dir, + writable: grant.writable, + }), + Err(e) => Err((grant.root, e.into())), } } - out } -/// Whether `path` lies in an allowed directory, and for a write, in one -/// granted read-write. -fn is_allowed(path: &Path, allowed: &[Allowed], write: bool) -> bool { - let norm = normalize_path(path); - allowed +/// The granted directory holding `path` and the path inside it, for an +/// operation that writes when `write` is set. +#[cfg(target_os = "linux")] +fn locate<'a, 'p>( + roots: &'a [Root], + path: &'p str, + write: bool, +) -> Result<(&'a Root, &'p Path), Response> { + let requested = Path::new(path); + roots .iter() - .any(|a| norm.starts_with(&a.root) && (a.writable || !write)) + .filter(|root| root.writable || !write) + .find_map(|root| relative_to(requested, &root.path).map(|rest| (root, rest))) + .ok_or_else(|| Response::err(format!("access denied: {path}"))) } -#[cfg(unix)] -fn handle_connection(stream: UnixStream, allowed: &[Allowed]) { +/// Opens `rest` inside `root`, never leaving it. +#[cfg(target_os = "linux")] +fn open_beneath( + root: &Root, + rest: &Path, + flags: rustix::fs::OFlags, +) -> std::io::Result { + use rustix::fs::{Mode, OFlags, ResolveFlags}; + let rest = if rest.as_os_str().is_empty() { + Path::new(".") + } else { + rest + }; + rustix::fs::openat2( + &root.dir, + rest, + flags | OFlags::CLOEXEC | OFlags::NOCTTY, + Mode::empty(), + ResolveFlags::BENEATH | ResolveFlags::NO_MAGICLINKS, + ) + .map_err(std::io::Error::from) +} + +#[cfg(target_os = "linux")] +fn handle_connection(stream: std::os::unix::net::UnixStream, roots: &[Root]) { let mut writer = match stream.try_clone() { Ok(s) => s, Err(e) => { @@ -143,22 +229,30 @@ fn handle_connection(stream: UnixStream, allowed: &[Allowed]) { return; } }; - let reader = BufReader::new(stream); - - for line in reader.lines() { - let line = match line { - Ok(l) => l, - Err(_) => break, - }; - if line.is_empty() { + let mut reader = BufReader::new(stream); + let mut line = Vec::new(); + loop { + line.clear(); + match (&mut reader) + .take(MAX_LINE as u64 + 1) + .read_until(b'\n', &mut line) + { + Ok(0) | Err(_) => break, + Ok(_) => {} + } + if line.len() > MAX_LINE { + let _ = writer.write_all(b"{\"error\":\"request too long\"}\n"); + break; + } + let text = String::from_utf8_lossy(&line); + let text = text.trim_end_matches(['\n', '\r']); + if text.is_empty() { continue; } - - let response = match serde_json::from_str::(&line) { - Ok(req) => handle_request(req, allowed), + let response = match serde_json::from_str::(text) { + Ok(req) => handle_request(req, roots), Err(e) => Response::err(format!("bad request: {e}")), }; - let mut out = serde_json::to_string(&response) .unwrap_or_else(|_| r#"{"error":"serialize"}"#.to_string()); out.push('\n'); @@ -168,246 +262,347 @@ fn handle_connection(stream: UnixStream, allowed: &[Allowed]) { } } -#[cfg_attr(not(any(unix, test)), allow(dead_code))] -fn handle_request(req: Request, allowed: &[Allowed]) -> Response { - match req { +#[cfg(target_os = "linux")] +fn handle_request(req: Request, roots: &[Root]) -> Response { + let result = match req { Request::Read { path } => { - let p = PathBuf::from(&path); - if !is_allowed(&p, allowed, false) { - return Response::err(format!("access denied: {path}")); - } - match std::fs::read(&p) { - Ok(data) => Response::OkData { - data_b64: base64::Engine::encode( - &base64::engine::general_purpose::STANDARD, - &data, - ), - }, - Err(e) => Response::err(e), - } + locate(roots, &path, false).and_then(|(root, rest)| read(root, rest)) } - Request::Write { path, data_b64 } => { - let p = PathBuf::from(&path); - if !is_allowed(&p, allowed, true) { - return Response::err(format!("access denied: {path}")); - } + Request::Write { path, data_b64 } => locate(roots, &path, true).and_then(|(root, rest)| { let data = - match base64::Engine::decode(&base64::engine::general_purpose::STANDARD, &data_b64) - { - Ok(d) => d, - Err(e) => return Response::err(format!("bad base64: {e}")), - }; - if let Some(Err(e)) = p.parent().map(std::fs::create_dir_all) { - return Response::err(e); - } - match std::fs::write(&p, &data) { - Ok(()) => Response::Ok, - Err(e) => Response::err(e), - } - } + base64::Engine::decode(&base64::engine::general_purpose::STANDARD, &data_b64) + .map_err(|e| Response::err(format!("bad base64: {e}")))?; + write(root, rest, &data) + }), Request::List { path } => { - let p = PathBuf::from(&path); - if !is_allowed(&p, allowed, false) { - return Response::err(format!("access denied: {path}")); - } - match std::fs::read_dir(&p) { - Ok(entries) => { - let mut names = Vec::new(); - for entry in entries.flatten() { - if let Some(name) = entry.file_name().to_str() { - names.push(name.to_string()); - } - } - names.sort(); - Response::OkEntries { entries: names } - } - Err(e) => Response::err(e), - } + locate(roots, &path, false).and_then(|(root, rest)| list(root, rest)) } - } + }; + result.unwrap_or_else(|response| response) } -#[cfg(test)] +#[cfg(target_os = "linux")] +fn read(root: &Root, rest: &Path) -> Result { + use rustix::fs::{FileType, OFlags}; + let fd = open_beneath(root, rest, OFlags::RDONLY | OFlags::NONBLOCK).map_err(Response::err)?; + let stat = rustix::fs::fstat(&fd).map_err(Response::err)?; + if FileType::from_raw_mode(stat.st_mode) != FileType::RegularFile { + return Err(Response::err("not a regular file")); + } + let mut data = Vec::new(); + std::fs::File::from(fd) + .take(MAX_FILE as u64 + 1) + .read_to_end(&mut data) + .map_err(Response::err)?; + if data.len() > MAX_FILE { + return Err(Response::err(format!("file larger than {MAX_FILE} bytes"))); + } + Ok(Response::OkData { + data_b64: base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &data), + }) +} + +#[cfg(target_os = "linux")] +fn list(root: &Root, rest: &Path) -> Result { + use rustix::fs::OFlags; + let fd = open_beneath(root, rest, OFlags::RDONLY | OFlags::DIRECTORY).map_err(Response::err)?; + let mut entries = rustix::fs::Dir::read_from(&fd).map_err(Response::err)?; + let mut names = Vec::new(); + while let Some(entry) = entries.read() { + let entry = entry.map_err(Response::err)?; + let Ok(name) = entry.file_name().to_str() else { + continue; + }; + if name == "." || name == ".." { + continue; + } + if names.len() == MAX_ENTRIES { + return Err(Response::err(format!("more than {MAX_ENTRIES} entries"))); + } + names.push(name.to_owned()); + } + names.sort(); + Ok(Response::OkEntries { entries: names }) +} + +/// Replaces the file `rest` in `root` with `data`: the data is written to a +/// new file in the same directory, flushed and renamed over the name, so +/// the file holds either the old or the new content. +#[cfg(target_os = "linux")] +fn write(root: &Root, rest: &Path, data: &[u8]) -> Result { + use rustix::fs::{Mode, OFlags}; + if data.len() > MAX_FILE { + return Err(Response::err(format!("file larger than {MAX_FILE} bytes"))); + } + let name = rest + .file_name() + .ok_or_else(|| Response::err("a write needs a file name"))?; + let parent = open_beneath( + root, + rest.parent().unwrap_or(Path::new("")), + OFlags::RDONLY | OFlags::DIRECTORY, + ) + .map_err(Response::err)?; + let temporary = format!( + ".weft-portal-{}-{}", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()) + ); + let file = rustix::fs::openat( + &parent, + temporary.as_str(), + OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL | OFlags::NOFOLLOW | OFlags::CLOEXEC, + Mode::from_raw_mode(0o600), + ) + .map_err(Response::err)?; + let mut file = std::fs::File::from(file); + let written = file + .write_all(data) + .and_then(|()| file.sync_all()) + .and_then(|()| { + rustix::fs::renameat(&parent, temporary.as_str(), &parent, name) + .map_err(std::io::Error::from) + }); + if let Err(e) = written { + let _ = rustix::fs::unlinkat(&parent, temporary.as_str(), rustix::fs::AtFlags::empty()); + return Err(Response::err(e)); + } + let _ = rustix::fs::fsync(&parent); + Ok(Response::Ok) +} + +#[cfg(all(test, target_os = "linux"))] mod tests { use super::*; + use std::fs; - fn rw(root: impl Into) -> Allowed { - Allowed { - root: root.into(), - writable: true, + fn grant(root: &Path, writable: bool) -> Vec { + vec![ + Root::open(Allowed { + root: root.to_path_buf(), + writable, + }) + .unwrap(), + ] + } + + fn temp(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("wfp_{name}_{}", std::process::id())); + let _ = fs::remove_dir_all(&dir); + fs::create_dir_all(dir.join("granted")).unwrap(); + dir + } + + fn path(p: &Path) -> String { + p.to_string_lossy().into_owned() + } + + fn denied(resp: &Response) -> bool { + matches!(resp, Response::Err { .. }) + } + + fn read_req(p: &Path) -> Request { + Request::Read { path: path(p) } + } + + fn write_req(p: &Path, data: &[u8]) -> Request { + Request::Write { + path: path(p), + data_b64: base64::Engine::encode(&base64::engine::general_purpose::STANDARD, data), } } - fn ro(root: impl Into) -> Allowed { - Allowed { - root: root.into(), - writable: false, - } - } - - #[test] - fn allowed_path_accepted() { - let allowed = vec![rw("/tmp/weft-test-allowed")]; - assert!(is_allowed( - Path::new("/tmp/weft-test-allowed/file.txt"), - &allowed, - false - )); - } - - #[test] - fn disallowed_path_rejected() { - let allowed = vec![rw("/tmp/weft-test-allowed")]; - assert!(!is_allowed(Path::new("/etc/passwd"), &allowed, false)); - } - - #[test] - fn dotdot_traversal_blocked() { - let allowed = vec![rw("/tmp/weft-test-allowed")]; - assert!(!is_allowed( - Path::new("/tmp/weft-test-allowed/../etc/passwd"), - &allowed, - false - )); - } - - #[test] - fn empty_allowlist_rejects_all() { - assert!(!is_allowed(Path::new("/tmp/anything"), &[], false)); - } - #[test] fn parse_allowed_extracts_paths() { let args: Vec = vec![ "--allow".into(), "/tmp/a".into(), - "--allow".into(), - "/tmp/b".into(), + "--allow-read".into(), + "/tmp/c".into(), ]; - let result = parse_allowed(&args); - assert_eq!(result, vec![rw("/tmp/a"), rw("/tmp/b")]); - let args: Vec = vec!["--allow-read".into(), "/tmp/c".into()]; - assert_eq!(parse_allowed(&args), vec![ro("/tmp/c")]); + assert_eq!( + parse_allowed(&args), + vec![ + Allowed { + root: "/tmp/a".into(), + writable: true + }, + Allowed { + root: "/tmp/c".into(), + writable: false + }, + ] + ); } #[test] - fn handle_request_read_denied() { - let resp = handle_request( - Request::Read { - path: "/etc/shadow".into(), - }, - &[rw("/tmp/safe")], + fn paths_must_name_a_place_inside_a_granted_directory_directly() { + let root = Path::new("/srv/granted"); + assert_eq!( + relative_to(Path::new("/srv/granted/a/b"), root), + Some(Path::new("a/b")) ); - let json = serde_json::to_string(&resp).unwrap(); - assert!(json.contains("access denied")); - } - - #[test] - fn handle_request_read_roundtrip() { - use std::fs; - let dir = std::env::temp_dir().join(format!("wfp_test_{}", std::process::id())); - let _ = fs::create_dir_all(&dir); - let file = dir.join("hello.txt"); - fs::write(&file, b"hello world").unwrap(); - - let allowed = vec![rw(dir.clone())]; - let resp = handle_request( - Request::Read { - path: file.to_string_lossy().into(), - }, - &allowed, + assert_eq!( + relative_to(Path::new("/srv/granted"), root), + Some(Path::new("")) ); - let json = serde_json::to_string(&resp).unwrap(); - assert!(json.contains("data_b64")); - - if let Response::OkData { data_b64 } = resp { - let decoded = - base64::Engine::decode(&base64::engine::general_purpose::STANDARD, &data_b64) - .unwrap(); - assert_eq!(decoded, b"hello world"); - } else { - panic!("expected OkData"); + for outside in [ + "/srv/grantedx/a", + "/srv/granted/../x", + "/srv/granted/a/../../x", + "/etc", + ] { + assert_eq!(relative_to(Path::new(outside), root), None, "{outside}"); } - - let _ = fs::remove_dir_all(&dir); } #[test] - fn handle_request_list() { - use std::fs; - let dir = std::env::temp_dir().join(format!("wfp_list_{}", std::process::id())); - let _ = fs::create_dir_all(&dir); - fs::write(dir.join("b.txt"), b"").unwrap(); - fs::write(dir.join("a.txt"), b"").unwrap(); - - let allowed = vec![rw(dir.clone())]; - let resp = handle_request( + fn reads_writes_and_lists_inside_the_directory() { + let dir = temp("roundtrip"); + let granted = dir.join("granted"); + let roots = grant(&granted, true); + assert!(matches!( + handle_request(write_req(&granted.join("b.txt"), b"hello"), &roots), + Response::Ok + )); + fs::write(granted.join("a.txt"), b"").unwrap(); + match handle_request(read_req(&granted.join("b.txt")), &roots) { + Response::OkData { data_b64 } => assert_eq!( + base64::Engine::decode(&base64::engine::general_purpose::STANDARD, data_b64) + .unwrap(), + b"hello" + ), + _ => panic!("expected data"), + } + match handle_request( Request::List { - path: dir.to_string_lossy().into(), + path: path(&granted), }, - &allowed, - ); - if let Response::OkEntries { entries } = resp { - assert_eq!(entries, vec!["a.txt", "b.txt"]); - } else { - panic!("expected OkEntries"); + &roots, + ) { + Response::OkEntries { entries } => assert_eq!(entries, ["a.txt", "b.txt"]), + _ => panic!("expected entries"), } - let _ = fs::remove_dir_all(&dir); } #[test] - fn handle_request_write_creates_parent_dirs() { - use std::fs; - let dir = std::env::temp_dir().join(format!("wfp_write_{}", std::process::id())); - let _ = fs::remove_dir_all(&dir); - let nested = dir.join("sub").join("deep").join("file.txt"); - let data = base64::Engine::encode( - &base64::engine::general_purpose::STANDARD, - b"nested content", - ); - let allowed = vec![rw(dir.clone())]; - let resp = handle_request( - Request::Write { - path: nested.to_string_lossy().into(), - data_b64: data, - }, - &allowed, - ); - assert!(matches!(resp, Response::Ok), "expected Ok response"); - assert_eq!(fs::read(&nested).unwrap(), b"nested content"); + fn links_cannot_lead_out_of_the_directory() { + let dir = temp("links"); + let granted = dir.join("granted"); + fs::write(dir.join("secret.txt"), b"secret").unwrap(); + fs::create_dir(granted.join("sub")).unwrap(); + std::os::unix::fs::symlink("/", granted.join("root")).unwrap(); + std::os::unix::fs::symlink("../secret.txt", granted.join("up")).unwrap(); + std::os::unix::fs::symlink(&dir, granted.join("parent")).unwrap(); + let roots = grant(&granted, true); + for escape in [ + granted.join("root/etc/passwd"), + granted.join("up"), + granted.join("parent/secret.txt"), + // The check this replaced normalised `link/..` away and then + // followed the link. + granted.join("root/../secret.txt"), + ] { + assert!( + denied(&handle_request(read_req(&escape), &roots)), + "{}", + escape.display() + ); + if escape != granted.join("up") { + assert!( + denied(&handle_request(write_req(&escape, b"x"), &roots)), + "{}", + escape.display() + ); + } + } + // A write to a name that is a link replaces the link, inside the + // directory, rather than writing where it points. + assert!(matches!( + handle_request(write_req(&granted.join("up"), b"x"), &roots), + Response::Ok + )); + assert!(fs::symlink_metadata(granted.join("up")).unwrap().is_file()); + assert_eq!(fs::read(dir.join("secret.txt")).unwrap(), b"secret"); + // A link that stays inside is followed. + std::os::unix::fs::symlink("sub", granted.join("inside")).unwrap(); + assert!(matches!( + handle_request(write_req(&granted.join("inside/f"), b"ok"), &roots), + Response::Ok + )); + assert_eq!(fs::read(granted.join("sub/f")).unwrap(), b"ok"); let _ = fs::remove_dir_all(&dir); } #[test] fn read_only_directories_refuse_writes() { - use std::fs; - let dir = std::env::temp_dir().join(format!("wfp_ro_{}", std::process::id())); + let dir = temp("ro"); + let granted = dir.join("granted"); + fs::write(granted.join("kept.txt"), b"original").unwrap(); + let roots = grant(&granted, false); + assert!(denied(&handle_request( + write_req(&granted.join("kept.txt"), b"x"), + &roots + ))); + assert_eq!(fs::read(granted.join("kept.txt")).unwrap(), b"original"); + assert!(matches!( + handle_request(read_req(&granted.join("kept.txt")), &roots), + Response::OkData { .. } + )); let _ = fs::remove_dir_all(&dir); - fs::create_dir_all(&dir).unwrap(); - fs::write(dir.join("kept.txt"), b"original").unwrap(); - let allowed = vec![ro(dir.clone())]; - let data = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, b"x"); - let resp = handle_request( - Request::Write { - path: dir.join("kept.txt").to_string_lossy().into(), - data_b64: data, - }, - &allowed, - ); - assert!( - serde_json::to_string(&resp) - .unwrap() - .contains("access denied") - ); - assert_eq!(fs::read(dir.join("kept.txt")).unwrap(), b"original"); - let resp = handle_request( - Request::Read { - path: dir.join("kept.txt").to_string_lossy().into(), - }, - &allowed, - ); - assert!(matches!(resp, Response::OkData { .. })); + } + + #[test] + fn writes_create_no_directories_and_leave_no_temporary_files() { + let dir = temp("nodirs"); + let granted = dir.join("granted"); + let roots = grant(&granted, true); + assert!(denied(&handle_request( + write_req(&granted.join("missing/f"), b"x"), + &roots + ))); + assert!(!granted.join("missing").exists()); + assert!(denied(&handle_request(write_req(&granted, b"x"), &roots))); + let left: Vec<_> = fs::read_dir(&granted).unwrap().flatten().collect(); + assert!(left.is_empty(), "{left:?}"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn oversized_files_are_refused() { + let dir = temp("size"); + let granted = dir.join("granted"); + fs::File::create(granted.join("big")) + .unwrap() + .set_len(MAX_FILE as u64 + 1) + .unwrap(); + let roots = grant(&granted, true); + assert!(denied(&handle_request( + read_req(&granted.join("big")), + &roots + ))); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn overlong_requests_end_the_connection() { + let dir = temp("line"); + let granted = dir.join("granted"); + let roots = grant(&granted, true); + let (client, server) = std::os::unix::net::UnixStream::pair().unwrap(); + let serve = std::thread::spawn(move || handle_connection(server, &roots)); + let mut writer = client.try_clone().unwrap(); + let sent = std::thread::spawn(move || { + let _ = writer.write_all(&vec![b'x'; MAX_LINE + 2]); + }); + let mut reply = String::new(); + BufReader::new(client).read_line(&mut reply).unwrap(); + serve.join().unwrap(); + let _ = sent.join(); + assert!(reply.contains("request too long"), "{reply}"); let _ = fs::remove_dir_all(&dir); } } diff --git a/crates/weft-runtime/src/main.rs b/crates/weft-runtime/src/main.rs index 1fe5d05..42ced3e 100644 --- a/crates/weft-runtime/src/main.rs +++ b/crates/weft-runtime/src/main.rs @@ -323,10 +323,6 @@ fn run_module( } } - if let Ok(portal_socket) = std::env::var("WEFT_FILE_PORTAL_SOCKET") { - ctx_builder.env("WEFT_FILE_PORTAL_SOCKET", &portal_socket); - } - for dir in preopen { let (dir_perms, file_perms) = match dir.access { Access::Read => (DirPerms::READ, FilePerms::READ), diff --git a/docs/architecture.md b/docs/architecture.md index ee92a31..f9934b5 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -32,7 +32,7 @@ Package management CLI. Subcommands: `check` (validate wapp.toml + wasm module), ### weft-file-portal -Per-session file proxy. Runs as a separate process with a path allowlist derived from the session's directory grants; read-only grants (`--allow-read`) refuse writes. Paths are checked lexically, so `..` is blocked but symbolic links are followed. Accepts JSON-lines requests over a Unix socket. Components cannot currently reach that socket, because the runtime grants them no socket access. +Per-session file proxy. Runs as a separate process with the session's directory grants; read-only grants (`--allow-read`) refuse writes. Every operation is resolved beneath the granted directory's descriptor by the kernel (see security.md), with bounded file, listing and request sizes. Accepts JSON-lines requests over a Unix socket. Components cannot currently reach that socket, because the runtime grants them no socket access. ### weft-mount-helper @@ -147,5 +147,5 @@ A package directory left empty by the move is removed. Nothing is moved, and `we | `WEFT_APPD_WS_PORT` | `7410` | WebSocket port for weft-appd | | `WEFT_EGL_RENDERING` | — | Set to `1` to use EGL rendering in Servo shell | | `WEFT_DISABLE_CGROUP` | — | Set to disable systemd-run cgroup wrapping | -| `WEFT_FILE_PORTAL_SOCKET` | — | Path forwarded to app runtime for file portal | +| `WEFT_FILE_PORTAL_SOCKET` | — | Path of the session's file portal socket, set for `weft-runtime`; not passed to the component | | `XDG_RUNTIME_DIR` | — | Standard XDG runtime dir (sockets written here) | diff --git a/docs/security.md b/docs/security.md index 09a6b4a..86a0b3f 100644 --- a/docs/security.md +++ b/docs/security.md @@ -16,7 +16,7 @@ Each app session runs as a separate OS process (`weft-runtime`). When systemd is ## Filesystem Isolation -Apps access the filesystem only through WASI preopened directories. Each capability maps to a specific host path preopened at a fixed guest path. The `weft-file-portal` process applies the same directory grants and access modes, but checks paths lexically: it blocks `..` traversal, not symbolic links. Components cannot currently reach its socket, since the runtime grants them no socket access. +Apps access the filesystem only through WASI preopened directories. Each capability maps to a specific host path preopened at a fixed guest path. The `weft-file-portal` process applies the same directory grants and access modes. It opens each granted directory once and resolves every request beneath that descriptor with `openat2(RESOLVE_BENEATH)`, so the kernel keeps the operation inside the directory: `..`, links pointing outside and links swapped in during the operation are refused. Requests must name a path without `.` or `..` components; files are limited to 16 MiB, listings to 10,000 entries, requests to one line of about 22 MiB, and the portal to 4 connections at a time. Writes replace a file atomically (a write to a name that is a link replaces the link) and never create directories. Components cannot currently reach its socket, since the runtime grants them no socket access, and the socket's path is not passed to them. ## Package Signing From ae2e864941cbe4dc8e42da54b6e5410f7e4dfa0d Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 18:06:59 +0000 Subject: [PATCH 2/5] fix(portal): report a path leading out of the granted directory as denied openat2 reports a resolution that would leave the directory as EXDEV, which reached clients as an invalid cross-device link. --- crates/weft-file-portal/src/main.rs | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/crates/weft-file-portal/src/main.rs b/crates/weft-file-portal/src/main.rs index 8b4815f..efb7cbf 100644 --- a/crates/weft-file-portal/src/main.rs +++ b/crates/weft-file-portal/src/main.rs @@ -217,7 +217,18 @@ fn open_beneath( Mode::empty(), ResolveFlags::BENEATH | ResolveFlags::NO_MAGICLINKS, ) - .map_err(std::io::Error::from) + .map_err(|e| { + // The kernel reports a resolution that would leave the directory as + // EXDEV. + if e == rustix::io::Errno::XDEV { + std::io::Error::new( + std::io::ErrorKind::PermissionDenied, + "access denied: the path leads out of the granted directory", + ) + } else { + e.into() + } + }) } #[cfg(target_os = "linux")] @@ -521,6 +532,10 @@ mod tests { } // A write to a name that is a link replaces the link, inside the // directory, rather than writing where it points. + match handle_request(read_req(&granted.join("root/etc/passwd")), &roots) { + Response::Err { error } => assert!(error.contains("leads out"), "{error}"), + _ => panic!("read through a link out of the directory"), + } assert!(matches!( handle_request(write_req(&granted.join("up"), b"x"), &roots), Response::Ok From 50418d4c0bc7557fca07b702eed996b35de3dca1 Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 18:15:28 +0000 Subject: [PATCH 3/5] fix(portal): refuse indirect paths as given and harden connection handling Path parsing drops '.' components, empty components and a trailing '/'. A request like dir/. was therefore accepted, and a write renamed over the directory itself instead of failing. The path text is now checked as given. Other fixes: - A replaced file keeps its permission bits. - A connection's slot is released even when its handler panics. - Connections close after 60 seconds without a request. - Temporary files get unique names and are not listed. - A request of exactly the line limit is accepted. A new test swaps a link between a directory inside the granted root and one outside while reads and writes run, and checks that nothing outside is read or written. weft-appd no longer sets WEFT_FILE_PORTAL_SOCKET for the runtime, which no longer reads it. --- crates/weft-appd/src/runtime.rs | 4 - crates/weft-file-portal/src/main.rs | 135 +++++++++++++++++++++++++--- docs/architecture.md | 1 - docs/security.md | 2 +- 4 files changed, 123 insertions(+), 19 deletions(-) diff --git a/crates/weft-appd/src/runtime.rs b/crates/weft-appd/src/runtime.rs index 6f9cce9..d4489f5 100644 --- a/crates/weft-appd/src/runtime.rs +++ b/crates/weft-appd/src/runtime.rs @@ -311,10 +311,6 @@ pub(crate) async fn supervise( cmd.arg("--ipc-socket").arg(&ipc_socket_path); cmd.arg("--module").arg(&package.module); - if let Some((ref sock, _)) = portal { - cmd.env("WEFT_FILE_PORTAL_SOCKET", sock); - } - for dir in &grants.dirs { cmd.arg("--preopen").arg(dir.preopen_arg()); } diff --git a/crates/weft-file-portal/src/main.rs b/crates/weft-file-portal/src/main.rs index efb7cbf..2bf09c9 100644 --- a/crates/weft-file-portal/src/main.rs +++ b/crates/weft-file-portal/src/main.rs @@ -26,6 +26,12 @@ const MAX_ENTRIES: usize = 10_000; /// The most connections served at once. #[cfg_attr(not(target_os = "linux"), allow(dead_code))] const MAX_CONNECTIONS: usize = 4; +/// How long a connection may stay silent before it is closed. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +const IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60); +/// The prefix of the temporary files writes create, never listed. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +const TEMPORARY_PREFIX: &str = ".weft-portal-"; #[derive(Deserialize)] #[serde(tag = "op", rename_all = "snake_case")] @@ -98,12 +104,22 @@ fn main() -> anyhow::Result<()> { let _ = stream.write_all(b"{\"error\":\"too many connections\"}\n"); continue; } + // The slot is released however the connection ends, a panic + // included. + struct Slot(Arc); + impl Drop for Slot { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::SeqCst); + } + } + let slot = Slot(Arc::clone(&active)); let roots = Arc::clone(&roots); - let active = Arc::clone(&active); - std::thread::spawn(move || { + if let Err(e) = std::thread::Builder::new().spawn(move || { + let _slot = slot; handle_connection(stream, &roots); - active.fetch_sub(1, Ordering::SeqCst); - }); + }) { + eprintln!("cannot serve a connection: {e}"); + } } Ok(()) } @@ -145,9 +161,19 @@ fn parse_allowed(args: &[String]) -> Vec { } /// The part of `path` inside the granted directory `root`, if `path` lies -/// in it and names its location directly: only plain components, no `.`, -/// `..` or repeated root. +/// in it and names its location directly: an absolute path of plain +/// components only, without `.`, `..`, empty components or a trailing `/`. +/// The text is checked as given, since path parsing drops `.` and repeated +/// separators. fn relative_to<'a>(path: &'a Path, root: &Path) -> Option<&'a Path> { + let text = path.to_str()?; + let direct = text.starts_with('/') + && text[1..] + .split('/') + .all(|segment| !matches!(segment, "" | "." | "..")); + if !direct { + return None; + } let rest = path.strip_prefix(root).ok()?; rest.components() .all(|c| matches!(c, Component::Normal(_))) @@ -240,18 +266,19 @@ fn handle_connection(stream: std::os::unix::net::UnixStream, roots: &[Root]) { return; } }; + let _ = stream.set_read_timeout(Some(IDLE_TIMEOUT)); let mut reader = BufReader::new(stream); let mut line = Vec::new(); loop { line.clear(); match (&mut reader) - .take(MAX_LINE as u64 + 1) + .take(MAX_LINE as u64 + 2) .read_until(b'\n', &mut line) { Ok(0) | Err(_) => break, Ok(_) => {} } - if line.len() > MAX_LINE { + if line.strip_suffix(b"\n").unwrap_or(&line).len() > MAX_LINE { let _ = writer.write_all(b"{\"error\":\"request too long\"}\n"); break; } @@ -324,7 +351,7 @@ fn list(root: &Root, rest: &Path) -> Result { let Ok(name) = entry.file_name().to_str() else { continue; }; - if name == "." || name == ".." { + if name == "." || name == ".." || name.starts_with(TEMPORARY_PREFIX) { continue; } if names.len() == MAX_ENTRIES { @@ -354,13 +381,22 @@ fn write(root: &Root, rest: &Path, data: &[u8]) -> Result { OFlags::RDONLY | OFlags::DIRECTORY, ) .map_err(Response::err)?; + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); let temporary = format!( - ".weft-portal-{}-{}", + "{TEMPORARY_PREFIX}{}-{}", std::process::id(), - std::time::SystemTime::now() - .duration_since(std::time::UNIX_EPOCH) - .map_or(0, |d| d.as_nanos()) + NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) ); + // A replaced file keeps its permission bits; a new one is private. + let mode = match rustix::fs::statat(&parent, name, rustix::fs::AtFlags::SYMLINK_NOFOLLOW) { + Ok(stat) + if rustix::fs::FileType::from_raw_mode(stat.st_mode) + == rustix::fs::FileType::RegularFile => + { + stat.st_mode & 0o777 + } + _ => 0o600, + }; let file = rustix::fs::openat( &parent, temporary.as_str(), @@ -368,6 +404,7 @@ fn write(root: &Root, rest: &Path, data: &[u8]) -> Result { Mode::from_raw_mode(0o600), ) .map_err(Response::err)?; + let _ = rustix::fs::fchmod(&file, Mode::from_raw_mode(mode)); let mut file = std::fs::File::from(file); let written = file .write_all(data) @@ -464,6 +501,11 @@ mod tests { "/srv/granted/../x", "/srv/granted/a/../../x", "/etc", + "/srv/granted/a/./b", + "/srv/granted/a/.", + "/srv/granted/a/", + "/srv/granted//a", + "srv/granted/a", ] { assert_eq!(relative_to(Path::new(outside), root), None, "{outside}"); } @@ -552,6 +594,73 @@ mod tests { let _ = fs::remove_dir_all(&dir); } + #[test] + fn a_directory_swapped_for_a_link_mid_operation_cannot_lead_out() { + let dir = temp("race"); + let granted = dir.join("granted"); + fs::create_dir(dir.join("outside")).unwrap(); + fs::write(dir.join("outside/f"), b"secret").unwrap(); + fs::create_dir(granted.join("real")).unwrap(); + fs::write(granted.join("real/f"), b"inside").unwrap(); + let roots = grant(&granted, true); + let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); + let swapper = { + let (granted, outside, stop) = (granted.clone(), dir.join("outside"), stop.clone()); + std::thread::spawn(move || { + // `swap` is alternately a link to the inside directory and + // a link out. + while !stop.load(std::sync::atomic::Ordering::Relaxed) { + let _ = std::os::unix::fs::symlink("real", granted.join("next")); + let _ = fs::rename(granted.join("next"), granted.join("swap")); + let _ = std::os::unix::fs::symlink(&outside, granted.join("next")); + let _ = fs::rename(granted.join("next"), granted.join("swap")); + } + }) + }; + let mut inside = 0; + for _ in 0..2000 { + if let Response::OkData { data_b64 } = + handle_request(read_req(&granted.join("swap/f")), &roots) + { + let data = + base64::Engine::decode(&base64::engine::general_purpose::STANDARD, data_b64) + .unwrap(); + assert_eq!(data, b"inside", "a read left the directory"); + inside += 1; + } + let _ = handle_request(write_req(&granted.join("swap/f"), b"inside"), &roots); + } + stop.store(true, std::sync::atomic::Ordering::Relaxed); + swapper.join().unwrap(); + assert_eq!(fs::read(dir.join("outside/f")).unwrap(), b"secret"); + assert!(inside > 0, "the race never resolved inside"); + let _ = fs::remove_dir_all(&dir); + } + + #[test] + fn a_replaced_file_keeps_its_mode() { + use std::os::unix::fs::PermissionsExt; + let dir = temp("mode"); + let granted = dir.join("granted"); + fs::write(granted.join("shared.txt"), b"old").unwrap(); + fs::set_permissions( + granted.join("shared.txt"), + fs::Permissions::from_mode(0o644), + ) + .unwrap(); + let roots = grant(&granted, true); + assert!(matches!( + handle_request(write_req(&granted.join("shared.txt"), b"new"), &roots), + Response::Ok + )); + let mode = fs::metadata(granted.join("shared.txt")) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o777, 0o644); + let _ = fs::remove_dir_all(&dir); + } + #[test] fn read_only_directories_refuse_writes() { let dir = temp("ro"); diff --git a/docs/architecture.md b/docs/architecture.md index f9934b5..78150ed 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -147,5 +147,4 @@ A package directory left empty by the move is removed. Nothing is moved, and `we | `WEFT_APPD_WS_PORT` | `7410` | WebSocket port for weft-appd | | `WEFT_EGL_RENDERING` | — | Set to `1` to use EGL rendering in Servo shell | | `WEFT_DISABLE_CGROUP` | — | Set to disable systemd-run cgroup wrapping | -| `WEFT_FILE_PORTAL_SOCKET` | — | Path of the session's file portal socket, set for `weft-runtime`; not passed to the component | | `XDG_RUNTIME_DIR` | — | Standard XDG runtime dir (sockets written here) | diff --git a/docs/security.md b/docs/security.md index 86a0b3f..ca04299 100644 --- a/docs/security.md +++ b/docs/security.md @@ -16,7 +16,7 @@ Each app session runs as a separate OS process (`weft-runtime`). When systemd is ## Filesystem Isolation -Apps access the filesystem only through WASI preopened directories. Each capability maps to a specific host path preopened at a fixed guest path. The `weft-file-portal` process applies the same directory grants and access modes. It opens each granted directory once and resolves every request beneath that descriptor with `openat2(RESOLVE_BENEATH)`, so the kernel keeps the operation inside the directory: `..`, links pointing outside and links swapped in during the operation are refused. Requests must name a path without `.` or `..` components; files are limited to 16 MiB, listings to 10,000 entries, requests to one line of about 22 MiB, and the portal to 4 connections at a time. Writes replace a file atomically (a write to a name that is a link replaces the link) and never create directories. Components cannot currently reach its socket, since the runtime grants them no socket access, and the socket's path is not passed to them. +Apps access the filesystem only through WASI preopened directories. Each capability maps to a specific host path preopened at a fixed guest path. The `weft-file-portal` process applies the same directory grants and access modes. It opens each granted directory once and resolves every request beneath that descriptor with `openat2(RESOLVE_BENEATH)`, so the kernel keeps the operation inside the directory: `..` and links pointing outside are refused, also when a link is swapped in while the operation runs; links that stay inside are followed. This needs Linux 5.6 or later; without `openat2` every operation fails. Requests must name an absolute path without `.`, `..` or empty components; files are limited to 16 MiB, listings to 10,000 entries, requests to one line of about 22 MiB, and the portal to 4 connections at a time, each closed after 60 seconds without a request. Writes replace a file atomically, keeping its permission bits but not its owner, extended attributes or hard links (a write to a name that is a link replaces the link), and never create directories. A granted directory that cannot be opened when the portal starts is not served. Components cannot currently reach its socket, since the runtime grants them no socket access, and the socket's path is not passed to them. ## Package Signing From ff1388c6d92ac180e31d66165f08c24dcc0abbe8 Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 18:59:01 +0000 Subject: [PATCH 4/5] test(portal): make the link-swap race test exercise both states, and fix limits The race test could finish before its swapping thread first ran, so in some runs nothing was exercised and the test failed. The link now exists from the start. The test runs until it has seen both reads that stay inside and reads refused for leading out, and it also swaps in a relative link that climbs out. Other fixes: - A request line ending in CRLF is measured without the CRLF. - Responses that the client stops reading time out like requests do. - Temporary file names include the portal's start time, so a file left by an earlier instance cannot collide with a new one. The test binary passed 30 runs in a row. --- crates/weft-file-portal/src/main.rs | 67 ++++++++++++++++++++--------- docs/security.md | 2 +- 2 files changed, 47 insertions(+), 22 deletions(-) diff --git a/crates/weft-file-portal/src/main.rs b/crates/weft-file-portal/src/main.rs index 2bf09c9..ecbace2 100644 --- a/crates/weft-file-portal/src/main.rs +++ b/crates/weft-file-portal/src/main.rs @@ -267,18 +267,20 @@ fn handle_connection(stream: std::os::unix::net::UnixStream, roots: &[Root]) { } }; let _ = stream.set_read_timeout(Some(IDLE_TIMEOUT)); + let _ = stream.set_write_timeout(Some(IDLE_TIMEOUT)); let mut reader = BufReader::new(stream); let mut line = Vec::new(); loop { line.clear(); match (&mut reader) - .take(MAX_LINE as u64 + 2) + .take(MAX_LINE as u64 + 3) .read_until(b'\n', &mut line) { Ok(0) | Err(_) => break, Ok(_) => {} } - if line.strip_suffix(b"\n").unwrap_or(&line).len() > MAX_LINE { + let content = line.strip_suffix(b"\n").unwrap_or(&line); + if content.strip_suffix(b"\r").unwrap_or(content).len() > MAX_LINE { let _ = writer.write_all(b"{\"error\":\"request too long\"}\n"); break; } @@ -382,8 +384,16 @@ fn write(root: &Root, rest: &Path, data: &[u8]) -> Result { ) .map_err(Response::err)?; static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + // Unique within this portal by the counter, and across restarts by the + // start time, so a file left by an earlier instance does not collide. + static STARTED: std::sync::OnceLock = std::sync::OnceLock::new(); + let started = STARTED.get_or_init(|| { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_nanos()) + }); let temporary = format!( - "{TEMPORARY_PREFIX}{}-{}", + "{TEMPORARY_PREFIX}{}-{started}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed) ); @@ -603,37 +613,52 @@ mod tests { fs::create_dir(granted.join("real")).unwrap(); fs::write(granted.join("real/f"), b"inside").unwrap(); let roots = grant(&granted, true); + // `swap` is a link, replaced in a loop, alternately to the inside + // directory and out of the granted one, absolute and relative. + std::os::unix::fs::symlink("real", granted.join("swap")).unwrap(); let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)); let swapper = { let (granted, outside, stop) = (granted.clone(), dir.join("outside"), stop.clone()); std::thread::spawn(move || { - // `swap` is alternately a link to the inside directory and - // a link out. - while !stop.load(std::sync::atomic::Ordering::Relaxed) { - let _ = std::os::unix::fs::symlink("real", granted.join("next")); - let _ = fs::rename(granted.join("next"), granted.join("swap")); - let _ = std::os::unix::fs::symlink(&outside, granted.join("next")); + let targets = [ + PathBuf::from("real"), + outside, + PathBuf::from("../../outside"), + ]; + for target in targets.iter().cycle() { + if stop.load(std::sync::atomic::Ordering::Relaxed) { + break; + } + let _ = std::os::unix::fs::symlink(target, granted.join("next")); let _ = fs::rename(granted.join("next"), granted.join("swap")); } }) }; - let mut inside = 0; - for _ in 0..2000 { - if let Response::OkData { data_b64 } = - handle_request(read_req(&granted.join("swap/f")), &roots) - { - let data = - base64::Engine::decode(&base64::engine::general_purpose::STANDARD, data_b64) - .unwrap(); - assert_eq!(data, b"inside", "a read left the directory"); - inside += 1; + let (mut inside, mut refused) = (0, 0); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20); + while (inside < 50 || refused < 50) && std::time::Instant::now() < deadline { + match handle_request(read_req(&granted.join("swap/f")), &roots) { + Response::OkData { data_b64 } => { + let data = base64::Engine::decode( + &base64::engine::general_purpose::STANDARD, + data_b64, + ) + .unwrap(); + assert_eq!(data, b"inside", "a read left the directory"); + inside += 1; + } + Response::Err { error } if error.contains("leads out") => refused += 1, + _ => {} } let _ = handle_request(write_req(&granted.join("swap/f"), b"inside"), &roots); } stop.store(true, std::sync::atomic::Ordering::Relaxed); swapper.join().unwrap(); assert_eq!(fs::read(dir.join("outside/f")).unwrap(), b"secret"); - assert!(inside > 0, "the race never resolved inside"); + assert!( + inside >= 50 && refused >= 50, + "the race was not exercised: {inside} reads inside, {refused} refused" + ); let _ = fs::remove_dir_all(&dir); } @@ -720,7 +745,7 @@ mod tests { let serve = std::thread::spawn(move || handle_connection(server, &roots)); let mut writer = client.try_clone().unwrap(); let sent = std::thread::spawn(move || { - let _ = writer.write_all(&vec![b'x'; MAX_LINE + 2]); + let _ = writer.write_all(&vec![b'x'; MAX_LINE + 64]); }); let mut reply = String::new(); BufReader::new(client).read_line(&mut reply).unwrap(); diff --git a/docs/security.md b/docs/security.md index ca04299..a69ddde 100644 --- a/docs/security.md +++ b/docs/security.md @@ -16,7 +16,7 @@ Each app session runs as a separate OS process (`weft-runtime`). When systemd is ## Filesystem Isolation -Apps access the filesystem only through WASI preopened directories. Each capability maps to a specific host path preopened at a fixed guest path. The `weft-file-portal` process applies the same directory grants and access modes. It opens each granted directory once and resolves every request beneath that descriptor with `openat2(RESOLVE_BENEATH)`, so the kernel keeps the operation inside the directory: `..` and links pointing outside are refused, also when a link is swapped in while the operation runs; links that stay inside are followed. This needs Linux 5.6 or later; without `openat2` every operation fails. Requests must name an absolute path without `.`, `..` or empty components; files are limited to 16 MiB, listings to 10,000 entries, requests to one line of about 22 MiB, and the portal to 4 connections at a time, each closed after 60 seconds without a request. Writes replace a file atomically, keeping its permission bits but not its owner, extended attributes or hard links (a write to a name that is a link replaces the link), and never create directories. A granted directory that cannot be opened when the portal starts is not served. Components cannot currently reach its socket, since the runtime grants them no socket access, and the socket's path is not passed to them. +Apps access the filesystem only through WASI preopened directories. Each capability maps to a specific host path preopened at a fixed guest path. The `weft-file-portal` process applies the same directory grants and access modes. It opens each granted directory once and resolves every request beneath that descriptor with `openat2(RESOLVE_BENEATH)`, so the kernel keeps the operation inside the directory: `..` and links pointing outside are refused, also when a link is swapped in while the operation runs; links that stay inside are followed. This needs Linux 5.6 or later; without `openat2` every operation fails. Requests must name an absolute path without `.`, `..` or empty components; files are limited to 16 MiB, listings to 10,000 entries, requests to one line of about 22 MiB, and the portal to 4 connections at a time, each closed when it sends or accepts no data for 60 seconds. Writes replace a file atomically, keeping its permission bits but not its owner, extended attributes or hard links (a write to a name that is a link replaces the link), and never create directories. A granted directory that cannot be opened when the portal starts is not served. Components cannot currently reach its socket, since the runtime grants them no socket access, and the socket's path is not passed to them. ## Package Signing From 0f4fafe701e6a439056fd6a6456d6c1fb7bf5088 Mon Sep 17 00:00:00 2001 From: Marco Allegretti Date: Fri, 9 Oct 2026 19:00:54 +0000 Subject: [PATCH 5/5] test(portal): point the relative escape link at the planted directory The relative link in the race test climbed one level too high, so it pointed at a directory that does not exist and could not catch a read that left the granted directory. --- crates/weft-file-portal/src/main.rs | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/crates/weft-file-portal/src/main.rs b/crates/weft-file-portal/src/main.rs index ecbace2..5becfcb 100644 --- a/crates/weft-file-portal/src/main.rs +++ b/crates/weft-file-portal/src/main.rs @@ -385,7 +385,8 @@ fn write(root: &Root, rest: &Path, data: &[u8]) -> Result { .map_err(Response::err)?; static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); // Unique within this portal by the counter, and across restarts by the - // start time, so a file left by an earlier instance does not collide. + // time of its first write, so a file left by an earlier instance does + // not collide. static STARTED: std::sync::OnceLock = std::sync::OnceLock::new(); let started = STARTED.get_or_init(|| { std::time::SystemTime::now() @@ -620,11 +621,7 @@ mod tests { let swapper = { let (granted, outside, stop) = (granted.clone(), dir.join("outside"), stop.clone()); std::thread::spawn(move || { - let targets = [ - PathBuf::from("real"), - outside, - PathBuf::from("../../outside"), - ]; + let targets = [PathBuf::from("real"), outside, PathBuf::from("../outside")]; for target in targets.iter().cycle() { if stop.load(std::sync::atomic::Ordering::Relaxed) { break;