Search code examples
javacode-injectiondtdxml

What is the effect of ignoring DTD specification in java?


Code analyzer tool is notifying about XML Entity Expansion Injection because there is no DTD specification implemented.

So i want to disable to the DTD specification check by

DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);

So I would like to know

  1. Will it break actual code flow?
  2. Will it cause anymore issues?
  3. Is there any other way to handle it?

Solution

  • To use parsers safely, you have to explicitly disable XXE in the parser you use. The following describes how to disable XXE in the most commonly used XML parsers for Java.

    JAXP DocumentBuilderFactory and SAXParserFactory

    Both DocumentBuilderFactory and SAXParserFactory XML Parsers can be configured using the same techniques to protect them against XXE. Only the DocumentBuilderFactory example is presented here.

    • The JAXP DocumentBuilderFactory setFeature method allows a developer to control which implementation-specific XML processor features are enabled or disabled

    .

    • Each XML processor implementation has its own features that govern how DTDs and external entities are processed.

    For a syntax highlighted code snippet for DocumentBuilderFactory, click here.

    For a syntax highlighted code snippet for SAXParserFactory, click here.

    The links will give you full details how to use DTD for both the parsers.

    Xerces 1 Features:

    Do not include external entities by setting this feature to false. Do not include parameter entities by setting this feature to false.

    Xerces 2 Features:

    Disallow an inline DTD by setting this feature to true. Do not include external entities by setting this feature to false. Do not include parameter entities by setting this feature to false. StAX and XMLInputFactory StAX parsers such as XMLInputFactory allow various properties and features to be set.

    To protect a Java XMLInputFactory from XXE, do this:

    xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false); // This disables DTDs entirely for that factory