Skip to content
javahacks.dev
Security

XXE Java Defences for DocumentBuilder SAX and StAX Parsers

Prevent XML external entity attacks in Java: disable DOCTYPE and external entities on DocumentBuilder, SAX, StAX, TransformerFactory and XMLReader.

6 min read
Summarize in AI
Flat illustration of a source file compiled to bytecode and run by the JVM, with the OpenJDK, Spring Security, Gradle and Apache Maven logos.

XML external entity injection, XXE, happens when a parser resolves an entity that points outside the document. An attacker who can submit XML makes your server read a local file, request an internal URL or exhaust memory, and the result may come back in the response. The unpleasant fact for Java developers is that several JDK parsers resolve external entities by default, so safe code requires setting options explicitly on every factory. This post lists the settings for each API on JDK 25, a way to centralise them, and a test that proves they work.

The attack

A document can declare an entity in its DOCTYPE and then use it:

XML
<?xml version="1.0"?>
<!DOCTYPE order [ <!ENTITY secret SYSTEM "file:///etc/passwd"> ]>
<order><note>&secret;</note></order>

A vulnerable parser replaces &secret; with the file's contents. Change file:// to http://169.254.169.254/latest/meta-data/ and the parser fetches a cloud metadata endpoint from inside your network, which is server-side request forgery delivered through XML. A third variant, the "billion laughs" document, defines entities that expand into one another and consumes gigabytes of memory from a few hundred bytes. XXE has a place in the OWASP top ten for Java developers, and the file-access side overlaps with path traversal.

The strongest defence is to refuse DOCTYPE declarations entirely. If an application does not need a DTD, and almost none does, disabling it removes the whole class of attack.

DocumentBuilder (DOM)

src/main/java/com/example/xml/SafeXml.javajava
static DocumentBuilder safeBuilder() throws ParserConfigurationException {
    var f = DocumentBuilderFactory.newInstance();
    f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
    f.setFeature("http://xml.org/sax/features/external-general-entities", false);
    f.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    f.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    f.setXIncludeAware(false);
    f.setExpandEntityReferences(false);
    return f.newDocumentBuilder();
}

disallow-doctype-decl is the setting that matters. The others are belt and braces for the case where a DOCTYPE is unavoidable. Setting a feature the parser does not recognise throws ParserConfigurationException, which is useful: it tells you that you are on a different parser implementation than you assumed. setXIncludeAware(false) stops xi:include from fetching external content, a separate path to the same result.

SAX and XMLReader

java
static SAXParser safeSax() throws Exception {
    var f = SAXParserFactory.newInstance();
    f.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    f.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
    f.setFeature("http://xml.org/sax/features/external-general-entities", false);
    f.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
    f.setNamespaceAware(true);
    return f.newSAXParser();
}

If you use XMLReaderFactory.createXMLReader() directly, set the same features on the reader. That factory is deprecated, so move to SAXParserFactory.

StAX

StAX has no DOCTYPE feature with the same name. Use its own properties:

java
static XMLInputFactory safeStax() {
    var f = XMLInputFactory.newFactory();
    f.setProperty(XMLInputFactory.SUPPORT_DTD, false);
    f.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
    return f;
}

With SUPPORT_DTD false, a DOCTYPE is ignored or rejected depending on the implementation, and entities are not expanded. It is the shortest of the three, which makes it easy to forget on code that reads feeds or uploads.

Transformers, schemas and validators

Anything that reads XML can fetch from it. For TransformerFactory, SchemaFactory and Validator, the JAXP access properties restrict what may be loaded:

java
var tf = TransformerFactory.newInstance();
tf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
tf.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");

var sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
sf.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
sf.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");

An empty string means "no protocols allowed". The two properties are part of JAXP since Java 7 and are the right answer when you cannot disable the DOCTYPE. XSLT adds its own risk, since a stylesheet can call extension functions; with secure processing on, those are limited, and you should never apply a stylesheet supplied by a user.

Libraries that parse XML for you

Frameworks hide the factory. JAXB, Jackson's XmlMapper, Spring's Jaxb2RootElementHttpMessageConverter, SOAP stacks, SAML libraries and Office document readers all parse XML. Check each library's documentation for its XXE posture. Current versions of most set safe defaults, but older ones did not, and a dependency from 2015 inside an upload path is how this bug returns. For JAXB, parse through a secured XMLStreamReader and pass that to the unmarshaller, not a raw InputStream.

Why the defaults are unsafe, and what changed in the JDK

The XML APIs date from a time when DTDs were the normal way to describe a document, and resolving an external entity was a feature. A conforming parser resolves them unless told not to. Over the years the JDK added the accessExternal* properties and FEATURE_SECURE_PROCESSING, and tightened some defaults, but a default that works on one parser implementation can differ on another when a library such as Xerces or Woodstox is on the classpath and takes over from the JDK's built-in one. That is the reason to configure each factory explicitly and test, not to trust what you remember of the defaults.

A subtle case is the parser that is picked through the service loader. DocumentBuilderFactory.newInstance() returns whichever implementation is first on the classpath, so adding a dependency can switch parsers and change which features are recognised. If disallow-doctype-decl suddenly throws ParserConfigurationException, a different implementation has taken over, and your helper class is the one place to adapt.

Where XML hides in an application

Uploads are the obvious input, but XML arrives in less obvious ways. A SAML response is XML, a SOAP request is XML, and an Office file, an SVG image and a .jar manifest alternative are ZIP files full of XML. Metadata extractors for images and documents often parse embedded XML (XMP). RSS importers and sitemap readers fetch XML from URLs a user provides. List each place your service accepts a file or a feed and ask whether the content ends up in a parser.

For each one, apply the same helper and record the decision in the code review. If the endpoint is only reachable by authenticated staff, the risk drops but does not vanish, because an account takeover turns a staff-only parser into a server-side file reader.

Centralise the factory

One class should own parser creation, so an unsafe DocumentBuilderFactory.newInstance() becomes a review finding rather than a style choice. Put the methods above in SafeXml, and make the rest of the code call it. Add a static analysis rule that flags direct newInstance() calls on the factories, using Error Prone, SpotBugs (XXE_DOCUMENT, XXE_SAXPARSER) or Semgrep, so a new call site cannot skip the helper.

Test it

java
@Test
void rejects_an_external_entity() {
    String xml = """
        <?xml version="1.0"?>
        <!DOCTYPE a [ <!ENTITY x SYSTEM "file:///etc/hostname"> ]>
        <a>&x;</a>""";
    assertThrows(SAXParseException.class,
        () -> SafeXml.safeBuilder().parse(new InputSource(new StringReader(xml))));
}

The test fails if someone removes the feature, and it documents the intent. Add one case for each parser type you use, plus a billion-laughs document that must be rejected quickly.

What is out of scope

These settings stop entity abuse. They do not make XML safe in general: a huge document still uses memory, so limit the request size at the edge and use jdk.xml.maxGeneralEntitySizeLimit style limits on parsers that honour them. They do not cover XML signature wrapping, which is an authentication problem in SAML and SOAP. The reference lists are the OWASP XXE prevention cheat sheet and the JAXP security guide. For the wider context, see security basics for backend developers.

Also inJava Core
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.