Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 2 of 6 · Worked example · 30 min · revision 3

Injection, Traversal, XSS and SSRF: Root Causes and Fixes

Trace SQL injection, path traversal, cross-site scripting and server-side request forgery to one root cause, and build the structural defence for each, including an SSRF guard with negative tests.

Contentsand lesson path

What you will learn

  • Confirm injection, path traversal, cross-site scripting and server-side request forgery flaws in an intentionally vulnerable application and apply the matching defence: parameterised queries, canonicalised and allow-listed file paths, contextual output encoding with CSP, and allow-listed outbound requests.
  • Harden the client side of a web application: sanitise untrusted rich content (Markdown, LLM output) before it reaches framework escape hatches such as dangerouslySetInnerHTML, enforce CSP with Trusted Types, load third-party scripts with Subresource Integrity, and enforce HTTPS with HSTS and no mixed content.

01. Why it matters

Many of the most damaging web flaws share one root cause: untrusted data is treated as instructions. A parser, filesystem, browser or HTTP client acts on user input as syntax rather than as inert data.

This lesson covers four classic results:

  • SQL injection (SQLi): the SQL parser runs attacker fragments as query keywords.
  • Path traversal: the filesystem follows ../ steps out of the folder you meant to serve.
  • Cross-site scripting (XSS): the browser runs untrusted text as JavaScript.
  • Server-side request forgery (SSRF): your backend fetches a URL that points at cloud metadata or a private service.

Deny-lists and regex clean-ups fail: attackers use mixed case (<sCrIpt>), nested strings (<scr<script>ipt>), encodings and, for SSRF, alternative address forms. The fixes below are structural: they keep data and instructions apart, or check the final, canonical value.

02. SQL injection and path traversal: mechanics and remediation

In vulnerable code, a query is built with an f-string: f"SELECT * FROM users WHERE email = '{email}'". If the attacker submits [email protected]' OR '1'='1, the quote ends the string literal and OR becomes part of the query logic.

The fix is parameterised queries (prepared statements). The query text with placeholders ($1, ?, %s) is parsed separately from the values, so the database treats each value as a literal, whatever quotes, semicolons or keywords it contains. ORMs bind parameters for you when you use their query builders. The risk returns when you build raw SQL strings yourself, for example text(f"... {value}") instead of text("... :value") with bound parameters. Identifiers such as column names cannot be parameters: map them from an allow-list.

Path traversal happens when a user-supplied name is joined into a filesystem path: open(f"/var/data/uploads/{filename}"). The path /var/data/uploads/../../etc/passwd normalises to /var/etc/passwd; the attacker needs three steps, ../../../etc/passwd, to reach /etc/passwd. Counting the steps is the attacker's job, so the defence must not depend on it.

The fix keeps only the final name component, resolves the result to a canonical absolute path (following .. and symlinks), and checks that this path is still inside the base folder. Where you can, go further and look files up by an ID in the database instead of accepting names at all.

Python · safe_paths.py (Python 3.9+ for Path.is_relative_to)
from pathlib import Path

BASE_UPLOAD_DIR = Path("/var/data/uploads").resolve()


def get_safe_file_path(user_supplied_filename: str) -> Path:
    """Return a path inside BASE_UPLOAD_DIR or raise PermissionError."""
    # 1. Keep only the last path component: "../../x" becomes "x"
    clean_name = Path(user_supplied_filename).name
    if clean_name in ("", ".", ".."):
        raise PermissionError("Access denied: empty or relative name")
    # 2. Resolve symlinks and ".." to an absolute, canonical path
    target_path = (BASE_UPLOAD_DIR / clean_name).resolve()
    # 3. The canonical path must still be inside the base folder
    if not target_path.is_relative_to(BASE_UPLOAD_DIR):
        raise PermissionError("Access denied: path escapes the upload folder")
    return target_path
Python · test_traversal.py
import os
import posixpath
import tempfile
from pathlib import Path

import safe_paths

print(posixpath.normpath("/var/data/uploads/../../etc/passwd"))
print(posixpath.normpath("/var/data/uploads/../../../etc/passwd"))

# Use a temporary folder so the test runs anywhere
safe_paths.BASE_UPLOAD_DIR = (Path(tempfile.mkdtemp()) / "uploads").resolve()
base = safe_paths.BASE_UPLOAD_DIR
base.mkdir()
path = safe_paths.get_safe_file_path("../../../etc/shadow")
assert path == base / "shadow", path
print("stripped to", path.relative_to(base.parent))

os.symlink("/etc/passwd", base / "evil")  # a link that points outside
for name in ("evil", "..", ""):
    try:
        safe_paths.get_safe_file_path(name)
    except PermissionError as exc:
        print(f"{name!r}: {exc}")
    else:
        raise AssertionError(f"{name!r} was allowed")
Expected output
$ python3 test_traversal.py
/var/etc/passwd
/etc/passwd
stripped to uploads/shadow
'evil': Access denied: path escapes the upload folder
'..': Access denied: empty or relative name
'': Access denied: empty or relative name

03. Cross-site scripting (XSS): contextual encoding and sanitisation

XSS happens when untrusted input reaches an HTML document without encoding for its context. It comes in three main forms:

  • Stored XSS: the payload is saved (a comment, a profile bio) and served to every later visitor.
  • Reflected XSS: input from the URL is echoed straight into an error page or search results.
  • DOM-based XSS: client-side JavaScript reads an untrusted source such as location.search and passes it to a sink such as element.innerHTML or eval().

The first defence is contextual output encoding: template engines and frameworks such as React escape text by default. Dangerous sinks bypass that escaping: innerHTML, outerHTML, document.write(), location.href set to a javascript: URL, and React's dangerouslySetInnerHTML.

Rich content is the hard case. Markdown from users and answers from a large language model (LLM) are both untrusted: Markdown passes raw HTML through, and a model can be steered by prompt injection into writing <img src=x onerror=...> or a [link](javascript:...). Before such content reaches an escape hatch, convert it to HTML and run that HTML through an allow-list sanitiser such as DOMPurify. Its html profile keeps ordinary HTML elements and drops SVG and MathML, and its default URI rules remove javascript: links.

JavaScript · render-markdown.jsx (DOMPurify 3.x; not run in this lesson)
import DOMPurify from 'dompurify';
import { marked } from 'marked';

// Markdown and LLM output are untrusted: Markdown passes raw HTML through.
export function toSafeHtml(untrustedMarkdown) {
  const html = marked.parse(untrustedMarkdown);
  // html profile: allow ordinary HTML elements, no SVG or MathML
  return DOMPurify.sanitize(html, { USE_PROFILES: { html: true } });
}

export function ChatAnswer({ markdown }) {
  return <div dangerouslySetInnerHTML={{ __html: toSafeHtml(markdown) }} />;
}

// Example from the DOMPurify README (default settings):
// '<img src=x onerror=alert(1)//>'    becomes '<img src="x">'

Sanitising is one layer. Two more come from the browser, as set up in Browser Trust and Client-Side Hardening:

  • Trusted Types: with the CSP directive require-trusted-types-for 'script', supporting browsers reject plain strings at sinks such as innerHTML. Call DOMPurify.sanitize(html, { RETURN_TRUSTED_TYPE: true }) inside a Trusted Types policy so only sanitised values reach the sink.
  • No mixed content: an HTTPS page that loads a script or stylesheet over plain HTTP lets a network attacker replace it. Browsers block such active mixed content. Serve every resource over HTTPS, send HSTS, and add the CSP directive upgrade-insecure-requests while you migrate old http:// links.

04. Worked example: Server-Side Request Forgery (SSRF) defence

SSRF happens when a backend accepts a URL from a user (a link preview, an avatar download, a webhook) and fetches it from inside your network. Attackers use it to reach:

  • Cloud metadata services: AWS, GCP and Azure serve instance metadata at the link-local address 169.254.169.254 (AWS also at fd00:ec2::254 over IPv6; Alibaba Cloud uses 100.100.100.200). Depending on the provider and settings, this can return temporary credentials for the instance's role. AWS IMDSv2 requires a session token obtained with a PUT request, which blocks most simple GET-based SSRF, but only if IMDSv1 is turned off.
  • Internal services: private addresses such as http://10.0.1.45:6379 or http://localhost:8080/metrics often have no authentication.

The safest design is an allow-list of destinations, as for webhooks to known partners. When you must accept arbitrary public URLs, apply four rules:

  1. Allow only http and https and the ports you need.
  2. Resolve the host name and reject the URL if any resolved address is not public. Use the properties of Python's ipaddress module (is_global, is_private, is_loopback, is_link_local, is_reserved, is_unspecified, is_multicast and, for IPv6, is_site_local) rather than your own list of ranges, and unwrap IPv4 addresses hidden inside IPv6 forms (IPv4-mapped ::ffff:a.b.c.d, 6to4 2002::/16, NAT64 64:ff9b::/96).
  3. Connect to the exact IP you vetted. If the HTTP client resolves the name again, an attacker's DNS server with a 1-second TTL can answer with a public IP for your check and 169.254.169.254 for the fetch. This is DNS rebinding.
  4. Do not follow redirects, or re-run the whole check on every hop. A public server can answer 302 Location: http://169.254.169.254/.

The first part of the guard parses and vets the URL. It returns a Target that carries the vetted IP:

Python · ssrf_guard.py, part 1: vetting (standard library only)
import http.client
import ipaddress
import socket
import ssl
from dataclasses import dataclass
from urllib.parse import urlsplit

ALLOWED_PORTS = {80, 443}
NAT64 = ipaddress.ip_network("64:ff9b::/96")
MAX_BYTES = 1_000_000


class SecurityError(ValueError):
    """The URL points somewhere this service must never call."""


@dataclass(frozen=True)
class Target:
    scheme: str
    host: str  # used for the Host header, SNI and the certificate check
    port: int
    ip: str  # the vetted address the socket will connect to
    path: str


def embedded_ipv4(ip):
    """Return an IPv4 address hidden inside an IPv6 one, or None."""
    if ip.version == 6:
        if ip.ipv4_mapped:  # ::ffff:169.254.169.254
            return ip.ipv4_mapped
        if ip.sixtofour:  # 2002:a9fe:a9fe::
            return ip.sixtofour
        if ip in NAT64:  # 64:ff9b::a9fe:a9fe
            return ipaddress.IPv4Address(int(ip) & 0xFFFFFFFF)
    return None


def is_public(ip) -> bool:
    for addr in (ip, embedded_ipv4(ip)):
        if addr is None:
            continue
        if (
            not addr.is_global
            or addr.is_private
            or addr.is_loopback
            or addr.is_link_local
            or addr.is_reserved
            or addr.is_unspecified
            or addr.is_multicast
            or getattr(addr, "is_site_local", False)  # IPv6 fec0::/10 only
        ):
            return False
    return True


def resolve_and_vet(url: str, resolver=socket.getaddrinfo) -> Target:
    parts = urlsplit(url)
    if parts.scheme not in ("http", "https"):
        raise SecurityError(f"scheme {parts.scheme!r} is not allowed")
    if not parts.hostname:
        raise SecurityError("URL has no host")
    port = parts.port or (443 if parts.scheme == "https" else 80)
    if port not in ALLOWED_PORTS:
        raise SecurityError(f"port {port} is not allowed")
    try:
        infos = resolver(parts.hostname, port, type=socket.SOCK_STREAM)
    except (socket.gaierror, UnicodeError) as exc:
        raise SecurityError(f"cannot resolve {parts.hostname!r}") from exc
    ips = [ipaddress.ip_address(info[4][0].split("%")[0]) for info in infos]
    blocked = sorted({str(ip) for ip in ips if not is_public(ip)})
    if not ips or blocked:
        raise SecurityError(f"non-public {blocked}")
    path = (parts.path or "/") + (f"?{parts.query}" if parts.query else "")
    return Target(parts.scheme, parts.hostname, port, str(ips[0]), path)

A simple range list is not enough. ip_address("::ffff:169.254.169.254") in ip_network("169.254.0.0/16") is False, because an IPv6 address is never inside an IPv4 network. is_global alone is not enough either: in Python 3.10 to 3.14 it returns True for multicast 224.0.0.1, for the deprecated IPv6 site-local range fec0::/10, and for the NAT64 address 64:ff9b::a9fe:a9fe, which a NAT64 gateway translates to 169.254.169.254. That is why the guard checks several properties.

Python classes all of ::/8 as reserved, so is_reserved already rejects every NAT64 address, even for public IPv4 sites. On an IPv6-only host behind DNS64 the guard therefore fails closed for IPv4-only sites. Unwrapping embedded IPv4 is defence in depth, because the ipaddress tables change between Python releases.

The second part makes the request. The connection classes override connect() so the socket goes to the vetted IP, while the Host header, TLS server name indication (SNI) and certificate check still use the real host name. Any 3xx response is refused:

Python · ssrf_guard.py, part 2: pinned fetch without redirects
class PinnedHTTPConnection(http.client.HTTPConnection):
    def __init__(self, target: Target, timeout: float):
        super().__init__(target.host, target.port, timeout=timeout)
        self.pinned_ip = target.ip

    def connect(self):
        # Connect to the vetted IP; never look the name up a second time.
        self.sock = socket.create_connection((self.pinned_ip, self.port), self.timeout)


class PinnedHTTPSConnection(PinnedHTTPConnection):
    default_port = 443

    def connect(self):
        super().connect()
        context = ssl.create_default_context()
        # SNI and certificate validation still use the real host name.
        self.sock = context.wrap_socket(self.sock, server_hostname=self.host)


def fetch_pinned(target: Target, timeout: float = 5.0) -> bytes:
    if target.scheme == "https":
        conn = PinnedHTTPSConnection(target, timeout)
    else:
        conn = PinnedHTTPConnection(target, timeout)
    try:
        conn.request("GET", target.path, headers={"User-Agent": "preview-bot/1"})
        resp = conn.getresponse()
        if 300 <= resp.status < 400:
            location = resp.getheader("Location")
            raise SecurityError(f"redirect to {location!r} refused")
        body = resp.read(MAX_BYTES + 1)
        if len(body) > MAX_BYTES:
            raise SecurityError("response is larger than MAX_BYTES")
        return body
    finally:
        conn.close()


def safe_fetch(url: str, resolver=socket.getaddrinfo) -> bytes:
    return fetch_pinned(resolve_and_vet(url, resolver))

Security code needs negative tests: inputs that must fail. The test below lists the attack URLs, fakes DNS answers for names (so it needs no network), proves that a rebinding resolver is asked only once and the socket goes to the first, vetted IP, and serves a real redirect from a local test server. Save both files in one folder and run python3 test_ssrf_guard.py.

Python · test_ssrf_guard.py
import http.server
import socket
import threading

import ssrf_guard
from ssrf_guard import SecurityError, Target, resolve_and_vet

ATTACK_URLS = [
    "http://127.0.0.1/",
    "http://127.1/",
    "http://2130706433/",  # 127.0.0.1 written as one decimal number
    "http://0.0.0.0/",  # reaches local services on Linux
    "http://10.0.0.5/",
    "http://172.16.0.1/",
    "http://192.168.1.1/",
    "http://169.254.169.254/latest/meta-data/",  # AWS, GCP, Azure metadata
    "http://100.100.100.200/latest/meta-data/",  # Alibaba Cloud metadata
    "http://[fd00:ec2::254]/latest/meta-data/",  # AWS metadata over IPv6
    "http://[::ffff:169.254.169.254]/",  # IPv4-mapped IPv6
    "http://[::ffff:7f00:1]/",  # ::ffff:127.0.0.1 in hex
    "http://[64:ff9b::a9fe:a9fe]/",  # NAT64 form of 169.254.169.254
    "http://[2002:a9fe:a9fe::]/",  # 6to4 form of 169.254.169.254
    "http://[::1]/",
    "http://[::]/",
    "http://[fe80::1]/",
    "http://[fec0::1]/",  # deprecated IPv6 site-local: is_global is True
    "http://224.0.0.1/",  # multicast: is_global alone lets it through
    "http://[email protected]/",
    "http://8.8.8.8:6379/",  # public IP, but not an allowed port
    "file:///etc/passwd",
    "gopher://127.0.0.1:6379/_INFO",
]


def fake_dns(answers):
    """A resolver that returns the next list of IPs on each call."""
    calls = []

    def resolve(host, port, type=0):
        ips = answers[min(len(calls), len(answers) - 1)]
        calls.append(host)
        return [(socket.AF_INET, type, 6, "", (ip, port)) for ip in ips]

    return resolve, calls


def expect_rejected(url, resolver=socket.getaddrinfo):
    try:
        resolve_and_vet(url, resolver)
    except SecurityError as exc:
        print(f"rejected {url} ({exc})")
    else:
        raise AssertionError(f"ALLOWED {url}")


def test_attack_urls():
    for url in ATTACK_URLS:
        expect_rejected(url)
    # Names go through a fake resolver, so the output is the same on every OS
    names = {
        "http://localhost/": ["127.0.0.1", "::1"],
        "http://metadata.google.internal/": ["169.254.169.254"],
        "http://mixed.attacker.test/": ["8.8.8.8", "10.0.0.7"],
    }
    for url, ips in names.items():
        expect_rejected(url, fake_dns([ips])[0])


def test_rebinding_cannot_reach_private_ip():
    # The first answer is public; every later answer is the metadata IP.
    resolver, calls = fake_dns([["93.184.215.14"], ["169.254.169.254"]])
    connected = []

    def fake_connect(address, *args):
        connected.append(address)
        raise ConnectionRefusedError("stop before any real traffic")

    real_connect = socket.create_connection
    socket.create_connection = fake_connect
    try:
        ssrf_guard.safe_fetch("http://rebind.attacker.test/", resolver)
    except ConnectionRefusedError:
        pass
    finally:
        socket.create_connection = real_connect
    assert calls == ["rebind.attacker.test"], calls
    assert connected == [("93.184.215.14", 80)], connected
    print(f"rebinding: {len(calls)} DNS lookup, socket went to {connected[0]}")


def test_redirect_is_refused():
    class Redirect(http.server.BaseHTTPRequestHandler):
        def do_GET(self):
            self.send_response(302)
            self.send_header("Location", "http://169.254.169.254/latest/")
            self.send_header("Content-Length", "0")
            self.end_headers()

        def log_message(self, *args):
            pass

    server = http.server.HTTPServer(("127.0.0.1", 0), Redirect)
    threading.Thread(target=server.serve_forever, daemon=True).start()
    # Test only: pin the local test server directly, skipping the vetting.
    target = Target("http", "preview.test", server.server_port, "127.0.0.1", "/")
    try:
        ssrf_guard.fetch_pinned(target)
    except SecurityError as exc:
        print(f"redirect: {exc}")
    else:
        raise AssertionError("redirect was followed")
    finally:
        server.shutdown()


def test_public_name_is_allowed():
    resolver, _ = fake_dns([["93.184.215.14"]])
    target = resolve_and_vet("https://example.com/a?b=1", resolver)
    assert (target.ip, target.port, target.path) == ("93.184.215.14", 443, "/a?b=1")
    print(f"allowed https://example.com/a?b=1, pinned to {target.ip}")


if __name__ == "__main__":
    test_attack_urls()
    test_rebinding_cannot_reach_private_ip()
    test_redirect_is_refused()
    test_public_name_is_allowed()
    print(f"OK: {len(ATTACK_URLS) + 3} attack URLs rejected")
Expected output (Python 3.12 to 3.14; Python 3.10 prints the two IPv4-mapped addresses in hex form)
$ python3 test_ssrf_guard.py
rejected http://127.0.0.1/ (non-public ['127.0.0.1'])
rejected http://127.1/ (non-public ['127.0.0.1'])
rejected http://2130706433/ (non-public ['127.0.0.1'])
rejected http://0.0.0.0/ (non-public ['0.0.0.0'])
rejected http://10.0.0.5/ (non-public ['10.0.0.5'])
rejected http://172.16.0.1/ (non-public ['172.16.0.1'])
rejected http://192.168.1.1/ (non-public ['192.168.1.1'])
rejected http://169.254.169.254/latest/meta-data/ (non-public ['169.254.169.254'])
rejected http://100.100.100.200/latest/meta-data/ (non-public ['100.100.100.200'])
rejected http://[fd00:ec2::254]/latest/meta-data/ (non-public ['fd00:ec2::254'])
rejected http://[::ffff:169.254.169.254]/ (non-public ['::ffff:169.254.169.254'])
rejected http://[::ffff:7f00:1]/ (non-public ['::ffff:127.0.0.1'])
rejected http://[64:ff9b::a9fe:a9fe]/ (non-public ['64:ff9b::a9fe:a9fe'])
rejected http://[2002:a9fe:a9fe::]/ (non-public ['2002:a9fe:a9fe::'])
rejected http://[::1]/ (non-public ['::1'])
rejected http://[::]/ (non-public ['::'])
rejected http://[fe80::1]/ (non-public ['fe80::1'])
rejected http://[fec0::1]/ (non-public ['fec0::1'])
rejected http://224.0.0.1/ (non-public ['224.0.0.1'])
rejected http://[email protected]/ (non-public ['127.0.0.1'])
rejected http://8.8.8.8:6379/ (port 6379 is not allowed)
rejected file:///etc/passwd (scheme 'file' is not allowed)
rejected gopher://127.0.0.1:6379/_INFO (scheme 'gopher' is not allowed)
rejected http://localhost/ (non-public ['127.0.0.1', '::1'])
rejected http://metadata.google.internal/ (non-public ['169.254.169.254'])
rejected http://mixed.attacker.test/ (non-public ['10.0.0.7'])
rebinding: 1 DNS lookup, socket went to ('93.184.215.14', 80)
redirect: redirect to 'http://169.254.169.254/latest/' refused
allowed https://example.com/a?b=1, pinned to 93.184.215.14
OK: 26 attack URLs rejected

05. Check your understanding

Practice check · 3 questions

Injection and SSRF defences

Three questions on parameterised queries and the SSRF guard from this lesson.

Q1. A search endpoint runs `f"SELECT * FROM items WHERE name LIKE '%{term}%'"`. Which change removes the injection?
Q2. A validator resolves the host, then rejects the URL if any address is `in` one of the IPv4 networks 127.0.0.0/8, 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 or 169.254.0.0/16. Which URL still reaches the metadata service?
Q3. A fetcher vets every resolved IP of a URL, then calls `httpx.get(url)` with the original URL. The attacker controls the DNS server for the host and sets a 1-second TTL. What can they achieve?
Practice only: not graded, not saved, not evidence.

06. Apply it

Audit a codebase you know, or the practice app, for string-built SQL, user-built file paths, HTML escape hatches and fetches of user-supplied URLs.

  • Move every query to bound parameters.
  • Add tests asserting that get_safe_file_path("../../../etc/shadow") never returns a path outside the upload folder (it returns <base>/shadow) and that a symlink inside the folder pointing outside raises PermissionError.
  • Build a page that renders user Markdown through a sanitiser, under a CSP with Trusted Types.
  • Put every URL fetcher behind a guard like ssrf_guard.py, and extend ATTACK_URLS with your cloud provider's metadata host name and any other address forms it adds.

In the next lesson, you will use an intercepting proxy, mitmproxy, to confirm flaws like these in a running practice app.

07. Review prompt

Describe the root cause shared by SQL injection, path traversal, XSS and SSRF. Explain why a parameterised query is safe where quote escaping is not, why the traversal check runs on the resolved path, and why Markdown or LLM output must be sanitised before dangerouslySetInnerHTML. Then list the four rules of the SSRF guard and, for each one, name an attack URL or trick that it stops.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check