Section 15.31

XML parsing

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 101010^{10} characters, about 9.3 GiB. This is the billion laughs attack, also called exponential entity expansion; its best-known form expands to 10910^9 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:

Setting up a parser for untrusted input takes five steps.

  1. 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.sax and xmlrpc all use the Expat parser library through the module pyexpat. pyexpat.EXPAT_VERSION names the Expat version in use, which may be the copy bundled with Python or the system’s. Third-party parsers, such as lxml, which is built on libxml2, have their own defaults.

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

  3. Bound the expansion. Where entities are admitted, cap the expanded size or the ratio of expanded output to input.

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

  5. 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 dd be the number of bytes read directly from the document and ii the number of bytes added by expanding entities and reading external DTD files. Once d+id + i reaches an activation threshold, 8 MiB by default, Expat stops with an error whenever the amplification (d+i)/d(d + i) / d 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 10×10=10010 \times 10 = 100 characters, &c; is 10×100=1,00010 \times 100 = 1{,}000 and &d; is 10×1,000=10,00010 \times 1{,}000 = 10{,}000. 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 210+3×45=345210 + 3 \times 45 = 345 bytes and expands to 10710^7 characters. With ten entities, a to j, it has 210+6×45=480210 + 6 \times 45 = 480 bytes and expands to 101010^{10} characters. At one byte per character that is 1010/230≈9.310^{10} / 2^{30} \approx 9.3 GiB, and the ratio of output to input is 1010/480≈2.1×10710^{10} / 480 \approx 2.1 \times 10^{7}.

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 10710^7 bytes exceed 8×220=8,388,6088 \times 2^{20} = 8{,}388{,}608 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 100,000+3×100,000=400,000100{,}000 + 3 \times 100{,}000 = 400{,}000 bytes. The output is 100,000×100,000=1010100{,}000 \times 100{,}000 = 10^{10} characters, a ratio of 1010/400,000=25,00010^{10} / 400{,}000 = 25{,}000. 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 nn characters with no references, and let the entity at each level jj, for 1≤j≤L1 \le j \le L, consist of kk references to the entity at level j−1j - 1. Then the entity at level LL expands to E=n⋅kLE = n \cdot k^{L} characters, while the declarations take a number of bytes roughly proportional to n+L⋅kn + L \cdot k. In the example, n=10n = 10, k=10k = 10 and L=3L = 3 give E=10×103=10,000E = 10 \times 10^{3} = 10{,}000. One entity of nn characters referenced rr times expands to E=n⋅rE = n \cdot r characters.

Let NN, MM and SS be limits that the application chooses. The contract a consumer of untrusted XML needs reads: for every input of at most NN bytes, parsing either fails with an error or finishes having produced at most MM bytes of expanded text, having opened no file or network address outside an allowed list (normally an empty one), and having used at most SS 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 101010^{10} 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].