1use std::{
5 fs::{File, Metadata, OpenOptions},
6 io,
7 path::{Path, PathBuf},
8};
9
10use crate::{Error, Mistrust, Result, Verifier, walk::PathType};
11
12#[derive(Debug, Clone)]
32pub struct CheckedDir {
33 mistrust: Mistrust,
35 location: PathBuf,
37 readable_okay: bool,
39}
40
41impl CheckedDir {
42 pub(crate) fn new(verifier: &Verifier<'_>, path: &Path) -> Result<Self> {
44 let mut mistrust = verifier.mistrust.clone();
45 mistrust.ignore_prefix = crate::canonicalize_opt_prefix(&Some(Some(path.to_path_buf())))?;
53 Ok(CheckedDir {
54 mistrust,
55 location: path.to_path_buf(),
56 readable_okay: verifier.readable_okay,
57 })
58 }
59
60 pub fn make_directory<P: AsRef<Path>>(&self, path: P) -> Result<()> {
66 let path = path.as_ref();
67 self.check_path(path)?;
68 self.verifier().make_directory(self.location.join(path))
69 }
70
71 pub fn make_secure_directory<P: AsRef<Path>>(&self, path: P) -> Result<CheckedDir> {
78 let path = path.as_ref();
79 self.make_directory(path)?;
80 self.verifier().secure_dir(self.location.join(path))
82 }
83
84 pub fn file_access(&self) -> crate::FileAccess<'_> {
86 crate::FileAccess::from_checked_dir(self)
87 }
88
89 pub fn open<P: AsRef<Path>>(&self, path: P, options: &OpenOptions) -> Result<File> {
100 self.file_access().open(path, options)
101 }
102
103 pub fn read_directory<P: AsRef<Path>>(&self, path: P) -> Result<std::fs::ReadDir> {
112 let path = self.verified_full_path(path.as_ref(), FullPathCheck::CheckPath)?;
113
114 std::fs::read_dir(&path).map_err(|e| Error::io(e, path, "read directory"))
115 }
116
117 pub fn remove_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
125 let path = self.verified_full_path(path.as_ref(), FullPathCheck::CheckParent)?;
131
132 std::fs::remove_file(&path).map_err(|e| Error::io(e, path, "remove file"))
133 }
134
135 pub fn as_path(&self) -> &Path {
141 self.location.as_path()
142 }
143
144 pub fn join<P: AsRef<Path>>(&self, path: P) -> Result<PathBuf> {
150 let path = path.as_ref();
151 self.check_path(path)?;
152 Ok(self.location.join(path))
153 }
154
155 pub fn read_to_string<P: AsRef<Path>>(&self, path: P) -> Result<String> {
162 self.file_access().read_to_string(path)
163 }
164
165 pub fn read<P: AsRef<Path>>(&self, path: P) -> Result<Vec<u8>> {
172 self.file_access().read(path)
173 }
174
175 pub fn write_and_replace<P: AsRef<Path>, C: AsRef<[u8]>>(
192 &self,
193 path: P,
194 contents: C,
195 ) -> Result<()> {
196 self.file_access().write_and_replace(path, contents)
197 }
198
199 pub fn metadata<P: AsRef<Path>>(&self, path: P) -> Result<Metadata> {
214 let path = self.verified_full_path(path.as_ref(), FullPathCheck::CheckParent)?;
215
216 let meta = path
217 .symlink_metadata()
218 .map_err(|e| Error::inspecting(e, &path))?;
219
220 if meta.is_symlink() {
221 let err = io::Error::other(format!("Path {:?} is a symlink", path));
225 return Err(Error::io(err, &path, "metadata"));
226 }
227
228 if let Some(error) = self
229 .verifier()
230 .check_one(path.as_path(), PathType::Content, &meta)
231 .into_iter()
232 .next()
233 {
234 Err(error)
235 } else {
236 Ok(meta)
237 }
238 }
239
240 pub fn verifier(&self) -> Verifier<'_> {
243 let mut v = self.mistrust.verifier();
244 if self.readable_okay {
245 v = v.permit_readable();
246 }
247 v
248 }
249
250 fn check_path(&self, p: &Path) -> Result<()> {
255 use std::path::Component;
256 if p.is_absolute() {
258 return Err(Error::InvalidSubdirectory);
259 }
260
261 for component in p.components() {
262 match component {
263 Component::Prefix(_) | Component::RootDir | Component::ParentDir => {
264 return Err(Error::InvalidSubdirectory);
265 }
266 Component::CurDir | Component::Normal(_) => {}
267 }
268 }
269
270 Ok(())
271 }
272
273 pub(crate) fn verified_full_path(
277 &self,
278 p: &Path,
279 check_type: FullPathCheck,
280 ) -> Result<PathBuf> {
281 self.check_path(p)?;
282 let full_path = self.location.join(p);
283 let to_verify: &Path = match check_type {
284 FullPathCheck::CheckPath => full_path.as_ref(),
285 FullPathCheck::CheckParent => full_path.parent().unwrap_or_else(|| full_path.as_ref()),
286 };
287 self.verifier().check(to_verify)?;
288
289 Ok(full_path)
290 }
291}
292
293#[derive(Clone, Copy, Debug)]
295pub(crate) enum FullPathCheck {
296 CheckPath,
298 CheckParent,
300}
301
302#[cfg(test)]
303mod test {
304 #![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_time_subtraction)]
314 #![allow(clippy::useless_vec)]
315 #![allow(clippy::needless_pass_by_value)]
316 #![allow(clippy::string_slice)] use super::*;
319 use crate::testing::Dir;
320 use std::io::Write;
321
322 #[test]
323 fn easy_case() {
324 let d = Dir::new();
325 d.dir("a/b/c");
326 d.dir("a/b/d");
327 d.file("a/b/c/f1");
328 d.file("a/b/c/f2");
329 d.file("a/b/d/f3");
330
331 d.chmod("a", 0o755);
332 d.chmod("a/b", 0o700);
333 d.chmod("a/b/c", 0o700);
334 d.chmod("a/b/d", 0o777);
335 d.chmod("a/b/c/f1", 0o600);
336 d.chmod("a/b/c/f2", 0o666);
337 d.chmod("a/b/d/f3", 0o600);
338
339 let m = Mistrust::builder()
340 .ignore_prefix(d.canonical_root())
341 .build()
342 .unwrap();
343
344 let sd = m.verifier().secure_dir(d.path("a/b")).unwrap();
345
346 sd.make_directory("c/sub1").unwrap();
348 #[cfg(target_family = "unix")]
349 {
350 let e = sd.make_directory("d/sub2").unwrap_err();
351 assert!(matches!(e, Error::BadPermission(..)));
352 }
353
354 let f1 = sd.open("c/f1", OpenOptions::new().read(true)).unwrap();
356 drop(f1);
357 #[cfg(target_family = "unix")]
358 {
359 let e = sd.open("c/f2", OpenOptions::new().read(true)).unwrap_err();
360 assert!(matches!(e, Error::BadPermission(..)));
361 let e = sd.open("d/f3", OpenOptions::new().read(true)).unwrap_err();
362 assert!(matches!(e, Error::BadPermission(..)));
363 }
364
365 let mut f3 = sd
367 .open("c/f-new", OpenOptions::new().write(true).create(true))
368 .unwrap();
369 f3.write_all(b"Hello world").unwrap();
370 drop(f3);
371
372 #[cfg(target_family = "unix")]
373 {
374 let e = sd
375 .open("d/f-new", OpenOptions::new().write(true).create(true))
376 .unwrap_err();
377 assert!(matches!(e, Error::BadPermission(..)));
378 }
379 }
380
381 #[test]
382 fn bad_paths() {
383 let d = Dir::new();
384 d.dir("a");
385 d.chmod("a", 0o700);
386
387 let m = Mistrust::builder()
388 .ignore_prefix(d.canonical_root())
389 .build()
390 .unwrap();
391
392 let sd = m.verifier().secure_dir(d.path("a")).unwrap();
393
394 let e = sd.make_directory("hello/../world").unwrap_err();
395 assert!(matches!(e, Error::InvalidSubdirectory));
396 let e = sd.metadata("hello/../world").unwrap_err();
397 assert!(matches!(e, Error::InvalidSubdirectory));
398
399 let e = sd.make_directory("/hello").unwrap_err();
400 assert!(matches!(e, Error::InvalidSubdirectory));
401 let e = sd.metadata("/hello").unwrap_err();
402 assert!(matches!(e, Error::InvalidSubdirectory));
403
404 sd.make_directory("hello/world").unwrap();
405 }
406
407 #[test]
408 fn read_and_write() {
409 let d = Dir::new();
410 d.dir("a");
411 d.chmod("a", 0o700);
412 let m = Mistrust::builder()
413 .ignore_prefix(d.canonical_root())
414 .build()
415 .unwrap();
416
417 let checked = m.verifier().secure_dir(d.path("a")).unwrap();
418
419 checked
421 .write_and_replace("foo.txt", "this is incredibly silly")
422 .unwrap();
423
424 let s1 = checked.read_to_string("foo.txt").unwrap();
425 let s2 = checked.read("foo.txt").unwrap();
426 assert_eq!(s1, "this is incredibly silly");
427 assert_eq!(s1.as_bytes(), &s2[..]);
428
429 let sub = "sub";
431 let sub_checked = checked.make_secure_directory(sub).unwrap();
432 assert_eq!(sub_checked.as_path(), checked.as_path().join(sub));
433
434 checked
436 .open("bar.tmp", OpenOptions::new().create(true).write(true))
437 .unwrap()
438 .write_all("be the other guy".as_bytes())
439 .unwrap();
440 assert!(checked.join("bar.tmp").unwrap().try_exists().unwrap());
441
442 checked
443 .write_and_replace("bar.txt", "its hard and nobody understands")
444 .unwrap();
445
446 assert!(!checked.join("bar.tmp").unwrap().try_exists().unwrap());
448 let s4 = checked.read_to_string("bar.txt").unwrap();
449 assert_eq!(s4, "its hard and nobody understands");
450 }
451
452 #[test]
453 fn read_directory() {
454 let d = Dir::new();
455 d.dir("a");
456 d.chmod("a", 0o700);
457 d.dir("a/b");
458 d.file("a/b/f");
459 d.file("a/c.d");
460 d.dir("a/x");
461
462 d.chmod("a", 0o700);
463 d.chmod("a/b", 0o700);
464 d.chmod("a/x", 0o777);
465 let m = Mistrust::builder()
466 .ignore_prefix(d.canonical_root())
467 .build()
468 .unwrap();
469
470 let checked = m.verifier().secure_dir(d.path("a")).unwrap();
471
472 assert!(matches!(
473 checked.read_directory("/"),
474 Err(Error::InvalidSubdirectory)
475 ));
476 assert!(matches!(
477 checked.read_directory("b/.."),
478 Err(Error::InvalidSubdirectory)
479 ));
480 let mut members: Vec<String> = checked
481 .read_directory(".")
482 .unwrap()
483 .map(|ent| ent.unwrap().file_name().to_string_lossy().to_string())
484 .collect();
485 members.sort();
486 assert_eq!(members, vec!["b", "c.d", "x"]);
487
488 let members: Vec<String> = checked
489 .read_directory("b")
490 .unwrap()
491 .map(|ent| ent.unwrap().file_name().to_string_lossy().to_string())
492 .collect();
493 assert_eq!(members, vec!["f"]);
494
495 #[cfg(target_family = "unix")]
496 {
497 assert!(matches!(
498 checked.read_directory("x"),
499 Err(Error::BadPermission(_, _, _))
500 ));
501 }
502 }
503
504 #[test]
505 fn remove_file() {
506 let d = Dir::new();
507 d.dir("a");
508 d.chmod("a", 0o700);
509 d.dir("a/b");
510 d.file("a/b/f");
511 d.dir("a/b/d");
512 d.dir("a/x");
513 d.dir("a/x/y");
514 d.file("a/x/y/z");
515
516 d.chmod("a", 0o700);
517 d.chmod("a/b", 0o700);
518 d.chmod("a/x", 0o777);
519
520 let m = Mistrust::builder()
521 .ignore_prefix(d.canonical_root())
522 .build()
523 .unwrap();
524 let checked = m.verifier().secure_dir(d.path("a")).unwrap();
525
526 assert!(checked.read_to_string("b/f").is_ok());
528 assert!(checked.metadata("b/f").unwrap().is_file());
529 checked.remove_file("b/f").unwrap();
530 assert!(matches!(
531 checked.read_to_string("b/f"),
532 Err(Error::NotFound(_))
533 ));
534 assert!(matches!(checked.metadata("b/f"), Err(Error::NotFound(_))));
535 assert!(matches!(
536 checked.remove_file("b/f"),
537 Err(Error::NotFound(_))
538 ));
539
540 assert!(matches!(
542 checked.remove_file("b/xyzzy/fred"),
543 Err(Error::NotFound(_))
544 ));
545
546 #[cfg(target_family = "unix")]
548 {
549 assert!(matches!(
550 checked.remove_file("x/y/z"),
551 Err(Error::BadPermission(_, _, _))
552 ));
553 assert!(matches!(
554 checked.metadata("x/y/z"),
555 Err(Error::BadPermission(_, _, _))
556 ));
557 }
558 }
559
560 #[test]
561 #[cfg(target_family = "unix")]
562 fn access_symlink() {
563 use crate::testing::LinkType;
564
565 let d = Dir::new();
566 d.dir("a/b");
567 d.file("a/b/f1");
568
569 d.chmod("a/b", 0o700);
570 d.chmod("a/b/f1", 0o600);
571 d.link_rel(LinkType::File, "f1", "a/b/f1-link");
572
573 let m = Mistrust::builder()
574 .ignore_prefix(d.canonical_root())
575 .build()
576 .unwrap();
577
578 let sd = m.verifier().secure_dir(d.path("a/b")).unwrap();
579
580 assert!(sd.open("f1", OpenOptions::new().read(true)).is_ok());
581
582 let e = sd.metadata("f1-link").unwrap_err();
584 assert!(
585 matches!(e, Error::Io { ref err, .. } if err.to_string().contains("is a symlink")),
586 "{e:?}"
587 );
588
589 let e = sd
591 .open("f1-link", OpenOptions::new().read(true))
592 .unwrap_err();
593 assert!(
594 matches!(e, Error::Io { ref err, .. } if err.raw_os_error() == Some(libc::ELOOP)),
595 "Expected ELOOP, but got: {e:?}"
596 );
597 }
598}