0

I read the --help text for mktemp recently (the man page wasn't available) and came upon this:

  -u, --dry-run       do not create anything; merely print a name (unsafe)

Why is this "unsafe"? Is there any specific reason for this being marked as such?

  • @jsotola I don't have the manual available (my system does not provide it) and I was not aware of the online manual. The only (and I mean only) thing I have available is this --help text. – S.S. Anne Sep 9 '19 at 1:07
  • 1
    I don't "feel" like mktemp without -u is particularly safe, either, at least when creating temp files, not dirs. The temp file could've been accidentally deleted since it was created until it was first used, and then we're back where we started from -- opportunity for symlink attack. If you're using any shell with here-strings (bash, ksh, zsh) on Linux, this will create a temp file with two separate handles (7 for read, 8 for write) to it, which will be completely managed by the shell (you don't have to remove it or care about its path, etc): exec 7<<<'' 8>/dev/fd/7. – mosvy Sep 9 '19 at 1:35
  • Unfortunately, that trick no longer works in bash-5.0. Apparently, it's the effect of a fix for this bug. Sad. – mosvy Oct 26 '19 at 0:37
  • But then, bash is (and was) just re-opening the temp file by its name, which is just as damn racy as any kludge put together with mktemp(1) and rm. – mosvy Oct 26 '19 at 0:40
  • For completion, here is an example of bash not being able to use a here-doc because the tempfile was "accidentally" deleted (the head -n 6000 may have to be adjusted): while ! rm /tmp/sh-thd* 2>/dev/null; do : ; done & (printf "cat <<foo >/dev/null\n"; yes line | head -n6000; printf "foo") | bash; kill $! – mosvy Oct 30 '19 at 9:17
5

The whole point of mktemp is, to quote its manual, to “create a temporary file or directory, safely”. Basically, in a script, you can write

file="$(mktemp)"

or

dir="$(mktemp -d)"

and use either as you wish, safe in the knowledge that the temporary file and directory are accessible only by the user running the command (and root, of course, in most setups), and that they aren’t a symlink to something else, etc. (There are still some caveats; in particular, you need to check the exit status, and the parent directory needs to be safe to use. See the documentation for details.)

mktemp -u doesn’t give these guarantees, because it separates the construction of the file name from its use; in a script, you’d have to run (don’t do this)

dir="$(mktemp -u)"
mkdir "$dir"
chmod 700 "$dir"

In between mktemp and mkdir, another process can create the directory, with different ownership; or, in the case of a file, another process can create the file or create a symlink in its place...

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.