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.
Temporary files, or "tempfiles", are mainly used to store intermediate information on disk for an application.
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.
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.
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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With