Full name: Extensible Markup Language (XML) parsing.
Definition
XML parsing is the conversion of an XML (Extensible Markup Language) document, text that marks up data with nested, named tags such as <price>3</price>, into a structure a program can use: elements, attributes and text. A document may also carry a DTD (document type definition), a header that can declare entities: named pieces of text that the parser substitutes for each reference such as &name;, or fetches from a file or network address. Entities make the cost of parsing depend on what the document says, not only on its length.
The idea
A web service accepts orders written in XML. An order of a few hundred bytes should cost a few hundred bytes of memory to parse. But XML lets the sender define abbreviations inside the document itself: an entity a that stands for ten characters, an entity b that stands for ten references to a, an entity c that stands for ten references to b, and so on. Each declaration is one short line, yet each level multiplies the expanded text by ten. A parser that expands everything turns a 480-byte document into characters, about 9.3 GiB. This is the billion laughs attack, also called exponential entity expansion; its best-known form expands to copies of the string lol.
An entity can also point outside the document. The declaration <!ENTITY x SYSTEM "file:///etc/passwd"> asks the parser to read a local file and insert its content wherever &x; appears. With an http address instead, a parser that resolves the entity sends a request from the server’s own position in the network. This is an XML external entity (XXE) attack. Through it, the document’s author can read local files when the service echoes parsed content or errors back, make the service contact internal machines the author cannot reach, which is called server-side request forgery (SSRF), or make the parser wait on a source that never ends.
The picture to keep: a document with a DTD is data plus a small program of text substitutions and fetches, which the parser runs. Parsing it safely means deciding which of those features may run and how much they may spend.
How it works
The parts of a document that matter here:
Elements and attributes, the data itself, such as
<order id="7">...</order>.The DTD, written inside
<!DOCTYPE ...>at the top of the document, or loaded from a separate file that the document names.Internal entities, declared as
<!ENTITY name "text">. The parser replaces each reference&name;with the text, and the text may itself contain references.External entities, declared as
<!ENTITY name SYSTEM "uri">. The replacement is the content found at a URI (Uniform Resource Identifier), which can be a file name or a network address.Parameter entities, referenced as
%name;, which are used inside the DTD itself, for example to pull in further declarations from elsewhere.
Setting up a parser for untrusted input takes five steps.
Know the parser. Name the library, its version and the library it is built on. In Python §12.23,
xml.etree.ElementTree,xml.dom.minidom,xml.saxandxmlrpcall use the Expat parser library through the modulepyexpat.pyexpat.EXPAT_VERSIONnames the Expat version in use, which may be the copy bundled with Python or the system’s. Third-party parsers, such aslxml, which is built on libxml2, have their own defaults.Refuse what is not needed. Most data formats need no DTD at all. The strongest setting rejects any document that contains
<!DOCTYPE. The next best forbids entity declarations, and the minimum forbids external entities and external DTDs.Bound the expansion. Where entities are admitted, cap the expanded size or the ratio of expanded output to input.
Bound everything else. Cap the input size before parsing, the nesting depth, the length of a single name or text run and the number of attributes, and parse within a time limit.
Check the meaning separately, after parsing, against the application’s own rules or a schema.
Expat’s own protections are concrete. Python’s documentation states that Expat by default opens no local files and makes no network connections. Since version 2.4.0, Expat also limits entity expansion. Let be the number of bytes read directly from the document and the number of bytes added by expanding entities and reading external DTD files. Once reaches an activation threshold, 8 MiB by default, Expat stops with an error whenever the amplification exceeds a maximum, 100 by default. A program can change both numbers. Python’s documentation warns that Expat versions older than 2.7.2 may still be open to the billion laughs, quadratic blowup and large token attacks, or to disproportionate use of memory, so the version matters.
Worked example
The following document is 210 bytes long, counting one newline at the end of each of its 8 lines:
<?xml version="1.0"?>
<!DOCTYPE r [
<!ENTITY a "0123456789">
<!ENTITY b "&a;&a;&a;&a;&a;&a;&a;&a;&a;&a;">
<!ENTITY c "&b;&b;&b;&b;&b;&b;&b;&b;&b;&b;">
<!ENTITY d "&c;&c;&c;&c;&c;&c;&c;&c;&c;&c;">
]>
<r>&d;</r>
Expand level by level. &a; is 10 characters. &b; is characters, &c; is and &d; is . So the 210-byte document yields an element r whose text is 10,000 characters long; Python’s ElementTree.fromstring returns exactly that.
Each further level adds one declaration line of 45 bytes and multiplies the output by 10. With seven entities, a to g, the document has bytes and expands to characters. With ten entities, a to j, it has bytes and expands to characters. At one byte per character that is GiB, and the ratio of output to input is .
With Expat 2.6.1, the version used to run this example, the four-entity document is accepted: its expansion stays below the 8 MiB activation threshold, so the amplification limit never applies. The seven-entity document is rejected with the error limit on input amplification factor (from DTD and entities) breached, because bytes exceed bytes and the amplification is far above 100. A parser without such a limit tries to build the 9.3 GiB string for the ten-entity document.
A depth limit alone does not stop the quadratic blowup variant. Declare one entity of 100,000 characters and reference it 100,000 times. The nesting depth is 1. Each reference &x; takes 3 bytes, so the input is about bytes. The output is characters, a ratio of . Only a limit on the total expanded size, or on the ratio, catches both forms.
Stated precisely
Let the entity at level 0 have replacement text of characters with no references, and let the entity at each level , for , consist of references to the entity at level . Then the entity at level expands to characters, while the declarations take a number of bytes roughly proportional to . In the example, , and give . One entity of characters referenced times expands to characters.
Let , and be limits that the application chooses. The contract a consumer of untrusted XML needs reads: for every input of at most bytes, parsing either fails with an error or finishes having produced at most bytes of expanded text, having opened no file or network address outside an allowed list (normally an empty one), and having used at most seconds of processor time. Each part of this contract comes from a specific setting of a specific parser version: a refusal of DTDs or of entity declarations, a disabled resolver for external entities, an expansion or amplification limit, and caps on depth and token length. That the parser can read the document, or that the document is well formed, meaning it follows XML’s syntax rules, establishes none of these parts.
Limits and common mistakes
Turning entity expansion off does not remove every cost. Very long names or text runs, deep nesting and many attributes cost memory and time too. Python’s documentation describes a large token problem: Expat re-parses an unfinished token each time more input arrives, which without the protection added in Expat 2.6.0 can take time quadratic in the token’s length. Input built to drive a program into such a worst case is an algorithmic complexity attack §15.35. A tree builder that recurses once per nesting level can end in a stack overflow §4.10 on a deeply nested document.
Compression is a separate multiplier. A compressed XML stream can expand a thousandfold or more before the parser sees a byte of it; Python’s documentation notes that xmlrpc is open to such decompression bombs. Bound the decompressed size first, as the zlib module §15.32 entry describes.
A safe parse is not an acceptable message. Being well formed, conforming to a schema, and being permitted to request the action are three separate checks, and parsing performs only the first.
Defaults differ between libraries and change between versions. Python’s SAX interface (Simple API for XML, an interface that reports a document as a stream of events) stopped resolving external general entities by default in Python 3.7.1, and Expat added its amplification limit in 2.4.0. A claim such as “this program is safe against XXE” is true only for a named module, version and configuration.
Repairing a document that fails to parse, for example by deleting its DTD and parsing again, changes what was received. Strict parsing §1.48 refuses the document and reports the parse error instead.
The Common Weakness Enumeration (CWE), a public catalog of software weaknesses, lists these problems as CWE-611, improper restriction of XML external entity reference, and CWE-776, improper restriction of recursive entity references in DTDs.
Questions answered
Can entity expansion or external references consume unexpected resources?
Yes. When the parser in use expands entities without a limit, a document of a few hundred bytes can demand gigabytes of memory and the processor time to fill them: ten nested entity levels, each referring ten times to the level below, turn a 480-byte XML (Extensible Markup Language) document into characters, about 9.3 GiB. When the parser resolves external entities or an external document type definition (the DTD, the header section that declares entities), the document decides which files the parser opens and which network addresses it contacts. That can disclose local files, reach internal machines, or leave the parser waiting on a slow or endless source.
Whether this happens depends on the named parser, its version and its settings, not on XML as such. Python’s built-in parsers use the Expat library, which by default opens no files and makes no network connections, and from version 2.4.0 stops parsing once the processed data has passed 8 MiB and is more than 100 times the document’s own size. For untrusted input, refuse DTDs or entity declarations when the format does not need them, keep external resolution off, cap the input size, the nesting depth and the expanded size, and treat a successful parse as proof of syntax only.
Related entries: zlib module (§15.32), Algorithmic complexity attack (§15.35), JSON (§12.26), Denial of service (DoS) (§1.28), Robustness principle and strict parsing (§1.48). Further reading: [146].