如何限制XSL中unparsed-text()函数的访问权限
针对XSLT中unparsed-text()的访问限制方案
unparsed-text()确实支持类似document()的URI解析控制,但不同XSLT处理器的实现方式存在差异,以下是主流处理器的具体解决方案:
1. Saxon处理器(XSLT 2.0+主流实现)
Saxon提供了UnparsedTextURIResolver接口,可直接拦截并控制unparsed-text()的资源请求:
- 自定义实现该接口,在
resolve方法中校验请求路径,拒绝访问受限目录:
public class RestrictedUnparsedTextResolver implements UnparsedTextURIResolver { @Override public Reader resolve(URI absoluteURI, String encoding, XPathContext context) throws XPathException { String path = absoluteURI.getPath(); // 拦截受限路径,抛出异常阻止访问 if (path.contains("/System32/") || path.startsWith("/C:/System32")) { throw new XPathException("Access to restricted path denied: " + absoluteURI); } // 允许访问的路径,使用默认解析逻辑 return new UnparsedTextURIResolver.Default().resolve(absoluteURI, encoding, context); } }
- 将自定义解析器注册到Saxon的配置中:
Processor processor = new Processor(false); processor.getUnderlyingConfiguration().setUnparsedTextURIResolver(new RestrictedUnparsedTextResolver());
2. Xalan处理器(Apache XSLT 1.0实现)
Xalan没有专门对应unparsed-text()的URI解析接口,但可通过全局安全机制限制文件访问:
- 使用
SecurityManager设置文件读取权限,将受限目录加入黑名单:
SecurityManager securityManager = new SecurityManager(); // 禁止读取C:/System32下的所有文件 securityManager.addPermission(new FilePermission("C:\\System32\\*", "read")); // 注册到TransformerFactory TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute(XalanConstants.SECURITY_MANAGER, securityManager);
注意:此方式为全局控制,会同时限制document()等其他文件读取操作。
3. 关于TransformerFactory标志的补充
你尝试的ACCESS_EXTERNAL_DTD、ACCESS_EXTERNAL_STYLESHEET等标志,仅控制DTD和外部样式表的访问权限,对unparsed-text()不生效,因此需要使用上述处理器特定的接口或安全机制。
关键注意事项
- XSLT版本差异:XSLT 1.0中unparsed-text()属于扩展函数,处理器支持有限;XSLT 2.0+为标准函数,控制逻辑更完善。
- 路径校验需覆盖所有可能写法(如绝对路径、相对路径转换后的绝对路径),避免被绕过。
内容的提问来源于stack exchange,提问作者suraj gopinath
相关产品推荐
相关产品推荐

