微信支付XML外部实体注入漏洞XXE,需要在代码中进行相应的设置。官方提供的是dom4j的一些主流解析xml的解决方法,而我的代码是使用的XmlPullParser解析的,不知道该如何设置?
private Map<String, String> doXMLParse(String xml) throws XmlPullParserException, IOException { InputStream inputStream = new ByteArrayInputStream(xml.getBytes()); Map<String, String> map = null; XmlPullParser pullParser = XmlPullParserFactory.newInstance().newPullParser(); pullParser.setInput(inputStream, "UTF-8"); // 为xml设置要解析的xml数据 int eventType = pullParser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { switch (eventType) { case XmlPullParser.START_DOCUMENT: map = new HashMap<String, String>(); break; case XmlPullParser.START_TAG: String key = pullParser.getName(); if (key.equals("xml")) break; String value = pullParser.nextText(); map.put(key, value); break; case XmlPullParser.END_TAG: break; } eventType = pullParser.next(); } return map; }
微信官方提供的是这样的
import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; //捕获不支持的功能 ... DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 字符串FEATURE = null; 尝试{ //这是主要的防守。如果不允许DTD(doctypes),则几乎所有XML实体攻击都会被阻止 //仅限Xerces 2 - http://xerces.apache.org/xerces2-j/features.html#disallow-doctype-decl FEATURE =“http://apache.org/xml/features/disallow-doctype-decl”; dbf.setFeature(FEATURE,true); //如果无法完全禁用DTD,那么至少要执行以下操作: // 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 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 FEATURE =“http://xml.org/sax/features/external-parameter-entities”; dbf.setFeature(FEATURE,false); //也禁用外部DTD FEATURE =“http://apache.org/xml/features/nonvalidating/load-external-dtd”; dbf.setFeature(FEATURE,false); //以及这些,根据Timothy Morgan的2014年论文:“XML Schema,DTD和Entity Attacks” dbf.setXIncludeAware(假); dbf.setExpandEntityReferences(假); //而且,根据蒂莫西·摩根的说法:“如果由于某种原因支持内联DOCTYPE是必需的,那么 //确保禁用实体设置(如上所示)并注意SSRF攻击 //(http://cwe.mitre.org/data/definitions/918.html)并拒绝 //服务攻击(例如十亿笑或通过“jar:”减压炸弹)是一种风险。“ //剩下的解析器逻辑 ... } catch(ParserConfigurationException e){ //这应该捕获一个失败的setFeature功能 logger.info(“抛出了ParserConfigurationException。功能'”+ 您的XML处理器可能不支持FEATURE +“'。”); ... } catch(SAXException e){ //在Apache上,禁用DOCTYPE时应抛出此值 logger.warning(“将DOCTYPE传递给XML文档”); ... } catch(IOException e){ //指向不存在的文件的XXE logger.error(“发生IOException,XXE可能仍然可能:”+ e.getMessage()); ... } DocumentBuilder safebuilder = dbf.newDocumentBuilder();