#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 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:
#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:
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:
$ 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): Enablehttp://apache.org/xml/features/disallow-doctype-declset totrue(and disableexternal-general-entitiesandexternal-parameter-entitiesif DTDs cannot be completely prohibited). - Python: Use
defusedxmlinstead of the standard libraryxml.etree.ElementTreeorminidomwhen parsing untrusted XML. - PHP (
libxml): Keep modern PHP versions (libxml>= 2.9 disables external entity loading by default) and never pass theLIBXML_NOENTflag on untrusted input. - .NET: Set
XmlReaderSettings.DtdProcessing = DtdProcessing.ProhibitandXmlResolver = 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/xmlendpoints but forget that SVG images,.docxfiles, SAML tokens, and RSS feeds also invoke XML parsers. - Relying on keyword blocklists for SSTI: Blocking words like
__class__orconfigis brittle because template languages support alternative attribute lookup syntax, string concatenation, and filter chains. - Assuming
autoescape=Truestops 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
SYSTEMorPUBLICexternal 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
defusedxmlacross all XML-based formats (including SVG and Office files), and prevent SSTI by strictly binding user input as context variables in static templates.