Mktemp is not in the book

jsmaby at virgo.umeche.maine.edu jsmaby at virgo.umeche.maine.edu
Fri Jan 31 14:36:55 PST 2003


> Right but is it sooo easy, just add a little "s" inbetween for all those
> ocurrences? I am no programer and therefore stay away from such if I see
> those surroundings.

You cannot simply insert an `s'.  mktemp returns a filename (and modifies
the provided string), while mkstemp returns an opened file descriptor
as well as modifies the string.  So by inserting an `s', you're creating
the temporary file.  The program most likely expects no file to be there;
especially since binutils uses mktemp to create directory names as
well as file names.

One could close the file descriptor, and unlink the file before returning,
but then you're no better than you were with mktemp, since someone can
create a symbolic link with that name between the time you unlink it and
open it later.  The correct way to patch these things is to modify them
to use the fd instead of the filename.  This is often non-trivial.  I
attempted to do so with binutils at one point, but introduced some bugs
on the way (maybe I should try it again since I've learned C quite a bit
more since then).  Of course, some are really simple changes, like
tac from textutils:
       template = xmalloc (strlen (tempdir) + 11);
     }
   sprintf (template, "%s/tacXXXXXX", tempdir);
-  tempfile = mktemp (template);
+  fd = mkstemp (template);
 
-  /*  Open temporary file exclusively, to foil a common
-      denial-of-service attack.  */
-  fd = open (tempfile, O_RDWR | O_CREAT | O_TRUNC | O_EXCL, 0600);
   if (fd == -1)
     error (EXIT_FAILURE, errno, "%s", tempfile);
Where the use of "O_TRUNC" would zap /etc/passwd if someone did a
ln -s /etc/passwd /tmp/tac* right before the open.

Unfortunately, most programs aren't that easy to fix, and require
API changes in their libraries which doesn't make the maintainers
too happy (like if it means returning an fd instead of a filename
from their function that uses mktemp).  This is the case with binutils,
m4, and patch.

-James Smaby
-- 
Unsubscribe: send email to listar at linuxfromscratch.org
and put 'unsubscribe lfs-dev' in the subject header of the message



More information about the lfs-dev mailing list