首页 > 解决方案 > 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 提出的类似问题

标签: springspring-bootsanitizationfortify

解决方案


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

Spring 不会自动处理这个问题!

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


推荐阅读