Skip to main content

aev_vm/
paths.rs

1//! XDG-aware persistent and runtime paths.
2
3use std::env;
4use std::fs;
5use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt};
6use std::path::{Component, Path, PathBuf};
7
8use anyhow::{Context, Result, bail};
9
10use crate::config::validate_name;
11
12/// All filesystem roots used by `KnottVM`.
13#[derive(Debug, Clone)]
14pub struct AppPaths {
15    /// Directory containing VM definitions.
16    pub config_root: PathBuf,
17    /// Directory containing disk and firmware state.
18    pub data_root: PathBuf,
19    /// Directory containing ephemeral sockets and process state.
20    pub runtime_root: PathBuf,
21    runtime_base: Option<PathBuf>,
22    fallback_runtime_base: bool,
23}
24
25impl AppPaths {
26    /// Resolve roots from the XDG environment.
27    pub fn discover() -> Result<Self> {
28        let home = env::var_os("HOME")
29            .map(PathBuf::from)
30            .context("HOME is not set and XDG paths cannot be resolved")?;
31        let config_default = home.join(".config");
32        let data_default = home.join(".local/share");
33        let config_home =
34            resolve_xdg_home(env::var_os("XDG_CONFIG_HOME").as_deref(), &config_default);
35        let data_home = resolve_xdg_home(env::var_os("XDG_DATA_HOME").as_deref(), &data_default);
36        let (runtime_base, fallback_runtime_base) =
37            if let Some(path) = env::var_os("XDG_RUNTIME_DIR") {
38                let path = require_absolute_runtime_dir(PathBuf::from(path))?;
39                (
40                    fs::canonicalize(path)
41                        .context("XDG_RUNTIME_DIR must name an existing directory")?,
42                    false,
43                )
44            } else {
45                // SAFETY: geteuid has no preconditions and does not access memory.
46                let uid = unsafe { libc::geteuid() };
47                (PathBuf::from(format!("/tmp/knottvm-{uid}")), true)
48            };
49        Ok(Self {
50            config_root: config_home.join("knottvm/vms"),
51            data_root: data_home.join("knottvm/vms"),
52            runtime_root: runtime_base.join("knottvm"),
53            runtime_base: Some(runtime_base),
54            fallback_runtime_base,
55        })
56    }
57
58    /// Construct explicit roots, primarily for isolated tests.
59    #[must_use]
60    pub const fn new(config_root: PathBuf, data_root: PathBuf, runtime_root: PathBuf) -> Self {
61        Self {
62            config_root,
63            data_root,
64            runtime_root,
65            runtime_base: None,
66            fallback_runtime_base: false,
67        }
68    }
69
70    /// Create roots and enforce owner-only runtime access.
71    pub fn ensure(&self) -> Result<()> {
72        let runtime_base = self
73            .runtime_base
74            .as_deref()
75            .or_else(|| self.runtime_root.parent())
76            .context("runtime root must have a parent directory")?;
77        if self.fallback_runtime_base {
78            ensure_fallback_runtime_base(Path::new("/tmp"), runtime_base)?;
79        } else {
80            validate_runtime_base(runtime_base)?;
81        }
82        ensure_private_dir(&self.config_root)?;
83        ensure_private_dir(&self.data_root)?;
84        ensure_private_dir(&self.runtime_root)
85    }
86
87    /// Return a VM's TOML definition path.
88    pub fn config(&self, name: &str) -> Result<PathBuf> {
89        validate_name(name)?;
90        Ok(self.config_root.join(format!("{name}.toml")))
91    }
92
93    /// Return a VM's persistent data directory.
94    pub fn data(&self, name: &str) -> Result<PathBuf> {
95        validate_name(name)?;
96        Ok(self.data_root.join(name))
97    }
98
99    /// Return a VM's ephemeral runtime directory.
100    pub fn runtime(&self, name: &str) -> Result<PathBuf> {
101        validate_name(name)?;
102        Ok(self.runtime_root.join(name))
103    }
104}
105
106fn resolve_xdg_home(value: Option<&std::ffi::OsStr>, fallback: &Path) -> PathBuf {
107    value
108        .map(PathBuf::from)
109        .filter(|path| path.is_absolute())
110        .unwrap_or_else(|| fallback.to_path_buf())
111}
112
113fn require_absolute_runtime_dir(path: PathBuf) -> Result<PathBuf> {
114    if !path.is_absolute() {
115        bail!("XDG_RUNTIME_DIR must be an absolute path");
116    }
117    Ok(path)
118}
119
120fn ensure_fallback_runtime_base(tmp_root: &Path, runtime_base: &Path) -> Result<()> {
121    ensure_fallback_runtime_base_owned_by(tmp_root, runtime_base, system_root_uid()?)
122}
123
124fn ensure_fallback_runtime_base_owned_by(
125    tmp_root: &Path,
126    runtime_base: &Path,
127    trusted_tmp_owner: u32,
128) -> Result<()> {
129    // SAFETY: geteuid has no preconditions and does not access memory.
130    let uid = unsafe { libc::geteuid() };
131    let expected = tmp_root.join(format!("knottvm-{uid}"));
132    if runtime_base != expected {
133        bail!("fallback runtime path is not the expected per-user directory");
134    }
135    validate_sticky_tmp_root(tmp_root, trusted_tmp_owner)?;
136    match fs::DirBuilder::new().mode(0o700).create(runtime_base) {
137        Ok(()) => {}
138        Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
139        Err(error) => {
140            return Err(error).with_context(|| {
141                format!("failed to create runtime base {}", runtime_base.display())
142            });
143        }
144    }
145    validate_runtime_base(runtime_base)
146}
147
148fn validate_sticky_tmp_root(path: &Path, trusted_owner: u32) -> Result<()> {
149    let metadata = fs::symlink_metadata(path)
150        .with_context(|| format!("failed to inspect temporary root {}", path.display()))?;
151    let mode = metadata.mode() & 0o7777;
152    if !metadata.is_dir()
153        || metadata.file_type().is_symlink()
154        || metadata.uid() != trusted_owner
155        || mode & 0o1000 == 0
156    {
157        bail!(
158            "temporary root {} is not a trusted sticky directory",
159            path.display()
160        );
161    }
162    Ok(())
163}
164
165fn system_root_uid() -> Result<u32> {
166    fs::symlink_metadata("/")
167        .map(|metadata| metadata.uid())
168        .context("failed to inspect filesystem root owner")
169}
170
171/// Validate every directory in the runtime path so another UID cannot replace
172/// a protected leaf through a writable ancestor. Shared sticky roots such as
173/// `/tmp` are safe only when owned by root or this user.
174fn validate_runtime_base(path: &Path) -> Result<()> {
175    if !path.is_absolute() {
176        bail!("runtime base must be an absolute path");
177    }
178    // SAFETY: geteuid has no preconditions and does not access memory.
179    let uid = unsafe { libc::geteuid() };
180    let root_uid = system_root_uid()?;
181    let mut current = PathBuf::new();
182    for component in path.components() {
183        match component {
184            Component::RootDir => current.push(component.as_os_str()),
185            Component::Normal(name) => current.push(name),
186            Component::CurDir | Component::ParentDir | Component::Prefix(_) => {
187                bail!("runtime base must be canonical")
188            }
189        }
190        let metadata = fs::symlink_metadata(&current)
191            .with_context(|| format!("failed to inspect runtime ancestor {}", current.display()))?;
192        let mode = metadata.mode() & 0o7777;
193        if !metadata.is_dir() || metadata.file_type().is_symlink() {
194            bail!("runtime ancestor {} is not a directory", current.display());
195        }
196        if current == path {
197            if metadata.uid() != uid {
198                bail!("runtime base {} is owned by another user", path.display());
199            }
200            if mode & 0o022 != 0 {
201                bail!(
202                    "runtime base {} is writable by another user",
203                    path.display()
204                );
205            }
206            continue;
207        }
208        if metadata.uid() != root_uid && metadata.uid() != uid {
209            bail!(
210                "runtime ancestor {} is owned by another user",
211                current.display()
212            );
213        }
214        if mode & 0o022 != 0
215            && !(mode & 0o1000 != 0 && (metadata.uid() == root_uid || metadata.uid() == uid))
216        {
217            bail!(
218                "runtime ancestor {} can be replaced by another user",
219                current.display()
220            );
221        }
222    }
223    fs::set_permissions(path, fs::Permissions::from_mode(0o700))
224        .with_context(|| format!("failed to secure runtime base {}", path.display()))?;
225    Ok(())
226}
227
228/// Create a directory and reject roots owned by another user.
229pub fn ensure_private_dir(path: &Path) -> Result<()> {
230    fs::create_dir_all(path)
231        .with_context(|| format!("failed to create directory {}", path.display()))?;
232    let metadata = fs::symlink_metadata(path)
233        .with_context(|| format!("failed to inspect directory {}", path.display()))?;
234    if !metadata.is_dir() {
235        bail!("{} is not a directory", path.display());
236    }
237    // SAFETY: geteuid has no preconditions and does not access memory.
238    let uid = unsafe { libc::geteuid() };
239    if metadata.uid() != uid {
240        bail!("directory {} is owned by another user", path.display());
241    }
242    fs::set_permissions(path, fs::Permissions::from_mode(0o700))
243        .with_context(|| format!("failed to secure directory {}", path.display()))?;
244    Ok(())
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250    use std::ffi::OsStr;
251    use std::os::unix::fs::symlink;
252    use tempfile::tempdir;
253
254    fn sticky_tmp(root: &Path) -> PathBuf {
255        let path = root.join("tmp");
256        fs::create_dir(&path).unwrap();
257        fs::set_permissions(&path, fs::Permissions::from_mode(0o1777)).unwrap();
258        path
259    }
260
261    #[test]
262    fn relative_or_empty_persistent_xdg_homes_use_home_defaults() {
263        let config_default = Path::new("/home/test/.config");
264        let data_default = Path::new("/home/test/.local/share");
265        for value in [
266            None,
267            Some(OsStr::new("")),
268            Some(OsStr::new("relative/path")),
269        ] {
270            assert_eq!(resolve_xdg_home(value, config_default), config_default);
271            assert_eq!(resolve_xdg_home(value, data_default), data_default);
272        }
273        assert_eq!(
274            resolve_xdg_home(Some(OsStr::new("/tmp/config")), config_default),
275            Path::new("/tmp/config")
276        );
277        assert_eq!(
278            resolve_xdg_home(Some(OsStr::new("/tmp/data")), data_default),
279            Path::new("/tmp/data")
280        );
281    }
282
283    #[test]
284    fn relative_runtime_dir_is_rejected_before_canonicalization() {
285        let error =
286            require_absolute_runtime_dir(PathBuf::from("missing-relative-runtime")).unwrap_err();
287        assert!(
288            error
289                .to_string()
290                .contains("XDG_RUNTIME_DIR must be an absolute path")
291        );
292    }
293
294    #[test]
295    fn fallback_runtime_base_is_created_atomically_and_private() {
296        // SAFETY: geteuid has no preconditions and does not access memory.
297        let uid = unsafe { libc::geteuid() };
298        let root = tempdir().unwrap();
299        let tmp = sticky_tmp(root.path());
300        let base = tmp.join(format!("knottvm-{uid}"));
301
302        if system_root_uid().unwrap() != uid {
303            assert!(ensure_fallback_runtime_base(&tmp, &base).is_err());
304            assert!(!base.exists());
305        }
306        ensure_fallback_runtime_base_owned_by(&tmp, &base, uid).unwrap();
307        let metadata = fs::symlink_metadata(&base).unwrap();
308        assert!(metadata.is_dir());
309        assert!(!metadata.file_type().is_symlink());
310        assert_eq!(metadata.uid(), uid);
311        assert_eq!(metadata.mode() & 0o777, 0o700);
312        assert!(!base.join("knottvm").exists());
313    }
314
315    #[test]
316    fn fallback_rejects_preexisting_writable_or_symlinked_parents() {
317        // SAFETY: geteuid has no preconditions and does not access memory.
318        let uid = unsafe { libc::geteuid() };
319        let root = tempdir().unwrap();
320        let tmp = sticky_tmp(root.path());
321        let writable = tmp.join(format!("knottvm-{uid}"));
322        fs::create_dir(&writable).unwrap();
323        fs::set_permissions(&writable, fs::Permissions::from_mode(0o777)).unwrap();
324        assert!(ensure_fallback_runtime_base_owned_by(&tmp, &writable, uid).is_err());
325        assert!(!writable.join("knottvm").exists());
326
327        fs::remove_dir(&writable).unwrap();
328        let target = root.path().join("attacker-owned");
329        fs::create_dir(&target).unwrap();
330        symlink(&target, &writable).unwrap();
331        assert!(ensure_fallback_runtime_base_owned_by(&tmp, &writable, uid).is_err());
332        assert!(!target.join("knottvm").exists());
333    }
334
335    #[test]
336    fn runtime_base_rejects_a_replaceable_ancestor() {
337        let root = tempdir().unwrap();
338        let parent = root.path().join("writable-parent");
339        fs::create_dir(&parent).unwrap();
340        fs::set_permissions(&parent, fs::Permissions::from_mode(0o777)).unwrap();
341        let base = parent.join("runtime");
342        fs::create_dir(&base).unwrap();
343        fs::set_permissions(&base, fs::Permissions::from_mode(0o700)).unwrap();
344
345        assert!(validate_runtime_base(&base).is_err());
346
347        let target = root.path().join("safe-target");
348        fs::create_dir(&target).unwrap();
349        fs::set_permissions(&target, fs::Permissions::from_mode(0o700)).unwrap();
350        let link = root.path().join("linked-parent");
351        symlink(&target, &link).unwrap();
352        assert!(validate_runtime_base(&link.join("runtime")).is_err());
353    }
354}