49
Example 2:
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.
Example Language: Perl (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:
Example Language: (Attack)
../../../etc/passwd
The program would generate a profile pathname like this:
Example Language: (Result)
/users/cwe/profiles/../../../etc/passwd
When the file is opened, the operating system resolves the "../" during path canonicalization and
actually accesses this file:
Example Language: (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 3:
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.
Example Language: HTML (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.
CWE Version 4.14
CWE-23: Relative Path Traversal
CWE-23: Relative Path Traversal