漏洞成因:field.setAccessible(true)
AccessibleObject允许程序员绕过由java说明符提供的access control检查。并反过来更改私有字段或调用私有方法、行为。
这里我只在网上查到了使用spring框架下的解决方案:ReflectionUtils.makeAccessible(field);
package com.example.springboot.entities;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
private Integer id;
private String lastName;
private String email;
//1 male, 0 female
private Integer gender;
private Department department;
private Date birth;
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", gender=" + gender +
", department=" + department +
", birth=" + birth +
'}';
}
}
如下代码是测试代码:
Object obj = Employee.class.newInstance();
Class<Employee> clazz = Employee.class;
//通过属性名获取属性
Field field = clazz.getDeclaredField("lastName");
System.out.println(1+"-----"+field.getName());
//这里如果不设置true,默认为false,只有在实体类employee
//的属性修饰符为public时才可以访问的到,否者访问不到属性的值,也无法为其设置具体的值
System.out.println(2+"-----"+field.getType());
System.out.println(3+"-----"+field.isAccessible());
//field.setAccessible(true);
//通过这里ield.setAccessible(true);的设置为访问权限为true即可访问,但是此处的方法会被fortify扫描出Access Specifier Manipulation漏洞,
// 如果你用的是spring可以通过另一个反射工具类去设置,这样做更安全,
ReflectionUtils.makeAccessible(field);
System.out.println(4+"-----"+field.isAccessible());
if(field.getType() == String.class){
field.set(obj,"Chow");
}
System.out.println(5+"-----"+obj.toString());
执行结果:
1-----lastName
2-----class java.lang.String
3-----false
4-----true
5-----Employee{id=null, lastName='Chow', email='null', gender=null, department=null, birth=null}
更多推荐
Access Specifier Manipulation解决方案(Spring)
发布评论