最佳答案
我希望根据文件是否已经存在来写入一个文件,只有在文件不存在的情况下才写入(实际上,我希望不断尝试文件,直到找到一个不存在的文件)。
下面的代码显示了潜在攻击者可以插入符号链接的方式,正如 这篇文章中在文件测试和正在编写的文件之间所建议的那样。如果代码以足够高的权限运行,这可能会覆盖任意文件。
有办法解决这个问题吗?
import os
import errno
file_to_be_attacked = 'important_file'
with open(file_to_be_attacked, 'w') as f:
f.write('Some important content!\n')
test_file = 'testfile'
try:
with open(test_file) as f: pass
except IOError, e:
# Symlink created here
os.symlink(file_to_be_attacked, test_file)
if e.errno != errno.ENOENT:
raise
else:
with open(test_file, 'w') as f:
f.write('Hello, kthxbye!\n')