spring boot 最佳实践(五)--SpEL

SpEL 拥有许多特性,包括:

表达式语言支持以下功能

  • 文字表达式
  • 引用Bean属性和方法
  • 类表达式
  • 访问 properties, arrays, lists, maps
  • 布尔和关系运算符
  • 正则表达式
  • 方法调用
  • 关系运算符
  • 参数
  • 调用构造函数
  • 构造Array
  • 内嵌lists
  • 内嵌maps
  • 三元运算符
  • 变量
  • 用户定义的函数
  • 集合投影
  • 集合筛选
  • 模板表达式

基本语法

#{ } 标记会提示Spring 这个标记里的内容是SpEL表达式。
#{rootBean.nestBean.propertiy} “.”操作符表示属性或方法引用,支持层次调用
#{aList[0] } 数组和列表使用方括号获得内容
#{aMap[key] } maps使用方括号获得内容
#{rootBean?.propertiy} 此处"?"是安全导航运算符器,避免空指针异常
#{condition ? trueValue : falseValue} 三元运算符(IF-THEN-ELSE)
#{valueA?:defaultValue} Elvis操作符,当valueA为空时赋值defaultValue

使用SpEL装配Bean

spring支持通过运行期执行的表达式将值装配到Bean的属性或构造器参数中。spring boot默认使用基于注解的配置,@Value注解可以在域,方法和方法/构造器参数中使用来指定一个默认值。

//import org.springframework.beans.factory.annotation.Value;
@Value("#{xxxx}")
private String attribute1;

目前在配置经常使用@Value(“${xxxx}”)
其中$表示获取配置参数

1. 文字表达式

@Value("#{24}")          //整型
@Value("#{'中国'}")       //String
//里面有个单引号,如果去掉会报错。String 类型的字面值可以使用单引号或双引号作为字符串的界定符。
@Value("my name is #{'david'}") //与非SpEL 表达式的值混用
@Value("#{120.4}")        //浮点型数字
@Value("#{true}")         //布尔值

2. 引用Bean属性和方法

@Value("#{beanId}")    //使用Bean ID 将一个Bean 装配到另一个Bean 的属性中
@Value("#{beanId.attribute}") //使用Bean 的引用来获取Bean 的属性
@Value("#{beanId.getSomenthing()}")   //调用引用Bean的方法

3. 类表达式

SpEL使用T() 运算符调用类作用域的方法和常量。

@Value("#{T(java.lang.Math).PI}") 
@Value("#{T(java.lang.Math).random()}") 
@Value("#{T(java.lang.Math).random() * 100.0 }")

4. 访问 properties

spel有两个可用的预定义变量 “systemProperties” 和 “systemEnvironment”。

  • systemProperties — java.util.Properties对象,从运行环境中检索属性。相当于java代码System.getProperty(arg0)
  • systemEnvironment — java.util.Properties对象,检索运行环境的具体属性。相当于java代码System.getenv(arg0)
@Value("#{ systemProperties['user.region'] }")
@Value("#{ systemEnvironment['profile'] }")

使用Spring的表达接口求值

下面的代码使用SpEL API来解析文本字符串表达式 Hello World.

ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'Hello World'");
String message = (String) exp.getValue(); // "hello world"

exp = parser.parseExpression("'Hello World'.concat('!')");
message = (String) exp.getValue();// "Hello World!"

模板数据绑定

#用户评分
SCORE=auditInfo.auditInfo==null?"":auditInfo.auditInfo["score"]
#渠道号
CHANNEL_NO=auditInfo.artificialAuditInfo.channelNo
#渠道名称
CHANNEL_NAME=auditInfo.artificialAuditInfo.channelName
Map<String, Expression> expressions = new HashMap<>();
propertis.keySet().forEach(
     k -> expressions.put(k, parser.parseExpression(propertis.getString(k))));
Map<String, Object> target = new HashMap<>();
expressions.keySet().forEach(key -> 
            target.put(key, expressions.get(key).getValue(origin))});

参考

http://itmyhome.com/spring/expressions.html

<think>我们正在查询关于`spring-boot-starter-data-rest`的历史漏洞信息。注意,该starter是Spring Boot中用于快速构建基于RESTful的Spring Data REST应用的模块。漏洞通常出现在其底层依赖(如Spring Framework、Spring Data REST)或传递依赖中。 根据历史漏洞记录,我们重点关注以下方面: 1. **Spring Data REST组件自身漏洞**:如暴露敏感数据、未授权访问等。 2. **Spring Framework核心漏洞**:因为Spring Data REST建立在Spring MVC之上。 3. **序列化库漏洞**:如Jackson(用于JSON处理)的安全问题。 通过CVE数据库和Spring官方安全公告,整理出以下相关漏洞: --- ### 1. **Spring Data REST 相关漏洞** - **CVE-2017-8046**(严重漏洞) - **描述**:Spring Data REST(在Spring Boot 1.5.9之前的版本中)存在远程代码执行(RDE)漏洞。攻击者通过恶意构造的PATCH请求,利用SpEL表达式注入执行任意代码[^1]。 - **影响版本**:Spring Data REST 2.6.9(Ingalls SR9)之前、3.0.0(Kay)之前的版本。 - **修复方案**:升级至Spring Boot 1.5.9+(对应Spring Data REST Ingalls SR9)或2.0.0+(对应Kay版本)[^1]。 - **CVE-2018-1259** - **描述**:Spring Data REST在响应中可能暴露未明确的HTTP资源(如不需要的API端点),导致信息泄露[^1]。 - **修复方案**:升级至Spring Data REST 3.0.8+(Spring Boot 2.0.4+)[^1]。 --- ### 2. **传递依赖漏洞(Spring Framework)** - **CVE-2022-22965**(Spring4Shell) - **描述**:Spring Framework 5.3.0-5.3.17、5.2.0-5.2.19存在远程代码执行漏洞,通过数据绑定的特性可绕过防御。Spring Data REST依赖Spring MVC,因此受影响[^2]。 - **修复方案**:升级Spring Framework至5.3.18+/5.2.20+(Spring Boot 2.6.6+/2.5.12+)[^2]。 - **CVE-2023-20883** - **描述**:Spring Framework 6.0.0-6.0.6、5.3.0-5.3.25存在拒绝服务风险,通过特定HTTP请求可导致服务不可用[^2]。 - **修复方案**:升级至Spring Framework 6.0.7+/5.3.26+(Spring Boot 3.0.5+/2.7.8+)[^2]。 --- ### 3. **Jackson序列化漏洞** - **CVE-2020-25649** - **描述**:Jackson-databind 2.9.10.6之前版本存在反序列化漏洞,攻击者可构造恶意JSON导致服务端远程代码执行。Spring Data REST默认使用Jackson处理JSON[^3]。 - **修复方案**:升级Jackson至2.9.10.6+(Spring Boot 2.3.5+)[^3]。 --- ### 漏洞修复实践 1. **升级Spring Boot版本**: 在`pom.xml`中指定安全版本: ```xml <!-- 针对Spring Boot 2.x用户 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.18</version> <!-- 包含所有关键修复 --> </parent> <!-- 或使用Spring Boot 3.x --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>3.2.0</version> </parent> ``` 2. **配置安全规则**: - 禁用不必要的HTTP方法(如PATCH): ```properties # application.properties spring.data.rest.detection-strategy=ANNOTATED ``` - 启用端点访问控制(集成Spring Security): ```java @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers(HttpMethod.PATCH, "/**").denyAll() // 禁用PATCH .anyRequest().authenticated(); } } ``` --- ### 监控与验证 - **漏洞扫描工具**: 使用`mvn dependency:tree`检查依赖树,并通过OWASP工具检测: ```bash mvn org.owasp:dependency-check-maven:check ``` - **官方公告渠道**: - [Spring Security 公告](https://spring.io/security) - [NVD漏洞数据库](https://nvd.nist.gov) --- ### 相关问题 1. 如何为Spring Data REST接口配置细粒度的访问控制? 2. Spring Boot 3.x中如何迁移Spring Data REST应用? 3. 如何禁用Spring Data REST的特定端点? 4. 使用Jackson时如何避免反序列化漏洞?</think>### `spring-boot-starter-data-rest` 历史漏洞及修复记录 该组件用于快速构建 RESTful 服务,历史漏洞主要源于底层依赖(如 Spring Framework、Jackson)或配置缺陷。以下是关键漏洞及修复方案: --- #### **1. 高风险漏洞记录** ##### **CVE-2017-8046**(远程代码执行)[^1] - **影响版本**:Spring Data REST ≤ 2.6.9 (Spring Boot 1.5.x) - **漏洞原理**: 恶意 PATCH 请求中的 SpEL 表达式注入,可导致任意代码执行。 示例攻击载荷: ```json [{ "op": "replace", "path": "T(java.lang.Runtime).getRuntime().exec('恶意命令')", "value": "" }] ``` - **修复方案**: 升级至 Spring Boot ≥ 1.5.10(Spring Data REST ≥ 2.6.10)或 ≥ 2.0.0。 ##### **CVE-2022-31690**(授权绕过)[^2] - **影响版本**:Spring Security 5.7.x/5.6.x(Spring Boot 2.7.x/2.6.x) - **漏洞原理**: 错误配置 `@PreAuthorize` 注解时,攻击者可绕过权限检查访问敏感 REST 端点。 - **修复方案**: 升级至 Spring Boot ≥ 2.7.3(Spring Security ≥ 5.7.4)。 ##### **Jackson 反序列化漏洞**(CVE-2020-25649)[^1] - **影响版本**:Jackson-databind ≤ 2.9.10.6 - **漏洞原理**: 恶意 JSON 载荷触发 `Gadget` 链,导致远程代码执行。 - **修复方案**: 升级至 Spring Boot ≥ 2.3.5(Jackson ≥ 2.9.10.6)。 --- #### **2. 中低风险漏洞** ##### **信息泄露风险**(无 CVE) - **触发场景**: 未禁用 `HAL Explorer` 时,暴露 `/explorer` 端点泄露 API 元数据[^3]。 - **修复方案**: ```properties # application.properties spring.data.rest.detection-strategy=ANNOTATED # 仅暴露显式注解的端点 spring.hateoas.use-hal-explorer=false ``` ##### **CSRF 防护缺失** - **风险**: 默认未启用 CSRF 防护,可能导致非幂等操作(如 POST/PUT)被伪造。 - **修复方案**: ```java @Configuration public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); } } ``` --- #### **3. 漏洞修复实践指南** 1. **版本升级**(强制): ```xml <!-- Spring Boot 2.7.x (推荐) --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.7.18</version> </parent> ``` 2. **安全配置加固**: - 禁用敏感端点: ```properties management.endpoints.web.exposure.include=health,info ``` - 启用内容协商安全: ```java @Bean public RepositoryRestConfigurer repositoryRestConfigurer() { return new RepositoryRestConfigurer() { @Override public void configureRepositoryRestConfiguration(RepositoryRestConfiguration config) { config.disableDefaultExposure(); // 禁用自动暴露所有仓库 } }; } ``` 3. **漏洞扫描**: ```bash mvn org.owasp:dependency-check-maven:check ``` --- #### **监控与参考** - **官方公告渠道**: [Spring Security Advisories](https://spring.io/security) | [NVD 漏洞数据库](https://nvd.nist.gov) - **关键日志监控**: 检查非常规 HTTP 方法(如 PATCH)的异常请求。 --- ### 相关问题 1. 如何为 Spring Data REST 接口配置细粒度的权限控制? 2. 使用 Spring Boot 3.x 时如何迁移旧版 Data REST 应用? 3. 如何防止 REST 接口的 JSON 参数注入攻击? 4. Spring Data REST 中如何自定义 HATEOAS 链接的安全策略?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值