Skip to main content
XML External Entity (XXE) & Server-Side Template Injection (SSTI)
Lesson 14 of 23

XML External Entity (XXE) & Server-Side Template Injection (SSTI)

Understand how XML parsers resolve untrusted Document Type Definitions to expose local files or internal HTTP targets, how server-side template injection differs from XSS, and how to harden XML parsers and template engines.

Advanced 34 min Web security
Authorised environments only — The techniques described here are used only in training labs and on systems you own or have written permission to test.

Learning objectives

  • Explain how Document Type Definitions and external entities allow file reads and SSRF in misconfigured XML parsers
  • Distinguish reflected XXE, blind out-of-band XXE, and entity-expansion denial of service
  • Fingerprint common server-side template engines using safe arithmetic probes and distinguish SSTI from XSS
  • Configure XML parsers to prohibit DTD processing and pass untrusted data strictly as template context variables

Recommended first: IDOR, Path Traversal and Core Web AttacksBlind/Time-Based SQLi & Filter-Bypass SSRF

#Why this matters

Web services frequently parse XML documents - from SOAP APIs and SAML assertions to SVG images and .docx or .xlsx uploads - and render dynamic HTML, PDFs, or emails using server-side template engines such as Jinja2, Twig, or Freemarker. Both subsystems become critical liabilities when untrusted data is treated as instructions.

If an XML parser evaluates a Document Type Definition (DTD) supplied by a client, external entity declarations can read local files or trigger Server-Side Request Forgery (SSRF). Similarly, if user input is concatenated into a template string before compilation instead of being passed as data, the template engine executes attacker-controlled expressions on the server.

#How XML External Entity (XXE) works

XML allows a <!DOCTYPE ...> declaration at the top of a document to define named shortcuts called entities. An external entity uses the SYSTEM keyword to tell the parser to fetch replacement content from a file path or URL before returning the parsed XML tree to the application.

xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE invoice [
  <!ENTITY labhost SYSTEM "file:///etc/hostname">
]>
<invoice>
  <customer>&labhost;</customer>
</invoice>

If the parser resolves external entities and the application echoes <customer> back in the response, the server returns the contents of /etc/hostname.

XXE variant Parser behaviour How impact is observed
Classic (in-band) Resolves SYSTEM entity into XML text File contents appear in the HTTP response
Blind out-of-band (OOB) Evaluates external DTD via parameter entities (%dtd;) Server makes DNS/HTTP callback to listener
Error-based References malformed URI or missing file path Parser error message leaks target file line
Entity expansion (DoS) Expands nested internal entities ("Billion Laughs") Excessive CPU and memory consumption

Even when the application returns no XML values, blind XXE can still force an outbound connection to an external listener or internal service:

Blind out-of-band XXE verification in a labBlind out-of-band XXE verification in a labClientAppXmlParserListenerPOST XML with external DTD http://192.0.2.5/probe.dtdParse body with DTD resolution enabledGET /probe.dtd200 OK (empty DTD)Outbound GET confirms external DTD fetching

#Server-Side Template Injection (SSTI)

Learners often confuse Cross-Site Scripting (XSS) with SSTI because both can involve HTML responses. The difference is where evaluation happens: XSS executes JavaScript in the victim's browser, whereas SSTI evaluates template directives inside the server process before the HTTP response is ever sent.

Consider a Flask route that formats a template string with Python f-strings:

python
from flask import Flask, request, render_template_string

app = Flask(__name__)

@app.route("/vuln")
def vuln_greet():
    name = request.args.get("name", "guest")
    # Vulnerable: user input becomes part of the template source
    return render_template_string(f"<h1>Hello, {name}</h1>")

@app.route("/safe")
def safe_greet():
    name = request.args.get("name", "guest")
    # Safe: static template, user input bound as context data
    return render_template_string("<h1>Hello, {{ name }}</h1>", name=name)

In /vuln, sending name={{7*7}} makes Jinja2 evaluate 7*7 and render <h1>Hello, 49</h1>. In /safe, Jinja2 treats name strictly as string data and autoescapes it, rendering the literal characters {{7*7}}.

#Fingerprinting the engine safely

Different template engines use different expression delimiters and semantics. A tester sends minimal arithmetic probes and watches the output:

Probing a lab greeting endpoint with curl
$ curl -s "http://lab.local/vuln?name=%7B%7B7*7%7D%7D"
<h1>Hello, 49</h1>
$ curl -s "http://lab.local/vuln?name=%7B%7B7*'7'%7D%7D"
<h1>Hello, 7777777</h1>

The second probe separates Python's Jinja2 from PHP's Twig: in Jinja2, multiplying an integer by a string repeats the string (7777777), whereas Twig casts the string and returns 49. Other engines use ${7*7} (Freemarker, Java EL) or <%= 7*7 %> (ERB).

Once an expression evaluates server-side, the risk goes far beyond arithmetic. Templates expose framework globals (such as Flask's config object) and object attributes. In Python-based engines, traversing an object's class hierarchy (__class__, __mro__, __subclasses__()) can expose loaded modules in the interpreter, turning an innocent greeting banner into full server compromise.

#Defending and common mistakes

Securing XML parsing requires disabling DTDs at the parser configuration level, not filtering strings with regular expressions:

  • Java (DocumentBuilderFactory): Enable http://apache.org/xml/features/disallow-doctype-decl set to true (and disable external-general-entities and external-parameter-entities if DTDs cannot be completely prohibited).
  • Python: Use defusedxml instead of the standard library xml.etree.ElementTree or minidom when parsing untrusted XML.
  • PHP (libxml): Keep modern PHP versions (libxml >= 2.9 disables external entity loading by default) and never pass the LIBXML_NOENT flag on untrusted input.
  • .NET: Set XmlReaderSettings.DtdProcessing = DtdProcessing.Prohibit and XmlResolver = null.

Securing template rendering follows one core rule: separate template code from user data.

  • Never pass concatenated or formatted strings into render_template_string, Twig::createTemplate, or similar dynamic compile APIs.
  • Always load static template files and bind untrusted values as named context parameters with HTML autoescaping enabled.
  • If a product genuinely requires user-editable templates, use a logic-less engine (such as Mustache) or a restricted sandbox (such as Jinja2 SandboxedEnvironment) with a strict allow-list of exposed attributes and methods.

Common mistakes to watch for during code review:

  • Forgetting XML-backed file formats: Teams harden /api/xml endpoints but forget that SVG images, .docx files, SAML tokens, and RSS feeds also invoke XML parsers.
  • Relying on keyword blocklists for SSTI: Blocking words like __class__ or config is brittle because template languages support alternative attribute lookup syntax, string concatenation, and filter chains.
  • Assuming autoescape=True stops SSTI: Autoescaping encodes HTML characters inside data variables, not expressions inside an untrusted template string.

#Summary

  • XXE occurs when an XML parser processes DTDs and resolves SYSTEM or PUBLIC external entities, enabling local file reads, SSRF, or entity-expansion DoS.
  • SSTI occurs when untrusted input is compiled as part of a server-side template rather than passed as a data variable, enabling server-side expression evaluation.
  • Safe probing with {{7*7}} and {{7*'7'}} distinguishes engines such as Jinja2 (7777777) and Twig (49).
  • Prevent XXE by prohibiting DTDs and using defusedxml across all XML-based formats (including SVG and Office files), and prevent SSTI by strictly binding user input as context variables in static templates.

Knowledge check

Sign in to take the test, complete lessons and save your progress. Log in

Practice: test your knowledge