On Wed, Apr 16, 2008 at 11:29 AM, Kyle McDonald <KMcDonald at egenera.com>
wrote:
> Does mktemp do anything to prevent race conditions between when it
> checks fo rthe file, and when it creates it?
>
> I believe, that the 'mkdir' command calls the 'mkdir' system call, and
> it's that syscall that is guaranteed to be atomic by the kernel.
> Does mktemp have the same semantics?
mktemp(1) says it does.
If mktemp can successfully generate a unique filename, the
file (or directory) is created with file permissions such
that it is only readable and writable by its owner (unless
the -u flag is given) and the filename is printed to stan-
dard output.
mktemp allows shell scripts to safely use temporary files.
Traditionally, many shell scripts take the name of the pro-
gram with the PID as a suffix and used that as a temporary
filename. This kind of naming scheme is predictable and the
race condition it creates is easy for an attacker to win. A
safer, though still inferior approach is to make a temporary
directory using the same naming scheme. While this guaran-
tees that a temporary file is not subverted, it still allows
a simple denial of service attack. Use mktemp instead.
But let's check.
$ truss -t creat,open mktemp /tmp/foo
open("/var/ld/ld.config", O_RDONLY) Err#2 ENOENT
open("/lib/libc.so.1", O_RDONLY) = 3
open("/platform/SUNW,SPARC-Enterprise-T5220/lib/libc_psr.so.1", O_RDONLY) = 3
open("/usr/lib/locale/en_US.ISO8859-1/en_US.ISO8859-1.so.3", O_RDONLY) = 3
open("/tmp/foo", O_RDWR|O_CREAT|O_EXCL, 0600) = 3
/tmp/foo
According to open(2):
O_EXCL
If O_CREAT and O_EXCL are set, open() fails if the file
exists. The check for the existence of the file and the
creation of the file if it does not exist is atomic with
respect to other threads executing open() naming the
same filename in the same directory with O_EXCL and
O_CREAT set. If O_EXCL and O_CREAT are set, and path
names a symbolic link, open() fails and sets errno to
EEXIST, regardless of the contents of the symbolic link.
If O_EXCL is set and O_CREAT is not set, the result is
undefined.
So, yes - mktemp does this in a safe and atomic way.
--
Mike Gerdts
http://mgerdts.blogspot.com/