Why do we need mktemp? [closed] Why do we need mktemp? [closed] linux linux

Why do we need mktemp? [closed]


mktemp randomizes the name. It is very important from the security point of view.

Just imagine that you do something like:

echo something > /tmp/temporary-file

in your root-running script.

And someone (who has read your script) does

ln -s /etc/passwd /tmp/temporary-file

before.

This results in /etc/passwd being overwritten, and potentially it can mean different unpleasant things starting from the system becomes broken, and ending with the system becomes hacked (when the input something could be carefully crafted).

The mktemp command could help you in this situation:

TEMP=$(mktemp /tmp/temporary-file.XXXXXXXX)echo something > ${TEMP}

Now this ln /etc/passwd attack will not work.

A brief insight into the history of mktemp: The mktemp command was invented by the OpenBSD folks, and first appeared in OpenBSD 2.1 back in 1997. Their goal was to improve the security of shell scripts. Previously the norm had been to add $$ to temporary file names, which was absolutely insecure. Now all UNIX/Linux systems have either mktemp or its alternatives, and it became standard de-facto. Funny enough, the mktemp C function was deprecated for being unsecure.


You often want a "scratchpad file" (or directory). Moreover, you might need several such files at the same time, and you don't want to bother figuring out how to name them so there's no conflict.

"mktemp" fits the bill :)


Ok actually it is written clearly in man pages.

mktemp - create a temporary file or directory.

Create a temporary file or directory, safely, and print its name.

It create a file or directory safely means no other user can access it, that's why its permission is 600

touch - change file timestamps

It simply change the timestamps of a file if already created and create a file if does not exist. But file permission is still 644 by default.

For more detail check following man pages:

http://linux.die.net/man/1/mktemp

http://linux.die.net/man/1/touch