77
path to the desired file. If the file does not exist when the script attempts to read it, an error is
printed to the user.
Example Language: Python (Bad)
import os
import sys
def main():
filename = sys.argv[1]
path = os.path.join(os.getcwd(), filename)
try:
with open(path, 'r') as f:
file_data = f.read()
except FileNotFoundError as e:
print("Error - file not found")
main()
However, if the user supplies an absolute path, the os.path.join() function will discard the path to
the current working directory and use only the absolute path provided. For example, if the current
working directory is /home/user/documents, but the user inputs /etc/passwd, os.path.join() will use
only /etc/passwd, as it is considered an absolute path. In the above scenario, this would cause the
script to access and read the /etc/passwd file.
Example Language: Python (Good)
import os
import sys
def main():
filename = sys.argv[1]
path = os.path.normpath(f"{os.getcwd()}{os.sep}{filename}")
try:
with open(path, 'r') as f:
file_data = f.read()
except FileNotFoundError as e:
print("Error - file not found")
main()
The constructed path string uses os.sep to add the appropriate separation character for the given
operating system (e.g. '\' or '/') and the call to os.path.normpath() removes any additional slashes
that may have been entered - this may occur particularly when using a Windows path. By putting
the pieces of the path string together in this fashion, the script avoids a call to os.path.join() and
any potential issues that might arise if an absolute path is entered. With this version of the script,
if the current working directory is /home/user/documents, and the user inputs /etc/passwd, the
resulting path will be /home/user/documents/etc/passwd. The user is therefore contained within the
current working directory as intended.
Observed Examples
Reference Description
CVE-2022-31503 Python package constructs filenames using an unsafe os.path.join call on
untrusted input, allowing absolute path traversal because os.path.join resets
the pathname to an absolute path that is specified as part of the input.
https://www.cve.org/CVERecord?id=CVE-2022-31503
CVE-2002-1345 Multiple FTP clients write arbitrary files via absolute paths in server responses
https://www.cve.org/CVERecord?id=CVE-2002-1345
CVE-2001-1269 ZIP file extractor allows full path
https://www.cve.org/CVERecord?id=CVE-2001-1269
CVE-2002-1818 Path traversal using absolute pathname
https://www.cve.org/CVERecord?id=CVE-2002-1818
CVE-2002-1913 Path traversal using absolute pathname
https://www.cve.org/CVERecord?id=CVE-2002-1913
CWE Version 4.14
CWE-36: Absolute Path Traversal
CWE-36: Absolute Path Traversal