SpringBoot 和消毒@PathVariable

问题描述

在我们的项目中,我们目前正在使用 Fortify 扫描器来扫描我们的代码,我们有一个有趣的问题。我们正在考虑类似

@PathVariable (required = true) String id

Spring 已经清理过了,但在我们的例子中,它在以下上下文中使用时会引发问题

@RequestMapping(
        method = RequestMethod.DELETE,path = "/{id}",consumes = "application/json"
)
public ResponseEntity cancelTask(
        @PathVariable (required = true) String id,@RequestBody (required = false) String reason
) {
    String userId = authenticationContext.getUserId();
    if (!authorizationService.hasPermission(userId,id,TaskAccessRight.EDIT)) {            log.warn("User {} is not authorized to cancel task {}",userId,id);
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Not authorized to cancel task " + id);
    }
 ...
}

Fortify 将此标记为跨站点脚本:反映问题。

我的问题是真的有可能通过说 id 类似于

<script>alert('Hello Jack')</script>

作为路径输入...如果是这样,我们应该如何在正文中对其进行消毒?

我们不确定这是否经过消毒,所以我们不确定这是误报,有人可以确认 Spring 会自动处理这个问题吗?

我们有几十个由 fortify 提出的类似问题

解决方法

基于静态代码分析,这个强化发现是有道理的。
字符串 id 是您方法的输入,您的代码不会验证或清理输入,并且在未经授权的情况下,您的代码将返回它。因此,“坏”代码流经您的应用程序并进行强化,而我不知道客户端对响应做了什么,因此存在某种风险。

Spring 不会自动处理这个!

您可以使用 Hibernate-Validator(请参阅 Maven 库 spring-boot-starter-validation)来验证输入并拒绝像您的脚本一样的无效输入。
在我的德文博客里,写过一篇关于Spring和验证的文章,见:
https://agile-coding.blogspot.com/2020/11/validation-with-spring.html