[Python-Dev] tempfile.mktemp and os.path.exists
iusty at k1024.org
Mon Nov 10 16:25:05 EST 2003
On Sun, Nov 09, 2003 at 06:11:57PM -0800, Guido van Rossum wrote:
> > The tempfile.mktemp function uses os.path.exists to test whether a file
> > already exists. Since this returns false for broken symbolic links,
> > wouldn't it be better if the function would actually do an os.lstat on
> > the filename?
> > I know the function is not safe by definition, but this issue could
> > (with a low probability) cause the file to actually be created in
> > another directory, as the non-existent target of the symlink, instead of
> > in the given directory (the one in which the symlink resides).
> Sounds like a good suggestion; I'll see if I can check something in.
The fix is trivial (IMHO). A patch is attached.
> (However, given that there already exists an attack on this function,
> does fixing this actually make any difference?)
Not really, but it is defensive programming (since the module is
security-oriented). Maybe you want a non-existent name for a block
device or a pipe (which mkstemp doesn't provide).
I happened to look into the module to see if I can replace some
hand-written functions with the ones in the module and I saw that
mktemp() could be improved maybe.
-------------- next part --------------
diff -urN old/tempfile.py new/tempfile.py
--- old/tempfile.py 2003-11-10 23:07:46.000000000 +0200
+++ new/tempfile.py 2003-11-10 23:22:57.000000000 +0200
@@ -338,7 +338,9 @@
for seq in xrange(TMP_MAX):
name = names.next()
file = _os.path.join(dir, prefix + name + suffix)
- if not _os.path.exists(file):
+ except _os.error:
raise IOError, (_errno.EEXIST, "No usable temporary filename found")
More information about the Python-Dev