在javax XML Validator中禁用DTD

时间:2016-08-02 12:53:29

标签: java xml security xml-validation owasp

我正在使用javax.xml.validation.Validator来验证我的xml,如下所示 -

        Validator validator = myschema.newValidator();
        validator.validate(new StreamSource(new StringReader(xmlString)));

我想通过完全禁用DTD(文档类型定义)来防止XML外部实体攻击,所以如果可能的话,我希望验证程序在我的xml中出现DTD时抛出异常。我已经阅读了使用DocumentBuilderFactory执行此操作的信息。我如何在Validator中配置它?

2 个答案:

答案 0 :(得分:2)

根据Java的OWASP XXE prevention spreadsheet,以下内容应该有效:

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

有关详细信息,请参阅XMLConstants JavaDocs

答案 1 :(得分:-1)

这也可以工作-

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)));