mktemp vs. umask 066 and touch?

874 views Asked by At

My bash shell requires a temp file. Suppose filename conflict is not an issue, can I say mktemp is not as good as manually touch a temp file after umask 066?

My assumption is: mktemp is a system function, compared to manually touch a file, it still takes a little bit more resource.

I've read something about ln -s etc/passwd attack, but it looks like a story decades ago when passwords were not shadowed.

Please correct me if my understanding is wrong.

2

There are 2 answers

2
Fred On

Those two commands are not destined to do the same thing. mktemp creates a file in a flexible way, and has features to make sure it uses a unique name. touch will modify the timestamp of a file (or create it if it does not exist), but you supply the name.

If you want to create an empty file for which you already have a name, then use touch ; if you are going to write to that file right after, you do not need to create it first, just redirect to it.

But if you really need to make a temporary file and ensure you will not overwrite any other file, touch does nothing for you. It is "lighter", maybe, but useless in this case, and you need mktemp.

0
Erwan Legrand On

The mktemp command was written by Todd C. Miller of OpenBSD to prevent common vulnerabilities in shell scripts. In his own words:

Mktemp is a simple utility designed to make temporary file handling in shells scripts be safe and simple. Traditionally, people writing shell scripts have used constructs like:

TFILE=/tmp/foop.$$

which are trivial to attack. If such a script is run as root it may be possible for an attacker on the local host to gain access to the root login, corrupt or unlink system files, or do a variety of other nasty things.

The basic problem is that most shells have no equivalent to open(2)'s O_EXCL flag. While it is possible to avoid this using temporary directories, I consider the use of mktemp(1) to be superior both in terms of simplicity and robustness.

Shadow passwords do not help here. If the script is run a root and it writes to a temporary file in an insecure way, then an attacker could possibly exploit race conditions to modify /etc/password or /etc/shadow or both!