简介
SSTI(Server Side Template Injection):模板引擎是一种通过将模板中的占位符替换为实际数据来动态生成内容的工具,如HTML页面、邮件等。它简化了视图层的设计,但如果未对用户输入进行有效校验,可能导致安全风险如任意代码执行 Java中常用的模板引擎有Freemarker、Velocity、Thymeleaf等,在这里以Thymeleaf引擎为例
1.漏洞场景:thymeleaf模版注入
攻击者可以操控return中的值,就有可能造成模板注入漏洞,当方法返回为void时,thymeleaf会以URL路由为视图名称,调用模板视图去解析
缺陷代码
public String vul1(@RequestParam String para, Model model) {
// 用户输入直接拼接到模板路径,可能导致SSTI(服务器端模板注入)漏洞
return "/vul/ssti/" + para;
}
public void vul2(@PathVariable String path) {
log.info("SSTI注入:"+path);
}
// 缺陷组件版本参考
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<!-- <version>2.7.14</version>-->
<version>2.4.1</version>
<relativePath/>
</parent>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.4.1</version>
</dependency>
2.安全场景:thymeleaf模版注入
安全编码规范:
1、避免用户输入直接作为模板名称或路径
2、对所有动态内容进行严格校验和转义,包括模板变量
3、选择支持自动转义的安全模板引擎(如Thymeleaf的th:text)
4、使用白名单限制动态渲染的模板,控制可访问的模板范围
public String safe1(String para, Model model) {
List<String> white_list = new ArrayList<>(Arrays.asList("vul", "ssti"));
if (white_list.contains(para)){
return "vul/ssti" + para;
} else{
return "common/401";
}
}
@GetMapping("/safe2/{path}")
public void safe2(@PathVariable String path, HttpServletResponse response) {
log.info("SSTI注入:"+path);
}