//! The installation target root. //! //! Host-versus-target path bugs are treated as HIGH SEVERITY. `TargetRoot` //! makes it impossible to accidentally write to the host through the normal //! APIs: every path is relative, must not be absolute, must not contain `..`, //! and is joined to the root. use std::path::{Component, Path, PathBuf}; use crate::error::{CoreError, Result}; #[derive(Debug, Clone, PartialEq, Eq)] pub struct TargetRoot { root: PathBuf, } impl TargetRoot { pub fn new(root: impl Into) -> Self { Self { root: root.into() } } pub fn path(&self) -> &Path { &self.root } /// Resolve a relative path beneath the target root. /// /// Rejects absolute paths, `..` traversal and `~`-style components. An /// empty relative path resolves to the root itself. pub fn resolve(&self, relative: &str) -> Result { let rel = Path::new(relative.trim_start_matches('/')); for component in rel.components() { match component { Component::ParentDir => { return Err(CoreError::Validation(format!( "target path must not contain `..`: {relative}" ))); } Component::RootDir | Component::Prefix(_) => { return Err(CoreError::Validation(format!( "target path must be relative: {relative}" ))); } _ => {} } } Ok(self.root.join(rel)) } /// Shorthand for an absolute target path, e.g. `target.path_for("/etc/fstab")`. pub fn path_for(&self, absolute: &str) -> Result { self.resolve(absolute) } pub fn etc(&self, relative: &str) -> Result { self.resolve(&format!("etc/{relative}")) } pub fn var(&self, relative: &str) -> Result { self.resolve(&format!("var/{relative}")) } pub fn boot(&self, relative: &str) -> Result { self.resolve(&format!("boot/{relative}")) } pub fn home(&self, relative: &str) -> Result { self.resolve(&format!("home/{relative}")) } /// Refuse to traverse a symlink while writing beneath the target root. /// /// A freshly installed target is created by the installer, but a stage3 /// archive (or a later, less careful writer) could leave a symlink whose /// target lies outside the root. Following it would write to the host. The /// write path therefore rejects symlinked components instead of resolving /// them. fn reject_symlink_components(&self, relative: &str) -> Result<()> { let rel = Path::new(relative.trim_start_matches('/')); let mut current = self.root.clone(); for component in rel.components() { if let Component::Normal(part) = component { current.push(part); if let Ok(meta) = std::fs::symlink_metadata(¤t) { if meta.file_type().is_symlink() { return Err(CoreError::Validation(format!( "refusing to write through a symlink inside the target: {}", current.display() ))); } } } } Ok(()) } pub fn ensure_dir(&self, relative: &str) -> Result { self.reject_symlink_components(relative)?; let path = self.resolve(relative)?; std::fs::create_dir_all(&path).map_err(|e| CoreError::io(path.clone(), e))?; Ok(path) } /// Create a directory with an explicit mode (on Unix). pub fn ensure_dir_mode(&self, relative: &str, mode: u32) -> Result { use std::os::unix::fs::PermissionsExt; let path = self.ensure_dir(relative)?; let perms = std::fs::Permissions::from_mode(mode); std::fs::set_permissions(&path, perms).map_err(|e| CoreError::io(path.clone(), e))?; Ok(path) } pub fn write(&self, relative: &str, contents: impl AsRef<[u8]>) -> Result { self.reject_symlink_components(relative)?; let path = self.resolve(relative)?; if let Some(parent) = path.parent() { std::fs::create_dir_all(parent).map_err(|e| CoreError::io(parent.to_path_buf(), e))?; } std::fs::write(&path, contents).map_err(|e| CoreError::io(path.clone(), e))?; Ok(path) } pub fn read_to_string(&self, relative: &str) -> Result { let path = self.resolve(relative)?; std::fs::read_to_string(&path).map_err(|e| CoreError::io(path, e)) } pub fn exists(&self, relative: &str) -> bool { self.resolve(relative).map(|p| p.exists()).unwrap_or(false) } } #[cfg(test)] mod tests { use super::*; #[test] fn resolves_relative_paths() { let t = TargetRoot::new("/mnt/phoebus"); assert_eq!( t.resolve("etc/fstab").unwrap(), PathBuf::from("/mnt/phoebus/etc/fstab") ); assert_eq!( t.etc("crypttab").unwrap(), PathBuf::from("/mnt/phoebus/etc/crypttab") ); assert_eq!(t.var("tmp").unwrap(), PathBuf::from("/mnt/phoebus/var/tmp")); // Leading slashes are stripped so callers may pass absolute-looking paths. assert_eq!( t.resolve("/etc/hosts").unwrap(), PathBuf::from("/mnt/phoebus/etc/hosts") ); } #[test] fn rejects_parent_traversal() { let t = TargetRoot::new("/mnt/phoebus"); assert!(t.resolve("../../etc/fstab").is_err()); assert!(t.resolve("etc/../../etc/fstab").is_err()); } #[test] fn writes_stay_inside_root() { let dir = tempfile::tempdir().unwrap(); let t = TargetRoot::new(dir.path()); let p = t.write("etc/fstab", "hello").unwrap(); assert!(p.starts_with(dir.path())); assert_eq!(t.read_to_string("etc/fstab").unwrap(), "hello"); } #[test] fn refuses_to_write_through_an_escaping_symlink() { let dir = tempfile::tempdir().unwrap(); let outside = tempfile::tempdir().unwrap(); let t = TargetRoot::new(dir.path()); std::os::unix::fs::symlink(outside.path(), dir.path().join("evil")).unwrap(); let err = t.write("evil/pwned", "owned").unwrap_err(); assert!( matches!(err, CoreError::Validation(_)), "expected a validation refusal, got {err:?}" ); assert!( !outside.path().join("pwned").exists(), "the write escaped the target root" ); // ensure_dir must refuse too. assert!(t.ensure_dir("evil/subdir").is_err()); } #[test] fn refuses_a_symlinked_leaf() { let dir = tempfile::tempdir().unwrap(); let outside = tempfile::tempdir().unwrap(); std::fs::write(outside.path().join("target"), "original").unwrap(); let t = TargetRoot::new(dir.path()); std::fs::create_dir_all(dir.path().join("etc")).unwrap(); std::os::unix::fs::symlink(outside.path().join("target"), dir.path().join("etc/passwd")) .unwrap(); assert!(t.write("etc/passwd", "overwritten").is_err()); assert_eq!( std::fs::read_to_string(outside.path().join("target")).unwrap(), "original" ); } }