Skip to content

XML Security Cheat Sheet

Introduction

While the specifications for XML and XML schemas provide you with the tools needed to protect XML applications, they also include multiple security flaws. They can be exploited to perform multiple types of attacks, including file retrieval, server side request forgery, port scanning, and brute forcing. This cheat sheet will make you aware of how attackers can exploit the different possibilities in XML used in libraries and software using two possible attack surfaces:

  • Malformed XML Documents: Exploiting vulnerabilities that occur when applications encounter XML documents that are not well-formed.
  • Invalid XML Documents: Exploiting vulnerabilities that occur when documents that do not have the expected structure.

Dealing with malformed XML documents

An XML document is malformed if it does not adhere to the XML syntax. A conforming parser rejects a malformed document and stops processing it, and the application should display an error message rather than continue. This is a syntax-level failure, distinct from a document that is well-formed but invalid against its schema. Typical causes are a missing end tag, elements ordered into a nonsensical structure, and forbidden characters.

To deal with malformed documents, use an XML processor that follows the W3C specifications, accept only well-formed documents, verify the contents of each element, and process only values within predefined boundaries.

Malformed input can also be expensive: some parsers take longer on malformed documents than on well-formed ones, which enables an asymmetric resource-consumption attack that becomes a denial of service when the attacker can send many documents. Compare the processing time of a malformed document with its well-formed equivalent to judge the exposure.

Some parsers can be configured to run in recovery mode, which accepts and corrects some malformed documents. Recovery has no predefined rules, so the result depends on the parser and its version, and two parsers can disagree about what the document contains. For example, lxml and PHP accept nested comments in recovery mode, although the specification forbids -- inside comments. Content obtained this way cannot be trusted for integrity-sensitive processing. Do not enable recovery mode (for example, recover=True in lxml or XML_PARSE_RECOVER in libxml2) for untrusted input.

Separately, canonicalization replaces CDATA sections with their character content and escapes the special characters in it (W3C: Canonical XML 1.1). The parsed value stays the same, but the serialized bytes change, and this happens to well-formed input too. Code that compares, signs, or filters the serialized form must account for this.

Coercive parsing is a separate attack on nesting depth: deeply nested elements can deplete the parser's resources and overflow the stack (Arnaboldi, Assessing and Exploiting XML Schema's Vulnerabilities, section 1.3). Leaving out the end tags only halves the payload size. The same attack works with a well-formed document, so disabling recovery mode does not prevent it. Arnaboldi reports a denial-of-service attack on Firefox that used 30,000 unterminated elements, tracked for Firefox 3.0.x as CVE-2009-1232. Limit nesting depth as well as total size. A simplified example:

<A1>
 <A2>
  <A3>
   ...
    <A30000>

Violation of XML Specification Rules

Unexpected consequences may result from manipulating documents using parsers that do not follow W3C specifications. It may be possible to achieve crashes and/or code execution when the software does not properly verify how to handle incorrect XML structures. Feeding the software with fuzzed XML documents may expose this behavior.

Dealing with invalid XML documents

Attackers may introduce unexpected values in documents to take advantage of an application that does not verify whether the document contains a valid set of values. Treat schema validation as a fail-closed contract: accept a document only after the entire document passes validation; otherwise reject it. More than one schema language can be layered (structural validation first, value restrictions second, for example). Streaming validators can deliver content before reporting a later validation failure, so do not commit application effects until all validation succeeds, and discard buffered results on failure.

Each XML document should be validated against a precisely defined XML Schema (not a DTD) in which every element and attribute carries explicit restrictions. The principles:

  • Validate against a strict, versioned, local schema. Compile the schema from files kept with the application (or from a known-good, integrity-checked repository) instead of following the schema location hints embedded in the document. If schema files are retrieved remotely, use secure, encrypted transport. Hint-driven loading fetches attacker-influenced URLs, and the Java Development Kit (JDK) documentation notes that "the use of schema location hints introduces a vulnerability to denial-of-service attacks" (javax.xml.validation.SchemaFactory). Keep the schema under version control, and re-validate whenever either the schema or the documents change.
  • Reject, do not repair. If validation fails, refuse the entire document. "Mostly valid" documents are exactly the shape used to smuggle a semantics-changing element past review.
  • Restrict every value with the schema's own facets. For strings, use length for a fixed length, or minLength and maxLength for a range, together with pattern or enumeration for allowed values. For numbers and amounts, use decimal types with minInclusive/maxInclusive and totalDigits/fractionDigits rather than floating point. Specify explicit units for measures, and explicit formats where a value is consumed by a legacy backend instead of the schema-checked pipeline.
  • Type by meaning, not by length. Where the receiving system enforces its own type (a database column, a currency type), the schema type should express the same size and range so the two layers cannot disagree about what was stored.
  • Keep documents small and shallow. Enforce document-size, nesting-depth, and element-count limits when receiving and parsing XML. In the schema, set an appropriate finite maxOccurs for repeated elements rather than maxOccurs="unbounded". Follow the XML External Entity Prevention Cheat Sheet for DTD and external-entity hardening. Schema validation is a second line of defense, not a replacement for parser hardening and resource limits.

Schema validity is not data authorization: a valid document can still come from an unprivileged user, so value-level authorization (resolving identifiers against server-side state instead of trusting document content, for example) remains the application's job.

The following element definition is the concise example for this section; facets restrict both its size and its vocabulary:

<xs:element name="country">
 <xs:simpleType>
  <xs:restriction base="xs:string">
   <xs:length value="2"/>
   <xs:pattern value="[A-Z]{2}"/>
  </xs:restriction>
 </xs:simpleType>
</xs:element>

Jumbo Payloads

Large XML documents can exhaust server resources through buffering, parsing, validation, or application processing. Small documents can also trigger disproportionate resource use through entity expansion or external resource retrieval. Both can lead to uncontrolled resource consumption.

Traditional Jumbo Payloads

Traditional jumbo payloads make the document itself very large, in one of two ways:

  • Depth attack: a huge number of elements, element names, and/or element values.
  • Width attack: a huge number of attributes, attribute names, and/or attribute values.
<SOAPENV:ENVELOPE XMLNS:SOAPENV="HTTP://SCHEMAS.XMLSOAP.ORG/SOAP/ENVELOPE/"
                  XMLNS:EXT="HTTP://COM/IBM/WAS/WSSAMPLE/SEI/ECHO/B2B/EXTERNAL">
 <SOAPENV:HEADER LARGENAME1="LARGEVALUE"
                 LARGENAME2="LARGEVALUE2"
                 LARGENAME3="LARGEVALUE3" …>
 ...

"Small" Jumbo Payloads

A very small document can have the same effect. An attacker can send it many times per second to consume most or all of the available resources:

<?xml version="1.0"?>
<!DOCTYPE root [
 <!ENTITY file SYSTEM "http://attacker/huge.xml" >
]>
<root>&file;</root>

Limiting Jumbo Payloads

Enforce the size, depth, and count limits from Dealing with invalid XML documents while parsing, before excessive resources are consumed, and also limit text and attribute-value lengths. These limits on the original input do not bound entity expansion or external resource retrieval. For those, follow XML Entity Expansion.

Schema Poisoning

When an attacker is capable of introducing modifications to a schema, there could be multiple high-risk consequences. In particular, the effect of these consequences will be more dangerous if the schemas are using DTD (e.g., file retrieval, denial of service). An attacker could exploit this type of vulnerability in numerous scenarios, always depending on the location of the schema.

Local Schema Poisoning

Local schema poisoning happens when schemas are available in the same host, whether or not the schemas are embedded in the same XML document.

Embedded Schema

The most trivial type of schema poisoning takes place when the schema is defined within the same XML document. Consider the following, unknowingly vulnerable example provided by the W3C :

<?xml version="1.0"?>
<!DOCTYPE note [
 <!ELEMENT note (to,from,heading,body)>
 <!ELEMENT to (#PCDATA)>
 <!ELEMENT from (#PCDATA)>
 <!ELEMENT heading (#PCDATA)>
 <!ELEMENT body (#PCDATA)>
]>
<note>
 <to>Tove</to>
 <from>Jani</from>
 <heading>Reminder</heading>
 <body>Don't forget me this weekend</body>
</note>

All restrictions on the note element could be removed or altered, allowing the sending of any type of data to the server. Furthermore, if the server is processing external entities, the attacker could use the schema, for example, to read remote files from the server. This type of schema only serves as a suggestion for sending a document, but it must contain a way to check the embedded schema integrity to be used safely. Attacks through embedded schemas are commonly used to exploit external entity expansions. Embedded XML schemas can also assist in port scans of internal hosts or brute force attacks.

Incorrect Permissions

You can often circumvent the risk of using remotely tampered versions by processing a local schema.

<!DOCTYPE note SYSTEM "note.dtd">
<note>
 <to>Tove</to>
 <from>Jani</from>
 <heading>Reminder</heading>
 <body>Don't forget me this weekend</body>
</note>

However, if the local schema does not contain the correct permissions, an internal attacker could alter the original restrictions. The following line exemplifies a schema using permissions that allow any user to make modifications:

-rw-rw-rw-  1 user  staff  743 Jan 15 12:32 note.dtd

The permissions set on name.dtd allow any user on the system to make modifications. This vulnerability is clearly not related to the structure of an XML or a schema, but since these documents are commonly stored in the filesystem, it is worth mentioning that an attacker could exploit this type of problem.

Remote Schema Poisoning

Schemas defined by external organizations are normally referenced remotely. If capable of diverting or accessing the network's traffic, an attacker could cause a victim to fetch a distinct type of content rather than the one originally intended.

Man-in-the-Middle (MitM) Attack

When documents reference remote schemas using the unencrypted Hypertext Transfer Protocol (HTTP), the communication is performed in plain text and an attacker could easily tamper with traffic. When XML documents reference remote schemas using an HTTP connection, the connection could be sniffed and modified before reaching the end user:

<!DOCTYPE note SYSTEM "http://example.com/note.dtd">
<note>
 <to>Tove</to>
 <from>Jani</from>
 <heading>Reminder</heading>
 <body>Don't forget me this weekend</body>
</note>

The remote file note.dtd could be susceptible to tampering when transmitted using the unencrypted HTTP protocol. One tool available to facilitate this type of attack is mitmproxy .

DNS-Cache Poisoning

Domain Name System (DNS) cache poisoning can change the IP address returned by a forward hostname lookup and redirect a schema connection. With HTTPS, the client must also verify the certificate against the requested hostname. DNS redirection alone does not let an attacker substitute schema content when that verification succeeds.

The previous example referenced the host example.com using an unencrypted protocol.

When switching to HTTPS, the location of the remote schema is https://example.com/note.dtd. Suppose a hostname lookup normally returns the following address:

$ host example.com
example.com has address 1.1.1.1

If an attacker compromises the DNS being used, the previous hostname could now point to a new, different IP controlled by the attacker 2.2.2.2:

$ host example.com
example.com has address 2.2.2.2

The redirected HTTPS connection must fail if the attacker cannot present a certificate trusted for example.com. Content substitution requires an additional failure, such as disabled certificate verification or compromise of the certificate trust chain or legitimate server credentials. Keep certificate and hostname verification enabled and stop schema retrieval on verification failure. HTTPS authenticates the server; it does not make a schema safe if the legitimate host is compromised.

Evil Employee Attack

When third parties host and define schemas, the contents are not under the control of the schemas' users. Any modifications introduced by a malicious employee-or an external attacker in control of these files-could impact all users processing the schemas. Subsequently, attackers could affect the confidentiality, integrity, or availability of other services (especially if the schema in use is DTD).

XML Entity Expansion

Processing a DTD from untrusted input enables two kinds of attack. Internal entities alone can exhaust memory and CPU (CWE-776): nested entities that each reference the next layer several times expand exponentially (the "billion laughs" attack), and many references to one large entity expand quadratically. These attacks need no external entity or network access, so blocking external entities does not stop them. External entities add local file disclosure (CWE-611) and requests to internal network resources (SSRF). One small document is enough to read a local file:

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

When the resolved entity is not reflected in the response or in an error message, the attacker can still confirm the attack or retrieve content out of band through parameter entities and a remote DTD. An external DTD reference in the DOCTYPE makes the parser fetch a URL even without any entity declaration (see Remote Schema Poisoning).

Disable DTD processing for untrusted XML; this blocks all of the attacks above. If a DTD is genuinely required, disable external entities and external DTD loading, and enforce entity expansion and entity size limits (for Java, see the processing limits in the JAXP Security Guide). Parser-specific settings are in the XML External Entity Prevention Cheat Sheet.

References