Apache Commons Secure XML 1.0.0 API

Apache Commons Secure XML

leafApache Commons Secure XML

Apache Commons Secure XML is part of the Apache Commons project.

Apache Commons Secure XML provides secure-by-default JAXP factory creation, abstracting over implementation-specific XXE securing differences between the stock JDK and external JAXP implementations.

leafTL;DR

To secure XML processing:

Map JAXP factory methods to Apache Commons Secure XML
Replace JAXP factory methods with Commons Secure XML
javax.xml.parsers.DocumentBuilderFactory org.apache.commons.xml.secure.SecureDocumentBuilderFactory
javax.xml.parsers.SAXParserFactory org.apache.commons.xml.secure.SecureSAXParserFactory
javax.xml.validation.SchemaFactory org.apache.commons.xml.secure.SecureSchemaFactory
javax.xml.transform.TransformerFactory org.apache.commons.xml.secure.SecureTransformerFactory
javax.xml.stream.XMLInputFactory org.apache.commons.xml.secure.SecureXMLInputFactory
javax.xml.xpath.XPathFactory org.apache.commons.xml.secure.SecureXPathFactory

Or use the OpenRewrite recipe.

leafWhy

Any Java library that parses XML has to secure JAXP before handing a factory to user code, and every library ends up copy-pasting the same securing snippet. The snippet is fragile: the attributes and features needed to secure a factory are not standardized, each JAXP implementation exposes a slightly different set, and setting an unknown one throws an exception that callers routinely swallow. Writing this block correctly for every implementation is real work, and duplicating it across projects means every project owns the maintenance burden on its own.

Defaults are also uneven. The stock JDK SAX and DOM parsers already prevent external entity resolution through FEATURE_SECURE_PROCESSING, and JAXP 1.5 conformant implementations ship reasonable defaults for most attacks. Others, such as standalone Xerces, Woodstox, or Saxon’s TrAX, need further configuration before they reach the same baseline. A library author has no control over which implementation is on the classpath at runtime, so the effective security posture of their code depends on a deployment decision made elsewhere.

This library provides that baseline. Each org.apache.commons.xml.secure factory call returns a new factory secured by an implementation-specific recipe, so the returned object behaves the same way security-wise regardless of which JAXP implementation resolved. Security becomes a property of the call, not of the classpath, and there is one place to update when a new securing setting becomes available or a default changes.

leafUsage

To add the library to your build, see Maven Coordinates.

Every factory method in org.apache.commons.xml.secure returns a new, secured factory. Pick the one that matches the API you already use; no other configuration is required. On secured factories an external resource reference (DTD, entity, schema, stylesheet) is never fetched: it resolves to empty content, so the parse continues without it (see Configuration below).

Supported Runtimes

The library requires OpenJDK 8 or later (or a JDK distribution built from it), or Android API level 26 or later.

The security guarantees are defined only on the OpenJDK family (see the Threat Model). No version of Android supports FEATURE_SECURE_PROCESSING (so states Android’s own documentation), so the library secures the platform’s parsers as best-effort. Android’s XmlPullParser API is not supported: it is not a JAXP API.

Supported Implementations

Out of the box the library recognizes the stock JDK JAXP implementations, Apache Xerces 2.x, Woodstox, and Saxon-HE. If a factory resolves to an implementation not covered by any bundled securing recipe, every org.apache.commons.xml.secure factory method throws IllegalStateException with a message naming the unsupported class. Adding support for a new JAXP implementation requires a code change to this library.

DOM Parsing via SecureDocumentBuilderFactory;

      
import org.w3c.dom.Document;
import org.apache.commons.xml.secure.SecureDocumentBuilderFactory;

Document doc = SecureDocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream);
      
    

SAX Parsing via SecureSAXParserFactory;

      
import org.apache.commons.xml.secure.SecureSAXParserFactory;

SecureSAXParserFactory.newInstance().newSAXParser().parse(inputStream, myDefaultHandler);
      
    

Streaming (StAX) Parsing via SecureXMLInputFactory:

      
import javax.xml.stream.XMLStreamReader;
import org.apache.commons.xml.secure.SecureXMLInputFactory;

XMLStreamReader reader = SecureXMLInputFactory.newInstance().createXMLStreamReader(inputStream);
      
    

XSLT Transforms via SecureTransformerFactory:

      
import javax.xml.transform.stream.StreamSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.commons.xml.secure.SecureTransformerFactory;

SecureTransformerFactory.newInstance()
        .newTransformer(new StreamSource(stylesheet))
        .transform(new StreamSource(inputStream), new StreamResult(outputStream));
      
    

XPath Queries via SecureXPathFactory:

      
import javax.xml.xpath.XPathConstants;
import org.w3c.dom.NodeList;
import org.apache.commons.xml.secure.SecureXPathFactory;

NodeList hits = (NodeList) SecureXPathFactory.newInstance()
        .newXPath()
        .evaluate("//item", doc, XPathConstants.NODESET);
      
    

W3C XML Schema Validation via SecureSchemaFactory:

      
import javax.xml.XMLConstants;
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.xml.secure.SecureSchemaFactory;

SecureSchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
        .newSchema(new StreamSource(xsdStream))
        .newValidator()
        .validate(new StreamSource(inputStream));
      
    

Wrappers, not the Original Factories

A returned factory is not necessarily an instance of the underlying implementation. It might be (and usually is) a wrapper around it, so it cannot be cast to the implementation’s own class. Everything else about the implementation’s behavior is preserved: features, properties, and attributes delegate to it, and only the security behavior is applied.

Preserved behavior includes the choice of internal parsers. Each TrAX, XPath, or schema implementation has its own way of instantiating them, and the library respects it:

  • Stock JDK factories use the JDK parsers by default, and expose the jdk.xml.overrideDefaultParser feature (and Java system property of the same name) to switch to parsers instantiated through ServiceLoader.
  • Saxon selects its parsers through its own configuration.

Whichever parser is selected, it is secured.

Factory Methods

Each factory class mirrors every static factory method its JAXP counterpart offers, so a secured factory is a drop-in replacement at any construction site: the class-name/class-loader overloads and the StAX newFactory family (JDK 8), newDefaultInstance() (Java 9, JDK-8169778), and the namespace-aware newNSInstance() family (Java 13, JDK-8223423).

All of these methods work on every supported runtime, including Java 8: - The newNSInstance methods enable namespace awareness on their non-NS counterpart, the behavior the JAXP methods are specified to have. - The newDefaultInstance methods resolve the platform’s own newDefaultInstance at run time and use it wherever the runtime provides one — Java 9 or later, and the Android API levels that ship the method — falling back to instantiating the JDK’s built-in implementation by class name on Java 8.

The newDefaultInstance methods are an opt-out of JAXP pluggability: they pin the platform’s built-in implementation instead of whatever a classpath lookup would resolve. That suits a library with minimal XML requirements, which can parse with the well-known platform parser rather than delegate the choice of implementation to the application developer.

Stylesheets and Schemas

The securing applies to documents parsed through the returned factory. Stylesheets given to TransformerFactory.newTransformer(Source) and schemas given to SchemaFactory.newSchema(Source) are read by a parser the implementation picks internally, and that parser may not be secured (Saxon’s TrAX is one such case, see Building below). Treat stylesheets and schemas as trusted input, or pre-parse them through a secured org.apache.commons.xml.secure parser and pass the result as a DOMSource or SAXSource . A stylesheet also chooses where the transform writes ( xsl:result-document): the securing governs reads only, so restrict output destinations yourself when running an untrusted stylesheet (see the Threat Model).

Transformer Handlers and Filters

The SAXTransformerFactory extension methods, newTransformerHandler(...), newTemplatesHandler() and newXMLFilter(...), if reachable by casting the factory from SecureTransformerFactory.newInstance(), produce handlers, filters and Templates carrying the same securing as the standard entry points: runtime document() resolves to empty content, and a filter with no caller-set parent parses its input through a secured reader. The SAX events you feed into a handler, and a parent reader you set on a filter, are your own configuration, like any caller-supplied parser. See the Threat Model for the exact scope.

Caching and Thread-Safety

There is no caching or pooling inside org.apache.commons.xml.secure; callers on a hot path are responsible for their own caching. The returned factories inherit the thread-safety properties of the underlying JAXP implementation, which in practice means they are not thread-safe. Create a new factory per thread or synchronize externally.

leafConfiguration

The secured factories need no configuration. When a document references an external resource (a DTD, an external entity, a schema, an XInclude target, or an XSLT document), the securing layer resolves the reference to an empty stream: nothing is fetched, nothing leaks into the result, and the parse continues wherever the implementation can proceed with empty content. This forgiving default accommodates documents that merely carry such references without needing them.

If your application should reject such documents instead of parsing them, tighten the factory yourself. The securing floor stays underneath whatever you configure, so the tightening carries no security weight and can be as strict as the application needs:

  • Set a stricter feature on the factory, for example http://apache.org/xml/features/disallow-doctype-decl to reject every document carrying a DOCTYPE, on implementations that support the feature.
  • Install a resolver that throws. A caller-supplied EntityResolver, XMLResolver, LSResourceResolver or URIResolver is consulted before the securing floor, so an allow-list and a deny-all are both one resolver away.

Resolvers

A resolver here serves the opposite purpose it does on a stock JAXP factory. There, returning null hands the reference back to the parser, which fetches it; on a secured factory, returning null leaves the reference unresolved, and the securing floor answers it with empty content. Whatever your resolver leaves unresolved is never fetched.

A resolver is therefore the way to opt a resource back in, and returning a non-null result is how you say “this one is allowed”. Your resolver is consulted before the floor and is never replaced by it, and what it returns is honored even where the JAXP 1.5 external-access properties would deny the fetch, because those properties do not apply to a resolved result.

DTDs, external entities, and xi:include targets on DocumentBuilder and XMLReader, via EntityResolver. An InputSource carrying only the system identifier is the shortest way to allow one: the parser opens it itself.

      
import org.xml.sax.InputSource;
import org.apache.commons.xml.secure.SecureDocumentBuilderFactory;

DocumentBuilder builder = SecureDocumentBuilderFactory.newInstance().newDocumentBuilder();
builder.setEntityResolver((publicId, systemId) -> ALLOWED.contains(systemId) ? new InputSource(systemId) : null);
      
    

Every fetch on the schema path on SchemaFactory, Schema, Validator and ValidatorHandler, via LSResourceResolver. This one resolver answers for the schema documents a schema pulls in (xs:include, xs:import, and xsi:schemaLocation hints) and for the DTD and the external entities of the instance document being validated. The type argument tells them apart, as DOM Level 3 Load and Save prescribes: XMLConstants.W3C_XML_SCHEMA_NS_URI for a schema document, XMLConstants.XML_DTD_NS_URI for a DTD or an entity. A schema references its neighbors relatively, so resolve the system identifier against the base URI before matching it.

      
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSInput;
import org.apache.commons.xml.secure.SecureSchemaFactory;

DOMImplementationLS domImplementationLS = (DOMImplementationLS) DOMImplementationRegistry.newInstance().getDOMImplementation("LS");

SchemaFactory factory = SecureSchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
factory.setResourceResolver((type, namespaceURI, publicId, systemId, baseURI) -> {
    String resolved = baseURI == null ? systemId : URI.create(baseURI).resolve(systemId).toString();
    if (!ALLOWED.contains(resolved)) {
        return null;
    }
    LSInput input = domImplementationLS.createLSInput();
    input.setSystemId(resolved);
    return input;
});
      
    

Every fetch on the transform path on TransformerFactory, Templates and Transformer, via URIResolver. This one resolver answers for the stylesheet modules pulled in at compile time (xsl:include and xsl:import) and for everything the transform fetches as it runs: document(), and on an XSLT 3.0 implementation the unparsed-text() family and json-doc() as well. A StreamSource you return is re-parsed with a secured reader, so the references inside the resource you allowed face the same floor again. A function that cannot accept an empty document in place of what it asked for, unparsed-text() among them, reports an error when the resolver declines rather than returning empty content; either way the resource is not fetched.

      
import javax.xml.transform.stream.StreamSource;
import org.apache.commons.xml.secure.SecureTransformerFactory;

TransformerFactory factory = SecureTransformerFactory.newInstance();
factory.setURIResolver((href, base) -> {
    String resolved = base == null ? href : URI.create(base).resolve(href).toString();
    return ALLOWED.contains(resolved) ? new StreamSource(resolved) : null;
});
      
    

Entities on the streaming path on XMLInputFactory, via XMLResolver. This is the one resolver that has to open the resource itself: it must return an InputStream, an XMLStreamReader or an XMLEventReader, and any other type is silently ignored (the stock JDK then falls back to fetching the identifier the document declared, not the one you returned).

      
import org.apache.commons.xml.secure.SecureXMLInputFactory;

XMLInputFactory factory = SecureXMLInputFactory.newInstance();
factory.setXMLResolver((publicID, systemID, baseURI, namespace) -> {
    String resolved = baseURI == null ? systemID : URI.create(baseURI).resolve(systemID).toString();
    return ALLOWED.contains(resolved) ? URI.create(resolved).toURL().openStream() : null;
});
      
    

As a temporary debugging measure, set the system property org.apache.commons.xml.secure.throwOnUnresolved to true: every unresolved external reference is then rejected with the resolution hook’s exception, and the message names the denied resource. The property is read at resolution time, so it can be toggled on a running application; treat it as a diagnostic switch, not as an application configuration.

leafWhy Not the JAXP 1.5 External-Access Properties

The securing installs deny-by-default resolver floors on every factory it returns instead of setting the JAXP 1.5 external-access properties (accessExternalDTD, accessExternalSchema, accessExternalStylesheet). The two mechanisms are not interchangeable: by specification, the external-access properties have no effect when a registered resolver returns a non-null source, so a resolver takes precedence over the properties on every conforming implementation. Beyond that ordering, three defects make the properties unfit as the basis of the securing:

  • On older JDK 8 versions, the accessExternalSchema check is applied even to a schema document supplied by a caller’s resolver.
  • No external-access property governs an XInclude fetch, and a value set through the API is not even honored inside an XIncluded document. Only a resolver can gate XInclude.
  • Schema documents named by xsi:schemaLocation hints are checked even when supplied by a caller’s resolver.

The first and third defect fail closed — a legitimately resolved document is denied, never fetched — so they break resolver-based applications without weakening the securing; the second fails open and would leave a real fetch channel unguarded. A resolver floor has neither problem: it covers every channel on every supported implementation, and it yields to a caller’s resolver without consulting the properties. The Threat Model documents the resulting contract.

Packages
Package
Description
Apache Commons Secure XML provides secure-by-default JAXP factory creation for Java.