os.makedirs should not succeed when the directory already exists (was Re: Python Doc Error: os.makedirs)

jepler at unpythonic.net jepler at unpythonic.net
Thu Oct 20 20:48:37 EDT 2005


On Wed, Oct 19, 2005 at 09:26:16AM -0700, Dr. Who wrote:
> The fact that the directory already exists is irrelevant to the function...it
> still failed to create the directory.

That's not true.  Imagine that os.makedirs() is used inside tempfile.mkdtemp()
(I looked, and it isn't) and the proposed behavior (do not raise an exception
when the directory already exists) is adopted.

In this case, there is a race condition between you and the attacker who
guesses the next directory you will attempt to make.  If he calls mkdir()
before you do, then your os.makedirs() returns successfully (instead of raising
an exception) and you place your files into a location that is under the
control of someone else.

If the attacker then makes the directory setuid himself, that files created in
the directory are owned by him.  Now, he can view and change the contents of
these files.  This can lead to a local priviledge escalation.

	Errors should never pass silently.
	Unless explicitly silenced.
		-- from the Zen of Python ('import this')
... and wanting them to do so may introduce a security bug in your software.

If you know more about your users and their environments than I do (for
instance, that none of them will ever use a multi-user computer system) maybe
you should choose to wrap os.makedirs with something that silences EEXIST.
But I'm glad Python does the secure thing and treats EEXIST as a failure by default.

Jeff
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20051020/4bd74b40/attachment.sig>


More information about the Python-list mailing list