用户工具

站点工具


cwe:cn:definition:22

CWE-22:对路径名的限制不恰当(路径遍历)

Description Summary

The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.

Extended Description

Many 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”, which may also be useful in accessing unexpected files. This is referred to as absolute path traversal.

In many programming languages, the injection of a null byte (the 0 or NUL) may allow an attacker to truncate a generated filename to widen the scope of attack. For example, the software may add ”.txt” to any pathname, thus limiting the attacker to text files, but a null injection may effectively remove this restriction.

Likelihood of Exploit

High to Very High

Common Consequences

Scope Technical Impace Note
Integrity
Confidentiality
Availability
Execute unauthorized code or commandsThe attacker may be able to create or overwrite critical files that are used to execute code, such as programs or libraries.
IntegrityModify files or directoriesThe attacker may be able to overwrite or create critical files, such as programs, libraries, or important data. If the targeted file is used for a security mechanism, then the attacker may be able to bypass that mechanism. For example, appending a new account at the end of a password file may allow an attacker to bypass authentication.
ConfidentialityRead files or directoriesThe attacker may be able read the contents of unexpected files and expose sensitive data. If the targeted file is used for a security mechanism, then the attacker may be able to bypass that mechanism. For example, by reading a password file, the attacker could conduct brute force password guessing attacks in order to break into an account on the system.
AvailabilityDoS: crash / exit / restartThe attacker may be able to overwrite, delete, or corrupt unexpected critical files such as programs, libraries, or important data. This may prevent the software from working at all and in the case of a protection mechanisms such as authentication, it has the potential to lockout every user of the software.

Detection Methods

Detection Method - 1

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 software's administrator - or other privileged users - and thus potentially valid behavior or, at worst, a bug instead of a vulnerability.

Detection Method - 2

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.

Detection Method - 3

Automated Static Analysis - Binary / Bytecode

According to SOAR, the following detection techniques may be useful:

Detection Method - 4

Manual Static Analysis - Binary / Bytecode

According to SOAR, the following detection techniques may be useful:

Detection Method - 5

=== Dynamic Analysis with automated results interpretation === According to SOAR, the following detection techniques may be useful:

Detection Method - 6

Dynamic Analysis with manual results interpretation

According to SOAR, the following detection techniques may be useful:

Detection Method - 7

Manual Static Analysis - Source Code

According to SOAR, the following detection techniques may be useful:

Detection Method - 8

Automated Static Analysis - Source Code

According to SOAR, the following detection techniques may be useful:

Detection Method - 9

Architecture / Design Review

According to SOAR, the following detection techniques may be useful:

Potential Mitigations

Mitigation - 1

Implementation

Strategy:Input Validation

Assume all input is malicious. Use an “accept known good” input validation strategy, i.e., use a whitelist 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 related fields, and conformance to business rules. As an example of business rule logic, “boat” may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as “red” or “blue.”

Do not rely exclusively on looking for malicious or malformed inputs (i.e., do not rely on a blacklist). A blacklist is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, blacklists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright.

When validating filenames, use stringent whitelists that limit the character set to be used. If feasible, only allow a single ”.” character in the filename to avoid weaknesses such as CWE-23, and exclude directory separators such as ”/” to avoid CWE-36. Use a whitelist of allowable file extensions, which will help to avoid CWE-434.

Do not rely exclusively on a filtering mechanism that removes potentially dangerous characters. This is equivalent to a blacklist, which may be incomplete (CWE-184). For example, filtering ”/” is insufficient protection if the filesystem also supports the use of “\” as a directory separator. Another possible error could occur when the filtering is applied in a way that still produces dangerous data (CWE-182). For example, if ”../” sequences are removed from the ”…/…//” string in a sequential fashion, two instances of ”../” would be removed from the original string, but the remaining characters would still form the ”../” string.

2013/05/30 09:37

Mitigation - 2

Architecture and Design

For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.

2013/05/30 09:37

Mitigation - 3

Implementation

Strategy:Input Validation

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 whitelist 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 removes ”..” sequences and symbolic links (CWE-23, CWE-59). This includes:

2013/05/30 09:37

Mitigation - 4

Architecture and Design

Strategy:Libraries or Frameworks

Use a vetted library or framework that does not allow this weakness to occur or provides constructs that make this weakness easier to avoid.

For example, use anti-CSRF packages such as the OWASP CSRFGuard. [R.352.3]

Another example is the ESAPI Session Management control, which includes a component for CSRF. [R.352.9]

2013/05/30 09:36

Mitigation - 5

Operation

Strategy:Firewall

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.

2013/05/30 09:37

Mitigation - 6

Architecture and Design Operation

Strategy:Environment Hardening

Run your code using the lowest privileges that are required to accomplish the necessary tasks [R.98.2]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations.

2013/05/30 09:37

Mitigation - 7

Architecture and Design

Strategy:Enforcement by Conversion

When the set of acceptable objects, such as filenames or URLs, is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs, and reject all other inputs.

For example, ID 1 could map to “inbox.txt” and ID 2 could map to “profile.txt”. Features such as the ESAPI AccessReferenceMap [R.98.1] provide this capability.

2013/05/30 09:37

Mitigation - 8

Architecture and Design Operation

Strategy:Sandbox or Jail

Run the code in a “jail” or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict which files can be accessed in a particular directory or which commands can be executed by the software.

OS-level examples include the Unix chroot jail, AppArmor, and SELinux. In general, managed code may provide some protection. For example, java.io.FilePermission in the Java SecurityManager allows the software to specify restrictions on file operations.

This may not be a feasible solution, and it only limits the impact to the operating system; the rest of the application may still be subject to compromise.

Be careful to avoid CWE-243 and other weaknesses related to jails.

2013/05/30 09:37

Mitigation - 9

Architecture and Design Operation

Strategy:Identify and Reduce Attack Surface

Store library, include, and utility files outside of the web document root, if possible. Otherwise, store them in a separate directory and use the web server's access control capabilities to prevent attackers from directly requesting them. One common practice is to define a fixed constant in each calling program, then check for the existence of the constant in the library/include file; if the constant does not exist, then the file was directly requested, and it can exit immediately.

This significantly reduces the chance of an attacker being able to bypass any protection mechanisms that are in the base program but not in the include files. It will also reduce the attack surface.

2013/05/30 13:23

Mitigation - 10

Implementation

Ensure that error messages only contain minimal details that are useful to the intended audience, and nobody else. The messages need to strike the balance between being too cryptic and not being cryptic enough. They should not necessarily reveal the methods that were used to determine the error. Such detailed information can be used to refine the original attack to increase the chances of success.

If errors must be tracked in some detail, capture them in log messages - but consider what could occur if the log messages can be viewed by attackers. Avoid recording highly sensitive information such as passwords in any form. Avoid inconsistent messaging that might accidentally tip off an attacker about internal state, such as whether a username is valid or not.

In the context of SQL Injection, error messages revealing the structure of a SQL query can help attackers tailor successful attack strings.

2013/05/30 13:23

Mitigation - 11

Operation Implementation

Strategy:Environment Hardening

When using PHP, configure the application so that it does not use register_globals. During implementation, develop the application so that it does not rely on this feature, but be wary of implementing a register_globals emulation that is subject to weaknesses such as CWE-95, CWE-621, and similar issues.

Often, programmers do not protect direct access to files intended only to be included by core programs. These include files may assume that critical variables have already been initialized by the calling program. As a result, the use of register_globals combined with the ability to directly access the include file may allow attackers to conduct file inclusion attacks. This remains an extremely common pattern as of 2009.

2013/05/30 09:37

Demonstrative Examples

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.

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:

../../../etc/passwd 

The program would generate a profile pathname like this:

/users/cwe/profiles/../../../etc/passwd 

When the file is opened, the operating system resolves the ”../” during path canonicalization and actually accesses this file:

/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.

2013/05/30 13:23

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.

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 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.

2013/05/30 13:23

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.

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:

../../../etc/passwd 

will have the first ”../” stripped, resulting in:

../../etc/passwd 

This value is then concatenated with the /home/user/ directory:

/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).

2013/05/30 09:37

Example - 4

The following code attempts to validate a given input path by checking it against a white list and once validated delete the given file. In this specific case, the path is considered valid if it starts with the string ”/safe_dir/”.

String path = getInputPath(); 
if (path.startsWith("/safe_dir/")) 
{ 
File f = new File(path); 
f.delete() 
 
} 

An attacker could provide an input such as this:

/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 HTML code is the same as in the previous example with the action attribute of the form sending the upload file request to the Java servlet instead of the PHP code.

<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.

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) { 
bw.write(line); 
bw.newLine(); 
bw.flush(); 
 
} 
 
} //end of for loop 
bw.close(); 
 
 
} catch (IOException ex) {...} 
// output successful upload response HTML page 
 
} 
// output unsuccessful upload response HTML page 
else 
{...} 
 
} 
... 
 
 
} 

As with the previous example this code does not perform a check on the type of the file being uploaded. 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-22, CWE-23). 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.

2013/05/30 13:23

Observed Examples

Reference Description
CVE-2010-0467Newsletter module allows reading arbitrary files using ”../” sequences.
CVE-2009-4194FTP server allows deletion of arbitrary files using ”..” in the DELE command.
CVE-2009-4053FTP server allows creation of arbitrary directories using ”..” in the MKD command.
CVE-2009-0244OBEX FTP service for a Bluetooth device allows listing of directories, and creation or reading of files using ”..” sequences.
CVE-2009-4013Software package maintenance program allows overwriting arbitrary files using ”../” sequences.
CVE-2009-4449Bulletin board allows attackers to determine the existence of files using the avatar.
CVE-2009-4581PHP program allows arbitrary code execution using ”..” in filenames that are fed to the include() function.
CVE-2010-0012Overwrite of files using a .. in a Torrent file.
CVE-2010-0013Chat program allows overwriting files using a custom smiley request.
CVE-2008-5748Chain: external control of values for user's desired language and theme enables path traversal.
CVE-2009-1936Chain: library file sends a redirect if it is directly requested but continues to execute, allowing remote file inclusion and path traversal.
cwe/cn/definition/22.txt · 最后更改: 2014/09/04 14:28 (外部编辑)