| Home > CWE List > CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') (4.20) |
|
CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
View customized information:
For users who are interested in more notional aspects of a weakness. Example: educators, technical writers, and project/program managers.
For users who are concerned with the practical application and details about the nature of a weakness and how to prevent it from happening. Example: tool developers, security researchers, pen-testers, incident response analysts.
For users who are mapping an issue to CWE/CAPEC IDs, i.e., finding the most appropriate CWE for a specific issue (e.g., a CVE record). Example: tool developers, security researchers.
For users who wish to see all available information for the CWE/CAPEC entry.
For users who want to customize what details are displayed.
×
Edit Custom FilterMany file operations are intended to take place within a restricted directory. By using special elements such as ".." and "/" separators, attackers can escape outside of the restricted location to access files or directories that are elsewhere on the system. One of the most common special elements is the "../" sequence, which in most modern operating systems is interpreted as the parent directory of the current location. This is referred to as relative path traversal. Path traversal also covers the use of absolute pathnames such as "/usr/local/bin" to access unexpected files. This is referred to as absolute path traversal.
This table specifies different individual consequences
associated with the weakness. The Scope identifies the application security area that is
violated, while the Impact describes the negative technical impact that arises if an
adversary succeeds in exploiting this weakness. The Likelihood provides information about
how likely the specific consequence is expected to be seen relative to the other
consequences in the list. For example, there may be high likelihood that a weakness will be
exploited to achieve a certain impact, but a low likelihood that it will be exploited to
achieve a different impact.
This table shows the weaknesses and high level categories that are related to this
weakness. These relationships are defined as ChildOf, ParentOf, MemberOf and give insight to
similar items that may exist at higher and lower levels of abstraction. In addition,
relationships such as PeerOf and CanAlsoBe are defined to show similar weaknesses that the user
may want to explore.
Relevant to the view "Research Concepts" (View-1000)
Relevant to the view "Software Development" (View-699)
Relevant to the view "Weaknesses for Simplified Mapping of Published Vulnerabilities" (View-1003)
Relevant to the view "CISQ Quality Measures (2020)" (View-1305)
Relevant to the view "CISQ Data Protection Measures" (View-1340)
The different Modes of Introduction provide information
about how and when this
weakness may be introduced. The Phase identifies a point in the life cycle at which
introduction
may occur, while the Note provides a typical scenario related to introduction during the
given
phase.
This listing shows possible areas for which the given
weakness could appear. These
may be for specific named Languages, Operating Systems, Architectures, Paradigms,
Technologies,
or a class of such platforms. The platform is listed along with how frequently the given
weakness appears for that instance.
Example 1 The following code could be for a social networking application in which each user's profile information is stored in a separate file. All files are stored in a single directory. (bad code)
Example Language: Perl
my $dataPath = "/users/cwe/profiles";
my $username = param("user"); my $profilePath = $dataPath . "/" . $username; open(my $fh, "<", $profilePath) || ExitError("profile read error: $profilePath"); print "<ul>\n"; while (<$fh>) { print "<li>$_</li>\n"; }print "</ul>\n"; While the programmer intends to access files such as "/users/cwe/profiles/alice" or "/users/cwe/profiles/bob", there is no verification of the incoming user parameter. An attacker could provide a string such as: (attack code)
../../../etc/passwd
The program would generate a profile pathname like this: (result)
/users/cwe/profiles/../../../etc/passwd
When the file is opened, the operating system resolves the "../" during path canonicalization and actually accesses this file: (result)
/etc/passwd
As a result, the attacker could read the entire text of the password file. Notice how this code also contains an error message information leak (CWE-209) if the user parameter does not produce a file that exists: the full pathname is provided. Because of the lack of output encoding of the file that is retrieved, there might also be a cross-site scripting problem (CWE-79) if profile contains any HTML, but other code would need to be examined. Example 2 In the example below, the path to a dictionary file is read from a system property and used to initialize a File object. (bad code)
Example Language: Java
String filename = System.getProperty("com.domain.application.dictionaryFile");
File dictionaryFile = new File(filename); However, the path is not validated or modified to prevent it from containing relative or absolute path sequences before creating the File object. This allows anyone who can control the system property to determine what file is used. Ideally, the path should be resolved relative to some kind of application or user home directory. Example 3 The following code takes untrusted input and uses a regular expression to filter "../" from the input. It then appends this result to the /home/user/ directory and attempts to read the file in the final resulting path. (bad code)
Example Language: Perl
my $Username = GetUntrustedInput();
$Username =~ s/\.\.\///; my $filename = "/home/user/" . $Username; ReadAndSendFile($filename); Since the regular expression does not have the /g global match modifier, it only removes the first instance of "../" it comes across. So an input value such as: (attack code)
../../../etc/passwd
will have the first "../" stripped, resulting in: (result)
../../etc/passwd
This value is then concatenated with the /home/user/ directory: (result)
/home/user/../../etc/passwd
which causes the /etc/passwd file to be retrieved once the operating system has resolved the ../ sequences in the pathname. This leads to relative path traversal (CWE-23). Example 4 The following code attempts to validate a given input path by checking it against an allowlist and once validated delete the given file. In this specific case, the path is considered valid if it starts with the string "/safe_dir/". (bad code)
Example Language: Java
String path = getInputPath();
if (path.startsWith("/safe_dir/")) { File f = new File(path); }f.delete() An attacker could provide an input such as this: (attack code)
/safe_dir/../important.dat
The software assumes that the path is valid because it starts with the "/safe_path/" sequence, but the "../" sequence will cause the program to delete the important.dat file in the parent directory Example 5 The following code demonstrates the unrestricted upload of a file with a Java servlet and a path traversal vulnerability. The action attribute of an HTML form is sending the upload file request to the Java servlet. (good code)
Example Language: HTML
<form action="FileUploadServlet" method="post" enctype="multipart/form-data">
Choose a file to upload: <input type="file" name="filename"/> <br/> <input type="submit" name="submit" value="Submit"/> </form> When submitted the Java servlet's doPost method will receive the request, extract the name of the file from the Http request header, read the file contents from the request and output the file to the local upload directory. (bad code)
Example Language: Java
public class FileUploadServlet extends HttpServlet {
...
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out = response.getWriter(); String contentType = request.getContentType(); // the starting position of the boundary header int ind = contentType.indexOf("boundary="); String boundary = contentType.substring(ind+9); String pLine = new String(); String uploadLocation = new String(UPLOAD_DIRECTORY_STRING); //Constant value // verify that content type is multipart form data if (contentType != null && contentType.indexOf("multipart/form-data") != -1) { // extract the filename from the Http header
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); ... pLine = br.readLine(); String filename = pLine.substring(pLine.lastIndexOf("\\"), pLine.lastIndexOf("\"")); ... // output the file to the local upload directory try { BufferedWriter bw = new BufferedWriter(new FileWriter(uploadLocation+filename, true));
for (String line; (line=br.readLine())!=null; ) { if (line.indexOf(boundary) == -1) { } //end of for loopbw.write(line); }bw.newLine(); bw.flush(); bw.close(); } catch (IOException ex) {...} // output successful upload response HTML page // output unsuccessful upload response HTML page else {...} ...
This code does not perform a check on the type of the file being uploaded (CWE-434). This could allow an attacker to upload any executable file or other file with malicious code. Additionally, the creation of the BufferedWriter object is subject to relative path traversal (CWE-23). Since the code does not check the filename that is provided in the header, an attacker can use "../" sequences to write to files outside of the intended directory. Depending on the executing environment, the attacker may be able to specify arbitrary files to write to, leading to a wide variety of consequences, from code execution, XSS (CWE-79), or system crash. Example 6 This script intends to read a user-supplied file from the current directory. The user inputs the relative path to the file and the script uses Python's os.path.join() function to combine the path to the current working directory with the provided path to the specified file. This results in an absolute 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. (bad code)
Example Language: Python
import os
import sys def main():
filename = sys.argv[1]
main()
path = os.path.join(os.getcwd(), filename) try:
with open(path, 'r') as f:
except FileNotFoundError as e:
file_data = f.read()
print("Error - file not found")
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. (good code)
Example Language: Python
import os
import sys def main():
filename = sys.argv[1]
main()
path = os.path.normpath(f"{os.getcwd()}{os.sep}{filename}") if path.startswith("/home/cwe/documents/"):
try:
with open(path, 'r') as f:
except FileNotFoundError as e:
file_data = f.read()
print("Error - file not found")
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. The path is checked against an expected directory (/home/cwe/documents); otherwise, an attacker could provide relative path sequences like ".." to cause normpath() to generate paths that are outside the intended directory (CWE-23). 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/cwe/documents, and the user inputs /etc/passwd, the resulting path will be /home/cwe/documents/etc/passwd. The user is therefore contained within the current working directory as intended. Example 7 This PHP code takes user input in a file argument, obtains its contents, and presents the contents back to the caller. (bad code)
Example Language: PHP
$filename = $_GET['file']; // User-controlled input
echo file_get_contents($filename); // Read and display the file contents An attacker could manipulate the file path using relative (../) or absolute paths, potentially accessing sensitive system files. For example, if an attacker provides ../../../../etc/passwd as input, the script will fetch and display the contents of the system's password file. Ideally, the file path should be validated and restricted to a specific directory to prevent unauthorized file access. (good code)
Example Language: PHP
$allowed_files = [
'readme' => 'public_files/readme.txt',
];'terms' => 'public_files/terms.txt', $key = $_GET['file'] ?? ''; if (!isset($allowed_files[$key])) {
http_response_code(404);
}exit('File not found.'); $filepath = __DIR__ . '/' . $allowed_files[$key]; if (!is_file($filepath) || !is_readable($filepath)) {
http_response_code(404);
}exit('File not found.'); echo htmlspecialchars(file_get_contents($filepath), ENT_QUOTES, 'UTF-8'); Note: this is a curated list of examples for users to understand the variety of ways in which this weakness can be introduced. It is not a complete list of all CVEs that are related to this CWE entry.
|
| Method | Details |
|---|---|
|
Automated Static Analysis |
Automated techniques can find areas where path traversal weaknesses exist. However, tuning or customization may be required to remove or de-prioritize path-traversal problems that are only exploitable by the product's administrator - or other privileged users - and thus potentially valid behavior or, at worst, a bug instead of a vulnerability.
Effectiveness: High |
|
Manual Static Analysis |
Manual white box techniques may be able to provide sufficient code coverage and reduction of false positives if all file access operations can be assessed within limited time constraints.
Effectiveness: High |
|
Automated Static Analysis - Binary or Bytecode |
According to SOAR [REF-1479], the following detection techniques may be useful: Highly cost effective:
Cost effective for partial coverage:
Effectiveness: High |
|
Manual Static Analysis - Binary or Bytecode |
According to SOAR [REF-1479], the following detection techniques may be useful: Cost effective for partial coverage:
Effectiveness: SOAR Partial |
|
Dynamic Analysis with Automated Results Interpretation |
According to SOAR [REF-1479], the following detection techniques may be useful: Highly cost effective:
Effectiveness: High |
|
Dynamic Analysis with Manual Results Interpretation |
According to SOAR [REF-1479], the following detection techniques may be useful: Highly cost effective:
Effectiveness: High |
|
Manual Static Analysis - Source Code |
According to SOAR [REF-1479], the following detection techniques may be useful: Highly cost effective:
Cost effective for partial coverage:
Effectiveness: High |
|
Automated Static Analysis - Source Code |
According to SOAR [REF-1479], the following detection techniques may be useful: Highly cost effective:
Effectiveness: High |
|
Architecture or Design Review |
According to SOAR [REF-1479], the following detection techniques may be useful: Highly cost effective:
Cost effective for partial coverage:
Effectiveness: High |
This MemberOf Relationships table shows additional CWE Categories and Views that
reference this weakness as a member. This information is often useful in understanding where a
weakness fits within the context of external information sources.
| Nature | Type | ID | Name |
|---|---|---|---|
| MemberOf | 635 | Weaknesses Originally Used by NVD from 2008 to 2016 | |
| MemberOf | 715 | OWASP Top Ten 2007 Category A4 - Insecure Direct Object Reference | |
| MemberOf | 723 | OWASP Top Ten 2004 Category A2 - Broken Access Control | |
| MemberOf | 743 | CERT C Secure Coding Standard (2008) Chapter 10 - Input Output (FIO) | |
| MemberOf | 802 | 2010 Top 25 - Risky Resource Management | |
| MemberOf | 813 | OWASP Top Ten 2010 Category A4 - Insecure Direct Object References | |
| MemberOf | 865 | 2011 Top 25 - Risky Resource Management | |
| MemberOf | 877 | CERT C++ Secure Coding Section 09 - Input Output (FIO) | |
| MemberOf | 884 | CWE Cross-section | |
| MemberOf | 932 | OWASP Top Ten 2013 Category A4 - Insecure Direct Object References | |
| MemberOf | 981 | SFP Secondary Cluster: Path Traversal | |
| MemberOf | 1031 | OWASP Top Ten 2017 Category A5 - Broken Access Control | |
| MemberOf | 1131 | CISQ Quality Measures (2016) - Security | |
| MemberOf | 1179 | SEI CERT Perl Coding Standard - Guidelines 01. Input Validation and Data Sanitization (IDS) | |
| MemberOf | 1200 | Weaknesses in the 2019 CWE Top 25 Most Dangerous Software Errors | |
| MemberOf | 1308 | CISQ Quality Measures - Security | |
| MemberOf | 1337 | Weaknesses in the 2021 CWE Top 25 Most Dangerous Software Weaknesses | |
| MemberOf | 1340 | CISQ Data Protection Measures | |
| MemberOf | 1345 | OWASP Top Ten 2021 Category A01:2021 - Broken Access Control | |
| MemberOf | 1350 | Weaknesses in the 2020 CWE Top 25 Most Dangerous Software Weaknesses | |
| MemberOf | 1387 | Weaknesses in the 2022 CWE Top 25 Most Dangerous Software Weaknesses | |
| MemberOf | 1404 | Comprehensive Categorization: File Handling | |
| MemberOf | 1425 | Weaknesses in the 2023 CWE Top 25 Most Dangerous Software Weaknesses | |
| MemberOf | 1430 | Weaknesses in the 2024 CWE Top 25 Most Dangerous Software Weaknesses | |
| MemberOf | 1435 | Weaknesses in the 2025 CWE Top 25 Most Dangerous Software Weaknesses | |
| MemberOf | 1436 | OWASP Top Ten 2025 Category A01:2025 - Broken Access Control | |
| MemberOf | 1447 | General Software Weaknesses that Appear in Products that Use or Support AI/ML Technology |
| Usage |
ALLOWED-WITH-REVIEW
(this CWE ID could be used to map to real-world vulnerabilities in limited situations requiring careful review)
|
| Reason | Abstraction |
|
Rationale |
This CWE entry might have children that would be more appropriate. |
|
Comments |
Examine children of this entry to see if there is a better fit. Consider children such as CWE-23 (or its descendants) for relative path traversal, or CWE-36 for absolute path traversal. |
|
Suggestions |
Relationship
Relationship
Terminology
Like other weaknesses, terminology is often based on the types of manipulations used, instead of the underlying weaknesses. Some people use "directory traversal" only to refer to the injection of ".." and equivalent sequences whose specific meaning is to traverse directories.
Other variants like "absolute pathname" and "drive letter" have the *effect* of directory traversal, but some people may not call it such, since it doesn't involve ".." or equivalent.
Research Gap
Research Gap
Incomplete diagnosis or reporting of vulnerabilities can make it difficult to know which variant is affected. For example, a researcher might say that "..\" is vulnerable, but not test "../" which may also be vulnerable.
Any combination of directory separators ("/", "\", etc.) and numbers of "." (e.g. "....") can produce unique variants; for example, the "//../" variant is not listed (CVE-2004-0325). See this entry's children and lower-level descendants.
Other
| Mapped Taxonomy Name | Node ID | Fit | Mapped Node Name |
|---|---|---|---|
| PLOVER | Path Traversal | ||
| OWASP Top Ten 2007 | A4 | CWE More Specific | Insecure Direct Object Reference |
| OWASP Top Ten 2004 | A2 | CWE More Specific | Broken Access Control |
| CERT C Secure Coding | FIO02-C | Canonicalize path names originating from untrusted sources | |
| SEI CERT Perl Coding Standard | IDS00-PL | Exact | Canonicalize path names before validating them |
| WASC | 33 | Path Traversal | |
| Software Fault Patterns | SFP16 | Path Traversal | |
| OMG ASCSM | ASCSM-CWE-22 |
| [REF-7] |
Michael Howard and David LeBlanc. "Writing Secure Code". Chapter 11, "Directory Traversal and Using Parent Paths (..)" Page 370. 2nd Edition. Microsoft Press. 2002-12-04.
<https://www.microsoftpressstore.com/store/writing-secure-code-9780735617223>. |
| [REF-45] |
OWASP. "OWASP Enterprise Security API (ESAPI) Project".
<https://owasp.org/www-project-enterprise-security-api/>. (URL validated: 2025-07-24) |
| [REF-185] |
OWASP. "Testing for Path Traversal (OWASP-AZ-001)".
<http://www.owasp.org/index.php/Testing_for_Path_Traversal_(OWASP-AZ-001)>. |
| [REF-186] |
Johannes Ullrich. "Top 25 Series - Rank 7 - Path Traversal". SANS Software Security Institute. 2010-03-09.
<https://www.sans.org/blog/top-25-series-rank-7-path-traversal/>. (URL validated: 2023-04-07) |
| [REF-76] |
Sean Barnum and Michael Gegick. "Least Privilege". 2005-09-14.
<https://web.archive.org/web/20211209014121/https://www.cisa.gov/uscert/bsi/articles/knowledge/principles/least-privilege>. (URL validated: 2023-04-07) |
| [REF-62] | Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 9, "Filenames and Paths", Page 503. 1st Edition. Addison Wesley. 2006. |
| [REF-962] |
Object Management Group (OMG). "Automated Source Code Security Measure (ASCSM)". ASCSM-CWE-22. 2016-01.
<http://www.omg.org/spec/ASCSM/1.0/>. |
| [REF-1448] |
Cybersecurity and Infrastructure Security Agency. "Secure by Design Alert: Eliminating Directory Traversal Vulnerabilities in Software". 2024-05-02.
<https://www.cisa.gov/resources-tools/resources/secure-design-alert-eliminating-directory-traversal-vulnerabilities-software>. (URL validated: 2024-07-14) |
| [REF-1479] |
Gregory Larsen, E. Kenneth Hong Fong, David A. Wheeler and Rama S. Moorthy. "State-of-the-Art Resources (SOAR) for Software Vulnerability Detection, Test, and Evaluation". 2014-07.
<https://www.ida.org/-/media/feature/publications/s/st/stateoftheart-resources-soar-for-software-vulnerability-detection-test-and-evaluation/p-5061.ashx>. (URL validated: 2025-09-05) |
| [REF-1481] |
D3FEND. "D3FEND: Application Layer Firewall".
<https://d3fend.mitre.org/dao/artifact/d3f:ApplicationLayerFirewall/>. (URL validated: 2025-09-06) |
| [REF-1482] |
D3FEND. "D3FEND: D3-TL Trusted Library".
<https://d3fend.mitre.org/technique/d3f:TrustedLibrary/>. (URL validated: 2025-09-06) |
|
Use of the Common Weakness Enumeration (CWE™) and the associated references from this website are subject to the Terms of Use. CWE is sponsored by the U.S. Department of Homeland Security (DHS) Cybersecurity and Infrastructure Security Agency (CISA) and managed by the Homeland Security Systems Engineering and Development Institute (HSSEDI) which is operated by The MITRE Corporation (MITRE). Copyright © 2006–2026, The MITRE Corporation. CWE, CWSS, CWRAF, and the CWE logo are trademarks of The MITRE Corporation. |
||

