os.mkfifo()
will fail with exception OSError: [Errno 17] File exists
if the file already exists, so there is no security issue here. The security issue with using tempfile.mktemp()
is the race condition where it is possible for an attacker to create a file with the same name before you open it yourself, but since os.mkfifo()
fails if the file already exists this is not a problem.
However, since mktemp()
is deprecated you shouldn't use it. You can use tempfile.mkdtemp()
instead:
import os, tempfile
tmpdir = tempfile.mkdtemp()
filename = os.path.join(tmpdir, 'myfifo')
print filename
try:
os.mkfifo(filename)
except OSError, e:
print "Failed to create FIFO: %s" % e
else:
fifo = open(filename, 'w')
# write stuff to fifo
print >> fifo, "hello"
fifo.close()
os.remove(filename)
os.rmdir(tmpdir)
EDIT: I should make it clear that, just because the mktemp()
vulnerability is averted by this, there are still the other usual security issues that need to be considered; e.g. an attacker could create the fifo (if they had suitable permissions) before your program did which could cause your program to crash if errors/exceptions are not properly handled.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…