public
anonymous / gist:5599156
Created

Disallowing XML external entities in Java DocumentBuilderFactory.

  • Download Gist
gistfile1.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException; // catching unsupported features
...
 
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
// Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities
// Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities
dbf.setFeature("http://xml.org/sax/features/external-general-entities", false);
 
// Xerces 2 only - http://xerces.apache.org/xerces-j/features.html#external-general-entities
dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false);
 
// remaining parser logic
...
 
} catch (ParserConfigurationException e) {
// Tried an unsupported feature. This may indicate that a different XML processor is being
// used. If so, then its features need to be researched and applied correctly.
// For example, using the Xerces 2 feature above on a Xerces 1 processor will throw this
// exception.
 
} catch ... {
}
...

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.