JDK8 J2EE应用XSL包含与SonarQube XXE漏洞适配方案问询
问题:JDK8下XSLT外部实体限制与xsl:include兼容方案
背景
维护一个基于JDK 8的Java J2EE老旧Web应用,通过XSL转换生成HTML。为实现代码复用,XSL文件使用<xsl:include>标签引入其他XSL文件,示例如下:
XSL示例(th1.xsl)
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0" xmlns:fo="http://www.w3.org/1999/XSL/Format"> <!-- TEMPLATE TH1 --> ... <xsl:include href="disclaimer.xsl"/> ...
Java代码示例
String xslt = "th1.xsl"; String xml = "xxe.xml"; TransformerFactory transformerFactory = javax.xml.transform.TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(new StreamSource(xslt)); StringWriter writer = new StringWriter(); transformer.transform(new StreamSource(xml), new StreamResult(writer)); String result = writer.toString();
问题
接入SonarQube后收到**"禁用XML解析中的外部实体访问"**漏洞告警。按照提示添加以下配置:
transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); transformerFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
配置后,<xsl:include>无法加载目标XSL文件,抛出异常:
Caused By: javax.xml.transform.TransformerConfigurationException: file:///conf/myWebApp/xsl/modele/th1.xsl: line 6: Could not read stylesheet target 'disclaimer.xsl', because 'file' access is not allowed due to restriction set by the accessExternalStylesheet property. at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTemplates(TransformerFactoryImpl.java:990) at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTransformer(TransformerFactoryImpl.java:761) at weblogic.xml.jaxp.WebLogicTransformerFactory.newTransformer(WebLogicTransformerFactory.java:208) at weblogic.xml.jaxp.RegistryTransformerFactory.newTransformer(RegistryTransformerFactory.java:209)
尝试将ACCESS_EXTERNAL_STYLESHEET设为"file"可避免异常,但SonarQube仍触发同一告警。需要找到既能限制<xsl:include>仅访问可信目录,又能通过SonarQube检测的方案。
解决方案:自定义URIResolver
通过自定义URIResolver实现样式文件的可信加载,代码如下:
URIResolver uRIResolver = new URIResolver() { @Override public Source resolve(String href, String base) throws TransformerException { // 示例: href = "disclaimer.xsl" // 示例: base = "file:///appli/myAppli/xsl/th1.xsl" InputStream inputStream = getClass().getClassLoader().getResourceAsStream(href); if (inputStream == null) { throw new TransformerException("Unable to resolve " + href + " from classpath"); } return new StreamSource(inputStream); } }; TransformerFactory tFactory = TransformerFactory.newInstance(); tFactory.setURIResolver(uRIResolver); tFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_DTD, ""); tFactory.setAttribute(XMLConstants.ACCESS_EXTERNAL_STYLESHEET, "");
内容的提问来源于stack exchange,提问作者BrunoLochet
相关产品推荐
相关产品推荐

