漏洞对比与安全建议
| 漏洞类型 | 核心原因 | 典型攻击路径 | 修复关键 |
| antMatchers | 路径后缀匹配机制 | /test/ | 使用 mvcMatchers 或通配符 |
| regexMatchers | 正则未考虑参数拼接 | /test?param=1 | 使用非贪婪正则 |
| 低版本后缀匹配 | useSuffixPatternMatch 默认开启 | /admin/delete.json | 升级版本或关闭配置 |
0x01 antMatchers 配置认证绕过
1. 问题原理
Spring Security 使用antMatchers("/test")保护路径时,因 Spring WebMVC 的useTrailingSlashMatch默认值为true,攻击者可通过/test/(带斜杠)路径绕过认证。该漏洞本质是路径匹配规则与 Web 容器默认行为的兼容性问题。
2. 漏洞代码示例
// Security配置
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .csrf().disable() .authorizeRequests() .antMatchers("/test").access("hasRole('ADMIN')") // 仅匹配/test.antMatchers("/**").permitAll(); }
}// 控制器
@RestController
public class TestController { @RequestMapping("/test") public String test() { return "ok"; }
}
3. 漏洞利用方式
访问http://localhost:8080/test/,Spring WebMVC 将其映射到/test路由,绕过 Security 的角色校验。
4. 修复方案
- 使用mvcMatchers("/test")精确匹配(适配 WebMVC):
-
.mvcMatchers("/test").access("hasRole('ADMIN')")
- 修改 antMatchers 为/test/**通配符匹配:
.antMatchers("/test/**").access("hasRole('ADMIN')")
5. 数据佐证
GitHub 统计显示antMatchers使用量达 49k,而mvcMatchers仅 1k,反映开发者对安全配置的忽视。
0x02 regexMatchers 配置认证绕过
1. 源码漏洞分析
RegexRequestMatcher.java的matches方法会将ServletPath与PathInfo、QueryString拼接后进行正则匹配。例如,请求/test?时,拼接后的 URL 为/test?,若正则为/test则匹配成功,导致认证绕过。
2. 漏洞配置示例
http.authorizeRequests().regexMatchers("/test").access("hasRole('ADMIN')").anyRequest().authenticated();
3. 漏洞利用方式
访问http://localhost:8080/test?param=1,拼接后的 URL 与/test正则匹配,未认证用户可访问。
4. 修复方案
使用非贪婪正则/test.*?确保严格匹配:
.regexMatchers("/test.*?").access("hasRole('ADMIN')")
5. 开发者误区
开发者常忽略参数拼接对正则匹配的影响,错误认为/test仅匹配纯净路径。
0x03 useSuffixPatternMatch 低版本认证绕过
1. 影响版本
- spring-webmvc ≤ 5.2.4.RELEASE
- spring-framework ≤ 5.2.6.RELEASE
- spring-boot-starter-parent ≤ 2.2.5.RELEASE
2. 漏洞原理
低版本中useSuffixPatternMatch默认开启,允许路径添加后缀(如.json)进行匹配。例如/admin路由可匹配/admin.json,绕过认证。
3. 漏洞示例
@RestController
public class AdminController { @RequestMapping("/admin/delete") public String delete() { return "仅管理员可访问"; }
}
攻击路径:/admin/delete.json
4. 修复方案
- 升级至 Spring Boot 2.3.0+(默认关闭后缀匹配)
- 手动关闭配置:
@Configuration
public class WebConfig implements WebMvcConfigurer {@Overridepublic void configurePathMatch(PathMatchConfigurer configurer) {configurer.setUseSuffixPatternMatch(false);}
}
开发实践建议:
- 新项目优先使用mvcMatchers,避免antMatchers的模糊匹配
- 正则表达式添加边界符(如^/api$),防止参数污染
- 建立版本升级机制,通过Dependency Check扫描漏洞
- 测试阶段增加路径变异用例(带斜杠、后缀、参数)
参考:LandGrey's Blog