Most XML parsers are vulnerable for XML external entitiy attacks (XXE) by default. So what’s your mitigation?
The easiest way to prevent XXE is to disallow the Doctype declaration completely:
import java.io.File; import org.jdom.Document; import org.jdom.JDOMException; import org.jdom.input.SAXBuilder; public class XEE_Disallow_Doctype_Decl { public static void main(String[] args) { String element= null; SAXBuilder objBuilder = null; Document objDocXML = null; try { objBuilder = new SAXBuilder("org.apache.xerces.parsers.SAXParser"); objBuilder.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); objDocXML = objBuilder.build(new File("data\\test.xml")); element= objDocXML.getRootElement().getChild("TestElement").getText(); System.out.println("Element: " + element); } catch(Exception e) { e.printStackTrace(); } } }
If this is not possible, because the Doctype declaration is required in your application, you can disallow external entities:
import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; public class XEE_Disallow_External_Entities { public static void main(String[] args) { String xmlFile = "data\\test.xml"; MyHandler handler = new MyHandler(); try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/external-general-entities", false); factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); SAXParser parser = factory.newSAXParser(); parser.parse(xmlFile, handler); } catch (Exception e) { e.printStackTrace(); } } }
To ensure if your configuration is secure, you should always verify the parser manually!
Want to learn more about XML external entity attacks and application security? Join our web application security trainings in Rapperswil/Jona next week:
- August 20th and 21st, Web Application Security Basic (in German)
- August 22nd and 23rd, Web Application Security Advanced (in German)
References
- XML External Entity Attacks http://www.csnc.ch/misc/files/publications/2010_w-jax_xml_theory_and_attacks_XXE.pdf
- Apache XML Project http://xerces.apache.org/xerces2-j/features.html
Leave a Reply