Skip to main content

create_dir_all_safe

Function create_dir_all_safe 

Source
pub fn create_dir_all_safe(path: &Path, mode: u32) -> Result<DirFd>
Expand description

Safely create all parent directories for a path using directory file descriptors. This prevents symlink race conditions by anchoring all operations to directory fds.

§Security

This function prevents TOCTOU race conditions for newly created directories by:

  1. Finding the deepest existing ancestor directory (path-based, following symlinks)
  2. Opening that ancestor with a file descriptor
  3. Creating all new directories using fd-based operations (mkdirat, openat with O_NOFOLLOW)

Once we have a fd for an existing ancestor, all subsequent operations use that fd as the anchor. If an attacker replaces a newly-created directory with a symlink, our openat with O_NOFOLLOW will fail, preventing the attack.

Pre-existing symlinks to directories in the path are followed (GNU coreutils behavior). O_DIRECTORY is used when opening them, so dangling or non-directory symlinks error out. Note that a residual TOCTOU window exists between stat and open for such symlinks, which is the same trade-off made by GNU coreutils.

§Arguments

  • path - The path to create directories for
  • mode - The mode to use when creating new directories (e.g., 0o755). The actual mode will be modified by the process umask.

§Returns

A DirFd for the final created directory, or the first existing parent if all directories already exist.