Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable DTD in javax XML Validator

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?

like image 630
Ankit Rustagi Avatar asked Aug 02 '16 12:08

Ankit Rustagi


1 Answers

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.

like image 76
coastalhacking Avatar answered Nov 09 '22 03:11

coastalhacking