Why do we need mktemp?

Shehbaz Jaffer picture Shehbaz Jaffer · Jul 24, 2012 · Viewed 47.1k times · Source

I do not understand the function of mktemp and what a temporary file means.

Whats the difference between say touch xyz and mktemp xyz (apart from the fact that mktemp will create some file with xxx appended to it and will have 600 permissions?)

Please clarify.

Answer

Igor Chubin picture Igor Chubin · Jul 24, 2012

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. Now everyone has root access on this system!

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.