1
//! Implement a wrapper for access to the members of a directory whose status
2
//! we've checked.
3

            
4
use std::{
5
    fs::{File, Metadata, OpenOptions},
6
    io,
7
    path::{Path, PathBuf},
8
};
9

            
10
use crate::{walk::PathType, Error, Mistrust, Result, Verifier};
11

            
12
/// A directory whose access properties we have verified, along with accessor
13
/// functions to access members of that directory.
14
///
15
/// The accessor functions will enforce that whatever security properties we
16
/// checked on the directory also apply to all of the members that we access
17
/// within the directory.
18
///
19
/// ## Limitations
20
///
21
/// Having a `CheckedDir` means only that, at the time it was created, we were
22
/// confident that no _untrusted_ user could access it inappropriately.  It is
23
/// still possible, after the `CheckedDir` is created, that a _trusted_ user can
24
/// alter its permissions, make its path point somewhere else, or so forth.
25
///
26
/// If this kind of time-of-use/time-of-check issue is unacceptable, you may
27
/// wish to look at other solutions, possibly involving `openat()` or related
28
/// APIs.
29
///
30
/// See also the crate-level [Limitations](crate#limitations) section.
31
#[derive(Debug, Clone)]
32
pub struct CheckedDir {
33
    /// The `Mistrust` object whose rules we apply to members of this directory.
34
    mistrust: Mistrust,
35
    /// The location of this directory, in its original form.
36
    location: PathBuf,
37
    /// The "readable_okay" flag that we used to create this CheckedDir.
38
    readable_okay: bool,
39
}
40

            
41
impl CheckedDir {
42
    /// Create a CheckedDir.
43
23637
    pub(crate) fn new(verifier: &Verifier<'_>, path: &Path) -> Result<Self> {
44
23637
        let mut mistrust = verifier.mistrust.clone();
45
        // Ignore the path that we already verified.  Since ignore_prefix
46
        // canonicalizes the path, we _will_ recheck the directory if it starts
47
        // pointing to a new canonical location.  That's probably a feature.
48
        //
49
        // TODO:
50
        //   * If `path` is a prefix of the original ignored path, this will
51
        //     make us ignore _less_.
52
23637
        mistrust.ignore_prefix = crate::canonicalize_opt_prefix(&Some(Some(path.to_path_buf())))?;
53
23637
        Ok(CheckedDir {
54
23637
            mistrust,
55
23637
            location: path.to_path_buf(),
56
23637
            readable_okay: verifier.readable_okay,
57
23637
        })
58
23637
    }
59

            
60
    /// Construct a new directory within this CheckedDir, if it does not already
61
    /// exist.
62
    ///
63
    /// `path` must be a relative path to the new directory, containing no `..`
64
    /// components.
65
3577
    pub fn make_directory<P: AsRef<Path>>(&self, path: P) -> Result<()> {
66
3577
        let path = path.as_ref();
67
3577
        self.check_path(path)?;
68
3573
        self.verifier().make_directory(self.location.join(path))
69
3577
    }
70

            
71
    /// Construct a new `CheckedDir` within this `CheckedDir`
72
    ///
73
    /// Creates the directory if it does not already exist.
74
    ///
75
    /// `path` must be a relative path to the new directory, containing no `..`
76
    /// components.
77
1722
    pub fn make_secure_directory<P: AsRef<Path>>(&self, path: P) -> Result<CheckedDir> {
78
1722
        let path = path.as_ref();
79
1722
        self.make_directory(path)?;
80
        // TODO I think this rechecks parents, but it need not, since we already did that.
81
1722
        self.verifier().secure_dir(self.location.join(path))
82
1722
    }
83

            
84
    /// Create a new [`FileAccess`](crate::FileAccess) for reading or writing files within this directory.
85
28794
    pub fn file_access(&self) -> crate::FileAccess<'_> {
86
28794
        crate::FileAccess::from_checked_dir(self)
87
28794
    }
88

            
89
    /// Open a file within this CheckedDir, using a set of [`OpenOptions`].
90
    ///
91
    /// `path` must be a relative path to the new directory, containing no `..`
92
    /// components.  We check, but do not create, the file's parent directories.
93
    /// We check the file's permissions after opening it.  If the file already
94
    /// exists, it must not be a symlink.
95
    ///
96
    /// If the file is created (and this is a unix-like operating system), we
97
    /// always create it with mode `600`, regardless of any mode options set in
98
    /// `options`.
99
38
    pub fn open<P: AsRef<Path>>(&self, path: P, options: &OpenOptions) -> Result<File> {
100
38
        self.file_access().open(path, options)
101
38
    }
102

            
103
    /// List the contents of a directory within this [`CheckedDir`].
104
    ///
105
    /// `path` must be a relative path, containing no `..` components.  Before
106
    /// listing the directory, we verify that that no untrusted user is able
107
    /// change its contents or make it point somewhere else.
108
    ///
109
    /// The return value is an iterator as returned by [`std::fs::ReadDir`].  We
110
    /// _do not_ check any properties of the elements of this iterator.
111
3646
    pub fn read_directory<P: AsRef<Path>>(&self, path: P) -> Result<std::fs::ReadDir> {
112
3646
        let path = self.verified_full_path(path.as_ref(), FullPathCheck::CheckPath)?;
113

            
114
3638
        std::fs::read_dir(&path).map_err(|e| Error::io(e, path, "read directory"))
115
3646
    }
116

            
117
    /// Remove a file within this [`CheckedDir`].
118
    ///
119
    /// `path` must be a relative path, containing no `..` components.
120
    ///
121
    /// Note that we ensure that the _parent_ of the file to be removed is
122
    /// unmodifiable by any untrusted user, but we do not check any permissions
123
    /// on the file itself, since those are irrelevant to removing it.
124
1053
    pub fn remove_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
125
        // We insist that the ownership and permissions on everything up to and
126
        // including the _parent_ of the path that we are removing have to be
127
        // correct.  (If it were otherwise, we could be tricked into removing
128
        // the wrong thing.)  But we don't care about the permissions on file we
129
        // are removing.
130
1053
        let path = self.verified_full_path(path.as_ref(), FullPathCheck::CheckParent)?;
131

            
132
1004
        std::fs::remove_file(&path).map_err(|e| Error::io(e, path, "remove file"))
133
1053
    }
134

            
135
    /// Return a reference to this directory as a [`Path`].
136
    ///
137
    /// Note that this function lets you work with a broader collection of
138
    /// functions, including functions that might let you access or create a
139
    /// file that is accessible by non-trusted users.  Be careful!
140
45666
    pub fn as_path(&self) -> &Path {
141
45666
        self.location.as_path()
142
45666
    }
143

            
144
    /// Return a new [`PathBuf`] containing this directory's path, with `path`
145
    /// appended to it.
146
    ///
147
    /// Return an error if `path` has any components that could take us outside
148
    /// of this directory.
149
15772
    pub fn join<P: AsRef<Path>>(&self, path: P) -> Result<PathBuf> {
150
15772
        let path = path.as_ref();
151
15772
        self.check_path(path)?;
152
15766
        Ok(self.location.join(path))
153
15772
    }
154

            
155
    /// Read the contents of the file at `path` within this directory, as a
156
    /// String, if possible.
157
    ///
158
    /// Return an error if `path` is absent, if its permissions are incorrect,
159
    /// if it has any components that could take us outside of this directory,
160
    /// or if its contents are not UTF-8.
161
1702
    pub fn read_to_string<P: AsRef<Path>>(&self, path: P) -> Result<String> {
162
1702
        self.file_access().read_to_string(path)
163
1702
    }
164

            
165
    /// Read the contents of the file at `path` within this directory, as a
166
    /// vector of bytes, if possible.
167
    ///
168
    /// Return an error if `path` is absent, if its permissions are incorrect,
169
    /// or if it has any components that could take us outside of this
170
    /// directory.
171
2550
    pub fn read<P: AsRef<Path>>(&self, path: P) -> Result<Vec<u8>> {
172
2550
        self.file_access().read(path)
173
2550
    }
174

            
175
    /// Store `contents` into the file located at `path` within this directory.
176
    ///
177
    /// We won't write to `path` directly: instead, we'll write to a temporary
178
    /// file in the same directory as `path`, and then replace `path` with that
179
    /// temporary file if we were successful.  (This isn't truly atomic on all
180
    /// file systems, but it's closer than many alternatives.)
181
    ///
182
    /// # Limitations
183
    ///
184
    /// This function will clobber any existing files with the same name as
185
    /// `path` but with the extension `tmp`.  (That is, if you are writing to
186
    /// "foo.txt", it will replace "foo.tmp" in the same directory.)
187
    ///
188
    /// This function may give incorrect behavior if multiple threads or
189
    /// processes are writing to the same file at the same time: it is the
190
    /// programmer's responsibility to use appropriate locking to avoid this.
191
1696
    pub fn write_and_replace<P: AsRef<Path>, C: AsRef<[u8]>>(
192
1696
        &self,
193
1696
        path: P,
194
1696
        contents: C,
195
1696
    ) -> Result<()> {
196
1696
        self.file_access().write_and_replace(path, contents)
197
1696
    }
198

            
199
    /// Return the [`Metadata`] of the file located at `path`.
200
    ///
201
    /// `path` must be a relative path, containing no `..` components.
202
    /// We check the file's parent directories,
203
    /// and the file's permissions.
204
    /// If the file exists, it must not be a symlink.
205
    ///
206
    /// Returns [`Error::NotFound`] if the file does not exist.
207
    ///
208
    /// Return an error if `path` is absent, if its permissions are incorrect[^1],
209
    /// if the permissions of any of its the parent directories are incorrect,
210
    /// or if it has any components that could take us outside of this directory.
211
    ///
212
    /// [^1]: the permissions are incorrect if the path is readable or writable by untrusted users
213
1310
    pub fn metadata<P: AsRef<Path>>(&self, path: P) -> Result<Metadata> {
214
1310
        let path = self.verified_full_path(path.as_ref(), FullPathCheck::CheckParent)?;
215

            
216
1064
        let meta = path
217
1064
            .symlink_metadata()
218
1064
            .map_err(|e| Error::inspecting(e, &path))?;
219

            
220
22
        if meta.is_symlink() {
221
            // TODO: this is inconsistent with CheckedDir::open()'s behavior, which returns a
222
            // FilesystemLoop io error in this case (we can't construct such an error here, because
223
            // ErrorKind::FilesystemLoop is only available on nightly)
224
2
            let err = io::Error::other(format!("Path {:?} is a symlink", path));
225
2
            return Err(Error::io(err, &path, "metadata"));
226
20
        }
227

            
228
20
        if let Some(error) = self
229
20
            .verifier()
230
20
            .check_one(path.as_path(), PathType::Content, &meta)
231
20
            .into_iter()
232
20
            .next()
233
        {
234
            Err(error)
235
        } else {
236
20
            Ok(meta)
237
        }
238
1310
    }
239

            
240
    /// Create a [`Verifier`] with the appropriate rules for this
241
    /// `CheckedDir`.
242
114107
    pub fn verifier(&self) -> Verifier<'_> {
243
114107
        let mut v = self.mistrust.verifier();
244
114107
        if self.readable_okay {
245
3002
            v = v.permit_readable();
246
111105
        }
247
114107
        v
248
114107
    }
249

            
250
    /// Helper: Make sure that the path `p` is a relative path that can be
251
    /// guaranteed to stay within this directory.
252
    ///
253
    /// (Specifically, we reject absolute paths, ".." items, and Windows path prefixes.)
254
103274
    fn check_path(&self, p: &Path) -> Result<()> {
255
        use std::path::Component;
256
        // This check should be redundant, but let's be certain.
257
103274
        if p.is_absolute() {
258
85
            return Err(Error::InvalidSubdirectory);
259
103189
        }
260

            
261
191399
        for component in p.components() {
262
191399
            match component {
263
                Component::Prefix(_) | Component::RootDir | Component::ParentDir => {
264
164
                    return Err(Error::InvalidSubdirectory)
265
                }
266
191235
                Component::CurDir | Component::Normal(_) => {}
267
            }
268
        }
269

            
270
103025
        Ok(())
271
103274
    }
272

            
273
    /// Check whether `p` is a valid relative path within this directory,
274
    /// verify its permissions or the permissions of its parent, depending on `check_type`,
275
    /// and return an absolute path for `p`.
276
60116
    pub(crate) fn verified_full_path(
277
60116
        &self,
278
60116
        p: &Path,
279
60116
        check_type: FullPathCheck,
280
60116
    ) -> Result<PathBuf> {
281
60116
        self.check_path(p)?;
282
60108
        let full_path = self.location.join(p);
283
60108
        let to_verify: &Path = match check_type {
284
12172
            FullPathCheck::CheckPath => full_path.as_ref(),
285
47936
            FullPathCheck::CheckParent => full_path.parent().unwrap_or_else(|| full_path.as_ref()),
286
        };
287
60108
        self.verifier().check(to_verify)?;
288

            
289
57884
        Ok(full_path)
290
60116
    }
291
}
292

            
293
/// Type argument for [`CheckedDir::verified_full_path`].
294
#[derive(Clone, Copy, Debug)]
295
pub(crate) enum FullPathCheck {
296
    /// Check all elements of the path, including the final element.
297
    CheckPath,
298
    /// Check all elements of the path, not including the final element.
299
    CheckParent,
300
}
301

            
302
#[cfg(test)]
303
mod test {
304
    // @@ begin test lint list maintained by maint/add_warning @@
305
    #![allow(clippy::bool_assert_comparison)]
306
    #![allow(clippy::clone_on_copy)]
307
    #![allow(clippy::dbg_macro)]
308
    #![allow(clippy::mixed_attributes_style)]
309
    #![allow(clippy::print_stderr)]
310
    #![allow(clippy::print_stdout)]
311
    #![allow(clippy::single_char_pattern)]
312
    #![allow(clippy::unwrap_used)]
313
    #![allow(clippy::unchecked_duration_subtraction)]
314
    #![allow(clippy::useless_vec)]
315
    #![allow(clippy::needless_pass_by_value)]
316
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
317
    use super::*;
318
    use crate::testing::Dir;
319
    use std::io::Write;
320

            
321
    #[test]
322
    fn easy_case() {
323
        let d = Dir::new();
324
        d.dir("a/b/c");
325
        d.dir("a/b/d");
326
        d.file("a/b/c/f1");
327
        d.file("a/b/c/f2");
328
        d.file("a/b/d/f3");
329

            
330
        d.chmod("a", 0o755);
331
        d.chmod("a/b", 0o700);
332
        d.chmod("a/b/c", 0o700);
333
        d.chmod("a/b/d", 0o777);
334
        d.chmod("a/b/c/f1", 0o600);
335
        d.chmod("a/b/c/f2", 0o666);
336
        d.chmod("a/b/d/f3", 0o600);
337

            
338
        let m = Mistrust::builder()
339
            .ignore_prefix(d.canonical_root())
340
            .build()
341
            .unwrap();
342

            
343
        let sd = m.verifier().secure_dir(d.path("a/b")).unwrap();
344

            
345
        // Try make_directory.
346
        sd.make_directory("c/sub1").unwrap();
347
        #[cfg(target_family = "unix")]
348
        {
349
            let e = sd.make_directory("d/sub2").unwrap_err();
350
            assert!(matches!(e, Error::BadPermission(..)));
351
        }
352

            
353
        // Try opening a file that exists.
354
        let f1 = sd.open("c/f1", OpenOptions::new().read(true)).unwrap();
355
        drop(f1);
356
        #[cfg(target_family = "unix")]
357
        {
358
            let e = sd.open("c/f2", OpenOptions::new().read(true)).unwrap_err();
359
            assert!(matches!(e, Error::BadPermission(..)));
360
            let e = sd.open("d/f3", OpenOptions::new().read(true)).unwrap_err();
361
            assert!(matches!(e, Error::BadPermission(..)));
362
        }
363

            
364
        // Try creating a file.
365
        let mut f3 = sd
366
            .open("c/f-new", OpenOptions::new().write(true).create(true))
367
            .unwrap();
368
        f3.write_all(b"Hello world").unwrap();
369
        drop(f3);
370

            
371
        #[cfg(target_family = "unix")]
372
        {
373
            let e = sd
374
                .open("d/f-new", OpenOptions::new().write(true).create(true))
375
                .unwrap_err();
376
            assert!(matches!(e, Error::BadPermission(..)));
377
        }
378
    }
379

            
380
    #[test]
381
    fn bad_paths() {
382
        let d = Dir::new();
383
        d.dir("a");
384
        d.chmod("a", 0o700);
385

            
386
        let m = Mistrust::builder()
387
            .ignore_prefix(d.canonical_root())
388
            .build()
389
            .unwrap();
390

            
391
        let sd = m.verifier().secure_dir(d.path("a")).unwrap();
392

            
393
        let e = sd.make_directory("hello/../world").unwrap_err();
394
        assert!(matches!(e, Error::InvalidSubdirectory));
395
        let e = sd.metadata("hello/../world").unwrap_err();
396
        assert!(matches!(e, Error::InvalidSubdirectory));
397

            
398
        let e = sd.make_directory("/hello").unwrap_err();
399
        assert!(matches!(e, Error::InvalidSubdirectory));
400
        let e = sd.metadata("/hello").unwrap_err();
401
        assert!(matches!(e, Error::InvalidSubdirectory));
402

            
403
        sd.make_directory("hello/world").unwrap();
404
    }
405

            
406
    #[test]
407
    fn read_and_write() {
408
        let d = Dir::new();
409
        d.dir("a");
410
        d.chmod("a", 0o700);
411
        let m = Mistrust::builder()
412
            .ignore_prefix(d.canonical_root())
413
            .build()
414
            .unwrap();
415

            
416
        let checked = m.verifier().secure_dir(d.path("a")).unwrap();
417

            
418
        // Simple case: write and read.
419
        checked
420
            .write_and_replace("foo.txt", "this is incredibly silly")
421
            .unwrap();
422

            
423
        let s1 = checked.read_to_string("foo.txt").unwrap();
424
        let s2 = checked.read("foo.txt").unwrap();
425
        assert_eq!(s1, "this is incredibly silly");
426
        assert_eq!(s1.as_bytes(), &s2[..]);
427

            
428
        // Checked subdirectory
429
        let sub = "sub";
430
        let sub_checked = checked.make_secure_directory(sub).unwrap();
431
        assert_eq!(sub_checked.as_path(), checked.as_path().join(sub));
432

            
433
        // Trickier: write when the preferred temporary already has content.
434
        checked
435
            .open("bar.tmp", OpenOptions::new().create(true).write(true))
436
            .unwrap()
437
            .write_all("be the other guy".as_bytes())
438
            .unwrap();
439
        assert!(checked.join("bar.tmp").unwrap().try_exists().unwrap());
440

            
441
        checked
442
            .write_and_replace("bar.txt", "its hard and nobody understands")
443
            .unwrap();
444

            
445
        // Temp file should be gone.
446
        assert!(!checked.join("bar.tmp").unwrap().try_exists().unwrap());
447
        let s4 = checked.read_to_string("bar.txt").unwrap();
448
        assert_eq!(s4, "its hard and nobody understands");
449
    }
450

            
451
    #[test]
452
    fn read_directory() {
453
        let d = Dir::new();
454
        d.dir("a");
455
        d.chmod("a", 0o700);
456
        d.dir("a/b");
457
        d.file("a/b/f");
458
        d.file("a/c.d");
459
        d.dir("a/x");
460

            
461
        d.chmod("a", 0o700);
462
        d.chmod("a/b", 0o700);
463
        d.chmod("a/x", 0o777);
464
        let m = Mistrust::builder()
465
            .ignore_prefix(d.canonical_root())
466
            .build()
467
            .unwrap();
468

            
469
        let checked = m.verifier().secure_dir(d.path("a")).unwrap();
470

            
471
        assert!(matches!(
472
            checked.read_directory("/"),
473
            Err(Error::InvalidSubdirectory)
474
        ));
475
        assert!(matches!(
476
            checked.read_directory("b/.."),
477
            Err(Error::InvalidSubdirectory)
478
        ));
479
        let mut members: Vec<String> = checked
480
            .read_directory(".")
481
            .unwrap()
482
            .map(|ent| ent.unwrap().file_name().to_string_lossy().to_string())
483
            .collect();
484
        members.sort();
485
        assert_eq!(members, vec!["b", "c.d", "x"]);
486

            
487
        let members: Vec<String> = checked
488
            .read_directory("b")
489
            .unwrap()
490
            .map(|ent| ent.unwrap().file_name().to_string_lossy().to_string())
491
            .collect();
492
        assert_eq!(members, vec!["f"]);
493

            
494
        #[cfg(target_family = "unix")]
495
        {
496
            assert!(matches!(
497
                checked.read_directory("x"),
498
                Err(Error::BadPermission(_, _, _))
499
            ));
500
        }
501
    }
502

            
503
    #[test]
504
    fn remove_file() {
505
        let d = Dir::new();
506
        d.dir("a");
507
        d.chmod("a", 0o700);
508
        d.dir("a/b");
509
        d.file("a/b/f");
510
        d.dir("a/b/d");
511
        d.dir("a/x");
512
        d.dir("a/x/y");
513
        d.file("a/x/y/z");
514

            
515
        d.chmod("a", 0o700);
516
        d.chmod("a/b", 0o700);
517
        d.chmod("a/x", 0o777);
518

            
519
        let m = Mistrust::builder()
520
            .ignore_prefix(d.canonical_root())
521
            .build()
522
            .unwrap();
523
        let checked = m.verifier().secure_dir(d.path("a")).unwrap();
524

            
525
        // Remove a file that is there, and then make sure it is gone.
526
        assert!(checked.read_to_string("b/f").is_ok());
527
        assert!(checked.metadata("b/f").unwrap().is_file());
528
        checked.remove_file("b/f").unwrap();
529
        assert!(matches!(
530
            checked.read_to_string("b/f"),
531
            Err(Error::NotFound(_))
532
        ));
533
        assert!(matches!(checked.metadata("b/f"), Err(Error::NotFound(_))));
534
        assert!(matches!(
535
            checked.remove_file("b/f"),
536
            Err(Error::NotFound(_))
537
        ));
538

            
539
        // Remove a file in a nonexistent subdirectory
540
        assert!(matches!(
541
            checked.remove_file("b/xyzzy/fred"),
542
            Err(Error::NotFound(_))
543
        ));
544

            
545
        // Remove a file in a directory whose permissions are too open.
546
        #[cfg(target_family = "unix")]
547
        {
548
            assert!(matches!(
549
                checked.remove_file("x/y/z"),
550
                Err(Error::BadPermission(_, _, _))
551
            ));
552
            assert!(matches!(
553
                checked.metadata("x/y/z"),
554
                Err(Error::BadPermission(_, _, _))
555
            ));
556
        }
557
    }
558

            
559
    #[test]
560
    #[cfg(target_family = "unix")]
561
    fn access_symlink() {
562
        use crate::testing::LinkType;
563

            
564
        let d = Dir::new();
565
        d.dir("a/b");
566
        d.file("a/b/f1");
567

            
568
        d.chmod("a/b", 0o700);
569
        d.chmod("a/b/f1", 0o600);
570
        d.link_rel(LinkType::File, "f1", "a/b/f1-link");
571

            
572
        let m = Mistrust::builder()
573
            .ignore_prefix(d.canonical_root())
574
            .build()
575
            .unwrap();
576

            
577
        let sd = m.verifier().secure_dir(d.path("a/b")).unwrap();
578

            
579
        assert!(sd.open("f1", OpenOptions::new().read(true)).is_ok());
580

            
581
        // Metadata returns an error if called on a symlink
582
        let e = sd.metadata("f1-link").unwrap_err();
583
        assert!(
584
            matches!(e, Error::Io { ref err, .. } if err.to_string().contains("is a symlink")),
585
            "{e:?}"
586
        );
587

            
588
        // Open returns an error if called on a symlink.
589
        let e = sd
590
            .open("f1-link", OpenOptions::new().read(true))
591
            .unwrap_err();
592
        assert!(
593
            matches!(e, Error::Io { ref err, .. } if err.to_string().contains("symbolic")), // Error is ELOOP.
594
            "{e:?}"
595
        );
596
    }
597
}