Why do we need mktemp?
LinuxShellFilesystemsLinux Problem Overview
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.
Linux Solutions
Solution 1 - Linux
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.
Solution 2 - Linux
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 :)
Solution 3 - Linux
One more extra reason: not all systems use /tmp
as temporary directory.
For example https://termux.com/ due to technical reasons (it runs as processes inside Android), has different long path as it's tmp directory.
Scripts that create temporary files or directories using mktemp
will be portable and also work in such special environments.
Solution 4 - Linux
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:
Solution 5 - Linux
At least in the bash shell you can do something like:
dirpath="/tmp/dir1-$$/dir2-$$"
mkdir -p $dirpath
chmod -R 0700 /tmp/dir1-$$
for instance.