Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Insecure temporary file

ID: py/insecure-temporary-fileKind: problemSecurity severity: 7.0Severity: errorPrecision: highTags:   - external/cwe/cwe-377   - securityQuery suites:   - python-code-scanning.qls   - python-security-extended.qls   - python-security-and-quality.qls

Click to see the query in the CodeQL repository

Functions that create temporary file names (such astempfile.mktemp andos.tempnam) are fundamentally insecure, as they do not ensure exclusive access to a file with the temporary name they return. The file name returned by these functions is guaranteed to be unique on creation but the file must be opened in a separate operation. There is no guarantee that the creation and open operations will happen atomically. This provides an opportunity for an attacker to interfere with the file before it is opened.

Note thatmktemp has been deprecated since Python 2.3.

Recommendation

Replace the use ofmktemp with some of the more secure functions in thetempfile module, such asTemporaryFile. If the file is intended to be accessed from other processes, consider using theNamedTemporaryFile function.

Example

The following piece of code opens a temporary file and writes a set of results to it. Because the file name is created usingmktemp, another process may access this file before it is opened usingopen.

fromtempfileimportmktempdefwrite_results(results):filename=mktemp()withopen(filename,"w+")asf:f.write(results)print("Results written to",filename)

By changing the code to useNamedTemporaryFile instead, the file is opened immediately.

fromtempfileimportNamedTemporaryFiledefwrite_results(results):withNamedTemporaryFile(mode="w+",delete=False)asf:f.write(results)print("Results written to",f.name)

References


[8]ページ先頭

©2009-2025 Movatter.jp