Skip to main content

dort_core/
observation.rs

1//! Read-only filesystem snapshots that do not follow symlinked parents.
2use crate::{Error, Result, context::validate_absolute, error::io_error};
3use rustix::fs::{self, AtFlags, FileType, Mode, OFlags};
4use serde::{Deserialize, Serialize};
5use sha2::{Digest, Sha256};
6use std::{
7    collections::BTreeSet,
8    ffi::OsString,
9    fs::File,
10    io::Read,
11    os::unix::ffi::OsStrExt,
12    path::{Component, Path, PathBuf},
13};
14
15const MAX_CONTENT: u64 = 16 * 1024 * 1024;
16const DIRECTORY_FLAGS: OFlags = OFlags::RDONLY
17    .union(OFlags::DIRECTORY)
18    .union(OFlags::NOFOLLOW)
19    .union(OFlags::CLOEXEC);
20
21#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
22#[serde(deny_unknown_fields)]
23pub struct Fingerprint {
24    pub device: u64,
25    pub inode: u64,
26    pub links: u64,
27    pub mode: u32,
28    pub uid: u32,
29    pub gid: u32,
30    pub size: i64,
31    pub modified: (i64, i64),
32    pub changed: (i64, i64),
33}
34
35impl Fingerprint {
36    #[allow(clippy::unnecessary_cast)] // stat field widths differ across Unix platforms.
37    pub(crate) fn from_stat(s: &fs::Stat) -> Self {
38        Self {
39            device: s.st_dev as u64,
40            inode: s.st_ino as u64,
41            links: s.st_nlink as u64,
42            mode: s.st_mode as u32,
43            uid: s.st_uid,
44            gid: s.st_gid,
45            size: s.st_size as i64,
46            modified: (s.st_mtime as i64, s.st_mtime_nsec as i64),
47            changed: (s.st_ctime as i64, s.st_ctime_nsec as i64),
48        }
49    }
50}
51
52#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
53#[serde(rename_all = "snake_case")]
54pub enum Kind {
55    Missing,
56    Regular,
57    Directory,
58    Symlink,
59    Special,
60}
61
62#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
63#[serde(deny_unknown_fields)]
64pub struct Parent {
65    pub path: PathBuf,
66    pub fingerprint: Fingerprint,
67}
68
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
70#[serde(deny_unknown_fields)]
71pub struct Entry {
72    pub path: PathBuf,
73    pub kind: Kind,
74    pub fingerprint: Option<Fingerprint>,
75    /// Includes every existing parent, even when a later component is absent.
76    pub parents: Vec<Parent>,
77    pub link_target: Option<PathBuf>,
78    pub sha256: Option<String>,
79    pub sensitive: bool,
80}
81
82impl Entry {
83    pub(crate) fn stable_parents(mut self) -> Self {
84        for parent in &mut self.parents {
85            parent.fingerprint.links = 0;
86            parent.fingerprint.size = 0;
87            parent.fingerprint.modified = (0, 0);
88            parent.fingerprint.changed = (0, 0);
89        }
90        self
91    }
92}
93
94pub(crate) struct ParentHandle {
95    pub(crate) directory: File,
96    pub(crate) name: OsString,
97    pub(crate) parents: Vec<Parent>,
98    pub(crate) missing: bool,
99}
100
101pub(crate) fn parent_handle(path: &Path) -> Result<ParentHandle> {
102    validate_output_path(path)?;
103    let name = path
104        .file_name()
105        .ok_or_else(|| Error::Invalid("cannot inspect root as a file".into()))?
106        .to_owned();
107    let mut directory = File::from(
108        fs::open("/", DIRECTORY_FLAGS, Mode::empty())
109            .map_err(|e| io_error("open filesystem root", path, e))?,
110    );
111    let mut walked = PathBuf::from("/");
112    let mut parents = vec![];
113    for component in path.parent().unwrap().components() {
114        let Component::Normal(name) = component else {
115            continue;
116        };
117        parents.push(parent_record(&directory, &walked)?);
118        walked.push(name);
119        match fs::openat(&directory, name, DIRECTORY_FLAGS, Mode::empty()) {
120            Ok(fd) => directory = File::from(fd),
121            Err(rustix::io::Errno::NOENT) => {
122                return Ok(ParentHandle {
123                    directory,
124                    name: path.file_name().unwrap().to_owned(),
125                    parents,
126                    missing: true,
127                });
128            }
129            Err(e) => {
130                return Err(io_error(
131                    "inspect parent without following symlinks (symlink or non-directory parents are forbidden)",
132                    &walked,
133                    e,
134                ));
135            }
136        }
137    }
138    parents.push(parent_record(&directory, &walked)?);
139    Ok(ParentHandle {
140        directory,
141        name,
142        parents,
143        missing: false,
144    })
145}
146
147fn parent_record(file: &File, path: &Path) -> Result<Parent> {
148    Ok(Parent {
149        path: path.to_owned(),
150        fingerprint: Fingerprint::from_stat(
151            &fs::fstat(file).map_err(|e| io_error("inspect directory", path, e))?,
152        ),
153    })
154}
155
156/// Output formats intentionally reject non-UTF-8 paths rather than corrupting their identity.
157pub fn validate_output_path(path: &Path) -> Result<()> {
158    validate_absolute(path)?;
159    if path.to_str().is_none() {
160        return Err(Error::Invalid(
161            "non-UTF-8 paths cannot be represented in Dort reports".into(),
162        ));
163    }
164    Ok(())
165}
166
167/// Hash only owned, single-link regular files. Never read directory/special/link contents.
168pub fn inspect(path: &Path, hash: bool) -> Result<Entry> {
169    let handle = parent_handle(path)?;
170    let mut entry = Entry {
171        path: path.to_owned(),
172        kind: Kind::Missing,
173        fingerprint: None,
174        parents: handle.parents.clone(),
175        link_target: None,
176        sha256: None,
177        sensitive: sensitive_path(path),
178    };
179    if handle.missing {
180        return Ok(entry);
181    }
182    let stat = match fs::statat(&handle.directory, &handle.name, AtFlags::SYMLINK_NOFOLLOW) {
183        Ok(stat) => stat,
184        Err(rustix::io::Errno::NOENT) => return Ok(entry),
185        Err(e) => return Err(io_error("inspect file", path, e)),
186    };
187    entry.kind = match FileType::from_raw_mode(stat.st_mode) {
188        FileType::RegularFile => Kind::Regular,
189        FileType::Directory => Kind::Directory,
190        FileType::Symlink => Kind::Symlink,
191        _ => Kind::Special,
192    };
193    let fingerprint = Fingerprint::from_stat(&stat);
194    if entry.kind == Kind::Symlink {
195        let target = fs::readlinkat(&handle.directory, &handle.name, Vec::new())
196            .map_err(|e| io_error("read link", path, e))?;
197        let target = PathBuf::from(OsString::from_vec(target.into_bytes()));
198        if target.to_str().is_none() {
199            return Err(Error::Invalid(
200                "non-UTF-8 link targets cannot be represented in Dort reports".into(),
201            ));
202        }
203        entry.link_target = Some(target);
204        let after = fs::statat(&handle.directory, &handle.name, AtFlags::SYMLINK_NOFOLLOW)
205            .map_err(|e| io_error("recheck link", path, e))?;
206        if fingerprint != Fingerprint::from_stat(&after) {
207            return Err(Error::Invalid("link changed during observation".into()));
208        }
209    }
210    if hash
211        && entry.kind == Kind::Regular
212        && fingerprint.links == 1
213        && fingerprint.uid == rustix::process::geteuid().as_raw()
214        && !entry.sensitive
215    {
216        let bytes = read_checked(&handle, path, &fingerprint)?;
217        entry.sensitive = sensitive_content(&bytes);
218        if !entry.sensitive {
219            entry.sha256 = Some(format!("{:x}", Sha256::digest(&bytes)));
220        }
221    }
222    entry.fingerprint = Some(fingerprint);
223    Ok(entry)
224}
225
226use std::os::unix::ffi::OsStringExt;
227
228pub(crate) fn read_checked(
229    handle: &ParentHandle,
230    path: &Path,
231    expected: &Fingerprint,
232) -> Result<Vec<u8>> {
233    read_checked_bounded(handle, path, expected, MAX_CONTENT)
234}
235
236pub(crate) fn read_checked_bounded(
237    handle: &ParentHandle,
238    path: &Path,
239    expected: &Fingerprint,
240    limit: u64,
241) -> Result<Vec<u8>> {
242    if expected.size < 0 || expected.size as u64 > limit {
243        return Err(Error::Invalid(
244            "file exceeds the 16 MiB observation limit".into(),
245        ));
246    }
247    let mut file = File::from(
248        fs::openat(
249            &handle.directory,
250            &handle.name,
251            OFlags::RDONLY | OFlags::NOFOLLOW | OFlags::NONBLOCK | OFlags::CLOEXEC,
252            Mode::empty(),
253        )
254        .map_err(|e| io_error("open regular file without following links", path, e))?,
255    );
256    let before = fs::fstat(&file).map_err(|e| io_error("inspect open file", path, e))?;
257    if &Fingerprint::from_stat(&before) != expected {
258        return Err(Error::Invalid("file changed before observation".into()));
259    }
260    let mut bytes = Vec::new();
261    (&mut file)
262        .take(limit + 1)
263        .read_to_end(&mut bytes)
264        .map_err(|e| io_error("read regular file", path, e))?;
265    let after = fs::fstat(&file).map_err(|e| io_error("recheck open file", path, e))?;
266    let named = fs::statat(&handle.directory, &handle.name, AtFlags::SYMLINK_NOFOLLOW)
267        .map_err(|e| io_error("recheck named file", path, e))?;
268    if bytes.len() as u64 > limit
269        || Fingerprint::from_stat(&after) != *expected
270        || Fingerprint::from_stat(&named) != *expected
271    {
272        return Err(Error::Invalid("file changed during observation".into()));
273    }
274    Ok(bytes)
275}
276
277/// Read a manifest through the same no-follow boundary. Contents are never in snapshots.
278pub fn read_manifest(path: &Path) -> Result<(crate::Manifest, Entry)> {
279    let (bytes, entry) = read_manifest_bytes(path)?;
280    let text =
281        std::str::from_utf8(&bytes).map_err(|_| Error::Invalid("manifest must be UTF-8".into()))?;
282    Ok((crate::Manifest::parse(text)?, entry))
283}
284
285pub(crate) fn read_manifest_bytes(path: &Path) -> Result<(Vec<u8>, Entry)> {
286    let entry = inspect(path, false)?;
287    let fp = entry
288        .fingerprint
289        .as_ref()
290        .filter(|f| {
291            entry.kind == Kind::Regular
292                && f.links == 1
293                && f.uid == rustix::process::geteuid().as_raw()
294        })
295        .ok_or_else(|| {
296            Error::Invalid("manifest must be an owned regular file without hard links".into())
297        })?;
298    let handle = parent_handle(path)?;
299    let bytes = read_checked(&handle, path, fp)?;
300    let mut entry = entry;
301    entry.sha256 = Some(format!("{:x}", Sha256::digest(&bytes)));
302    Ok((bytes, entry))
303}
304
305/// Normalize a link lexically; this does not grant permission to follow it.
306pub fn link_path(entry: &Entry) -> Option<PathBuf> {
307    let raw = entry.link_target.as_ref()?;
308    let path = if raw.is_absolute() {
309        raw.clone()
310    } else {
311        entry.path.parent()?.join(raw)
312    };
313    let mut normalized = PathBuf::from("/");
314    for component in path.components() {
315        match component {
316            Component::Normal(name) => normalized.push(name),
317            Component::ParentDir => {
318                normalized.pop();
319            }
320            _ => {}
321        }
322    }
323    Some(normalized)
324}
325
326#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
327#[serde(rename_all = "snake_case")]
328pub enum LinkState {
329    Regular,
330    Directory,
331    Special,
332    Broken,
333    Loop,
334    UnsafeParent,
335}
336
337/// Resolve terminal symlink chains only. Symlinked parents remain forbidden, not followed.
338pub fn link_state(entry: &Entry) -> Result<LinkState> {
339    let mut current = entry.clone();
340    let mut seen = BTreeSet::new();
341    for _ in 0..40 {
342        if !seen.insert(current.path.clone()) {
343            return Ok(LinkState::Loop);
344        }
345        let Some(path) = link_path(&current) else {
346            return Ok(match current.kind {
347                Kind::Missing => LinkState::Broken,
348                Kind::Regular => LinkState::Regular,
349                Kind::Directory => LinkState::Directory,
350                _ => LinkState::Special,
351            });
352        };
353        current = match inspect(&path, false) {
354            Ok(entry) => entry,
355            Err(_) => return Ok(LinkState::UnsafeParent),
356        };
357    }
358    Ok(LinkState::Loop)
359}
360
361/// Conservative filename heuristic, not a proof that other files contain no secrets.
362pub fn sensitive_path(path: &Path) -> bool {
363    path.components().any(|part| {
364        let name = part.as_os_str().as_bytes().to_ascii_lowercase();
365        let name = String::from_utf8_lossy(&name);
366        [
367            ".ssh",
368            ".gnupg",
369            ".aws",
370            ".azure",
371            ".kube",
372            ".netrc",
373            ".npmrc",
374            ".pypirc",
375            ".git-credentials",
376            ".env",
377            "keychains",
378            "keyring",
379            "keyrings",
380            "gh",
381            "gcloud",
382            "vault",
383            "rclone",
384            "age",
385            "sops",
386            "credentials",
387            "credential",
388            "secrets",
389            "secret",
390            "privatekeys",
391            "passwords",
392            "auth",
393            "auth.json",
394            ".auth.json",
395            ".auth",
396            ".sessions",
397            "authentication",
398            "session",
399            "sessions",
400            "session-store",
401            "sessionstore",
402            "cookies",
403            "cookies.sqlite",
404            "login data",
405            "1password",
406            "bitwarden",
407            "keepass",
408            "keepassxc",
409            "lastpass",
410            ".password-store",
411        ]
412        .contains(&name.as_ref())
413            || [
414                "auth",
415                "authentication",
416                "credential",
417                "credentials",
418                "secret",
419                "secrets",
420                "session",
421                "sessions",
422                "cookies",
423            ]
424            .contains(&name.trim_start_matches('.').split('.').next().unwrap_or(""))
425            || name.starts_with(".env.")
426            || name.starts_with("id_rsa")
427            || name.starts_with("id_ed25519")
428            || name.starts_with("id_ecdsa")
429            || name.starts_with("id_dsa")
430            || name.ends_with(".pem")
431            || name.ends_with(".key")
432            || name.contains("token")
433    })
434}
435
436pub(crate) fn sensitive_content(bytes: &[u8]) -> bool {
437    let lower = bytes.to_ascii_lowercase();
438    [
439        b"private key".as_slice(),
440        b"\"password\"",
441        b"\"token\"",
442        b"\"secret\"",
443        b"\"credentials\"",
444        b"accesstoken",
445        b"apikey",
446        b"clientsecret",
447        b"authorization:",
448        b"bearer ",
449        b"password=",
450        b"password =",
451        b"token=",
452        b"token =",
453        b"secret=",
454        b"secret =",
455        b"aws_access_key_id",
456        b"oauth_token",
457        b"access_token",
458        b"api_key",
459        b"api-key",
460        b"client_secret",
461        b"private_key",
462        b"age-secret-key-",
463        b"secret_access_key",
464    ]
465    .iter()
466    .any(|needle| lower.windows(needle.len()).any(|part| part == *needle))
467}
468
469/// Enumerate names through a retained no-follow directory descriptor, with a hard limit.
470pub(crate) fn names(path: &Path, limit: usize) -> Result<Vec<OsString>> {
471    let handle = parent_handle(path)?;
472    if handle.missing {
473        return Ok(vec![]);
474    }
475    let directory = File::from(
476        fs::openat(
477            &handle.directory,
478            &handle.name,
479            DIRECTORY_FLAGS,
480            Mode::empty(),
481        )
482        .map_err(|e| io_error("open discovery directory without following links", path, e))?,
483    );
484    let mut names = vec![];
485    let dir = fs::Dir::read_from(&directory)
486        .map_err(|e| io_error("read discovery directory", path, e))?;
487    for item in dir {
488        let item = item.map_err(|e| io_error("read discovery entry", path, e))?;
489        let name = item.file_name().to_bytes();
490        if name == b"." || name == b".." {
491            continue;
492        }
493        if names.len() >= limit {
494            return Err(Error::Invalid("discovery entry limit exceeded".into()));
495        }
496        names.push(OsString::from_vec(name.to_vec()));
497    }
498    names.sort();
499    Ok(names)
500}