Why mktemp with -u option is stated as unsafe in its manual?

570 views Asked by At

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)
1

There are 1 answers

1
Toby Speight On BEST ANSWER

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.