fs_mistrust/lib.rs
1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3// TODO: Stuff to add before this crate is ready....
4// - Test the absolute heck out of it.
5
6// POSSIBLY TODO:
7// - Cache information across runs.
8
9// @@ begin lint list maintained by maint/add_warning @@
10#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
11#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
12#![warn(missing_docs)]
13#![warn(noop_method_call)]
14#![warn(unreachable_pub)]
15#![warn(clippy::all)]
16#![deny(clippy::await_holding_lock)]
17#![deny(clippy::cargo_common_metadata)]
18#![deny(clippy::cast_lossless)]
19#![deny(clippy::checked_conversions)]
20#![allow(clippy::cognitive_complexity)] // See arti#2556
21#![deny(clippy::debug_assert_with_mut_call)]
22#![deny(clippy::exhaustive_enums)]
23#![deny(clippy::exhaustive_structs)]
24#![deny(clippy::expl_impl_clone_on_copy)]
25#![deny(clippy::fallible_impl_from)]
26#![deny(clippy::implicit_clone)]
27#![deny(clippy::large_stack_arrays)]
28#![warn(clippy::manual_ok_or)]
29#![deny(clippy::missing_docs_in_private_items)]
30#![warn(clippy::needless_borrow)]
31#![warn(clippy::needless_pass_by_value)]
32#![warn(clippy::option_option)]
33#![warn(clippy::or_fun_call)]
34#![deny(clippy::print_stderr)]
35#![deny(clippy::print_stdout)]
36#![warn(clippy::rc_buffer)]
37#![deny(clippy::ref_option_ref)]
38#![warn(clippy::semicolon_if_nothing_returned)]
39#![warn(clippy::trait_duplication_in_bounds)]
40#![deny(clippy::unchecked_time_subtraction)]
41#![deny(clippy::unnecessary_wraps)]
42#![warn(clippy::unseparated_literal_suffix)]
43#![deny(clippy::unwrap_used)]
44#![deny(clippy::mod_module_files)]
45#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
46#![allow(clippy::uninlined_format_args)]
47#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
48#![allow(clippy::result_large_err)] // temporary workaround for arti#587
49#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
50#![allow(clippy::needless_lifetimes)] // See arti#1765
51#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
52#![allow(clippy::collapsible_if)] // See arti#2342
53#![deny(clippy::unused_async)]
54#![deny(clippy::string_slice)] // See arti#2571
55#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
56//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
57
58// This crate used to have unsafe code to interact with various libc functions.
59// Nowadays we use pwd_grp, which is tested with miri.
60// This #[forbid] assures us that we have removed all direct unsafe libc access.
61//
62// If this crate grows some other reason to want some unsafe, it is OK to remove this,
63// subject to all the usual considerations when writing unsafe.
64#![forbid(unsafe_code)]
65// TODO: add to the list maintained by maint/add_warning once it's available on all crates
66#![warn(unnameable_types)]
67
68mod dir;
69mod disable;
70mod err;
71mod file_access;
72mod imp;
73#[cfg(all(
74 target_family = "unix",
75 not(target_os = "ios"),
76 not(target_os = "android"),
77 not(target_os = "tvos")
78))]
79mod user;
80
81#[cfg(feature = "anon_home")]
82pub mod anon_home;
83#[cfg(test)]
84pub(crate) mod testing;
85pub mod walk;
86
87#[cfg(feature = "serde")]
88use serde::{Deserialize, Serialize};
89use std::{
90 fs::DirBuilder,
91 path::{Path, PathBuf},
92 sync::Arc,
93};
94
95pub use dir::CheckedDir;
96pub use disable::GLOBAL_DISABLE_VAR;
97pub use err::{Error, format_access_bits};
98pub use file_access::FileAccess;
99
100/// A result type as returned by this crate
101pub type Result<T> = std::result::Result<T, Error>;
102
103#[cfg(all(
104 target_family = "unix",
105 not(target_os = "ios"),
106 not(target_os = "android"),
107 not(target_os = "tvos")
108))]
109pub use user::{TrustedGroup, TrustedUser};
110
111/// Configuration for verifying that a file or directory is really "private".
112///
113/// By default, we mistrust everything that we can: we assume that every
114/// directory on the filesystem is potentially misconfigured. This object can
115/// be used to change that.
116///
117/// Once you have a working [`Mistrust`], you can call its "`check_*`" methods
118/// directly, or use [`verifier()`](Mistrust::verifier) to configure a more
119/// complicated check.
120///
121/// See the [crate documentation](crate) for more information.
122///
123/// # Environment variables
124///
125/// The [`Mistrust`] can be configured to consider an environment variable.
126/// See [`MistrustBuilder::controlled_by_default_env_var`] and similar methods.
127///
128/// Names that seem to say "don't disable" are treated as "false". Any
129/// other value is treated as "true". (That is, we err on the side of
130/// assuming that if you set a disable variable, you meant to disable.)
131///
132/// If the `Mistrust` is configured to use an environment variable,
133/// this environment variable typically becomes part of the application's public interface,
134/// so this library commits to a stable behaviour for parsing these variables.
135/// Specifically the following case-insensitive strings are considered "false":
136/// "false", "no", "never", "n", "0", "".
137///
138/// Examples using the default environment variable:
139///
140/// - `FS_MISTRUST_DISABLE_PERMISSIONS_CHECKS="false"` — checks enabled
141/// - `FS_MISTRUST_DISABLE_PERMISSIONS_CHECKS=" false "` — checks enabled
142/// - `FS_MISTRUST_DISABLE_PERMISSIONS_CHECKS="NO"` — checks enabled
143/// - `FS_MISTRUST_DISABLE_PERMISSIONS_CHECKS=0` — checks enabled
144/// - `FS_MISTRUST_DISABLE_PERMISSIONS_CHECKS=` — checks enabled
145/// - `FS_MISTRUST_DISABLE_PERMISSIONS_CHECKS=" "` — checks enabled
146/// - `FS_MISTRUST_DISABLE_PERMISSIONS_CHECKS="true"` — checks disabled
147/// - `FS_MISTRUST_DISABLE_PERMISSIONS_CHECKS="asdf"` — checks disabled
148///
149/// # TODO
150///
151/// * support more kinds of trust configuration, including more trusted users,
152/// trusted groups, multiple trusted directories, etc?
153#[derive(Debug, Clone, derive_builder::Builder, Eq, PartialEq)]
154#[cfg_attr(feature = "serde", builder(derive(Debug, Serialize, Deserialize)))]
155#[cfg_attr(not(feature = "serde"), builder(derive(Debug)))]
156#[builder(build_fn(error = "Error"))]
157#[cfg_attr(feature = "serde", builder_struct_attr(serde(default)))]
158pub struct Mistrust {
159 /// If the user called [`MistrustBuilder::ignore_prefix`], what did they give us?
160 ///
161 /// (This is stored in canonical form.)
162 #[builder(
163 setter(into, strip_option),
164 field(build = "canonicalize_opt_prefix(&self.ignore_prefix)?")
165 )]
166 ignore_prefix: Option<PathBuf>,
167
168 /// Are we configured to disable all permission and ownership tests?
169 ///
170 /// (This field is present in the builder only.)
171 #[builder(setter(custom), field(type = "Option<bool>", build = "()"))]
172 dangerously_trust_everyone: (),
173
174 /// Should we check the environment to decide whether to disable permission
175 /// and ownership tests?
176 ///
177 /// (This field is present in the builder only.)
178 #[builder(setter(custom), field(type = "Option<disable::Disable>", build = "()"))]
179 #[cfg_attr(feature = "serde", builder_field_attr(serde(skip)))]
180 disable_by_environment: (),
181
182 /// Internal value combining `dangerously_trust_everyone` and
183 /// `disable_by_environment` to decide whether we're doing permissions
184 /// checks or not.
185 #[builder(setter(custom), field(build = "self.should_be_enabled()"))]
186 #[cfg_attr(feature = "serde", builder_field_attr(serde(skip)))]
187 status: disable::Status,
188
189 /// What user ID do we trust by default (if any?)
190 #[cfg(all(
191 target_family = "unix",
192 not(target_os = "ios"),
193 not(target_os = "android"),
194 not(target_os = "tvos")
195 ))]
196 #[builder(
197 setter(into),
198 field(type = "TrustedUser", build = "self.trust_user.get_uid()?")
199 )]
200 trust_user: Option<u32>,
201
202 /// What group ID do we trust by default (if any?)
203 #[cfg(all(
204 target_family = "unix",
205 not(target_os = "ios"),
206 not(target_os = "android"),
207 not(target_os = "tvos")
208 ))]
209 #[builder(
210 setter(into),
211 field(type = "TrustedGroup", build = "self.trust_group.get_gid()?")
212 )]
213 trust_group: Option<u32>,
214}
215
216/// Compute the canonical prefix for a given path prefix.
217///
218/// The funny types here are used to please derive_builder.
219#[allow(clippy::option_option)]
220fn canonicalize_opt_prefix(prefix: &Option<Option<PathBuf>>) -> Result<Option<PathBuf>> {
221 match prefix {
222 Some(Some(path)) if path.as_os_str().is_empty() => Ok(None),
223 Some(Some(path)) => Ok(Some(
224 path.canonicalize()
225 .map_err(|e| Error::inspecting(e, path))?,
226 )),
227 _ => Ok(None),
228 }
229 // TODO: Permit "not found?" .
230}
231
232impl MistrustBuilder {
233 /// Configure this `Mistrust` to trust only the admin (root) user.
234 ///
235 /// By default, both the currently running user and the root user will be
236 /// trusted.
237 ///
238 /// This option disables the default group-trust behavior as well.
239 #[cfg(all(
240 target_family = "unix",
241 not(target_os = "ios"),
242 not(target_os = "android"),
243 not(target_os = "tvos"),
244 ))]
245 pub fn trust_admin_only(&mut self) -> &mut Self {
246 self.trust_user = TrustedUser::None;
247 self.trust_group = TrustedGroup::None;
248 self
249 }
250
251 /// Configure this `Mistrust` to trust no groups at all.
252 ///
253 /// By default, we trust the group (if any) with the same name as the
254 /// current user if we are currently running as a member of that group.
255 ///
256 /// With this option set, no group is trusted, and any group-readable or
257 /// group-writable objects are treated the same as world-readable and
258 /// world-writable objects respectively.
259 #[cfg(all(
260 target_family = "unix",
261 not(target_os = "ios"),
262 not(target_os = "android"),
263 not(target_os = "tvos"),
264 ))]
265 pub fn trust_no_group_id(&mut self) -> &mut Self {
266 self.trust_group = TrustedGroup::None;
267 self
268 }
269
270 /// Configure this `Mistrust` to trust every user and every group.
271 ///
272 /// With this option set, every file and directory is treated as having
273 /// valid permissions: even world-writeable files are allowed. File-type
274 /// checks are still performed.
275 ///
276 /// This option is mainly useful to handle cases where you want to make
277 /// these checks optional, and still use [`CheckedDir`] without having to
278 /// implement separate code paths for the "checking on" and "checking off"
279 /// cases.
280 ///
281 /// Setting this flag will supersede any value set in the environment.
282 pub fn dangerously_trust_everyone(&mut self) -> &mut Self {
283 self.dangerously_trust_everyone = Some(true);
284 self
285 }
286
287 /// Remove any ignored prefix, restoring this [`MistrustBuilder`] to a state
288 /// as if [`MistrustBuilder::ignore_prefix`] had not been called.
289 pub fn remove_ignored_prefix(&mut self) -> &mut Self {
290 self.ignore_prefix = Some(None);
291 self
292 }
293
294 /// Configure this [`MistrustBuilder`] to become disabled based on the
295 /// environment variable `var`.
296 ///
297 /// See [`Mistrust`](Mistrust#environment-variables) for details about
298 /// the handling of the environment variable.
299 ///
300 /// If `var` is not set, then we'll look at
301 /// `$FS_MISTRUST_DISABLE_PERMISSIONS_CHECKS`.
302 pub fn controlled_by_env_var(&mut self, var: &str) -> &mut Self {
303 self.disable_by_environment = Some(disable::Disable::OnUserEnvVar(var.to_string()));
304 self
305 }
306
307 /// Like `controlled_by_env_var`, but do not override any previously set
308 /// environment settings.
309 ///
310 /// See [`Mistrust`](Mistrust#environment-variables) for details about
311 /// the handling of the environment variable.
312 ///
313 /// (The `arti-client` wants this, so that it can inform a caller-supplied
314 /// `MistrustBuilder` about its Arti-specific env var, but only if the
315 /// caller has not already provided a variable of its own. Other code
316 /// embedding `fs-mistrust` may want it too.)
317 pub fn controlled_by_env_var_if_not_set(&mut self, var: &str) -> &mut Self {
318 if self.disable_by_environment.is_none() {
319 self.controlled_by_env_var(var)
320 } else {
321 self
322 }
323 }
324
325 /// Configure this [`MistrustBuilder`] to become disabled based on the
326 /// environment variable `$FS_MISTRUST_DISABLE_PERMISSIONS_CHECKS` only,
327 ///
328 /// See [`Mistrust`](Mistrust#environment-variables) for details about
329 /// the handling of the environment variable.
330 ///
331 /// This is the default.
332 pub fn controlled_by_default_env_var(&mut self) -> &mut Self {
333 self.disable_by_environment = Some(disable::Disable::OnGlobalEnvVar);
334 self
335 }
336
337 /// Configure this [`MistrustBuilder`] to never consult the environment to
338 /// see whether it should be disabled.
339 pub fn ignore_environment(&mut self) -> &mut Self {
340 self.disable_by_environment = Some(disable::Disable::Never);
341 self
342 }
343
344 /// Considering our settings, determine whether we should trust all users
345 /// (and thereby disable our permission checks.)
346 fn should_be_enabled(&self) -> disable::Status {
347 // If we've disabled checks in our configuration, then that settles it.
348 if self.dangerously_trust_everyone == Some(true) {
349 return disable::Status::DisableChecks;
350 }
351
352 // Otherwise, we use our "disable_by_environment" setting to see whether
353 // we should check the environment.
354 match &self.disable_by_environment {
355 Some(d) => d.should_disable_checks(),
356 None => disable::Disable::default().should_disable_checks(),
357 }
358 }
359
360 /// Fill in any values for this `MistrustBuilder` that have defaults,
361 /// and are not already set.
362 ///
363 /// It is not necessary to call this method if you're just planning
364 /// to build a [`Mistrust`]; you only need it if you are going to
365 /// re-serialize the builder and you want to make the defaults explicit.
366 pub fn apply_defaults(&mut self) -> std::result::Result<(), void::Void> {
367 self.dangerously_trust_everyone.get_or_insert_default();
368 self.disable_by_environment.get_or_insert_default();
369 Ok(())
370 }
371}
372
373impl Default for Mistrust {
374 fn default() -> Self {
375 MistrustBuilder::default()
376 .build()
377 .expect("Could not build default")
378 }
379}
380
381/// An object used to perform a single check.
382///
383/// Obtained from [`Mistrust::verifier()`].
384///
385/// A `Verifier` is used when [`Mistrust::check_directory`] and
386/// [`Mistrust::make_directory`] are not sufficient for your needs.
387#[derive(Clone, Debug)]
388#[must_use]
389pub struct Verifier<'a> {
390 /// The [`Mistrust`] that was used to create this verifier.
391 mistrust: &'a Mistrust,
392
393 /// Has the user called [`Verifier::permit_readable`]?
394 readable_okay: bool,
395
396 /// Has the user called [`Verifier::all_errors`]?
397 collect_multiple_errors: bool,
398
399 /// If the user called [`Verifier::require_file`] or
400 /// [`Verifier::require_directory`], which did they call?
401 enforce_type: Type,
402
403 /// If true, we want to check all the contents of this directory as well as
404 /// the directory itself. Requires the `walkdir` feature.
405 check_contents: bool,
406}
407
408/// A type of object that we have been told to require.
409#[derive(Debug, Clone, Copy)]
410enum Type {
411 /// A directory.
412 Dir,
413 /// A regular file.
414 File,
415 /// A directory or a regular file.
416 DirOrFile,
417 /// Absolutely anything at all.
418 Anything,
419}
420
421impl Mistrust {
422 /// Return a new [`MistrustBuilder`].
423 pub fn builder() -> MistrustBuilder {
424 MistrustBuilder::default()
425 }
426
427 /// Initialize a new default `Mistrust`.
428 ///
429 /// By default:
430 /// * we will inspect all directories that are used to resolve any path that is checked.
431 pub fn new() -> Self {
432 Self::default()
433 }
434
435 /// Construct a new `Mistrust` that trusts all users and all groups.
436 ///
437 /// (In effect, this `Mistrust` will have all of its permissions checks
438 /// disabled, since if all users and groups are trusted, it doesn't matter
439 /// what the permissions on any file and directory are.)
440 pub fn new_dangerously_trust_everyone() -> Self {
441 Self::builder()
442 .dangerously_trust_everyone()
443 .build()
444 .expect("Could not construct a Mistrust")
445 }
446
447 /// Create a new [`Verifier`] with this configuration, to perform a single check.
448 pub fn verifier(&self) -> Verifier<'_> {
449 Verifier {
450 mistrust: self,
451 readable_okay: false,
452 collect_multiple_errors: false,
453 enforce_type: Type::DirOrFile,
454 check_contents: false,
455 }
456 }
457
458 /// Verify that `dir` is a directory that only trusted users can read from,
459 /// list the files in, or write to.
460 ///
461 /// If it is, and we can verify that, return `Ok(())`. Otherwise, return
462 /// the first problem that we encountered when verifying it.
463 ///
464 /// `m.check_directory(dir)` is equivalent to
465 /// `m.verifier().require_directory().check(dir)`. If you need different
466 /// behavior, see [`Verifier`] for more options.
467 pub fn check_directory<P: AsRef<Path>>(&self, dir: P) -> Result<()> {
468 self.verifier().require_directory().check(dir)
469 }
470
471 /// As `check_directory`, but create the directory if needed.
472 ///
473 /// `m.check_directory(dir)` is equivalent to
474 /// `m.verifier().make_directory(dir)`. If you need different behavior, see
475 /// [`Verifier`] for more options.
476 pub fn make_directory<P: AsRef<Path>>(&self, dir: P) -> Result<()> {
477 self.verifier().make_directory(dir)
478 }
479
480 /// Return true if this `Mistrust` object has been configured to trust all
481 /// users.
482 pub(crate) fn is_disabled(&self) -> bool {
483 self.status.disabled()
484 }
485
486 /// Create a new [`FileAccess`] for reading or writing files
487 /// while enforcing the rules of this `Mistrust`.
488 pub fn file_access(&self) -> FileAccess<'_> {
489 self.verifier().file_access()
490 }
491}
492
493impl<'a> Verifier<'a> {
494 /// Create a new [`FileAccess`] for reading or writing files
495 /// while enforcing the rules of this `Verifier`.
496 pub fn file_access(self) -> FileAccess<'a> {
497 FileAccess::from_verifier(self)
498 }
499
500 /// Configure this `Verifier` to require that all paths it checks be
501 /// files (not directories).
502 pub fn require_file(mut self) -> Self {
503 self.enforce_type = Type::File;
504 self
505 }
506
507 /// Configure this `Verifier` to require that all paths it checks be
508 /// directories.
509 pub fn require_directory(mut self) -> Self {
510 self.enforce_type = Type::Dir;
511 self
512 }
513
514 /// Configure this `Verifier` to allow the paths that it checks to be
515 /// filesystem objects of any type.
516 ///
517 /// By default, the final path (after resolving all links) must be a
518 /// directory or a regular file, not (for example) a block device or a named
519 /// pipe.
520 pub fn permit_all_object_types(mut self) -> Self {
521 self.enforce_type = Type::Anything;
522 self
523 }
524
525 /// Configure this `Verifier` to permit the target files/directory to be
526 /// _readable_ by untrusted users.
527 ///
528 /// By default, we assume that the caller wants the target file or directory
529 /// to be only readable or writable by trusted users. With this flag, we
530 /// permit the target file or directory to be readable by untrusted users,
531 /// but not writable.
532 ///
533 /// (Note that we always allow the _parent directories_ of the target to be
534 /// readable by untrusted users, since their readability does not make the
535 /// target readable.)
536 pub fn permit_readable(mut self) -> Self {
537 self.readable_okay = true;
538 self
539 }
540
541 /// Tell this `Verifier` to accumulate as many errors as possible, rather
542 /// than stopping at the first one.
543 ///
544 /// If a single error is found, that error will be returned. Otherwise, the
545 /// resulting error type will be [`Error::Multiple`].
546 ///
547 /// # Example
548 ///
549 /// ```
550 /// # use fs_mistrust::Mistrust;
551 /// if let Err(e) = Mistrust::new().verifier().all_errors().check("/home/gardenGnostic/.gnupg/") {
552 /// for error in e.errors() {
553 /// println!("{}", e)
554 /// }
555 /// }
556 /// ```
557 pub fn all_errors(mut self) -> Self {
558 self.collect_multiple_errors = true;
559 self
560 }
561
562 /// Configure this verifier so that, after checking the directory, check all
563 /// of its contents.
564 ///
565 /// Symlinks are not permitted; both files and directories are allowed. This
566 /// option implies `require_directory()`, since only a directory can have
567 /// contents.
568 ///
569 /// Requires that the `walkdir` feature is enabled.
570 #[cfg(feature = "walkdir")]
571 pub fn check_content(mut self) -> Self {
572 self.check_contents = true;
573 self.require_directory()
574 }
575
576 /// Check whether the file or directory at `path` conforms to the
577 /// requirements of this `Verifier` and the [`Mistrust`] that created it.
578 pub fn check<P: AsRef<Path>>(&self, path: P) -> Result<()> {
579 let path = path.as_ref();
580
581 // This is the powerhouse of our verifier code:
582 //
583 // See the `imp` module for actual implementation logic.
584 let mut error_iterator = self
585 .check_errors(path.as_ref())
586 .chain(self.check_content_errors(path.as_ref()));
587
588 // Collect either the first error, or all errors.
589 let opt_error: Option<Error> = if self.collect_multiple_errors {
590 error_iterator.collect()
591 } else {
592 let next = error_iterator.next();
593 drop(error_iterator); // so that "canonical" is no longer borrowed.
594 next
595 };
596
597 if let Some(err) = opt_error {
598 return Err(err);
599 }
600
601 Ok(())
602 }
603 /// Check whether `path` is a valid directory, and create it if it doesn't
604 /// exist.
605 ///
606 /// Returns `Ok` if the directory already existed or if it was just created,
607 /// and it conforms to the requirements of this `Verifier` and the
608 /// [`Mistrust`] that created it.
609 ///
610 /// Return an error if:
611 /// * there was a permissions or ownership problem in the path or any of
612 /// its ancestors,
613 /// * there was a problem when creating the directory
614 /// * after creating the directory, we found that it had a permissions or
615 /// ownership problem.
616 pub fn make_directory<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
617 self.enforce_type = Type::Dir;
618
619 let path = path.as_ref();
620 match self.clone().check(path) {
621 Err(Error::NotFound(_)) => {}
622 Err(other_error) => return Err(other_error),
623 Ok(()) => return Ok(()), // no error; file exists.
624 }
625
626 // Looks like we got a "not found", so we're creating the path.
627 let mut bld = DirBuilder::new();
628 #[cfg(target_family = "unix")]
629 {
630 use std::os::unix::fs::DirBuilderExt;
631 bld.mode(0o700);
632 }
633 bld.recursive(true)
634 .create(path)
635 .map_err(|e| Error::CreatingDir(Arc::new(e)))?;
636
637 // We built the path! But for paranoia's sake, check it again.
638 self.check(path)
639 }
640
641 /// Check whether `path` is a directory conforming to the requirements of
642 /// this `Verifier` and the [`Mistrust`] that created it.
643 ///
644 /// If it is, then return a new [`CheckedDir`] that can be used to securely access
645 /// the contents of this directory.
646 pub fn secure_dir<P: AsRef<Path>>(self, path: P) -> Result<CheckedDir> {
647 let path = path.as_ref();
648 self.clone().require_directory().check(path)?;
649 CheckedDir::new(&self, path)
650 }
651
652 /// Check whether `path` is a directory conforming to the requirements of
653 /// this `Verifier` and the [`Mistrust`] that created it.
654 ///
655 /// If successful, then return a new [`CheckedDir`] that can be used to
656 /// securely access the contents of this directory.
657 pub fn make_secure_dir<P: AsRef<Path>>(self, path: P) -> Result<CheckedDir> {
658 let path = path.as_ref();
659 self.clone().require_directory().make_directory(path)?;
660 CheckedDir::new(&self, path)
661 }
662}
663
664#[cfg(test)]
665mod test {
666 // @@ begin test lint list maintained by maint/add_warning @@
667 #![allow(clippy::bool_assert_comparison)]
668 #![allow(clippy::clone_on_copy)]
669 #![allow(clippy::dbg_macro)]
670 #![allow(clippy::mixed_attributes_style)]
671 #![allow(clippy::print_stderr)]
672 #![allow(clippy::print_stdout)]
673 #![allow(clippy::single_char_pattern)]
674 #![allow(clippy::unwrap_used)]
675 #![allow(clippy::unchecked_time_subtraction)]
676 #![allow(clippy::useless_vec)]
677 #![allow(clippy::needless_pass_by_value)]
678 #![allow(clippy::string_slice)] // See arti#2571
679 //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
680 use super::*;
681 use assert_matches::assert_matches;
682 use testing::{Dir, MistrustOp, mistrust_build};
683
684 #[cfg(target_family = "unix")]
685 use testing::LinkType;
686
687 #[cfg(target_family = "unix")]
688 #[test]
689 fn simple_cases() {
690 let d = Dir::new();
691 d.dir("a/b/c");
692 d.dir("e/f/g");
693 d.chmod("a", 0o755);
694 d.chmod("a/b", 0o755);
695 d.chmod("a/b/c", 0o700);
696 d.chmod("e", 0o755);
697 d.chmod("e/f", 0o777);
698 d.link_rel(LinkType::Dir, "a/b/c", "d");
699
700 let m = mistrust_build(&[
701 MistrustOp::IgnorePrefix(d.canonical_root()),
702 MistrustOp::TrustNoGroupId(),
703 ]);
704
705 // /a/b/c should be fine...
706 m.check_directory(d.path("a/b/c")).unwrap();
707 // /e/f/g should not.
708 let e = m.check_directory(d.path("e/f/g")).unwrap_err();
709 assert!(matches!(e, Error::BadPermission(_, 0o777, 0o022)));
710 assert_eq!(e.path().unwrap(), d.path("e/f").canonicalize().unwrap());
711
712 m.check_directory(d.path("d")).unwrap();
713 }
714
715 #[cfg(target_family = "unix")]
716 #[test]
717 fn admin_only() {
718 use std::os::unix::prelude::MetadataExt;
719
720 let d = Dir::new();
721 d.dir("a/b");
722 d.chmod("a", 0o700);
723 d.chmod("a/b", 0o700);
724
725 if d.path("a/b").metadata().unwrap().uid() == 0 {
726 // Nothing to do here; we _are_ root.
727 return;
728 }
729
730 // With normal settings should be okay...
731 let m = mistrust_build(&[MistrustOp::IgnorePrefix(d.canonical_root())]);
732 m.check_directory(d.path("a/b")).unwrap();
733
734 // With admin_only, it'll fail.
735 let m = mistrust_build(&[
736 MistrustOp::IgnorePrefix(d.canonical_root()),
737 MistrustOp::TrustAdminOnly(),
738 ]);
739
740 let err = m.check_directory(d.path("a/b")).unwrap_err();
741 assert!(matches!(err, Error::BadOwner(_, _)));
742 assert_eq!(err.path().unwrap(), d.path("a").canonicalize().unwrap());
743 }
744
745 #[test]
746 fn want_type() {
747 let d = Dir::new();
748 d.dir("a");
749 d.file("b");
750 d.chmod("a", 0o700);
751 d.chmod("b", 0o600);
752
753 let m = mistrust_build(&[
754 MistrustOp::IgnorePrefix(d.canonical_root()),
755 MistrustOp::TrustNoGroupId(),
756 ]);
757
758 // If we insist stuff is its own type, it works fine.
759 m.verifier().require_directory().check(d.path("a")).unwrap();
760 m.verifier().require_file().check(d.path("b")).unwrap();
761
762 // If we insist on a different type, we hit an error.
763 let e = m
764 .verifier()
765 .require_directory()
766 .check(d.path("b"))
767 .unwrap_err();
768 assert!(matches!(e, Error::BadType(_)));
769 assert_eq!(e.path().unwrap(), d.path("b").canonicalize().unwrap());
770
771 let e = m.verifier().require_file().check(d.path("a")).unwrap_err();
772 assert!(matches!(e, Error::BadType(_)));
773 assert_eq!(e.path().unwrap(), d.path("a").canonicalize().unwrap());
774
775 // TODO: Possibly, make sure that a special file matches neither.
776 }
777
778 #[cfg(target_family = "unix")]
779 #[test]
780 fn readable_ok() {
781 let d = Dir::new();
782 d.dir("a/b");
783 d.file("a/b/c");
784 d.chmod("a", 0o750);
785 d.chmod("a/b", 0o750);
786 d.chmod("a/b/c", 0o640);
787
788 let m = mistrust_build(&[
789 MistrustOp::IgnorePrefix(d.canonical_root()),
790 MistrustOp::TrustNoGroupId(),
791 ]);
792
793 // These will fail, since the file or directory is readable.
794 let e = m.verifier().check(d.path("a/b")).unwrap_err();
795 assert!(matches!(e, Error::BadPermission(..)));
796 assert_eq!(e.path().unwrap(), d.path("a/b").canonicalize().unwrap());
797 let e = m.verifier().check(d.path("a/b/c")).unwrap_err();
798 assert!(matches!(e, Error::BadPermission(..)));
799 assert_eq!(e.path().unwrap(), d.path("a/b/c").canonicalize().unwrap());
800
801 // Now allow readable targets.
802 m.verifier().permit_readable().check(d.path("a/b")).unwrap();
803 m.verifier()
804 .permit_readable()
805 .check(d.path("a/b/c"))
806 .unwrap();
807 }
808
809 #[cfg(target_family = "unix")]
810 #[test]
811 fn multiple_errors() {
812 let d = Dir::new();
813 d.dir("a/b");
814 d.chmod("a", 0o700);
815 d.chmod("a/b", 0o700);
816
817 let m = mistrust_build(&[
818 MistrustOp::IgnorePrefix(d.canonical_root()),
819 MistrustOp::TrustNoGroupId(),
820 ]);
821
822 // Only one error occurs, so we get that error.
823 let e = m
824 .verifier()
825 .all_errors()
826 .check(d.path("a/b/c"))
827 .unwrap_err();
828 assert!(matches!(e, Error::NotFound(_)));
829 assert_eq!(1, e.errors().count());
830
831 // Introduce a second error...
832 d.chmod("a/b", 0o770);
833 let e = m
834 .verifier()
835 .all_errors()
836 .check(d.path("a/b/c"))
837 .unwrap_err();
838 assert!(matches!(e, Error::Multiple(_)));
839 let errs: Vec<_> = e.errors().collect();
840 assert_eq!(2, errs.len());
841 assert!(matches!(&errs[0], Error::BadPermission(..)));
842 assert!(matches!(&errs[1], Error::NotFound(_)));
843 }
844
845 #[cfg(target_family = "unix")]
846 #[test]
847 fn sticky() {
848 let d = Dir::new();
849 d.dir("a/b/c");
850 d.chmod("a", 0o777);
851 d.chmod("a/b", 0o755);
852 d.chmod("a/b/c", 0o700);
853
854 let m = mistrust_build(&[MistrustOp::IgnorePrefix(d.canonical_root())]);
855
856 // `a` is world-writable, so the first check will fail.
857 m.check_directory(d.path("a/b/c")).unwrap_err();
858
859 // Now `a` is world-writable _and_ sticky, so the check should succeed.
860 d.chmod("a", 0o777 | crate::imp::STICKY_BIT);
861
862 m.check_directory(d.path("a/b/c")).unwrap();
863
864 // Make sure we got the right definition!
865 #[allow(clippy::useless_conversion)]
866 {
867 assert_eq!(crate::imp::STICKY_BIT, u32::from(libc::S_ISVTX));
868 }
869 }
870
871 #[cfg(target_family = "unix")]
872 #[test]
873 fn trust_gid() {
874 use std::os::unix::prelude::MetadataExt;
875 let d = Dir::new();
876 d.dir("a/b");
877 d.chmod("a", 0o770);
878 d.chmod("a/b", 0o770);
879
880 let m = mistrust_build(&[
881 MistrustOp::IgnorePrefix(d.canonical_root()),
882 MistrustOp::TrustNoGroupId(),
883 ]);
884
885 // By default, we shouldn't be accept this directory, since it is
886 // group-writable.
887 let e = m.check_directory(d.path("a/b")).unwrap_err();
888 assert!(matches!(e, Error::BadPermission(..)));
889
890 // But we can make the group trusted, which will make it okay for the
891 // directory to be group-writable.
892 let gid = d.path("a/b").metadata().unwrap().gid();
893
894 let m = mistrust_build(&[
895 MistrustOp::IgnorePrefix(d.canonical_root()),
896 MistrustOp::TrustGroup(gid),
897 ]);
898
899 m.check_directory(d.path("a/b")).unwrap();
900
901 // OTOH, if we made a _different_ group trusted, it'll fail.
902 let m = mistrust_build(&[
903 MistrustOp::IgnorePrefix(d.canonical_root()),
904 MistrustOp::TrustGroup(gid ^ 1),
905 ]);
906
907 let e = m.check_directory(d.path("a/b")).unwrap_err();
908 assert!(matches!(e, Error::BadPermission(..)));
909 }
910
911 #[test]
912 fn make_directory() {
913 let d = Dir::new();
914 d.dir("a/b");
915
916 let m = mistrust_build(&[MistrustOp::IgnorePrefix(d.canonical_root())]);
917
918 #[cfg(target_family = "unix")]
919 {
920 // Try once with bad permissions.
921 d.chmod("a", 0o777);
922 let e = m.make_directory(d.path("a/b/c/d")).unwrap_err();
923 assert!(matches!(e, Error::BadPermission(..)));
924
925 // Now make the permissions correct.
926 d.chmod("a", 0o0700);
927 d.chmod("a/b", 0o0700);
928 }
929
930 // Make the directory!
931 m.make_directory(d.path("a/b/c/d")).unwrap();
932
933 // Make sure it exists and has good permissions.
934 m.check_directory(d.path("a/b/c/d")).unwrap();
935
936 // Try make_directory again and make sure _that_ succeeds.
937 m.make_directory(d.path("a/b/c/d")).unwrap();
938 }
939
940 #[cfg(target_family = "unix")]
941 #[cfg(feature = "walkdir")]
942 #[test]
943 fn check_contents() {
944 let d = Dir::new();
945 d.dir("a/b/c");
946 d.file("a/b/c/d");
947 d.chmod("a", 0o700);
948 d.chmod("a/b", 0o700);
949 d.chmod("a/b/c", 0o755);
950 d.chmod("a/b/c/d", 0o666);
951
952 let m = mistrust_build(&[MistrustOp::IgnorePrefix(d.canonical_root())]);
953
954 // A check should work...
955 m.check_directory(d.path("a/b")).unwrap();
956
957 // But we get an error if we check the contents.
958 let e = m
959 .verifier()
960 .all_errors()
961 .check_content()
962 .check(d.path("a/b"))
963 .unwrap_err();
964 assert_eq!(1, e.errors().count());
965
966 // We only expect an error on the _writable_ contents: the _readable_
967 // a/b/c is okay.
968 assert_eq!(e.path().unwrap(), d.path("a/b/c/d"));
969 }
970
971 #[test]
972 fn trust_everyone() {
973 let d = Dir::new();
974 d.dir("a/b/c");
975 d.file("a/b/c/d");
976 d.chmod("a", 0o777);
977 d.chmod("a/b", 0o777);
978 d.chmod("a/b/c", 0o777);
979 d.chmod("a/b/c/d", 0o666);
980
981 let m = mistrust_build(&[MistrustOp::DangerouslyTrustEveryone()]);
982
983 // This is fine.
984 m.check_directory(d.path("a/b/c")).unwrap();
985 // This isn't a directory!
986 let err = m.check_directory(d.path("a/b/c/d")).unwrap_err();
987 assert!(matches!(err, Error::BadType(_)));
988
989 // But it _is_ a file.
990 m.verifier()
991 .require_file()
992 .check(d.path("a/b/c/d"))
993 .unwrap();
994 }
995
996 #[test]
997 fn default_mistrust() {
998 // we can't test a mistrust without ignore_prefix, but we should make sure that we can build one.
999 let _m = Mistrust::default();
1000 }
1001
1002 #[test]
1003 fn empty_path() {
1004 let m = mistrust_build(&[MistrustOp::DangerouslyTrustEveryone()]);
1005 assert_matches!(m.check_directory(""), Err(Error::NotFound(_)));
1006
1007 let m = Mistrust::default();
1008 assert_matches!(m.check_directory(""), Err(Error::NotFound(_)));
1009 }
1010
1011 // TODO: Write far more tests.
1012 // * Can there be a test for a failed readlink()? I can't see an easy way
1013 // to provoke that without trying to make a time-of-check/time-of-use race
1014 // condition, since we stat the link before we call readlink on it.
1015 // * Can there be a test for a failing call to std::env::current_dir? Seems
1016 // hard to provoke without calling set_current_dir(), which isn't good
1017 // manners in a test.
1018}