简介:Spring Boot中推荐使用Thymeleaf作为模板引擎.因为Thymeleaf提供了完美的SpringMVC支持。Thymeleaf是一个java类库,他是一个xml/xhtml/html5的模板引擎,可以作为mvc的web应用的view层。
一、问题描述:可通过thymeleaf模板注入,篡改用户页面显示内容。
漏洞复现访问路径如下(只要是渲染不存在的视图路径均会出现截图中的空白错误页面):http://localhost:8088/test/__$%7b4*4%7d__::.x
漏洞截图如下:
欲实现效果:不要将地址栏的参数动态注入到用户页面中。
导致问题的关键代码:(如下代码需要动态渲染test目录下的html文件)
@RequestMapping("test/{viewName}")
public String tohomePage(@PathVariable("viewName") String viewName,Model model,HttpServletRequest request) {
return "test/"+viewName;
}
经查找目前解决模板注入问题主要有三种方案:
1. 设置ResponseBody注解
2.设置redirect重定向
3. HttpServletResponse response
在方法参数中加上 HttpServletResponse 参数,这样spring会认为已经处理了response,无须再去进行视图名的解析。(在ServletResponseMethodArgumentResolver类中检查了此参数)
需要上述三种方案可参考以下链接:
spring boot Thymeleaf 模板注入 测试实践 - 妇愁者纞萌 - 博客园
不适用理由:但是thymeleaf大概就是通过语法,将属性保存到modelAttribute中,再返回一个视图的路径,渲染视图,同时模版引擎解析modelAttribute中的属性赋值到html中,返回一个视图路径要能渲染为视图,就不能使用RestController,或者加@Response Body注解。因此上述三种方法并不能解决我的问题。
二、尝试用全局捕捉异常的方法自定义返回信息
异常信息TemplateInputException截图如下:
org.thymeleaf.exceptions.TemplateInputException: Error resolving template "home/rdindex5", template might not exist or might not be accessible by any of the configured Template Resolvers
用@ControllerAdvice做了个全局异常处理的类,结果没进断点位置,无法捕捉到该异常。原因是TemplateInputException异常发生在模板引擎上,而非Controller上,因此无法捕捉到。于是尝试第三种方法,解决了此漏洞问题。
全局监听器可参考:SpringBoot thymeleaf自定义错误页面_憧憬个人博客-CSDN博客
三、自定义thymeleaf的错误页面(解决漏洞的方案)
在templates的文件夹下创建一个/error.html的页面,当thymeleaf无法渲染出视图时就会加载该错误页面。并且可以动态获取thymeleaf错误异常response的状态码status。(放置路径:templates/error.html,使用thymeleaf模板的html路径根目录均默认为/templates)
代码错误的html代码如下:
<!DOCTYPE html>
<html>
<head>
<title>Error <h4 th:text="${status}"></h4></title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Thymeleaf have an error occurred.</h1>
<p>Sorry, the page you are looking for is currently unavailable.<br/>
Please try again later.</p>
<p>If you are the system administrator of this resource then you should check
the error log for details.</p>
</body>
</html>
效果图如下: