Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need mktemp? [closed]

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.

like image 983
Shehbaz Jaffer Avatar asked Jul 24 '12 18:07

Shehbaz Jaffer


People also ask

What does tmp mean in Python?

Temporary files, or "tempfiles", are mainly used to store intermediate information on disk for an application.

What is $( mktemp?

The mktemp() function generates a unique temporary filename from template. The last six characters of template must be XXXXXX and these are replaced with a string that makes the filename unique.

What does mktemp return?

mktemp creates a temporary file and returns its filename. The file is not automatically destroyed when the process ends. FILENAME=$(mktemp) if [ -f $FILENAME ]; then echo "Temporary file $FILENAME exists" else echo "Temporary file $FILENAME does not exist" fi.

Can mktemp fail?

Yes, mktemp can fail. For example, "TMPDIR=/dev/null mktemp -d" will reliably fail. You shouldn't be validating it starts with "/tmp" though, because on quite a few systems, people set TMPDIR=/var/tmp. You absolutely should check if mktemp exited nonzero, but if it exited 0, the directory should be safe to use.


2 Answers

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.

like image 176
Igor Chubin Avatar answered Sep 28 '22 01:09

Igor Chubin


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

like image 21
paulsm4 Avatar answered Sep 28 '22 03:09

paulsm4