LFI && LFD && RFI
Server-Side Attacks
Mechanism of Exploitation
LFI vulnerabilities commonly manifest in templating engines used across web applications. These engines facilitate uniformity in appearance by loading static elements like headers, navigation bars, and footers from shared templates. Dynamic content, specified via parameters in URLs such as /index.php?page=about is then loaded separately without needing modification to every page for static changes. Exploiting this setup involves manipulating the parameter (about
in this case) to retrieve and display unintended files, potentially exposing sensitive information.
Implications of LFI
Exploiting LFI can result in severe consequences, including:
Source Code Disclosure: Attackers can access and study application source code, aiding in identifying and exploiting further vulnerabilities.
Sensitive Data Exposure: Critical data stored on the server, such as configuration files or credentials, may be exposed, facilitating deeper attacks.
Remote Code Execution (RCE): In specific scenarios, attackers may execute arbitrary code on the server, potentially compromising the entire infrastructure connected to it.
Examples of Vulnerable Code
PHP
in PHP (include(), include_once(). require
(), require
_once(),file_get_contents()
)
Node.js
in js ⇒ FS()
Here, the readFile
function uses req.query.language
directly to construct the file path. If not properly validated, this can allow an attacker to read arbitrary files from the server. A similar risk exists in frameworks like Express.js when using functions such as render()
to render specific files based on user-supplied parameters in the URL path.
.NET (C#)
In .NET applications, the Response.WriteFile
function is commonly used to serve files dynamically. If the file path is derived from user input, it can lead to vulnerabilities. Below is an example in C# demonstrating this issue:
Here, if language
is not properly validated, an attacker could control which file content gets written to the response. This could potentially expose sensitive data or allow for the execution of malicious code.
Exploit & Advanced Bypass Techniques for Local File Inclusion (LFI)
Non-Recursive Path Traversal Filters
if code have str_replace('../', '', $_GET['language']);
Approved Paths
Bypass
Null Bytes
Pre-5.5 PHP versions are vulnerable to null byte injections (%00
). Adding %00
truncates appended extensions (/etc/passwd%00.php
) and includes only the path before the null byte (**/etc/passwd**
).
PHP
This is solved since PHP 5.4
PHP Filters for Exploiting LFI
Leveraging PHP Filters
PHP Filters serve as specialized PHP wrappers that allow input to be filtered according to specified criteria. For LFI attacks, the php://filter/
wrapper is particularly useful
PHP Filter Types
php://filter
String Filters: Modify strings based on specified rules.
Conversion Filters: Convert data between different formats (
convert.*
), useful for altering how data is read from files.Compression Filters: Compress or decompress data on the fly (
zlib.*
).Encryption Filters: Encrypt or decrypt data (
mcrypt.*
,mdecrypt.*
).
From existent folder
Maybe the back-end is checking the folder path:
Copy
Path Truncation Technique
/
etc/passwd
,/etc//passwd
,/etc/./passwd
, and/etc/passwd/
are all treated as the same path.When the last 6 characters are
passwd
, appending a/
(making itpasswd/
) doesn't change the targeted file.Similarly, if
.php
is appended to a file path (likeshellcode.php
), adding a/.
at the end will not alter the file being accessed.
Remote File Inclusion
usnig HTTP:// or HTTPS:// Filter
or
Using PHP://
Top 25 parameters
Exploiting LFI for RCE
Data Wrapper (data://)
The data:// wrapper allows inclusion of data directly into PHP scripts, making it ideal for injecting PHP code snippets and executing them on the server.
RCE via data://
PHP
In this example:
We encode our PHP payload (<?php system($_GET["cmd"]); ?>) in Base64.
We pass it using data:// and specify text/plain;base64 as the content type.
Input Wrapper (input://)
The input:// wrapper allows PHP to read data from the standard input, typically used in POST requests. This wrapper is useful when the vulnerable parameter accepts POST data.
RCE via input:/
Shell
Here:
We send a POST request with our PHP payload using php://input.
The vulnerable script interprets this input and executes the command specified in cmd.
Expect Wrapper (expect://)
The expect:// wrapper is used to execute external commands directly through URL streams. It requires the expect PHP extension to be installed and enabled on the server.
RCE via expect://
Shell
In this scenario:
We directly execute the id command using the expect:// wrapper.
The result is returned as the output of the HTTP request.
Exploiting LFI and Web File Upload Attacks
Local File Inclusion (LFI) vulnerabilities can be leveraged to achieve Remote Code Execution (RCE) when combined with web file upload functionalities. Let's explore how we can craft malicious uploads and use them to exploit LFI vulnerabilities effectively.
Image Upload Exploitation
Web applications often allow users to upload images. Exploiting an LFI vulnerability in such a scenario involves uploading a malicious file (e.g., shell.gif containing PHP code) and then including it via the vulnerable file inclusion mechanism.
Crafting a Malicious Image
Create the Malicious Image (shell.gif):
Shell
Here, GIF8 represents the GIF file header, ensuring the file starts with valid image magic bytes.
Upload the Image: After uploading shell.gif to the server via the application's upload functionality, assuming the upload directory is accessible (e.g., /profile_images/), we can include it in our LFI exploit.
Exploiting LFI with Uploaded Image
Assuming the path to the uploaded image is /profile_images/shell.gif:
Shell
Replace <SERVER_IP> and <PORT> with the appropriate values for your target.
Zip Upload Exploitation
Some applications may allow uploading zip archives, which can be abused using the zip:// wrapper to execute PHP code stored within the zip file.
Creating and Exploiting a Zip Archive
Create a PHP Web Shell (shell.php):
Shell
Zip the PHP File:
Shell
This creates a zip archive named shell.jpg containing shell.php.
Exploit LFI with Zip Archive: Assuming the path to the uploaded zip archive is /profile_images/shell.jpg:
Shell
Phar Upload Exploitation
Using the phar:// wrapper, we can similarly exploit LFI vulnerabilities by crafting a phar archive that contains PHP code.
Creating and Exploiting a Phar Archive
Create a PHP Script to Create Phar (shell.php):
PHP
Compile PHP Script into Phar Archive:
Shell
This compiles shell.php into shell.phar and renames it to shell.jpg.
Exploit LFI with Phar Archive: Assuming the path to the uploaded phar archive is /profile_images/shell.jpg:
Shell
Poisoning
Log File poisoning
This is a technique where an attacker injects malicious code into log files on the server, including via the LFI vulnerability. Since log files often record user input (such as User-Agent strings or GET/POST parameters, SSH login/ FTP Login, Apache Log), an attacker can manipulate these inputs to inject PHP code.
Steps:Inject malicious code (usually PHP) into a log file
Once the log file eis poisoned
Files Commonly Targeted for Log Poisoning:
Web server access/error logs (
/var/log/apache2/access.log
,/var/log/httpd/access.log
).Mail logs (
/var/log/mail.log
).User logins (
/var/log/auth.log
).
SSH Login Log Poisoning
Step 1: Connect to the server via SSH and input malicious PHP code as the username or password. For example:
go to the auth.log file or secure
LFI via FTP Login Log Poisoning
step1; connect to the FTP
The login will fail, but the attempt is logged in the FTP log files (e.g., /var/log/vsftpd.log
or /var/log/xferlog
).
Step 2: Use the LFI vulnerability to include the FTP log file:
Inject Commands (Metadata)
we will cover adding commands to the metadata by manipulating HTTP Headers like
(User-Agent, Referer. X-Forwarded-For)
using Curl to manipulate the User-Agent
-A => User-Agent
-e => Referer
-H => X-Forwarded-for
User-Agent Header Injection:
Referer Header Injection:
X-Forwarded-For Header Injection:
Executing Commands via LFI
Exploit Steps for LFI via /proc/self/environ
/proc/self/environ
-A
sets theUser-Agent
header.The malicious payload
<?php system($_GET["cmd"]); ?>
is now part of the environment variable associated withUser-Agent
.
2. Using LFI to Include /proc/self/environ
Once the PHP code is injected into the environment, you can use the LFI vulnerability to include the /proc/self/environ
file.
Data Wrapper (data://
)
data://
)The data://
wrapper allows inclusion of data directly into PHP scripts, making it ideal for injecting PHP code snippets and executing them on the server.
RCE via data://
In this example:
We encode our PHP payload (
<?php system($_GET["cmd"]); ?>
) in Base64.We pass it using
data://
and specifytext/plain;base64
as the content type.
Mitigation
Disable Dangerous Wrappers: Disable the data
://
wrapper by ensuring allow_url_include=Off
in php.ini
Preventing and Mitigating File Inclusion Vulnerabilities
Preventing
input validation
Avoid Using User-Controllablelike (include, require, file_get_contents)
file Permission
config Hardening disable (allow_url_fopen, alow_url_include)
Mitigation Techniques:
Contextual Validation:
Implement context-specific validation of user inputs. For example, validate that URLs used for file inclusion are from trusted domains and not manipulated to include unintended files.
Server-Side Security Controls:
Utilize web application firewalls (WAFs) and intrusion detection systems (IDS) to monitor and block requests that attempt to exploit file inclusion vulnerabilities.
File Path Handling:
LFI: Use relative file paths instead of absolute paths whenever possible. This reduces the risk of an attacker specifying arbitrary files on the server.
RFI: Avoid dynamically constructing URLs for file inclusion. If necessary, validate and sanitize URLs rigorously to prevent unauthorized access.
Logging and Monitoring:
Implement logging mechanisms to record access attempts and exceptions related to file operations. Monitor logs for suspicious activities or attempts to access restricted files.
Regular Security Audits:
Conduct regular security audits and code reviews to identify and mitigate file inclusion vulnerabilities. Use automated tools and manual testing to detect and address vulnerabilities proactively.
Last updated