Add query and qhelp.

This commit is contained in:
Taus Brock-Nannestad
2019-01-17 14:39:38 +01:00
parent 65337ef835
commit 7c3dc929ac
4 changed files with 84 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
from tempfile import mktemp
def write_results(results):
filename = mktemp()
with open(filename, "w+") as f:
f.write(results)
print("Results written to", filename)

View File

@@ -0,0 +1,51 @@
<!DOCTYPE qhelp PUBLIC "-//Semmle//qhelp//EN" "qhelp.dtd">
<qhelp>
<overview>
<p>
Creating a new temporary file using the <code>mktemp</code> function in the
<code>tempfile</code> does not ensure exclusive access to the file, as it simply
returns a filename that is guaranteed to be unique at the point when
<code>mktemp</code> returns. Opening a file with this name must then happen
separately, and there is no guarantee that these operations will happen
atomically. Because of this, it may be possible for an attacker to interfere
with the file before it is opened.
</p>
<p>
Note that <code>mktemp</code> has been deprecated since Python 2.3.
</p>
</overview>
<recommendation>
<p>
Replace the use of <code>mktemp</code> with some of the more secure functions
in the <code>tempfile</code> module, such as <code>TemporaryFile</code>. If the
file is intended to be accessed from other processes, consider using the
<code>NamedTemporaryFile</code> function.
</p>
</recommendation>
<example>
<p>
The following piece of code opens a temporary file and writes a set of results
to it. Because the filename is created using <code>mktemp</code>, another
process may have accessed this file before it is opened using <code>open</code>.
</p>
<sample src="InsecureTemporaryFile.py" />
<p>
By changing the code to use <code>NamedTemporaryFile</code> instead, the file is
opened immediately.
</p>
<sample src="SecureTemporaryFile.py" />
</example>
<references>
<li>
Python Standard Library: <a href="https://docs.python.org/3/library/tempfile.html#tempfile.mktemp">tempfile.mktemp</a>.
</li>
</references>
</qhelp>

View File

@@ -0,0 +1,20 @@
/**
* @name Insecure temporary file
* @description Creating a temporary file using mktemp may be insecure.
* @id py/insecure-temporary-file
* @problem.severity error
* @sub-severity high
* @precision high
* @tags external/cwe/cwe-377
* security
*/
import python
FunctionObject mktemp() {
result = any(ModuleObject m | m.getName() = "tempfile").getAttribute("mktemp")
}
from CallNode c
where c.getFunction().refersTo(mktemp())
select c, "Call to deprecated function mktemp may be insecure."

View File

@@ -0,0 +1,6 @@
from tempfile import NamedTemporaryFile
def write_results(results):
with NamedTemporaryFile(mode="w+", delete=False) as f:
f.write(results)
print("Results written to", f.name)