不安全写法,存在漏洞:
public static Object convertXmlToObj(Class clazz, String xmlStr)throws Exception {
JAXBContext context = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = context.createUnmarshaller();
return unmarshaller.unmarshal(new StringReader(xmlStr));
}
安全写法,漏洞防护:
public static Object xmlToObjectSafe(Class<?> klass, String xml) throws Exception {
// 将外部实体、参数实体和内联DTD 都设置为false,从而避免XXE漏洞
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
spf.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
spf.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
// Do unmarshall operation
Source xmlSource = new SAXSource(spf.newSAXParser().getXMLReader(), new InputSource(new StringReader(xml)));
JAXBContext context = JAXBContext.newInstance(klass);
Unmarshaller unmarshaller = context.createUnmarshaller();
return unmarshaller.unmarshal(xmlSource);
}
XXE防护官方文档:(包含各种xml转bean防护方法)https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/XML_External_Entity_Prevention_Cheat_Sheet.md
参考:
https://www.cnblogs.com/wfzWebSecuity/p/6681114.html
https://blog.spoock.com/2018/10/23/java-xxe/
https://blog.csdn.net/SouthWind0/article/details/89455611