Wanted to know how we can fix Xml EXternal Entity (XXE) vulnerability with Xstream API.
Like we can do
// 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
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
String FEATURE = null;
FEATURE = "http://apache.org/xml/features/disallow-doctype-decl";
dbf.setFeature(FEATURE, true);
with DocumentBuilderFactory. More details - https://www.owasp.org/index.php/XML_External_Entity_%28XXE%29_Prevention_Cheat_Sheet
My code is something like -
public static Class<?>[] myAnnotatedClasses = { Test1.class, Test2.class };
public static Object parseStr(String str) throws XStreamException
{
XStream xstream = new XStream(new StaxDriver());
xstream.processAnnotations(myAnnotatedClasses);
Object obj =xstream.fromXML(str);
return obj;
}
According to the XStream FAQs:
StaxDriver
tries to turns off support for external entities for the standard StaX parser. However, the finally used StAX implementation is defined externally (see JDK documentation) and a test should be made on the target platform to ensure that the parser respects the setting.
What this is saying is that StaxDriver
tries to tell the StAX
implementation to do the right thing, but the StAX
implementation you are using may ignore this. If it does ignore it, the simple answer is to use one of the alternative drivers listed in the FAQ that doesn't have the problem.