The documentation for the os
module makes the following assertion:
Note
Using access() to check if a user is authorized to e.g. open a file before actually doing so using open() creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it. It’s preferable to use EAFP techniques. For example:
if os.access("myfile", os.R_OK):
with open("myfile") as fp:
return fp.read()
return "some default data"`
is better written as:
try:
fp = open("myfile")
except PermissionError:
return "some default data"
else:
with fp:
return fp.read()
I don't understand how a user "might exploit" the interval. If open
was going to raise an exception, I'm not sure how os.access
would prevent that exception from being raised. Likewise, if the user manipulate the file somehow, why not perform the file manipulation prior to the EAFP version's open
command?
I do understand that the second version may be more robust, since os.access
may fail to correctly recognize a condition that could raise a PermissionError
, but I don't see how the LBYL version is less secure. Can someone explain this?