ฉันต้องการเขียนลงในไฟล์โดยขึ้นอยู่กับว่าไฟล์นั้นมีอยู่แล้วหรือไม่เพียงเขียนเมื่อไม่มีอยู่แล้วเท่านั้น (ในทางปฏิบัติฉันต้องการลองไฟล์ต่อไปจนกว่าฉันจะพบไฟล์ที่ไม่มีอยู่)
โค้ดต่อไปนี้แสดงวิธีที่ผู้โจมตีอาจแทรก symlink ตามที่แนะนำในโพสต์นี้ระหว่างการทดสอบไฟล์และไฟล์ที่กำลังเขียน หากรหัสถูกเรียกใช้โดยมีสิทธิ์สูงเพียงพอสิ่งนี้อาจเขียนทับไฟล์โดยพลการ
มีวิธีใดในการแก้ปัญหานี้หรือไม่?
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')