|
| 1 | +<!DOCTYPE qhelp PUBLIC "-//Semmle//qhelp//EN" "qhelp.dtd"> |
| 2 | +<qhelp> |
| 3 | + |
| 4 | +<overview> |
| 5 | +<p> |
| 6 | +Creating a new temporary file using the <code>mktemp</code> function in the |
| 7 | +<code>tempfile</code> does not ensure exclusive access to the file, as it simply |
| 8 | +returns a filename that is guaranteed to be unique at the point when |
| 9 | +<code>mktemp</code> returns. Opening a file with this name must then happen |
| 10 | +separately, and there is no guarantee that these operations will happen |
| 11 | +atomically. Because of this, it may be possible for an attacker to interfere |
| 12 | +with the file before it is opened. |
| 13 | +</p> |
| 14 | +<p> |
| 15 | +Note that <code>mktemp</code> has been deprecated since Python 2.3. |
| 16 | +</p> |
| 17 | +</overview> |
| 18 | + |
| 19 | +<recommendation> |
| 20 | +<p> |
| 21 | +Replace the use of <code>mktemp</code> with some of the more secure functions |
| 22 | +in the <code>tempfile</code> module, such as <code>TemporaryFile</code>. If the |
| 23 | +file is intended to be accessed from other processes, consider using the |
| 24 | +<code>NamedTemporaryFile</code> function. |
| 25 | +</p> |
| 26 | +</recommendation> |
| 27 | + |
| 28 | +<example> |
| 29 | +<p> |
| 30 | +The following piece of code opens a temporary file and writes a set of results |
| 31 | +to it. Because the filename is created using <code>mktemp</code>, another |
| 32 | +process may have accessed this file before it is opened using <code>open</code>. |
| 33 | +</p> |
| 34 | +<sample src="InsecureTemporaryFile.py" /> |
| 35 | + |
| 36 | +<p> |
| 37 | +By changing the code to use <code>NamedTemporaryFile</code> instead, the file is |
| 38 | +opened immediately. |
| 39 | +</p> |
| 40 | +<sample src="SecureTemporaryFile.py" /> |
| 41 | + |
| 42 | +</example> |
| 43 | + |
| 44 | +<references> |
| 45 | + |
| 46 | +<li> |
| 47 | +Python Standard Library: <a href="https://docs.python.org/3/library/tempfile.html#tempfile.mktemp">tempfile.mktemp</a>. |
| 48 | +</li> |
| 49 | +</references> |
| 50 | + |
| 51 | +</qhelp> |
0 commit comments