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