A lightweight WebAssembly runtime that is fast, secure, and standards-compliant
wasi: don't follow a trailing-slash symlink in `rename` (#14729)
Alex Crichtond7a44f54e4f7
diff --git a/crates/test-programs/src/bin/p1_path_rename_trailing_slashes.rs b/crates/test-programs/src/bin/p1_path_rename_trailing_slashes.rsnew file mode 100644index 0000000000..7f08d3eb83--- /dev/null+++ b/crates/test-programs/src/bin/p1_path_rename_trailing_slashes.rs@@ -0,0 +1,66 @@+use std::process;+use test_programs::preview1::{config, create_file, open_scratch_directory};++unsafe fn assert_not_directory(dir_fd: wasip1::Fd, old_path: &str, new_path: &str) {+ let err = match unsafe { wasip1::path_rename(dir_fd, old_path, dir_fd, new_path) } {+ Ok(()) => panic!("renaming {old_path:?} to {new_path:?} should fail"),+ Err(err) => err,+ };+ assert_eq!(+ err,+ wasip1::ERRNO_NOTDIR,+ "unexpected error renaming {old_path:?} to {new_path:?}"+ );+}++unsafe fn test_path_rename_trailing_slashes(dir_fd: wasip1::Fd) {+ unsafe {+ // A symlink to a directory outside of the preopen with a trailing+ // slash on either path isn't followed, so the directory isn't moved+ // into the preopen. The host checks that it's still in place. Windows+ // can't create such a symlink in the first place.+ match wasip1::path_symlink("../outside", dir_fd, "up") {+ Ok(()) => {+ assert_not_directory(dir_fd, "up/", "stolen");+ assert_not_directory(dir_fd, "up", "stolen/");+ wasip1::path_unlink_file(dir_fd, "up").expect("removing a symlink");+ }+ Err(wasip1::ERRNO_PERM) if config().errno_expect_windows() => {}+ Err(err) => panic!("creating a symlink: {err:?}"),+ }++ // A symlink to a directory inside of the preopen with a trailing slash+ // on either path isn't followed either.+ wasip1::path_create_directory(dir_fd, "dir").expect("creating a directory");+ wasip1::path_symlink("dir", dir_fd, "link").expect("creating a symlink");+ assert_not_directory(dir_fd, "link/", "target");+ assert_not_directory(dir_fd, "link", "target/");+ wasip1::path_filestat_get(dir_fd, 0, "dir").expect("the directory wasn't renamed");+ wasip1::path_filestat_get(dir_fd, 0, "link").expect("the symlink wasn't renamed");+ wasip1::path_unlink_file(dir_fd, "link").expect("removing a symlink");+ wasip1::path_rename(dir_fd, "dir/", dir_fd, "renamed/").expect("renaming a directory");+ wasip1::path_remove_directory(dir_fd, "renamed").expect("removing a directory");++ // A file with a trailing slash on either path isn't a directory.+ create_file(dir_fd, "file");+ assert_not_directory(dir_fd, "file/", "target");+ assert_not_directory(dir_fd, "file", "target/");+ wasip1::path_filestat_get(dir_fd, 0, "file").expect("the file wasn't renamed");+ wasip1::path_unlink_file(dir_fd, "file").expect("removing a file");+ }+}++fn main() {+ // This test program requires a preopen at the path "sandbox", next to an+ // "outside" directory which isn't preopened.+ let dir_fd = match open_scratch_directory("sandbox") {+ Ok(dir_fd) => dir_fd,+ Err(err) => {+ eprintln!("failed to open sandbox preopen: {err}");+ process::exit(1)+ }+ };++ // Run the tests.+ unsafe { test_path_rename_trailing_slashes(dir_fd) }+}diff --git a/crates/test-programs/src/bin/p2_path_rename_dir_trailing_slashes.rs b/crates/test-programs/src/bin/p2_path_rename_dir_trailing_slashes.rsdeleted file mode 100644index 46e92609c5..0000000000--- a/crates/test-programs/src/bin/p2_path_rename_dir_trailing_slashes.rs+++ /dev/null@@ -1,26 +0,0 @@-use wasip2::filesystem::preopens::get_directories;-use wasip2::filesystem::types::Descriptor;--fn test_path_rename_trailing_slashes(dir: &Descriptor) {- // Test renaming a directory with a trailing slash in the name.- dir.create_directory_at("source")- .expect("creating a directory");- dir.rename_at("source/", dir, "target")- .expect("renaming a directory with a trailing slash in the source name");- dir.rename_at("target", dir, "source/")- .expect("renaming a directory with a trailing slash in the destination name");- dir.rename_at("source/", dir, "target/")- .expect("renaming a directory with a trailing slash in the source and destination names");- dir.rename_at("target", dir, "source")- .expect("renaming a directory with no trailing slashes at all should work");- dir.remove_directory_at("source")- .expect("removing the directory");-}--fn main() {- let preopens = get_directories();- let (dir, _name) = &preopens[0];-- // Run the tests.- test_path_rename_trailing_slashes(dir)-}diff --git a/crates/test-programs/src/bin/p2_path_rename_trailing_slashes.rs b/crates/test-programs/src/bin/p2_path_rename_trailing_slashes.rsnew file mode 100644index 0000000000..77ae0aa073--- /dev/null+++ b/crates/test-programs/src/bin/p2_path_rename_trailing_slashes.rs@@ -0,0 +1,86 @@+use test_programs::preview1::config;+use wasip2::filesystem::preopens::get_directories;+use wasip2::filesystem::types::{Descriptor, DescriptorFlags, ErrorCode, OpenFlags, PathFlags};++fn assert_not_directory(dir: &Descriptor, old_path: &str, new_path: &str) {+ let err = match dir.rename_at(old_path, dir, new_path) {+ Ok(()) => panic!("renaming {old_path:?} to {new_path:?} should fail"),+ Err(err) => err,+ };+ assert!(+ matches!(err, ErrorCode::NotDirectory),+ "unexpected error {err:?} renaming {old_path:?} to {new_path:?}"+ );+}++fn test_path_rename_trailing_slashes(dir: &Descriptor) {+ // A directory with a trailing slash on either path is renamed.+ dir.create_directory_at("source")+ .expect("creating a directory");+ dir.rename_at("source/", dir, "target")+ .expect("renaming a directory with a trailing slash in the source name");+ dir.rename_at("target", dir, "source/")+ .expect("renaming a directory with a trailing slash in the destination name");+ dir.rename_at("source/", dir, "target/")+ .expect("renaming a directory with a trailing slash in the source and destination names");+ dir.rename_at("target", dir, "source")+ .expect("renaming a directory with no trailing slashes at all should work");+ dir.remove_directory_at("source")+ .expect("removing the directory");++ // A symlink to a directory outside of the preopen with a trailing slash on+ // either path isn't followed, so the directory isn't moved into the+ // preopen. The host checks that it's still in place. Windows can't create+ // such a symlink in the first place.+ match dir.symlink_at("../outside", "up") {+ Ok(()) => {+ assert_not_directory(dir, "up/", "stolen");+ assert_not_directory(dir, "up", "stolen/");+ dir.unlink_file_at("up").expect("removing a symlink");+ }+ Err(ErrorCode::NotPermitted) if config().errno_expect_windows() => {}+ Err(err) => panic!("creating a symlink: {err:?}"),+ }++ // A symlink to a directory inside of the preopen with a trailing slash on+ // either path isn't followed either.+ dir.create_directory_at("dir")+ .expect("creating a directory");+ dir.symlink_at("dir", "link").expect("creating a symlink");+ assert_not_directory(dir, "link/", "target");+ assert_not_directory(dir, "link", "target/");+ dir.stat_at(PathFlags::empty(), "dir")+ .expect("the directory wasn't renamed");+ dir.stat_at(PathFlags::empty(), "link")+ .expect("the symlink wasn't renamed");+ dir.unlink_file_at("link").expect("removing a symlink");+ dir.remove_directory_at("dir")+ .expect("removing a directory");++ // A file with a trailing slash on either path isn't a directory.+ dir.open_at(+ PathFlags::empty(),+ "file",+ OpenFlags::CREATE,+ DescriptorFlags::empty(),+ )+ .expect("creating a file");+ assert_not_directory(dir, "file/", "target");+ assert_not_directory(dir, "file", "target/");+ dir.stat_at(PathFlags::empty(), "file")+ .expect("the file wasn't renamed");+ dir.unlink_file_at("file").expect("removing a file");+}++fn main() {+ // This test program requires a preopen at the path "sandbox", next to an+ // "outside" directory which isn't preopened.+ let preopens = get_directories();+ let (dir, _) = preopens+ .iter()+ .find(|(_, path)| path == "sandbox")+ .expect("find preopen named sandbox");++ // Run the tests.+ test_path_rename_trailing_slashes(dir)+}diff --git a/crates/test-programs/src/bin/p3_path_rename_trailing_slashes.rs b/crates/test-programs/src/bin/p3_path_rename_trailing_slashes.rsnew file mode 100644index 0000000000..f31a55c27a--- /dev/null+++ b/crates/test-programs/src/bin/p3_path_rename_trailing_slashes.rs@@ -0,0 +1,107 @@+use test_programs::p3::wasi;+use test_programs::p3::wasi::filesystem::types::{+ Descriptor, DescriptorFlags, ErrorCode, OpenFlags, PathFlags,+};+use test_programs::preview1::config;++struct Component;++test_programs::p3::export!(Component);++impl test_programs::p3::exports::wasi::cli::run::Guest for Component {+ async fn run() -> Result<(), ()> {+ // This test program requires a preopen at the path "sandbox", next to+ // an "outside" directory which isn't preopened.+ let preopens = wasi::filesystem::preopens::get_directories();+ let (dir, _) = preopens+ .iter()+ .find(|(_, path)| path == "sandbox")+ .expect("find preopen named sandbox");++ test_path_rename_trailing_slashes(dir).await;+ Ok(())+ }+}++fn main() {+ unreachable!()+}++async fn assert_not_directory(dir: &Descriptor, old_path: &str, new_path: &str) {+ let err = match dir+ .rename_at(old_path.to_string(), dir, new_path.to_string())+ .await+ {+ Ok(()) => panic!("renaming {old_path:?} to {new_path:?} should fail"),+ Err(err) => err,+ };+ assert!(+ matches!(err, ErrorCode::NotDirectory),+ "unexpected error {err:?} renaming {old_path:?} to {new_path:?}"+ );+}++async fn test_path_rename_trailing_slashes(dir: &Descriptor) {+ // A symlink to a directory outside of the preopen with a trailing slash on+ // either path isn't followed, so the directory isn't moved into the+ // preopen. The host checks that it's still in place. Windows can't create+ // such a symlink in the first place.+ match dir+ .symlink_at("../outside".to_string(), "up".to_string())+ .await+ {+ Ok(()) => {+ assert_not_directory(dir, "up/", "stolen").await;+ assert_not_directory(dir, "up", "stolen/").await;+ dir.unlink_file_at("up".to_string())+ .await+ .expect("removing a symlink");+ }+ Err(ErrorCode::NotPermitted) if config().errno_expect_windows() => {}+ Err(err) => panic!("creating a symlink: {err:?}"),+ }++ // A symlink to a directory inside of the preopen with a trailing slash on+ // either path isn't followed either.+ dir.create_directory_at("dir".to_string())+ .await+ .expect("creating a directory");+ dir.symlink_at("dir".to_string(), "link".to_string())+ .await+ .expect("creating a symlink");+ assert_not_directory(dir, "link/", "target").await;+ assert_not_directory(dir, "link", "target/").await;+ dir.stat_at(PathFlags::empty(), "dir".to_string())+ .await+ .expect("the directory wasn't renamed");+ dir.stat_at(PathFlags::empty(), "link".to_string())+ .await+ .expect("the symlink wasn't renamed");+ dir.unlink_file_at("link".to_string())+ .await+ .expect("removing a symlink");+ dir.rename_at("dir/".to_string(), dir, "renamed/".to_string())+ .await+ .expect("renaming a directory");+ dir.remove_directory_at("renamed".to_string())+ .await+ .expect("removing a directory");++ // A file with a trailing slash on either path isn't a directory.+ dir.open_at(+ PathFlags::empty(),+ "file".to_string(),+ OpenFlags::CREATE,+ DescriptorFlags::empty(),+ )+ .await+ .expect("creating a file");+ assert_not_directory(dir, "file/", "target").await;+ assert_not_directory(dir, "file", "target/").await;+ dir.stat_at(PathFlags::empty(), "file".to_string())+ .await+ .expect("the file wasn't renamed");+ dir.unlink_file_at("file".to_string())+ .await+ .expect("removing a file");+}diff --git a/crates/wasi/src/filesystem/primitives/mod.rs b/crates/wasi/src/filesystem/primitives/mod.rsindex c57ea17ce6..2d1937f931 100644--- a/crates/wasi/src/filesystem/primitives/mod.rs+++ b/crates/wasi/src/filesystem/primitives/mod.rs@@ -244,27 +244,43 @@ pub(crate) fn rename(// it as equivalent to a trailing slash-dot, so strip any trailing slashes// for the purposes of `open_parent`.//- // And on Unix, remember whether the source started with a slash so that we- // can still fail if it is and the source is a regular file.- #[cfg(unix)]- let old_starts_with_slash = path_has_trailing_slash(old_path);+ // And remember whether either path ended with a slash so that we can still+ // fail if the source isn't a directory.+ let requires_dir = path_has_trailing_slash(old_path) || path_has_trailing_slash(new_path);let old_path = strip_dir_suffix(old_path);let new_path = strip_dir_suffix(new_path);let (old_dir, old_basename) = open_parent(old_start, &old_path)?;let (new_dir, new_basename) = open_parent(new_start, &new_path)?;- // On Unix, re-append a slash if needed.- #[cfg(unix)]- let concat;- #[cfg(unix)]- let old_basename = if old_starts_with_slash {- concat = append_dir_suffix(old_basename.to_owned().into());+ // A trailing slash on either path requires the source to be a directory.+ //+ // On Linux, re-append a slash to the source and let the kernel check that+ // atomically with the rename. Linux never follows a symlink named with a+ // trailing slash in `renameat` and fails with `ENOTDIR` instead.+ #[cfg(target_os = "linux")]+ let mut concat;+ #[cfg(target_os = "linux")]+ let old_basename = if requires_dir {+ concat = old_basename.to_owned();+ concat.push("/");concat.as_os_str()} else {old_basename};+ // Elsewhere, such as on macOS and FreeBSD, `renameat` follows a symlink+ // named with a trailing slash. Check without following symlinks and rename+ // by the plain names instead, so such a symlink is never followed out of+ // `old_start`. The check isn't atomic with the rename, but whatever+ // replaces the source in between is still renamed by its plain name.+ #[cfg(not(target_os = "linux"))]+ if requires_dir+ && !stat_unchecked(&old_dir, Path::new(old_basename), FollowSymlinks::No)?.is_dir()+ {+ return Err(errors::is_not_directory());+ }+rename_unchecked(&old_dir,old_basename.as_ref(),diff --git a/crates/wasi/src/filesystem/primitives/unix/dir_utils.rs b/crates/wasi/src/filesystem/primitives/unix/dir_utils.rsindex 2e144b32a2..a7f5f34094 100644--- a/crates/wasi/src/filesystem/primitives/unix/dir_utils.rs+++ b/crates/wasi/src/filesystem/primitives/unix/dir_utils.rs@@ -1,18 +1,12 @@use crate::filesystem::primitives::OpenOptions;use rustix::fs::OFlags;-use std::ffi::{OsStr, OsString};+use std::ffi::OsStr;use std::ops::Deref;#[cfg(unix)]-use std::os::unix::{- ffi::{OsStrExt, OsStringExt},- fs::OpenOptionsExt,-};+use std::os::unix::{ffi::OsStrExt, fs::OpenOptionsExt};#[cfg(target_os = "wasi")]-use std::os::wasi::{- ffi::{OsStrExt, OsStringExt},- fs::OpenOptionsExt,-};-use std::path::{Path, PathBuf};+use std::os::wasi::{ffi::OsStrExt, fs::OpenOptionsExt};+use std::path::Path;use std::{fs, io};/// Rust's `Path` implicitly strips redundant slashes, however they aren't@@ -54,14 +48,6 @@ pub(crate) fn path_has_trailing_slash(path: &Path) -> bool {bytes.ends_with(b"/")}-/// Append a trailing `/`. This can be used to require that the given `path`-/// names a directory.-pub(crate) fn append_dir_suffix(path: PathBuf) -> PathBuf {- let mut bytes = path.into_os_string().into_vec();- bytes.push(b'/');- OsString::from_vec(bytes).into()-}-/// Strip trailing `/`s, unless this reduces `path` to `/` itself. This is/// used by `create_dir` and others to prevent paths like `foo/` from/// canonicalizing to `foo/.` since these syscalls treat these differently.diff --git a/crates/wasi/tests/all/p1.rs b/crates/wasi/tests/all/p1.rsindex ebaaf1f39c..d4cbdd6ec8 100644--- a/crates/wasi/tests/all/p1.rs+++ b/crates/wasi/tests/all/p1.rs@@ -89,6 +89,18 @@ async fn p1_poll_oneoff_files() {async fn p1_readlink() {run(P1_READLINK, |_| {}).await.unwrap()}++#[test_log::test(tokio::test(flavor = "multi_thread"))]+async fn p1_path_rename_trailing_slashes() {+ let fixture = crate::store::SandboxFixture::new().unwrap();+ run(P1_PATH_RENAME_TRAILING_SLASHES, |b| {+ fixture.configure_wasi(b)+ })+ .await+ .expect("run guest");+ fixture.assert_secure();+}+#[test_log::test(tokio::test(flavor = "multi_thread"))]async fn p1_renumber() {run(P1_RENUMBER, |_| {}).await.unwrap()diff --git a/crates/wasi/tests/all/p2/async_.rs b/crates/wasi/tests/all/p2/async_.rsindex fb196faaf8..408616c87e 100644--- a/crates/wasi/tests/all/p2/async_.rs+++ b/crates/wasi/tests/all/p2/async_.rs@@ -93,6 +93,18 @@ async fn p1_poll_oneoff_files() {async fn p1_readlink() {run(P1_READLINK_COMPONENT, |_| {}).await.unwrap()}++#[test_log::test(tokio::test(flavor = "multi_thread"))]+async fn p1_path_rename_trailing_slashes() {+ let fixture = crate::store::SandboxFixture::new().unwrap();+ run(P1_PATH_RENAME_TRAILING_SLASHES_COMPONENT, |b| {+ fixture.configure_wasi(b)+ })+ .await+ .expect("run guest");+ fixture.assert_secure();+}+#[test_log::test(tokio::test(flavor = "multi_thread"))]async fn p1_renumber() {run(P1_RENUMBER_COMPONENT, |_| {}).await.unwrap()@@ -280,12 +292,18 @@ async fn p2_path_open_create_existing() {async fn p2_path_open_missing() {run(P2_PATH_OPEN_MISSING_COMPONENT, |_| {}).await.unwrap()}+#[test_log::test(tokio::test(flavor = "multi_thread"))]-async fn p2_path_rename_dir_trailing_slashes() {- run(P2_PATH_RENAME_DIR_TRAILING_SLASHES_COMPONENT, |_| {})- .await- .unwrap()+async fn p2_path_rename_trailing_slashes() {+ let fixture = crate::store::SandboxFixture::new().unwrap();+ run(P2_PATH_RENAME_TRAILING_SLASHES_COMPONENT, |b| {+ fixture.configure_wasi(b)+ })+ .await+ .expect("run guest");+ fixture.assert_secure();}+#[test_log::test(tokio::test(flavor = "multi_thread"))]async fn p2_remove_nonempty_directory() {run(P2_REMOVE_NONEMPTY_DIRECTORY_COMPONENT, |_| {})diff --git a/crates/wasi/tests/all/p2/sync.rs b/crates/wasi/tests/all/p2/sync.rsindex cf65ce8f0c..9eb34b00f2 100644--- a/crates/wasi/tests/all/p2/sync.rs+++ b/crates/wasi/tests/all/p2/sync.rs@@ -94,6 +94,17 @@ fn p1_poll_oneoff_files() {fn p1_readlink() {run(P1_READLINK_COMPONENT, |_| {}).unwrap()}++#[test_log::test]+fn p1_path_rename_trailing_slashes() {+ let fixture = crate::store::SandboxFixture::new().unwrap();+ run(P1_PATH_RENAME_TRAILING_SLASHES_COMPONENT, |b| {+ fixture.configure_wasi(b)+ })+ .expect("run guest");+ fixture.assert_secure();+}+#[test_log::test]fn p1_renumber() {run(P1_RENUMBER_COMPONENT, |_| {}).unwrap()@@ -271,10 +282,17 @@ fn p2_path_open_create_existing() {fn p2_path_open_missing() {run(P2_PATH_OPEN_MISSING_COMPONENT, |_| {}).unwrap()}+#[test_log::test]-fn p2_path_rename_dir_trailing_slashes() {- run(P2_PATH_RENAME_DIR_TRAILING_SLASHES_COMPONENT, |_| {}).unwrap()+fn p2_path_rename_trailing_slashes() {+ let fixture = crate::store::SandboxFixture::new().unwrap();+ run(P2_PATH_RENAME_TRAILING_SLASHES_COMPONENT, |b| {+ fixture.configure_wasi(b)+ })+ .expect("run guest");+ fixture.assert_secure();}+#[test_log::test]fn p2_remove_nonempty_directory() {run(P2_REMOVE_NONEMPTY_DIRECTORY_COMPONENT, |_| {}).unwrap()diff --git a/crates/wasi/tests/all/p3/mod.rs b/crates/wasi/tests/all/p3/mod.rsindex a14cc6e696..13b85ea516 100644--- a/crates/wasi/tests/all/p3/mod.rs+++ b/crates/wasi/tests/all/p3/mod.rs@@ -228,6 +228,17 @@ async fn p3_readdir_blocking() -> wasmtime::Result<()> {run_allow_blocking_current_thread(P3_READDIR_COMPONENT, true).await}+#[test_log::test(tokio::test(flavor = "multi_thread"))]+async fn p3_path_rename_trailing_slashes() -> wasmtime::Result<()> {+ let fixture = crate::store::SandboxFixture::new()?;+ run_with_builder(P3_PATH_RENAME_TRAILING_SLASHES_COMPONENT, false, |b| {+ fixture.configure_wasi(b)+ })+ .await?;+ fixture.assert_secure();+ Ok(())+}+#[test_log::test(tokio::test(flavor = "multi_thread"))]async fn p3_file_write() -> wasmtime::Result<()> {run(P3_FILE_WRITE_COMPONENT).awaitdiff --git a/crates/wasi/tests/all/store.rs b/crates/wasi/tests/all/store.rsindex afd06ebe42..d9ef26606d 100644--- a/crates/wasi/tests/all/store.rs+++ b/crates/wasi/tests/all/store.rs@@ -148,3 +148,40 @@ pub fn prepare_extreme_mtime_fixture(dir: &std::path::Path) -> Result<()> {let _ = f.set_times(times);Ok(())}++/// A `sandbox` directory to preopen next to an `outside` directory which isn't+/// preopened, for checking that the guest can't move `outside` into `sandbox`.+pub struct SandboxFixture {+ tempdir: TempDir,+}++impl SandboxFixture {+ pub fn new() -> Result<Self> {+ let tempdir = prepare_workspace("sandbox")?;+ std::fs::create_dir(tempdir.path().join("sandbox"))?;+ std::fs::create_dir(tempdir.path().join("outside"))?;+ std::fs::write(tempdir.path().join("outside/secret"), b"secret\n")?;+ Ok(Self { tempdir })+ }++ pub fn configure_wasi(&self, builder: &mut WasiCtxBuilder) {+ builder+ .preopened_dir(+ self.tempdir.path().join("sandbox"),+ "sandbox",+ FsPerms::ReadWrite,+ )+ .unwrap();+ }++ pub fn assert_secure(&self) {+ assert!(+ self.tempdir.path().join("outside/secret").exists(),+ "`outside` was moved out of place"+ );+ assert!(+ !self.tempdir.path().join("sandbox/stolen").exists(),+ "`outside` was moved into the sandbox"+ );+ }+}