Base · Medium

CWE-23: Relative Path Traversal

The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as ".." that can resolve to a location that is...

CWE-23 · Base Level ·34 CVEs ·3 Mitigations

Description

The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as ".." that can resolve to a location that is outside of that directory.

Potential Impact

Integrity, Confidentiality, Availability

Execute Unauthorized Code or Commands

Integrity

Modify Files or Directories

Confidentiality

Read Files or Directories

Availability

DoS: Crash, Exit, or Restart

Demonstrative Examples

The following URLs are vulnerable to this attack:
Bad
http://example.com/get-files.jsp?file=report.pdfhttp://example.com/get-page.php?home=aaa.htmlhttp://example.com/some-page.asp?page=index.html
A simple way to execute this attack is like this:
Attack
http://example.com/get-files?file=../../../../somedir/somefilehttp://example.com/../../../../etc/shadowhttp://example.com/get-files?file=../../../../etc/passwd
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
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
../../../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.
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
<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
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 headerint 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 dataif (contentType != null && contentType.indexOf("multipart/form-data") != -1) {
                                 
                                    // extract the filename from the Http headerBufferedReader 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 directorytry {
                                          BufferedWriter bw = new BufferedWriter(new FileWriter(uploadLocation+filename, true));for (String line; (line=br.readLine())!=null; ) {if (line.indexOf(boundary) == -1) {bw.write(line);bw.newLine();bw.flush();}} //end of for loopbw.close();
                                       
                                       
                                       } catch (IOException ex) {...}// output successful upload response HTML page
                                 }// output unsuccessful upload response HTML pageelse{...}
                           }...
                        
                     }
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.

Mitigations & Prevention

Implementation

Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across relat

Implementation

Inputs should be decoded and canonicalized to the application's current internal representation before being validated (CWE-180). Make sure that the application does not decode the same input twice (CWE-174). Such errors could be used to bypass allowlist validation schemes by introducing dangerous inputs after they have been checked. Use a built-in path canonicalization function (such as realpath() in C) that produces the canonical version of the pathname, which effectively r

Operation Moderate

Use an application firewall that can detect attacks against this weakness. It can be beneficial in cases in which the code cannot be fixed (because it is controlled by a third party), as an emergency prevention measure while more comprehensive software assurance measures are applied, or to provide defense in depth [REF-1481].

Detection Methods

  • Automated Static Analysis High — Automated static analysis, commonly referred to as Static Application Security Testing (SAST), can find some instances of this weakness by analyzing source code (or binary/compiled code) without having to execute it. Typically, this is done by building a model of data flow and control flow, then sea

Real-World CVE Examples

CVE IDDescription
CVE-2024-37032Large language model (LLM) management tool does not validate the format of a digest value (CWE-1287) from a private, untrusted model registry, enabling relative
CVE-2024-0520Product for managing datasets for AI model training and evaluation allows both relative (CWE-23) and absolute (CWE-36) path traversal to overwrite files via the Content-Disposition header
CVE-2022-45918Chain: a learning management tool debugger uses external input to locate previous session logs (CWE-73) and does not properly validate the given path (CWE-20), allowing for filesystem path traversal u
CVE-2019-20916Python package manager does not correctly restrict the filename specified in a Content-Disposition header, allowing arbitrary file read using path traversal sequences such as "../"
CVE-2022-24877directory traversal in Go-based Kubernetes operator app allows accessing data from the controller's pod file system via ../ sequences in a yaml file
CVE-2020-4053a Kubernetes package manager written in Go allows malicious plugins to inject path traversal sequences into a plugin archive ("Zip slip") to copy a file outside the intended directory
CVE-2021-21972Chain: Cloud computing virtualization platform does not require authentication for upload of a tar format file (CWE-306), then uses .. path traversal sequences (CWE-23) in the file to access unexpecte
CVE-2019-10743Go-based archive library allows extraction of files to locations outside of the target folder with "../" path traversal sequences in filenames in a zip file, aka "Zip Slip"
CVE-2002-0298Server allows remote attackers to cause a denial of service via certain HTTP GET requests containing a %2e%2e (encoded dot-dot), several "/../" sequences, or several "../" in a URI.
CVE-2002-0661"\" not in denylist for web server, allowing path traversal attacks when the server is run in Windows and other OSes.
CVE-2002-0946Arbitrary files may be read files via ..\ (dot dot) sequences in an HTTP request.
CVE-2002-1042Directory traversal vulnerability in search engine for web server allows remote attackers to read arbitrary files via "..\" sequences in queries.
CVE-2002-1209Directory traversal vulnerability in FTP server allows remote attackers to read arbitrary files via "..\" sequences in a GET request.
CVE-2002-1178Directory traversal vulnerability in servlet allows remote attackers to execute arbitrary commands via "..\" sequences in an HTTP request.
CVE-2002-1987Protection mechanism checks for "/.." but doesn't account for Windows-specific "\.." allowing read of arbitrary files.

Showing 15 of 34 observed examples.

Taxonomy Mappings

  • PLOVER: — Relative Path Traversal
  • Software Fault Patterns: SFP16 — Path Traversal

Frequently Asked Questions

What is CWE-23?

CWE-23 (Relative Path Traversal) is a software weakness identified by MITRE's Common Weakness Enumeration. It is classified as a Base-level weakness. The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as ".." that can resolve to a location that is...

How can CWE-23 be exploited?

Attackers can exploit CWE-23 (Relative Path Traversal) to execute unauthorized code or commands. This weakness is typically introduced during the Implementation phase of software development.

How do I prevent CWE-23?

Key mitigations include: Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not stric

What is the severity of CWE-23?

CWE-23 is classified as a Base-level weakness (Medium abstraction). It has been observed in 34 real-world CVEs.