Normally when parsing XML in java, it's possible to avoid falling victim to entity expansion attacks by using
dbf.setFeature(javax.xml.XMLConstants.FEATURE_SECURE_PROCESSING, true);
Where dbf is a DocumentBuilderFactory used to create DocumentBuilders for XML parsing.
However, suppose I am unmarshalling some XML using JAXB, e.g. like this:
final JAXBContext context = JAXBContext.newInstance(MyClass.class);
final Unmarshaller unmarshaller = context.createUnmarshaller();
final MyClass result = (MyClass) unmarshaller.unmarshal(input);
How can I configure JAXB to use FEATURE_SECURE_PROCESSING on the underlying XML parser?
Googling for answers brings up the following as the best result: http://forums.java.net/node/699983
However, I don't want to have to bring in implementations of XMLStreamFactory and the like just to make entity expansion configurable. Is there a way to solve this problem using just the JAXB API?
The safest way to prevent XXE is always to disable DTDs (External Entities) completely. Depending on the parser, the method should be similar to the following: factory. setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
Generally JAXB is quite efficient and you shouldn't care about memory issues unless your application handles XMLs of very large size.
Bind the Schema. JAXB simplifies access to an XML document from a Java program by presenting the XML document to the program in a Java format. The first step in this process is to bind the schema for the XML document into a set of Java classes that represents the schema.
Java Architecture for XML Binding (JAXB) provides a fast and convenient way to bind XML schemas and Java representations, making it easy for Java developers to incorporate XML data and processing functions in Java applications.
Java SE 5 limits the number of entity expansions to 64,000:
I would expect that all JAXB implementations would leave this default protection in place. However if you want to be 100% sure you can create a SAXSource in the following way and have JAXB unmarshal that:
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
SAXParser sp = spf.newSAXParser();
XMLReader xmlReader = sp.getXMLReader();
SAXSource saxSource = new SAXSource(xmlReader, inputSource);
For more information see:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With