Recently I’ve got a security violation report from Sonar. It is the XXE attack. This is indeed a scary scenario, with attacker able to access server internal file with ease.
The simplest approach is to disable this feature.
XMLInputFactory xif = XMLInputFactory.newFactory(); xif.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false); xif.setProperty(XMLInputFactory.SUPPORT_DTD, false); XMLStreamReader xsr = xif.createXMLStreamReader(source);
However in my case, I actually need the feature to take reference of the packed XMLs.
So one approach for mitigating the risk is to use a customized XMLResolver. Then in this XMLResolver, whitelist only the essential resource accesses (or better, do the resolution in memory, if possible).
XMLInputFactory xif = XMLInputFactory.newFactory(); xif.setXMLResolver(resolver); XMLStreamReader xsr = xif.createXMLStreamReader(source);