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