protected static void enableOrDisableExternalEntityParsing ( DocumentBuilderFactory factory , boolean enableExternalEntities ) { // Feature list drawn from: // https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing /* Enable or disable external general entities */ String [ ] externalGeneralEntitiesFeatures = { // General "http://xml.org/sax/features/external-general-entities" , // 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" , } ; boolean success = false ; for ( String feature : externalGeneralEntitiesFeatures ) { try { factory . setFeature ( feature , enableExternalEntities ) ; success = true ; break ; } catch ( ParserConfigurationException e ) { } } if ( ! success && failIfExternalEntityParsingCannotBeConfigured ) { throw new XMLBuilderRuntimeException ( new ParserConfigurationException ( "Failed to set 'external-general-entities' feature to " + enableExternalEntities ) ) ; } /* Enable or disable external parameter entities */ String [ ] externalParameterEntitiesFeatures = { // General "http://xml.org/sax/features/external-parameter-entities" , // 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" , } ; success = false ; for ( String feature : externalParameterEntitiesFeatures ) { try { factory . setFeature ( feature , enableExternalEntities ) ; success = true ; break ; } catch ( ParserConfigurationException e ) { } } if ( ! success && failIfExternalEntityParsingCannotBeConfigured ) { throw new XMLBuilderRuntimeException ( new ParserConfigurationException ( "Failed to set 'external-parameter-entities' feature to " + enableExternalEntities ) ) ; } }
Explicitly enable or disable the external - general - entities and external - parameter - entities features of the underlying DocumentBuilderFactory .