Reputation: 5637
I am using javax.xml.validation.Validator to validate my xml as below -
Validator validator = myschema.newValidator();
validator.validate(new StreamSource(new StringReader(xmlString)));
I would like to prevent XML External Entity attacks by disabling DTDs (Document Type Definitions) completely, so I'd like for the validator to throw an exception in case of a DTD in my xml if possible. I have read about doing this using DocumentBuilderFactory
. How do i do configure this in Validator?
Upvotes: 7
Views: 12495
Reputation: 1
This would also work-
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
Schema myschema = factory.newSchema();
Validator validator = myschema.newValidator();
validator.validate(new StreamSource(new StringReader(xmlString)));
Upvotes: -1
Reputation: 307
According to the OWASP XXE prevention spreadsheet for Java, the following should work:
SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
Schema myschema = factory.newSchema();
Validator validator = myschema.newValidator();
try {
validator.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
validator.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
validator.validate(new StreamSource(new StringReader(xmlString)));
} catch ...
Refer to the XMLConstants
JavaDocs for more details.
Upvotes: 4