java代码审计之fastjson反序列化漏洞

fastjson反序列化漏洞分析

Fastjson 是一个 Java 库,可以将 Java 对象转换为 JSON 格式,当然它也可以将 JSON 字符串转换为 Java 对象。Fastjson 可以操作任何 Java 对象,即使是一些预先存在的没有源码的对象。该产品主要提供了两个接口,JSON.toJSONString和JSON.parseObject/JSON.parse分别实现序列化和反序列化。

1. Fastjson使用

  1. 新建一个maven项目,引入对应的依赖包
		<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.24</version>
        </dependency>
  1. 新建一个类
package org.example;

import java.io.Serializable;

public class Person{
   
   
    private String name;
    private int age;
    private boolean sex;

    public Person() {
   
   
        System.out.println("执行构造函数方法");
    }

    public String getName() {
   
   
        System.out.println("执行获取到name方法");
        return name;
    }

    public void setName(String name) {
   
   
        System.out.println("执行到setage方法");
        this.name = name;
    }

    public int getAge() {
   
   
        System.out.println("执行获取到age方法");
        return age;
    }

    public void setAge(int age) {
   
   
        System.out.println("执行setage方法");
        this.age = age;
    }

    public boolean isSex() {
   
   
        return sex;
    }

    public void setSex(boolean sex) {
   
   
        System.out.println("执行到setSex方法");
        this.sex = sex;
    }
}
  1. json序列化
package org.example;

import com.alibaba.fastjson.JSON;

public class Main {
   
   
    public static void main(String[] args) {
   
   
        Person person = new Person();
        person.setName("小明");
        person.setAge(18);
        person.setSex(false);
        String jsonString = JSON.toJSONString(person);
        System.out.println(jsonString);
    }
}
//输出:{"age":18,"name":"小明","sex":false}
  • 不使用 SerializerFeature.WriteClassName:生成的 JSON 数据不包含类的全限定名。
  • 使用 SerializerFeature.WriteClassName:生成的 JSON 数据包含类的全限定名(以 @type 字段表示)。
package org.example;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;

public class Main {
   
   
    public static void main(String[] args) {
   
   
        Person person = new Person();
        person.setName("小明");
        person.setAge(18);
        person.setSex(false);
        String jsonString = JSON.toJSONString(person, SerializerFeature.WriteClassName);
        System.out.println(jsonString);
    }
}
//输出:{"@type":"org.example.Person","age":18,"name":"小明","sex":false}
  1. 反序列化

在fastjson中,使用JSON.parseObject进行反序列化,及将JSON字符串转化为对象

使用:

package org
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值