Перейти к основному содержимому
SSRF Fundamentals & Local/Remote File Inclusion
Урок 8 из 18

SSRF Fundamentals & Local/Remote File Inclusion

Learn how Server-Side Request Forgery abuses server network trust and how Local and Remote File Inclusion turn path parameters into file disclosure or code execution, along with layered defences.

Средний 28 мин Веб-безопасность
Этого урока пока нет на выбранном языке — показана версия на другом языке. Перевод готовится.
Только в разрешённой среде — Описанные здесь приёмы применяются только в учебных лабораториях и в системах, которые принадлежат вам или на которые есть письменное разрешение.

Цели обучения

  • Explain how Server-Side Request Forgery turns a web server into a proxy for internal and cloud metadata requests
  • Distinguish between path traversal, Local File Inclusion (LFI), and Remote File Inclusion (RFI)
  • Demonstrate safe lab probing for SSRF redirects and PHP stream wrapper file disclosure
  • Implement allow-list URL validation, resolved-IP checks, IMDSv2, and safe file-inclusion mappings

Рекомендуется заранее: HTTP-запросы и ответы, cookie и управление сессиямиIDOR, Path Traversal и основные веб-атакиCross-Site Request Forgery (CSRF) & SameSite Defenses

#Why this matters

Modern web applications often fetch external resources (link previews, webhooks, PDF generators, avatar importers) and dynamically load server-side templates or language packs. When user input controls the destination URL or the file path without strict validation, the server's own trust boundary collapses.

With Server-Side Request Forgery (SSRF), an attacker borrows the server's network position to query internal services that sit behind firewalls. With Local or Remote File Inclusion (LFI/RFI), an attacker forces the application runtime to read sensitive files or execute unintended code on disk.

Both vulnerability classes arise from the same design mistake: trusting user-supplied locations across a security boundary. Firewalls and cloud metadata services implicitly trust traffic originating from the application host, while language runtimes implicitly trust paths passed to file loaders. When input reaches either sink without canonical validation, an unauthenticated visitor inherits capabilities meant only for internal services or local administrators.

#How Server-Side Request Forgery works

SSRF occurs when a server takes a URL from a request parameter, header, or document body and sends an HTTP request to it. Because the request originates from the backend host, firewalls and access lists that trust loopback (127.0.0.1), private RFC 1918 subnets (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16), or cloud metadata endpoints (169.254.169.254) accept traffic from the vulnerable app.

In-band SSRF targeting internal metadataIn-band SSRF targeting internal metadataBrowserlab.localMetadataPOST /preview url=http://169.254.169.254/latest/meta-data/GET /latest/meta-data/200 OK (instance role and keys)200 OK (metadata rendered in preview)The browser could not reach 169.254.169.254 directly, so lab.local acted as a proxy

Not every SSRF returns the internal response to the caller. Testers encounter three main patterns:

Pattern Server behaviour Typical lab signal
In-band (basic) Returns fetched body or error snippet Internal HTML, JSON, or port-closed errors appear in HTTP response
Blind (out-of-band) Fetches URL but hides response body Callback arrives at a listener on example.test or response timing changes
Redirect-based Validates initial URL, then follows 302 http://example.test/redir redirects server to http://127.0.0.1:8080/admin

Developers often try to block SSRF with string checks, which fail easily. Blocklisting "127.0.0.1" or "localhost" misses alternative representations such as http://0.0.0.0/, IPv6 loopback http://[::1]/, decimal IP notation (http://2130706433/), or a domain on example.test whose DNS record resolves to 127.0.0.1.

Two deeper flaws break naive URL validators even when IP formats are normalised. First, parser differentials occur when the validation function and the underlying HTTP client interpret the same URL differently, such as handling @ userinfo syntax (http://allowed.example.test@127.0.0.1/), whitespace, or unusual port numbers inconsistently. Second, DNS rebinding exploits a time-of-check to time-of-use race: the validator resolves an attacker-controlled hostname on example.test to a public address, approves the request, and then the HTTP client performs a second DNS lookup after a short TTL expires and receives an internal IP address.

When an endpoint is blind and returns no fetched content, authorised testers rely on out-of-band and timing signals instead. A successful DNS query or HTTP callback to a controlled listener on example.test proves the server initiated an outbound connection, while distinct response latencies can reveal whether an internal port is open, immediately refusing connections, or silently dropped by a firewall.

#Local and Remote File Inclusion (LFI and RFI)

Path traversal lets an attacker read static files by escaping a base directory with ../ sequences. File inclusion goes further: the application passes the resolved path to a runtime loader such as PHP's include or require, or a template renderer. If the included file contains executable syntax, the server runs it rather than just echoing bytes.

php
<?php
// Vulnerable template loader: untrusted input reaches include()
$lang = $_GET['lang'] ?? 'en';
include("locales/" . $lang . ".php");

In a lab running PHP, two complications shape LFI testing:

  1. Direct inclusion executes .php files. Requesting lang=../config executes config.php silently instead of printing database credentials.
  2. Appended extensions block plain reads. If the code appends .php, reading /etc/hostname fails unless older null-byte bugs exist (fixed since PHP 5.3.4) or a stream wrapper is used.

PHP stream wrappers solve the first problem cleanly during an authorised audit. The php://filter wrapper transforms the file stream before include() parses it:

Probing a lab LFI endpoint with php://filter
$ curl -s "http://lab.local/index.php?lang=php://filter/convert.base64-encode/resource=config"
PD9waHAKJGRiX3Bhc3MgPSAiTEFCX1RFU1RfU0VDUkVUIjsKPz4K
$ echo "PD9waHAKJGRiX3Bhc3MgPSAiTEFCX1RFU1RfU0VDUkVUIjsKPz4K" | base64 -d
<?php
$ db_pass = "LAB_TEST_SECRET";
?>

Because the base64 output contains no <?php opening tag, PHP prints the encoded text directly into the page instead of executing config.php.

Understanding why LFI is more dangerous than plain path traversal helps prioritise fixes. A traversal flaw in a static file-download endpoint only exposes bytes already stored on disk, whereas an inclusion sink evaluates any valid code inside the target file within the web application's process. Whenever an attacker can place controlled text into a readable local file, LFI escalates from information disclosure to full code execution.

Remote File Inclusion (RFI) happens when an inclusion function accepts a network scheme (http:// or ftp://) and downloads code from an external server such as http://example.test/payload.txt. In PHP, RFI requires allow_url_include=On, which has been disabled by default for many releases. Where RFI is blocked, attackers look for LFI-to-RCE chains such as poisoned log files, uploaded images containing PHP tags, or php://input when allow_url_include is enabled. For example, if a lab server logs the HTTP User-Agent header to a readable access log or writes user profile fields into a PHP session file, injecting harmless marker code into that field and including the file triggers execution without needing external network access.

#Defending against SSRF and file inclusion

Effective defences eliminate user control over destinations and paths instead of filtering bad strings:

  1. Allow-list outbound destinations for SSRF. When the app only needs to contact known partners or CDNs, permit only https:// and exact hostnames from an allow-list.
  2. Validate resolved IPs and disable redirects. If arbitrary public URLs are required, resolve DNS once, verify the resulting IP is not loopback, private, link-local, or multicast, connect directly to that IP, and disable 30x redirects.
  3. Require IMDSv2 on cloud instances. IMDSv2 requires a PUT request with a X-aws-ec2-metadata-token-ttl-seconds header to obtain a session token, defeating simple GET-based SSRF.
  4. Use fixed identifier maps for file loading. Replace dynamic include($dir . $input) calls with an explicit lookup table:
php
<?php
$allowed = ['en' => 'locales/en.php', 'uz' => 'locales/uz.php'];
$lang = $_GET['lang'] ?? 'en';
$file = $allowed[$lang] ?? $allowed['en'];
include($file);

Layer network and filesystem controls beneath application checks for defence in depth. Outbound firewall rules or a dedicated egress proxy should block application hosts from reaching loopback interfaces, private RFC 1918 ranges, and 169.254.169.254 unless explicitly required. When dynamic file paths are unavoidable for static downloads, strip directory components with basename(), resolve the canonical path with realpath(), and confirm it starts with the intended base directory before opening the file.

#Common mistakes

  • Checking the URL hostname with a regular expression before the HTTP library resolves DNS, leaving a time-of-check to time-of-use (DNS rebinding) or parser-differential bypass.
  • Stripping ../ once with str_replace("../", "", $path), which turns ....// into ../.
  • Blocking "169.254.169.254" in decimal while forgetting hex (0xa9fea9fe), IPv6-mapped IPv4 ([::ffff:169.254.169.254]), or HTTP redirects.
  • Checking only whether a file ends in .php while still passing php://filter/... strings into include().

#Summary

  • SSRF abuses server-side URL fetchers to reach internal services, loopback ports, and cloud metadata endpoints (169.254.169.254).
  • LFI passes a user-controlled local path to an inclusion function, risking both file disclosure (often via php://filter) and code execution; RFI loads files from remote URLs when enabled.
  • Naive string blocklists fail against alternate IP encodings, DNS rebinding, HTTP redirects, and non-recursive ../ stripping.
  • Defend with strict allow-lists, post-resolution IP filtering with redirects disabled, IMDSv2, and fixed server-side key-to-file mappings.

Проверка знаний

Войдите, чтобы проходить тест, завершать уроки и сохранять прогресс. Войти в систему

Практика: проверьте свои знания