2

I wanted to create a temporary file and was going through the mktemp manual and found that mktemp with -u option is stated as unsafe, what is the reason behind this ?

  mktemp --help
    Usage: mktemp [OPTION]... [TEMPLATE]
    Create a temporary file or directory, safely, and print its name.
    TEMPLATE must contain at least 3 consecutive 'X's in last component.
    If TEMPLATE is not specified, use tmp.XXXXXXXXXX, and --tmpdir is implied.
    Files are created u+rw, and directories u+rwx, minus umask restrictions.
    
      -d, --directory     create a directory, not a file
      -u, --dry-run       do not create anything; merely print a name (unsafe)
  • I would simply say it's the fact that you are not actually completely creating the file and as the process is not being followed, it is described as unsafe. It would perhaps be more opt to define unsafe as "not as safe" in this case. – Raman Sailopal Mar 01 '21 at 11:33
  • 1
    This is what I found from the mktemp doc http://www.gnu.org/software/coreutils/manual/html_node/mktemp-invocation.html#mktemp-invocation : "Generate a temporary name that does not name an existing file, without changing the file system contents. Using the output of this command to create a new file is inherently unsafe, as there is a window of time between generating the name and using it where another process can create an object by the same name." – Shamantha Krishna Mar 01 '21 at 11:46

1 Answers1

3

When you use -u, no file is created, so using the name later doesn't guarantee to access a temporary file created by you.

There's a window of opportunity for another process to create a file of that name between invoking mktemp and using the result. That file may be a symbolic link, enabling another user to abuse your permissions to write somewhere.

If you use mktemp -u, you need to very carefully ensure that such a race is not exploitable.

Usually, it's better to create a temporary directory (mktemp -d), and use names of your choice within that directory.

Toby Speight
  • 27,591
  • 48
  • 66
  • 103