Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 53 ยท Web Application Security

SSRF, Path Traversal, Deserialization and Upload Risks

Understand how SSRF, path traversal, unsafe deserialization and file upload flaws work, and fix them with allow-lists, safe path handling and strict validation.

Some of the most damaging web flaws never touch the browser. They happen on the server, where the application reads a file, calls another URL, rebuilds an object from bytes, or stores something a visitor uploaded. In each case the program makes a powerful move on behalf of a request it cannot fully trust. This lesson covers four such bug classes at the concept level: server-side request forgery (SSRF), path traversal, insecure deserialization and unsafe file uploads.

The goal is to recognise the pattern and apply the fix, not to build exploits. Real servers and internal networks cannot run in this site, so any real framework code is read-only. The runnable parts are stand-ins: two Node.js validators, one for file paths and one for URLs, run against made-up inputs and a fake directory. They model the checks well enough to learn the logic but are not complete, production-ready defenses.

Four server-side traps

SSRF Server fetches a URL the user chose.
Path traversal ../ escapes the intended folder.
Deserialization Untrusted bytes become objects.
Uploads A file is not what it claims.

Each one trusts input to choose a resource.

1 / 2

Path traversal

A path traversal (or directory traversal) bug appears when a program builds a file path from user input without making sure the result stays in the intended folder. Consider a download endpoint that serves /var/app/public/ plus the filename the client asks for. The sequence .. means "parent folder", so a filename containing ../ steps out of the public folder and may reach configuration files, keys or source code. Encoded variants (%2e%2e%2f), mixed separators (..\) and absolute paths (/etc/hosts) are the same idea in other clothes.

Blocklists such as "remove ../" fail because of nested forms (....// becomes ../ after one pass) and encodings. The robust method is:

  1. Prefer IDs over paths. Let users request file=42 and look up the stored path in a database.
  2. If a name must be used, resolve the full path and then check that it is still inside the base folder.
  3. Reject null bytes and absolute paths, and run the process as an account that can read only what it needs.

The stand-in below uses Node's path module on a made-up base folder. It is purely a string exercise: it never touches the real file system.

Node.js Path traversal check (strings only)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In the unsafe column, ../config/database.yml becomes /srv/app/config/database.yml and ../../../etc/hosts becomes /etc/hosts, both outside the public folder. (An absolute name such as /etc/hosts is merely joined under the base by join, but code that uses resolve or opens the name directly would let it replace the base, which is why the safe version rejects it.) The safe column returns null for every attempt to leave the folder, and also for the null byte. The percent-encoded entry stays inside as a strange filename here because the model does not decode it. A real server decodes URLs before the check, so make sure the decode happens first and only once. Note the BASE + "/" detail: comparing against /srv/app/public without the slash would wrongly accept a sibling called /srv/app/public-secret.

SSRF: server-side request forgery

Many applications fetch a URL on the user's behalf: link previews, image importers, webhooks, PDF generators, "fetch from URL" fields. In an SSRF flaw the attacker supplies a URL and the server makes the request from its own network position. That position is often privileged. The server can reach internal admin panels, databases and other services that the internet cannot, and cloud servers can reach the metadata service on a link-local address, which may hold temporary credentials. The attacker never reaches those systems directly. The vulnerable server is used as a proxy.

flowchart LR
    A["Attacker"] -->|"url=http://internal-host/"| S["Public web app"]
    S -->|"fetches the URL"| I["Internal service<br/>(not internet-reachable)"]
    I -->|"response"| S
    S -->|"data returned or leaked"| A

SSRF: the server fetches on the attacker's behalf from inside the network.

Defenses combine several layers:

  • Allow-list destinations where possible: only specific hosts, only https, only expected ports.
  • Parse, don't pattern-match the URL. Check the scheme and the hostname, as in Web Application Security Basics.
  • Resolve the name and check the IP address against private, loopback and link-local ranges, and connect to that address, so a DNS answer cannot change between the check and the request (a DNS rebinding trick).
  • Do not follow redirects blindly. A permitted host can redirect to a forbidden one, so re-validate each hop or disable redirects.
  • Network egress controls. Put the fetching component in a segment that cannot reach internal services, and on cloud platforms require the hardened version of the metadata service.
  • Never return raw responses to the user, and cap size and time.

The model below validates a URL string with an allow-list and a check against private IPv4 ranges. It does no networking and no DNS, which a real defense must also handle, so treat it as the logic of the first check only.

Node.js URL allow-list and private-address check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Several of these are traps for naive checks. images.example.com.evil.test and [email protected] both begin with the trusted name, but the parsed host is evil.test, so a startsWith or includes test would be fooled. Because the URL parser does the work, the allow-list compares the real hostname. What this model leaves out is exactly where real SSRF defenses get hard: alternative IP spellings, IPv6, DNS names that point to private addresses, and redirects. That is why network-level egress rules matter.

Insecure deserialization

Serialization turns an in-memory object into bytes or text for storage or transport, and deserialization rebuilds it. Some formats can describe which classes to create and which code runs while doing so, for example native object serialization in Java, PHP, Python's pickle and .NET's older binary formatters. If the bytes come from an untrusted source, the attacker chooses the objects, and certain combinations of classes already present in the application can lead to code execution, file access or denial of service. Plain data formats (JSON, with a defined schema) do not carry behaviour and are far safer.

Prevent it by:

  • Not deserializing untrusted data with native formats at all. Use JSON or another data-only format and validate it against a schema.
  • Signing serialized data you hand to clients (cookies, hidden fields) with a secret key, and verifying before parsing. Remember a signature proves integrity, not safety of your own bad format choices.
  • Using type allow-lists if a framework offers them, and keeping libraries patched.
  • Running with minimal privileges so a bug costs less.

Unsafe file uploads

An upload feature accepts content you did not write, and files carry names, types and contents that the sender controls. Typical problems include uploading a script that the server later executes (when the upload folder is served as code), overwriting existing files through a crafted name, filling the disk, and "image" files that are really documents with active content (some formats such as SVG can contain script).

A sound design:

  • Never trust the filename or the Content-Type header. Generate your own random name and choose the extension from a server-side check of the content.
  • Allow-list types and sizes, and verify the real content (for images, decode and re-encode them).
  • Store uploads outside the web root or on separate storage, and serve them through a handler or a static-only domain that never executes code.
  • Serve user content with safe headers, such as Content-Disposition: attachment and X-Content-Type-Options: nosniff, ideally from a separate origin.
  • Scan for malware where users share files with each other, and apply per-user quotas.

The same allow-list thinking shows up in all four bug classes: decide what is acceptable, check the resolved thing, and give the process as little power as you can. These rules go into code reviews and pipelines in Secure Coding and DevSecOps. In authorized tests, you would confirm them only against your own lab or in-scope systems, and note each finding for the report.

Server misconfiguration and template injection

Two more server-side problems complete the picture: one is about settings, the other about code.

Misconfiguration

Most servers ship with convenient defaults that are unsafe on the internet. Security misconfiguration is simply the gap between the defaults and a hardened setup, and it is one of the most common findings in real assessments. Typical examples:

  • Directory listing enabled, so a folder without an index page shows every file in it.
  • Default accounts, sample applications and admin consoles left in place with known credentials.
  • Verbose errors and debug mode that print stack traces, file paths, SQL queries or configuration values to visitors.
  • Unnecessary services and HTTP methods enabled, such as TRACE or a management port exposed to the internet.
  • Missing security headers and weak TLS settings.
  • Permissive cloud storage or cross-origin rules that allow any origin to read responses.
  • Backups and source files such as .bak, .old, .git folders and .env files inside the web root (the kind of thing content discovery finds).

The fix is a repeatable hardening baseline: minimal installs, no defaults, errors logged privately and shown generically to users, configuration under version control, and automated checks that detect drift.

Server-side template injection (SSTI)

Template engines build pages by combining a template with data. The safe pattern is a fixed template with the user's data inserted as a value: the data is only ever displayed. Server-side template injection happens when a developer builds the template itself from user input, for example by concatenating a name into the template string before rendering. Then the user's text is interpreted as template syntax, evaluated on the server and, in many engines, able to reach powerful objects. The impact ranges from information disclosure to remote code execution.

A harmless way to detect the issue in an authorized test is to submit a small arithmetic expression in the engine's syntax, such as {{7*7}}, and see whether the response contains 49. If it does, the input was evaluated, not displayed. Different engines use different delimiters, so testers try several forms and note which one evaluates.

Prevention:

  • Never build templates from user input. Pass user data as variables to a fixed template.
  • Let the engine auto-escape output, and use its sandbox features if you must allow user-edited templates.
  • Prefer logic-less engines for user-provided content, and keep user template editing for trusted staff only.
  • Run the application with least privilege so that an evaluation flaw cannot reach the whole system.

The stand-in has a tiny template engine that replaces {{ expression }} with its result. The vulnerable handler concatenates user input into the template before rendering; the safe one passes it as data. The expression language is deliberately limited to arithmetic and one lookup, so nothing dangerous can run.

Node.js Template injection in a toy engine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Because the toy engine only evaluates a restricted arithmetic string, it demonstrates detection (49) without anything more dangerous. Real engines are far more capable, which is exactly why the rule is "never build the template from input". See also business logic and secure development for the broader habit of treating all input as data.

SSRF prevention: allow-lists and deny-lists

Server-side request forgery (SSRF) is prevented by controlling where the server may connect. A deny-list (blacklist) tries to block known bad targets such as 127.0.0.1 or cloud metadata addresses; it fails because attackers find alternative encodings (decimal or hexadecimal IPs, DNS names that resolve to internal addresses, redirects). An allow-list (whitelist) permits only specific destinations the feature needs and rejects everything else, which is far safer. Prefer allow-lists, resolve the name yourself and check the final IP, do not follow redirects blindly, block private and link-local ranges at the network level, require the metadata service's session-token mode in the cloud, and give the server only the network access it needs. Return generic errors so responses cannot be used to map the internal network.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the most reliable way to avoid path traversal in a download feature?

    Blocklists are bypassed by nested and encoded forms. Resolving then checking the result, or avoiding user-chosen paths, is robust.
  2. 2. In SSRF, why is the server's network position valuable to an attacker?

    The server acts as a proxy into places the attacker cannot reach directly.
  3. 3. Why is startsWith('https://images.example.com') a poor URL check?

    String prefix tests are not hostname tests. Parse the URL and compare the host exactly.
  4. 4. Which data format is generally safest to accept from untrusted clients?

    Data-only formats do not describe which classes or code to run during parsing.
  5. 5. How should an upload feature name stored files?

    Filenames and Content-Type are attacker controlled. Generate names yourself and verify real content.

Summary

  • Server-side flaws arise when the server uses input to choose a file, URL, object type or stored file.
  • Path traversal is stopped by using IDs, or resolving the path and checking it stays in the base folder.
  • SSRF is stopped by allow-listing destinations, validating parsed hosts and resolved IPs, controlling redirects and restricting network egress.
  • Never deserialize untrusted data with native formats; prefer schema-validated JSON and sign data you hand to clients.
  • Treat upload names, types and contents as hostile, store outside the web root and serve safely.
  • Allow-lists, canonical forms and least privilege are the shared remedy.

Next: API Security Testing and Hardening.