Total Tests:

CWE Glossary

CWE is a trademark of the MITRE Corporation.

Stay in Touch

Get exclusive updates and invitations to our events and webinars:

Your data will stay confidential Private and Confidential

Path Traversal [CWE-22]

Path traversal or Directory traversal is a security vulnerability that describes improper limitation of pathname to a restricted directory.

Path Traversal [CWE-22]

Created: September 11, 2012
Latest Update: December 29, 2020

Table of Content

  1. Description
  2. Potential impact
  3. Attack patterns
  4. Affected software
  5. Exploitation Examples
  6. Severity and CVSS Scoring
  7. Mitigations
  8. Vulnerability Remediation Techniques and Examples
  9. Common Fix Errors and Bypasses
  10. References
  11. Related Security Advisories

Want to have an in-depth understanding of all modern aspects of
Path Traversal [CWE-22]? Read carefully this article and bookmark it to get back later, we regularly update this page.

1. Description

Path traversal or Directory traversal is a security vulnerability that occurs when software uses attacker-controlled input to construct a pathname to a directory or file located outside of the restricted directory. An attacker might be able to read arbitrary files on the target system.

There are two types of path traversal weaknesses:

1.1 Relative path traversal [CWE-23]

An attacker can use special separators such as ".." and "/" to escape the current directory and access files and directories outside of the restricted location. One of the most popular special element sequences is "../", which is interpreted in modern operating systems as the parent directory above the current location. In many programming languages null byte (%00) can be used to truncate the generated filename and widen the scope of attack.

In case the NULL byte is filtered, a remote attacker can use alternative techniques such as maximum path length limitations of different systems.

The application uses untrusted input as part of a filename and then reads a .txt file from the system. The following code in PHP reads a file located in the "dir" directory with .txt extension:

  1. echo file_get_contents ($_SERVER["DOCUMENT_ROOT"]."/dir/".$_GET["lang"].".txt");

An attacker can truncate the .txt extension and read arbitrary file on the system, e.g. /etc/passwd using the following request:
http://[host]/vuln_script.php?lang=../../../../etc/passwd././././././././././ ... ./././

1.2 Absolute path traversal [CWE-36]

If the application relies only on input to read files, an attacker can use absolute path to read arbitrary file on the system.


  1. echo file_get_contents ($_GET["lang"]);

An attacker can read arbitrary files by supplying an absolute path:

2. Potential impact

An attacker can gain access to sensitive and system information on the system, delete or modify files. The maximum impact depends on the functionality of the application.

How to Detect Path Traversal Vulnerabilities
Website Security Test
  • GDPR & PCI DSS Test
  • Website CMS Security Test
  • CSP & HTTP Headers Check
  • WordPress & Drupal Scanning
Try For Free

3. Attack patterns

There are following CAPEC (Common Attack Pattern Enumeration and Classification) patterns for the weakness:

This weakness is also mentioned in alternative WASC Threat Classification under WASC-33 and is treated as an attack.

4. Affected software

Software that uses external input to manipulate files is potentially vulnerable to this weakness.

5. Exploitation Examples

As an example we will use HTB23079 security advisory (CVE-2012-1467). This vulnerability allows renaming arbitrary files on the target system. We will demonstrate how to use this weakness to read database credentials.

This vulnerability can be exploited by authenticated users only, however user registration is enabled by default. We will use the PoC code provided in the advisory: http://[host]/lib/pkp/lib/tinymce/jscripts/tiny_mce/plugins/ibrowser/scripts/rfiles.php?lang=en&param=rename|/../../../../../../../../../../../../|1x.txt%00.jpg

The above code renames the file into 1x.txt which is accessible remotely. Now, we can use the following URL http://[host]/public/site/images/[user]/1x.txt to read the contents of the file:

HTB23079 advisory (CVE-2012-1467) CWE-22 PoC exploitation example
As demonstrated above, we obtained credentials of the database user. This technique can be used to gain complete control over the application or even the entire system.

6. Severity and CVSS Scoring

In most cases this vulnerability can be used to access restricted information. Depending on software design, this could be exploited to read and write files on the system or even execute arbitrary code.

In case of information disclosure, when an attacker can read only certain files, this weakness should be scored as:
5.3 [CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N] – Medium severity.

If an attacker can read arbitrary file on the system, it should be scored as:
7.5 [CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:N/A:N] – High severity.

If an attacker can write files to arbitrary locations on the system, the vulnerability is usually scored as:
9.8 [CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H] – Critical severity.

7. Mitigations

To protect the application from this weakness it is advised to follow these instructions:

  • Never use attacker controlled data as a filename or part of the filename when performing operations on files or folders. If filename should be based on the user's choice use predefined conditions instead of direct input.
  • Perform whitelist checks when working with files or directories using user controlled input.
  • Use sandbox environments (e.g. jail, chroot) that enforce strict boundaries between the process and the operating system.

8. Vulnerability Remediation Techniques and Examples

8.1 General recommendations for software developers

In the provided examples we consider the "param" variable to be received from a user via HTTP GET or POST request and used as part of a filename in functions that work with files. To avoid the vulnerability we need to handle the variable as recommended below. The examples illustrate the variable handling in popular programming languages.

  1. $param=preg_replace("/[^a-z0-9]/i", "", $param);
  1. $param=~s/[^a-z0-9]//gi;
  1. <asp:RegularExpressionValidator runat="server" id="ParamValidator" ControlToValidate="param" ErrorMessage="Invalid input. You are allowed to enter characters and digits only" ValidationExpression="^[a-zA-Z0-9]" />
  1. <cfscript>
  2.         param=ReReplace(param,'[^A-Za-z0-9]','','all');
  3. </cfscript>

or with POSIX class:

  1. <cfscript>
  2.         param=ReReplace(param,'[^[:alnum:]]','','all');
  3. </cfscript>
  1. param = re.sub("[^a-zA-Z0-9]+", "_", param)
  1. param.replaceAll("[^a-z0-9]","");

These are general recommendations. Every case must be treated separately, considering the logic of the application as well as singularity of the system and tasks. Direct coping of the data into the code may cause disruption of the application functionality or can lead to improper patching of the vulnerability.

Caution: do not blindly copy-paste the above-mentioned solutions into your application code. In some cases this may result in incorrect behavior of the application or an inconsistent patch. Carefully read the References or consult security specialists in case you are not sure how to patch a vulnerability.

8.2 Using Web Application Firewall (WAF)

Web Application Firewalls can be an efficient solution to prevent vulnerability exploitation while you are developing or waiting for a security patch. We do not recommend using a WAF as a long-term solution, neither as a replacement for properly developed security patch.

As an example, we will use an open source web application firewall ModSecurity developed by Trustwave. There are many rule sets for ModSecurity licensed under ASLv2 and widely distributed by security companies and organizations. These rule sets can be applied to cover all basic cases of vulnerabilities’ exploitation and can be used on production servers.

The following rule is a part of the core rule set modsecurity_crs_42_tight_security.conf and can be used to protect a web application against the majority of directory traversal attacks:
SecRule REQUEST_URI|REQUEST_BODY|REQUEST_HEADERS|XML:/*|!REQUEST_HEADERS:Referer "(?i)(?:\x5c|(?:%(?:2(?:5(?:2f|5c)|%46|f)|c(?:0%(?:9v|af)|1%1c)|u(?:221[56]|002f)|%32(?:%46|F)|e0%80%af|1u|5c)|\/))(?:%(?:2(?:(?:52)?e|%45)|(?:e0%8|c)0%ae|u(?:002e|2024)|%32(?:%45|E))|\.){2}(?:\x5c|(?:%(?:2(?:5(?:2f|5c)|%46|f)|c(?:0%(?:9v|af)|1%1c)|u(?:221[56]|002f)|%32(?:%46|F)|e0%80%af|1u|5c)|\/))" "phase:2,rev:'2',ver:'OWASP_CRS/2.2.7',maturity:'9',accuracy:'7',t:none, ctl:auditLogParts=+E,block,msg:'Path Traversal Attack',id:'950103',severity:'2',logdata:'Matched Data: %{TX.0} found within %{MATCHED_VAR_NAME}: %{MATCHED_VAR}',t:none,capture,tag:'OWASP_CRS/WEB_ATTACK/DIR_TRAVERSAL', setvar:'tx.msg=%{rule.msg}',setvar:tx.anomaly_score=+%{tx.critical_anomaly_score},setvar:'tx.%{}-OWASP_CRS/WEB_ATTACK/DIR_TRAVERSAL-%{matched_var_name}=%{matched_var}'"

Let’s have a look at a vulnerable PHP script that reads contents of a file passed via the “file” HTTP GET parameter:

  1. <?php
  2. echo file_get_contents($_SERVER["DOCUMENT_ROOT"]."/".$_GET["file"]);
  3. ?>

The abovementioned SecRule will be triggered if we try to use classic exploitation example:

Now, let’s have a look at a real-world example of vulnerable code described in HTB23144 (CVE-2013-1469):

  1. <?
  2. if (!empty($_GET['dl']) && file_exists(PHPWG_ROOT_PATH.$conf['data_location'].'pwg_'.$_GET['dl']))
  3. {
  4. $filename = PHPWG_ROOT_PATH.$conf['data_location'].'pwg_'.$_GET['dl'];
  5. ...
  6. echo file_get_contents($filename);
  7. ...
  8. }
  9. ?>

This vulnerability can be exploited on systems where the "file_exists()" PHP function returns "true" for nonexistent directories within the filename.
The following PoC code will be blocked by the provided rule and will protect the vulnerable application:

Another example of path traversal weakness in ocPortal descibed in HTB23078 (CVE-2012-1471) accepts a full file path via the file parameter and displays contents of the provided filename. Unfortunately, this vulnerability will not be blocked by the default rule set since there is no need to use directory traversal sequences to exploit this vulnerability:

The following rule will block access to any file outside the current directory:
SecRule ARGS_GET:file "(/)|(\\\\)" "phase:2,rev:'1',ver:'HTBRIDGE /0.1',maturity:'9',accuracy:'7', t:none, ctl:auditLogParts=+E,block, msg:'Path Traversal in ocPortal HTB23078',id:'1000000001',severity:'2', logdata:'Matched Data: %{TX.0} found within %{MATCHED_VAR_NAME}: %{MATCHED_VAR}',capture,tag:'HTBRIDGE/WEB_ATTACK/TRAVERSAL',setvar:'tx.msg=%{rule.msg}'"

We remind once again that delegation of web application security to a WAF may be quite an efficient temporary solution. However, it is not intended to replace a proper security patch.

9. Common Fix Errors and Bypasses

There are numerous techniques attackers may use to fool weak defence implementations, a subset of common techniques is listed below:

URL Encoding


Double URL encoding

Encoding the traversal sequences twice may fool systems that decode the input once:


Unicode Encoding

Encoding the traversal sequences with 16-bit Unicode encoding:


Overlong Unicode UTF-8 Encoding

Works on systems that have the capability to process overlong UTF-8 sequences:


Valid Traversal Sequences

The web browser will treat the following examples as valid:

http://[host]/vuln_script.php?lang=/%5C../%5C../%5C../%5C../%5C../%5C..etc/passwd http://[host]/vuln_script.php?lang=..//.//.//etc/passwd

10. References

  1. CWE-22: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') []
  2. Path Traversal []
  3. Top 25 Series - Rank 7 - Path Traversal []

11. Path Traversal Vulnerabilities, Exploits and Examples

Copyright Disclaimer: Any above-mentioned content can be copied and used for non-commercial purposes only if proper credit to ImmuniWeb is given.

↑ Back to Top
Book a Call Ask a Question
Talk to ImmuniWeb Experts
ImmuniWeb AI Platform
Have a technical question?

Our security experts will answer within
one business day. No obligations.

Have a sales question?
Tel: +41 22 560 6800 (Switzerland)
Tel: +1 720 605 9147 (USA)
Your data will stay private and confidential