1
//! Functionality for opening files while verifying their permissions.
2

            
3
use std::{
4
    borrow::Cow,
5
    fs::{File, OpenOptions},
6
    io::{Read as _, Write},
7
    path::{Path, PathBuf},
8
};
9

            
10
#[cfg(unix)]
11
use std::os::unix::fs::OpenOptionsExt as _;
12

            
13
use 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.
30
pub 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.
41
pub(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

            
48
impl<'a> FileAccess<'a> {
49
    /// Create a new `FileAccess` to access files within CheckedDir,
50
    /// using default options.
51
28794
    pub(crate) fn from_checked_dir(checked_dir: &'a CheckedDir) -> Self {
52
28794
        Self::from_inner(Inner::CheckedDir(checked_dir))
53
28794
    }
54
    /// Create a new `FileAccess` to access files anywhere on the filesystem,
55
    /// using default options.
56
646
    pub(crate) fn from_verifier(verifier: Verifier<'a>) -> Self {
57
646
        Self::from_inner(Inner::Verifier(verifier))
58
646
    }
59
    /// Create a new `FileAccess` from `inner`,
60
    /// using default options.
61
29440
    fn from_inner(inner: Inner<'a>) -> Self {
62
29440
        Self {
63
29440
            inner,
64
29440
            #[cfg(unix)]
65
29440
            create_with_mode: None,
66
29440
            follow_final_links: false,
67
29440
        }
68
29440
    }
69
    /// Check path constraints on `path` and verify its permissions
70
    /// (or the permissions of its parent) according to `check_type`
71
43747
    fn verified_full_path(&self, path: &Path, check_type: FullPathCheck) -> Result<PathBuf> {
72
43747
        match &self.inner {
73
43101
            Inner::CheckedDir(cd) => cd.verified_full_path(path, check_type),
74
646
            Inner::Verifier(v) => {
75
646
                let to_verify = match check_type {
76
642
                    FullPathCheck::CheckPath => path,
77
4
                    FullPathCheck::CheckParent => path.parent().unwrap_or(path),
78
                };
79
646
                v.check(to_verify)?;
80
326
                Ok(path.into())
81
            }
82
        }
83
43747
    }
84
    /// Return a `Verifier` to use for checking permissions.
85
23347
    fn verifier(&self) -> crate::Verifier {
86
23347
        match &self.inner {
87
22861
            Inner::CheckedDir(cd) => cd.verifier(),
88
486
            Inner::Verifier(v) => v.clone(),
89
        }
90
23347
    }
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
14469
    fn location_unverified<'b>(&self, path: &'b Path) -> Result<Cow<'b, Path>> {
96
14469
        Ok(match self.inner {
97
14307
            Inner::CheckedDir(cd) => cd.join(path)?.into(),
98
162
            Inner::Verifier(_) => path.into(),
99
        })
100
14469
    }
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
4
    pub fn create_with_mode(mut self, mode: u32) -> Self {
107
4
        #[cfg(unix)]
108
4
        {
109
4
            self.create_with_mode = Some(mode);
110
4
        }
111
4
        self
112
4
    }
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
1274
    pub fn follow_final_links(mut self, follow: bool) -> Self {
130
1274
        self.follow_final_links = follow;
131
1274
        self
132
1274
    }
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
4340
    pub fn open<P: AsRef<Path>>(self, path: P, options: &OpenOptions) -> Result<File> {
149
4340
        self.open_internal(path.as_ref(), options)
150
4340
    }
151

            
152
    /// As `open`, but take `self` by reference.  For internal use.
153
29440
    fn open_internal(&self, path: &Path, options: &OpenOptions) -> Result<File> {
154
29440
        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
29440
        let check_type = if follow_links {
160
1274
            FullPathCheck::CheckPath
161
        } else {
162
28166
            FullPathCheck::CheckParent
163
        };
164

            
165
29440
        let path = match self.verified_full_path(path.as_ref(), check_type) {
166
27536
            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
162
            Err(Error::NotFound(_)) if follow_links => self.location_unverified(path.as_ref())?,
173
1742
            Err(e) => return Err(e),
174
        };
175

            
176
        #[allow(unused_mut)]
177
27698
        let mut options = options.clone();
178
27698

            
179
27698
        #[cfg(unix)]
180
27698
        {
181
27698
            let create_mode = self.create_with_mode.unwrap_or(0o600);
182
27698
            options.mode(create_mode);
183
27698
            // Don't follow symlinks out of a secure directory.
184
27698
            if !follow_links {
185
26661
                options.custom_flags(libc::O_NOFOLLOW);
186
26661
            }
187
        }
188

            
189
27698
        let file = options
190
27698
            .open(&path)
191
27756
            .map_err(|e| Error::io(e, path.as_ref(), "open file"))?;
192
23347
        let meta = file
193
23347
            .metadata()
194
23347
            .map_err(|e| Error::inspecting(e, path.as_ref()))?;
195

            
196
23347
        if let Some(error) = self
197
23347
            .verifier()
198
23347
            .check_one(path.as_ref(), PathType::Content, &meta)
199
23347
            .into_iter()
200
23347
            .next()
201
        {
202
81
            Err(error)
203
        } else {
204
23266
            Ok(file)
205
        }
206
29440
    }
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
1726
    pub fn read_to_string<P: AsRef<Path>>(self, path: P) -> Result<String> {
215
1726
        let path = path.as_ref();
216
1726
        let mut file = self.open(path, OpenOptions::new().read(true))?;
217
1022
        let mut result = String::new();
218
1022
        file.read_to_string(&mut result)
219
1022
            .map_err(|e| Error::io(e, path, "read file"))?;
220
1020
        Ok(result)
221
1726
    }
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
2560
    pub fn read<P: AsRef<Path>>(self, path: P) -> Result<Vec<u8>> {
229
2560
        let path = path.as_ref();
230
2560
        let mut file = self.open(path, OpenOptions::new().read(true))?;
231
748
        let mut result = Vec::new();
232
748
        file.read_to_end(&mut result)
233
748
            .map_err(|e| Error::io(e, path, "read file"))?;
234
748
        Ok(result)
235
2560
    }
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
1700
    pub fn write_and_replace<P: AsRef<Path>, C: AsRef<[u8]>>(
254
1700
        self,
255
1700
        path: P,
256
1700
        contents: C,
257
1700
    ) -> Result<()> {
258
1700
        let path = path.as_ref();
259
1700
        let final_path = self.verified_full_path(path, FullPathCheck::CheckParent)?;
260

            
261
1700
        let tmp_name = path.with_extension("tmp");
262
1700
        // We remove the temporary file before opening it, if it's present: otherwise it _might_ be
263
1700
        // a symlink to somewhere silly.
264
1700
        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
1700
        let mut tmp_file = self.open_internal(
269
1700
            &tmp_name,
270
1700
            OpenOptions::new().create(true).truncate(true).write(true),
271
1700
        )?;
272

            
273
        // Write the data.
274
1700
        tmp_file
275
1700
            .write_all(contents.as_ref())
276
1700
            .map_err(|e| Error::io(e, &tmp_name, "write to file"))?;
277
        // Flush and close.
278
1700
        drop(tmp_file);
279
1700

            
280
1700
        // Replace the old file.
281
1700
        std::fs::rename(
282
1700
            // It's okay to use location_unverified here, since we already verified it when we
283
1700
            // called `open`.
284
1700
            self.location_unverified(tmp_name.as_path())?,
285
1700
            final_path,
286
1700
        )
287
1700
        .map_err(|e| Error::io(e, path, "replace file"))?;
288
1700
        Ok(())
289
1700
    }
290
}
291

            
292
#[cfg(test)]
293
mod 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
}