使用JAXB实现XML转对象导致XXE漏洞防护

博客介绍了XXE的不安全写法,存在漏洞,同时给出安全写法用于漏洞防护,还提供了XXE防护官方文档,包含各种xml转bean防护方法,此外还列出了相关参考链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

不安全写法,存在漏洞:

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.youkuaiyun.com/SouthWind0/article/details/89455611

### 如何在Java中修复XXE漏洞 为了有效防范XXEXML External Entity)攻击,在Java环境中应当采取一系列措施确保安全性。当涉及到基于DOM的方式解析XML时,可以通过设置`DocumentBuilderFactory`的安全特性来阻止外部实体加载[^1]。 ```java DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); // 或者对于其他厂商的实现也可以尝试如下通用特征 dbf.setFeature("http://xml.org/sax/features/external-general-entities", false); dbf.setFeature("http://xml.org/sax/features/external-parameter-entities", false); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(new File("input.xml")); ``` 针对SAX解析器,则需调整对应的工厂实例: ```java SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); SAXParser saxParser = spf.newSAXParser(); saxParser.parse(new InputSource(new StringReader(xmlString)), new DefaultHandler()); ``` 如果项目依赖于JAXB来进行XML绑定操作,除了上述预防手段外,还应考虑使用更安全的数据交换格式替代XML,比如JSON;或者采用支持禁用DOCTYPE声明及其他潜在风险特性的库版本,并合理配置相关参数以增强防护能力[^3]。 另外值得注意的是,某些特殊场景下可能会遇到自定义URL协议处理器的情况,例如提到过的`jar:`协议。在这种情形里,务必谨慎评估并限制其访问权限范围,以免成为新的安全隐患入口[^2]。 最后提醒一点,保持第三方组件及其依赖项处于最新状态同样重要,因为官方往往会及时修补已知缺陷和弱点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值