Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Secure SAXParserFactory that prevents XXE
import javax.xml.parsers.ParserConfigurationException; // catching unsupported features
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.SAXNotRecognizedException; // catching unknown features
import org.xml.sax.SAXNotSupportedException; // catching known but unsupported features
import org.xml.sax.XMLReader;
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser saxParser = spf.newSAXParser();
XMLReader reader = saxParser.getXMLReader();
try {
// Xerces 1 -
// Xerces 2 -
// Using the SAXParserFactory's setFeature
spf.setFeature("", false);
// Using the XMLReader's setFeature
reader.setFeature("", false);
// Xerces 2 only -
spf.setFeature("", true);
// remaining parser logic
} catch (ParserConfigurationException e) {
// Tried an unsupported feature.
} catch (SAXNotRecognizedException e) {
// Tried an unknown feature.
} catch (SAXNotSupportedException e) {
// Tried a feature known to the parser but unsupported.
} catch ... {

This comment has been minimized.

Copy link

JohnsonTay commented Jul 5, 2018

Got it,it's useful for me!


This comment has been minimized.

Copy link

AlainODea commented Jan 30, 2019

If you came here from and are wondering about DocumentBuilderFactory, I have a Gist for that.

DocumentBuilderFactory that mitigates XXE using OWASP guidance:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.