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?
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.
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