fs_mistrust/
file_access.rs

1//! Functionality for opening files while verifying their permissions.
2
3use std::{
4    borrow::Cow,
5    fs::{File, OpenOptions},
6    io::{Read as _, Write},
7    path::{Path, PathBuf},
8};
9
10#[cfg(unix)]
11use std::os::unix::fs::OpenOptionsExt as _;
12
13use crate::{dir::FullPathCheck, walk::PathType, CheckedDir, Error, Result, Verifier};
14
15/// Helper object for accessing a file on disk while checking the necessary permissions.
16///
17/// You can use a `FileAccess` when you want to read or write a file,
18/// while making sure that the file obeys the permissions rules of
19/// an associated [`CheckedDir`] or [`Verifier`].
20///
21/// `FileAccess` is a separate type from `CheckedDir` and `Verifier`
22/// so that you can set options to control the behavior of how files are opened.
23///
24/// Note: When we refer to a path _"obeying the constraints"_ of this `FileAccess`,
25/// we mean:
26/// * If the `FileAccess` wraps a `CheckedDir`, the requirement that it is a relative path
27///   containing no ".." elements,
28///   or other elements that would take it outside the `CheckedDir`.
29/// * If the `FileAccess` wraps a `Verifier`, there are no requirements.
30pub struct FileAccess<'a> {
31    /// Validator object that we use for checking file permissions.
32    pub(crate) inner: Inner<'a>,
33    /// If set, we create files with this mode.
34    #[cfg(unix)]
35    create_with_mode: Option<u32>,
36    /// If set, we follow final-position symlinks in provided paths.
37    follow_final_links: bool,
38}
39
40/// Inner object for checking file permissions.
41pub(crate) enum Inner<'a> {
42    /// A CheckedDir backing this FileAccess.
43    CheckedDir(&'a CheckedDir),
44    /// A Verifier backing this FileAccess.
45    Verifier(Verifier<'a>),
46}
47
48impl<'a> FileAccess<'a> {
49    /// Create a new `FileAccess` to access files within CheckedDir,
50    /// using default options.
51    pub(crate) fn from_checked_dir(checked_dir: &'a CheckedDir) -> Self {
52        Self::from_inner(Inner::CheckedDir(checked_dir))
53    }
54    /// Create a new `FileAccess` to access files anywhere on the filesystem,
55    /// using default options.
56    pub(crate) fn from_verifier(verifier: Verifier<'a>) -> Self {
57        Self::from_inner(Inner::Verifier(verifier))
58    }
59    /// Create a new `FileAccess` from `inner`,
60    /// using default options.
61    fn from_inner(inner: Inner<'a>) -> Self {
62        Self {
63            inner,
64            #[cfg(unix)]
65            create_with_mode: None,
66            follow_final_links: false,
67        }
68    }
69    /// Check path constraints on `path` and verify its permissions
70    /// (or the permissions of its parent) according to `check_type`
71    fn verified_full_path(&self, path: &Path, check_type: FullPathCheck) -> Result<PathBuf> {
72        match &self.inner {
73            Inner::CheckedDir(cd) => cd.verified_full_path(path, check_type),
74            Inner::Verifier(v) => {
75                let to_verify = match check_type {
76                    FullPathCheck::CheckPath => path,
77                    FullPathCheck::CheckParent => path.parent().unwrap_or(path),
78                };
79                v.check(to_verify)?;
80                Ok(path.into())
81            }
82        }
83    }
84    /// Return a `Verifier` to use for checking permissions.
85    fn verifier(&self) -> crate::Verifier {
86        match &self.inner {
87            Inner::CheckedDir(cd) => cd.verifier(),
88            Inner::Verifier(v) => v.clone(),
89        }
90    }
91    /// Return the location of `path` relative to this verifier.
92    ///
93    /// Fails if `path` does not [obey the constraints](FileAccess) of this `FileAccess`,
94    /// but does not do any permissions checking.
95    fn location_unverified<'b>(&self, path: &'b Path) -> Result<Cow<'b, Path>> {
96        Ok(match self.inner {
97            Inner::CheckedDir(cd) => cd.join(path)?.into(),
98            Inner::Verifier(_) => path.into(),
99        })
100    }
101
102    /// Configure this FileAccess: when used to create a file,
103    /// that file will be created with the provided unix permissions.
104    ///
105    /// If this option is not set, newly created files have mode 0600.
106    pub fn create_with_mode(mut self, mode: u32) -> Self {
107        #[cfg(unix)]
108        {
109            self.create_with_mode = Some(mode);
110        }
111        self
112    }
113
114    /// Configure this FileAccess: if the file to be accessed is a symlink,
115    /// and this is set to true, we will follow that symlink when creating or reading the file.
116    ///
117    /// By default, this option is false.
118    ///
119    /// Note that if you use this option with a `CheckedDir`,
120    /// it can read or write a file outside of the `CheckedDir`,
121    /// which might not be what you wanted.
122    ///
123    /// This option does not affect the handling of links that are _not_
124    /// in the final position of the path.
125    ///
126    /// This option does not disable the regular `fs-mistrust` checks:
127    /// we still ensure that the link's target, and its location, are not
128    /// modifiable by an untrusted user.
129    pub fn follow_final_links(mut self, follow: bool) -> Self {
130        self.follow_final_links = follow;
131        self
132    }
133
134    /// Open a file relative to this `FileAccess`, using a set of [`OpenOptions`].
135    ///
136    /// `path` must be a path to the new file, [obeying the constraints](FileAccess) of this `FileAccess`.
137    /// We check, but do not create, the file's parent directories.
138    /// We check the file's permissions after opening it.
139    ///
140    /// If the file is created (and this is a unix-like operating system), we
141    /// always create it with a mode based on [`create_with_mode()`](Self::create_with_mode),
142    /// regardless of any mode set in `options`.
143    /// If `create_with_mode()` wasn't called, we create the file with mode 600.
144    //
145    // Note: This function, and others, take ownership of `self`, to prevent people from storing and
146    // reusing FileAccess objects.  We're avoiding that because we don't want people confusing
147    // FileAccess objects created with CheckedDir and Verifier.
148    pub fn open<P: AsRef<Path>>(self, path: P, options: &OpenOptions) -> Result<File> {
149        self.open_internal(path.as_ref(), options)
150    }
151
152    /// As `open`, but take `self` by reference.  For internal use.
153    fn open_internal(&self, path: &Path, options: &OpenOptions) -> Result<File> {
154        let follow_links = self.follow_final_links;
155
156        // If we're following links, then we want to look at the whole path,
157        // since the final element might be a link.  If so, we need to look at
158        // where it is linking to, and validate that as well.
159        let check_type = if follow_links {
160            FullPathCheck::CheckPath
161        } else {
162            FullPathCheck::CheckParent
163        };
164
165        let path = match self.verified_full_path(path.as_ref(), check_type) {
166            Ok(path) => path.into(),
167            // We tolerate a not-found error if we're following links:
168            // - If the final element of the path is what wasn't found, then we might create it
169            //   ourselves when we open it.
170            // - If an earlier element of the path wasn't found, we will get a second NotFound error
171            //   when we try to open the file, which is okay.
172            Err(Error::NotFound(_)) if follow_links => self.location_unverified(path.as_ref())?,
173            Err(e) => return Err(e),
174        };
175
176        #[allow(unused_mut)]
177        let mut options = options.clone();
178
179        #[cfg(unix)]
180        {
181            let create_mode = self.create_with_mode.unwrap_or(0o600);
182            options.mode(create_mode);
183            // Don't follow symlinks out of a secure directory.
184            if !follow_links {
185                options.custom_flags(libc::O_NOFOLLOW);
186            }
187        }
188
189        let file = options
190            .open(&path)
191            .map_err(|e| Error::io(e, path.as_ref(), "open file"))?;
192        let meta = file
193            .metadata()
194            .map_err(|e| Error::inspecting(e, path.as_ref()))?;
195
196        if let Some(error) = self
197            .verifier()
198            .check_one(path.as_ref(), PathType::Content, &meta)
199            .into_iter()
200            .next()
201        {
202            Err(error)
203        } else {
204            Ok(file)
205        }
206    }
207
208    /// Read the contents of the file at `path` relative to this `FileAccess`, as a
209    /// String, if possible.
210    ///
211    /// Return an error if `path` is absent, if its permissions are incorrect,
212    /// if it does not [obey the constraints](FileAccess) of this `FileAccess`,
213    /// or if its contents are not UTF-8.
214    pub fn read_to_string<P: AsRef<Path>>(self, path: P) -> Result<String> {
215        let path = path.as_ref();
216        let mut file = self.open(path, OpenOptions::new().read(true))?;
217        let mut result = String::new();
218        file.read_to_string(&mut result)
219            .map_err(|e| Error::io(e, path, "read file"))?;
220        Ok(result)
221    }
222
223    /// Read the contents of the file at `path` relative to this `FileAccess`, as a
224    /// vector of bytes, if possible.
225    ///
226    /// Return an error if `path` is absent, if its permissions are incorrect,
227    /// or if it does not [obey the constraints](FileAccess) of this `FileAccess`.
228    pub fn read<P: AsRef<Path>>(self, path: P) -> Result<Vec<u8>> {
229        let path = path.as_ref();
230        let mut file = self.open(path, OpenOptions::new().read(true))?;
231        let mut result = Vec::new();
232        file.read_to_end(&mut result)
233            .map_err(|e| Error::io(e, path, "read file"))?;
234        Ok(result)
235    }
236
237    /// Store `contents` into the file located at `path` relative to this `FileAccess`.
238    ///
239    /// We won't write to `path` directly: instead, we'll write to a temporary
240    /// file in the same directory as `path`, and then replace `path` with that
241    /// temporary file if we were successful.  (This isn't truly atomic on all
242    /// file systems, but it's closer than many alternatives.)
243    ///
244    /// # Limitations
245    ///
246    /// This function will clobber any existing files with the same name as
247    /// `path` but with the extension `tmp`.  (That is, if you are writing to
248    /// "foo.txt", it will replace "foo.tmp" in the same directory.)
249    ///
250    /// This function may give incorrect behavior if multiple threads or
251    /// processes are writing to the same file at the same time: it is the
252    /// programmer's responsibility to use appropriate locking to avoid this.
253    pub fn write_and_replace<P: AsRef<Path>, C: AsRef<[u8]>>(
254        self,
255        path: P,
256        contents: C,
257    ) -> Result<()> {
258        let path = path.as_ref();
259        let final_path = self.verified_full_path(path, FullPathCheck::CheckParent)?;
260
261        let tmp_name = path.with_extension("tmp");
262        // We remove the temporary file before opening it, if it's present: otherwise it _might_ be
263        // a symlink to somewhere silly.
264        let _ignore = std::fs::remove_file(&tmp_name);
265
266        // TODO: The parent directory  verification performed by "open" here is redundant with that done in
267        // `verified_full_path` above.
268        let mut tmp_file = self.open_internal(
269            &tmp_name,
270            OpenOptions::new().create(true).truncate(true).write(true),
271        )?;
272
273        // Write the data.
274        tmp_file
275            .write_all(contents.as_ref())
276            .map_err(|e| Error::io(e, &tmp_name, "write to file"))?;
277        // Flush and close.
278        drop(tmp_file);
279
280        // Replace the old file.
281        std::fs::rename(
282            // It's okay to use location_unverified here, since we already verified it when we
283            // called `open`.
284            self.location_unverified(tmp_name.as_path())?,
285            final_path,
286        )
287        .map_err(|e| Error::io(e, path, "replace file"))?;
288        Ok(())
289    }
290}
291
292#[cfg(test)]
293mod test {
294    // @@ begin test lint list maintained by maint/add_warning @@
295    #![allow(clippy::bool_assert_comparison)]
296    #![allow(clippy::clone_on_copy)]
297    #![allow(clippy::dbg_macro)]
298    #![allow(clippy::mixed_attributes_style)]
299    #![allow(clippy::print_stderr)]
300    #![allow(clippy::print_stdout)]
301    #![allow(clippy::single_char_pattern)]
302    #![allow(clippy::unwrap_used)]
303    #![allow(clippy::unchecked_duration_subtraction)]
304    #![allow(clippy::useless_vec)]
305    #![allow(clippy::needless_pass_by_value)]
306    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
307
308    use std::fs;
309
310    use super::*;
311    use crate::{testing::Dir, Mistrust};
312
313    #[test]
314    fn create_public_in_checked_dir() {
315        let d = Dir::new();
316        d.dir("a");
317
318        d.chmod("a", 0o700);
319
320        let m = Mistrust::builder()
321            .ignore_prefix(d.canonical_root())
322            .build()
323            .unwrap();
324        let checked = m.verifier().secure_dir(d.path("a")).unwrap();
325
326        {
327            let mut f = checked
328                .file_access()
329                .open(
330                    "private-1.txt",
331                    OpenOptions::new().write(true).create_new(true),
332                )
333                .unwrap();
334            f.write_all(b"Hello world\n").unwrap();
335
336            checked
337                .file_access()
338                .write_and_replace("private-2.txt", b"Hello world 2\n")
339                .unwrap();
340        }
341        {
342            let mut f = checked
343                .file_access()
344                .create_with_mode(0o640)
345                .open(
346                    "public-1.txt",
347                    OpenOptions::new().write(true).create_new(true),
348                )
349                .unwrap();
350            f.write_all(b"Hello wider world\n").unwrap();
351
352            checked
353                .file_access()
354                .create_with_mode(0o644)
355                .write_and_replace("public-2.txt", b"Hello wider world 2")
356                .unwrap();
357        }
358
359        #[cfg(target_family = "unix")]
360        {
361            use std::os::unix::fs::MetadataExt;
362            assert_eq!(
363                fs::metadata(d.path("a/private-1.txt")).unwrap().mode() & 0o7777,
364                0o600
365            );
366            assert_eq!(
367                fs::metadata(d.path("a/private-2.txt")).unwrap().mode() & 0o7777,
368                0o600
369            );
370            assert_eq!(
371                fs::metadata(d.path("a/public-1.txt")).unwrap().mode() & 0o7777,
372                0o640
373            );
374            assert_eq!(
375                fs::metadata(d.path("a/public-2.txt")).unwrap().mode() & 0o7777,
376                0o644
377            );
378        }
379    }
380
381    #[test]
382    #[cfg(unix)]
383    fn open_symlinks() {
384        use crate::testing::LinkType;
385        let d = Dir::new();
386        d.dir("a");
387        d.dir("a/b");
388        d.dir("a/c");
389        d.file("a/c/file1.txt");
390        d.link_rel(LinkType::File, "../c/file1.txt", "a/b/present");
391        d.link_rel(LinkType::File, "../c/file2.txt", "a/b/absent");
392        d.chmod("a", 0o700);
393        d.chmod("a/b", 0o700);
394        d.chmod("a/c", 0o700);
395        d.chmod("a/c/file1.txt", 0o600);
396
397        let m = Mistrust::builder()
398            .ignore_prefix(d.canonical_root())
399            .build()
400            .unwrap();
401
402        // Try reading
403        let contents = m
404            .file_access()
405            .follow_final_links(true)
406            .read(d.path("a/b/present"))
407            .unwrap();
408        assert_eq!(
409            &contents[..],
410            &b"This space is intentionally left blank"[..]
411        );
412        let error = m
413            .file_access()
414            .follow_final_links(true)
415            .read(d.path("a/b/absent"))
416            .unwrap_err();
417        assert!(matches!(error, Error::NotFound(_)));
418
419        // Try writing.
420        {
421            let mut f = m
422                .file_access()
423                .follow_final_links(true)
424                .open(
425                    d.path("a/b/present"),
426                    OpenOptions::new().write(true).truncate(true),
427                )
428                .unwrap();
429            f.write_all(b"This is extremely serious!").unwrap();
430        }
431        let contents = m
432            .file_access()
433            .follow_final_links(true)
434            .read(d.path("a/b/present"))
435            .unwrap();
436        assert_eq!(&contents[..], &b"This is extremely serious!"[..]);
437
438        let contents = m.file_access().read(d.path("a/c/file1.txt")).unwrap();
439        assert_eq!(&contents[..], &b"This is extremely serious!"[..]);
440        {
441            let mut f = m
442                .file_access()
443                .follow_final_links(true)
444                .open(
445                    d.path("a/b/absent"),
446                    OpenOptions::new().create(true).write(true),
447                )
448                .unwrap();
449            f.write_all(b"This is extremely silly!").unwrap();
450        }
451        let contents = m.file_access().read(d.path("a/c/file2.txt")).unwrap();
452        assert_eq!(&contents[..], &b"This is extremely silly!"[..]);
453    }
454}