private static DocumentBuilderFactory createSecureDocumentBuilderFactory()

in log4j-changelog/src/main/java/org/apache/logging/log4j/changelog/util/XmlUtils.java [48:87]


    private static DocumentBuilderFactory createSecureDocumentBuilderFactory() {
        final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        String feature = null;
        try {

            // This is the PRIMARY defense.
            // If DTDs (doctypes) are disallowed, almost all XML entity attacks are prevented.
            // Xerces 2 only - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl
            feature = "http://apache.org/xml/features/disallow-doctype-decl";
            dbf.setFeature(feature, true);

            // If you can't completely disable DTDs, then at least do the following:
            // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-general-entities
            // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-general-entities
            // JDK7+ - http://xml.org/sax/features/external-general-entities
            // This feature has to be used together with the following one, otherwise it will not protect you from XXE for sure.
            feature = "http://xml.org/sax/features/external-general-entities";
            dbf.setFeature(feature, false);

            // Xerces 1 - http://xerces.apache.org/xerces-j/features.html#external-parameter-entities
            // Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#external-parameter-entities
            // JDK7+ - http://xml.org/sax/features/external-parameter-entities
            // This feature has to be used together with the previous one, otherwise it will not protect you from XXE for sure.
            feature = "http://xml.org/sax/features/external-parameter-entities";
            dbf.setFeature(feature, false);

            // Disable external DTDs as well
            feature = "http://apache.org/xml/features/nonvalidating/load-external-dtd";
            dbf.setFeature(feature, false);

            // and these as well, per Timothy Morgan's 2014 paper: "XML Schema, DTD, and Entity Attacks"
            dbf.setXIncludeAware(false);
            dbf.setExpandEntityReferences(false);

        } catch (final ParserConfigurationException error) {
            final String message = String.format("`%s` is probably not supported by your XML processor", feature);
            throw new RuntimeException(message, error);
        }
        return dbf;
    }