Secure Coding mailing list archives

temporary directories


From: dwheeler at ida.org (David A. Wheeler)
Date: Wed, 03 Jan 2007 10:51:25 -0500

"Robert C. Seacord" <rcs at cert.org> wrote:
I've seen advice here and there to use the mkdtemp() function to create
temporary directories, for example:
...
- David Wheeler's Secure Programming for Linux and Unix HOWTO at
http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO.html
mentions it may not be a good idea if tmp cleaners are in use (but this
sort of suggests maybe it is ok if they are not.)

(I also mention later on that there are issues with NFS.  But anyway...)

The mkdtemp() function generates a uniquely-named temporary directory
from template.  This function appears to work exactly like mktemp()
works for files, except of course mktemp() has been widely discredited
because of possible TOCTOU conditions and problems generating unique,
unpredictable names.

So my question is, why is mkdtemp() considered safe?  Isn't it also
susceptible to race conditions?  Is there a reason why these race
conditions are not at issue in this case?  Or is it only considered safe
because there is no alternative?

mkdtemp() is safe from TOCTOU issues because the check-if-exists and
creation-of-object operations are atomic.
Under normal Unix/Linux semantics you can't create a directory
of a given name if the given name already exists.
(I guess there could be a kernel out there that gets this wrong,
but I don't know of any.)

open() is also safe if you use O_EXCL and O_CREAT, together, for
the same reason: it forces checking and creation to be atomic.
One problem is that many languages do NOT give you access directly
to open(), but are only implemented using C's "fopen()" call... and
fopen() has no standard way to implement exclusive creation.

I wish that the C standard body would update the C library and add
an "exclusive create" capability for fopen(), so that languages
that build on fopen() can do so.

This doesn't work on at least old versions of NFS reliably,
unfortunately.  I believe that's been fixed, but I have not
verified that.

--- David A. Wheeler




Current thread: