You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Saxon9.7下SonarQube XML外部实体禁用修复及升级适配问题咨询

Saxon XXE漏洞修复及版本适配方案

问题1:Saxon 9.7版本兼容SonarQube修复规则方案(无需升级)

核心逻辑是兼顾静态扫描要求和运行时兼容性,代码实现如下:

TransformerFactory tfactory = TransformerFactory.newInstance();
// 保留SonarQube要求的配置项,满足静态扫描规则
try {
    tfactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, "");
    tfactory.setAttribute(javax.xml.XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
} catch (IllegalArgumentException e) {
    // 捕获Saxon 9.7不支持该属性的异常,使用Saxon专属安全配置实现同等防护能力
    tfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
    // 针对Saxon实现添加更严格的外部资源访问限制
    if (tfactory instanceof net.sf.saxon.jaxp.TransformerFactoryImpl) {
        net.sf.saxon.Configuration saxonConfig = ((net.sf.saxon.jaxp.TransformerFactoryImpl) tfactory).getConfiguration();
        saxonConfig.setBooleanProperty(net.sf.saxon.lib.FeatureKeys.ALLOW_EXTERNAL_DTD, false);
        saxonConfig.setBooleanProperty(net.sf.saxon.lib.FeatureKeys.ALLOW_EXTERNAL_STYLESHEET, false);
        saxonConfig.setBooleanProperty(net.sf.saxon.lib.FeatureKeys.ALLOW_EXTERNAL_FUNCTIONS, false);
    }
}
return tfactory;
  • 规则适配:代码中已包含SonarQube要求的两个属性配置,静态扫描时不会触发违规
  • 运行兼容:Saxon 9.7环境下会进入异常分支,通过Saxon原生配置实现XXE漏洞防护,不会抛出未知属性异常
  • 可选备选方案:如果业务场景不依赖Saxon的XSLT高级特性,可以直接指定使用JDK内置的TransformerFactory实现,跳过Saxon实现的加载:
    TransformerFactory tfactory = new com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl();

问题2:Saxon 10.x版本TraceListener适配方案

Saxon 10.x重构了Trace监听API,原有getConstructType()返回值可以通过两种方式获取,适配代码如下:

@Override
public void enter(Traceable instruction,           
 java.util.Map<java.lang.String,java.lang.Object> properties, XPathContext context){
    int constructType = -1;
    // 优先从入参properties中获取构造类型(Saxon 10.x默认会传递该属性)
    if (properties != null && properties.get("constructType") instanceof Integer) {
        constructType = (Integer) properties.get("constructType");
    }
    // 兜底逻辑:若instruction为InstructionInfo实例,直接强转取值
    else if (instruction instanceof net.sf.saxon.trace.InstructionInfo) {
        constructType = ((net.sf.saxon.trace.InstructionInfo) instruction).getConstructType();
    }
    if ((constructType == 155) || (constructType == 200)) {
        // 原有业务逻辑保持不变
    }
}

内容的提问来源于stack exchange,提问作者Dharani Dharan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 06:57:02