FAQ - Help and questions

How do I create temporary files safely, and replace a file in one step?

#security#files#tempfilepublished 0 replies0 views
ReplyWatch
Share
Hacker NewsRedditLinkedInE-mail

Short answer

Use the tempfile crate: it creates files with unpredictable names and exclusive creation, and deletes them when dropped. To change an existing file, write a temporary file in the same folder and persist it over the target, so readers see the old or the new file but never a half-written one.

Checked with rustc 1.93.0, tempfile 3.27.0, Windows 11

Frequently asked question, written and answered by the Ruststudio team. Replies are open: corrections are welcome.

#1

Answer#

A temporary file with a predictable name in a shared folder (/tmp/myapp.tmp) is an old attack: another local user creates that name first, as a link to a file they want you to overwrite. The tempfile crate avoids it by creating the file with a random name and failing if the name already exists.

The same crate solves a second problem: crashes during writes. Write the new content to a temporary file in the same directory as the target (a rename across volumes is not atomic), then persist it over the target.

Cargo.tomltoml
[dependencies]
tempfile = "3"
src/main.rsrust
use std::fs::OpenOptions;
use std::io::Write;
use tempfile::NamedTempFile;

fn main() -> std::io::Result<()> {
    let dir = tempfile::tempdir()?;
    let target = dir.path().join("settings.json");

    // Write the whole file under a random name, then move it into place in one step.
    let mut tmp = NamedTempFile::new_in(dir.path())?;
    tmp.write_all(b"{\"v\":1}")?;
    tmp.persist(&target).map_err(|e| e.error)?;
    println!("settings.json holds {} bytes", std::fs::metadata(&target)?.len());

    // create_new fails if the path already exists, so an existing file or link is never reused.
    let again = OpenOptions::new().write(true).create_new(true).open(&target);
    println!("second create_new: {:?}", again.map(|_| ()).map_err(|e| e.kind()));
    Ok(())
}
text
settings.json holds 7 bytes
second create_new: Err(AlreadyExists)

create_new(true) is the standard-library way to say "create this file, and fail if anything is already there", which also refuses to follow a link that was put in place beforehand.

How to do it#

  1. Use NamedTempFile::new_in(dir) for files that are renamed into place, and tempfile::tempfile() for scratch data with no name.
  2. Write, flush, and only then persist.
  3. Keep the directory private to the service account.
  4. Use create_new whenever "this file must not exist yet" is part of the logic.

Common mistakes#

  • Building a name from the process ID or the time.
  • Using fs::write directly on a configuration file and losing it when the power fails halfway.
  • Persisting into a different file system than the temporary file lives on.

Is persist atomic on Windows?#

The crate documents the behaviour of each platform; read its notes for the version you use before relying on atomic replacement.

What is the difference between tempfile() and NamedTempFile?#

tempfile() returns an unnamed file that disappears when closed. NamedTempFile has a path, which you need if you want to rename it into place.

Sources#

    QuoteReply
    Share
    Hacker NewsRedditLinkedInE-mail

    No replies yet