# 6.2 Deserialization

{% embed url="<https://portswigger.net/web-security/deserialization#what-is-serialization>" %}

## **Serialization vs Deserialization**

**Serialization** is the process of converting an object into a stream of data, while deserialization is the reverse process of converting that stream back into an object. Serialization

* Saves and transmits the state of an object&#x20;
* Can be used to store objects in files, databases, or memory&#x20;
* Can be used to exchange data between applications, over networks, and more&#x20;
* Can be used to identify changes in data over time&#x20;

**Deserialization**

* Reconstructs the original object from serialized data&#x20;
* Makes data easier to read and modify as a native structure in a programming language&#x20;
* Can be used to recreate objects after they have been serialized for transmission&#x20;

Security considerations

Serialized objects can be vulnerable to security risks if not handled carefully, attackers can manipulate serialized objects to inject malicious code or objects into the application during deserialization&#x20;

## **Java Insecure Deserialization**

Insecure deserialization in Java occurs when an application deserializes untrusted data without proper validation, allowing an attacker to manipulate the serialized object and achieve remote code execution (RCE), privilege escalation, or other malicious activities.

#### **Key Concepts**

**Gadgets and Gadget Libraries**

* **Gadget**: A property or method inside an object that can be leveraged for exploitation when deserialized.
* **Gadget Library**: Some Java libraries contain pre-existing gadgets that attackers can use to construct an exploit. Examples include:
  * **Apache CommonsCollections** (versions 1-6)
  * **Spring Framework**
  * **JDK classes (e.g., `java.rmi.server.UnicastRemoteObject`)**
  * **Jackson, Fastjson, and XStream**

Even though these libraries are not inherently vulnerable, if an application deserializes untrusted input while these libraries are present in the classpath, an attacker can exploit them to create a **gadget chain**, leading to successful exploitation.

**How Java Deserialization Works**

Serialization in Java is the process of converting an object into a byte stream that can be stored or transmitted.

* `ObjectOutputStream.writeObject(obj)`: Serializes an object.
* `ObjectInputStream.readObject()`: Deserializes the byte stream into an object.

If the input passed to `readObject()` is attacker-controlled, it can be exploited to execute arbitrary code.

### **Exploitation and Attack Vectors**

**Exploiting Java Insecure Deserialization**

An attacker can exploit insecure deserialization by sending a crafted malicious serialized object to a vulnerable application. Common attack vectors include:

* **Cookies** → Sending serialized payloads via HTTP cookies.
* **Web Requests** → Injecting payloads through POST/GET parameters.
* **Files** → Uploading serialized payloads as files.
* **Inter-Process Communication (IPC)** → Sending malicious objects through network sockets, RMI, or JNDI.

**Ysoserial Tool**

[ysoserial](https://github.com/frohoff/ysoserial) is a popular tool for generating exploit payloads using known gadget libraries.\
Example command:

```bash
bashCopiaModificajava -jar ysoserial.jar CommonsCollections1 "whoami" > payload.ser
```

* This generates a payload that executes `whoami` upon deserialization.
* The payload is then sent to the vulnerable application, which executes the system command when deserialized.

#### **Exploit Example**

If an application deserializes objects from an untrusted source, an attacker can craft a malicious object like:

```java
javaCopiaModificaimport java.io.*;

public class MaliciousPayload implements Serializable {
    private void readObject(ObjectInputStream in) throws Exception {
        Runtime.getRuntime().exec("calc.exe");  // Arbitrary code execution
    }
}
```

When deserialized, this object spawns a calculator on Windows or executes a system command.

### **Mitigation Strategies**

* **Avoid deserialization of untrusted data.**
* **Use `ObjectInputFilter` (Java 9+)** to allowlist safe classes:

  ```java
  javaCopiaModificaObjectInputFilter filter = info -> info.serialClass().getName().startsWith("trusted.package") 
      ? ObjectInputFilter.Status.ALLOWED 
      : ObjectInputFilter.Status.REJECTED;
  ```
* **Use safer data formats like JSON or protobuf** instead of Java serialization.
* **Keep dependencies updated** to avoid known gadget chains.
* **Restrict available classes** in the classpath to prevent gadget chains.

## **PHP Insecure Deserialization**

PHP serialization allows objects, arrays, and values to be converted into a storable string format using `serialize()`. However, when `unserialize()` is used on untrusted data, it can lead to arbitrary code execution, data manipulation, or unauthorized object injection.

#### **How PHP Serialization Works**

```php
phpCopiaModificaclass User {
    public $username;
    public function __construct($name) {
        $this->username = $name;
    }
}

$user = new User("admin");
$serialized = serialize($user);
echo $serialized;
```

**Output:**

```
cssCopiaModificaO:4:"User":1:{s:8:"username";s:5:"admin";}
```

This serialized string can be stored in a database, session, or sent over a network.

### **Magic Methods & Exploitation**

In PHP, special **magic methods** can be abused during deserialization:

* **`__wakeup()`** → Executes code when an object is unserialized.
* **`__sleep()`** → Executes code before serialization.
* **`__destruct()`** → Executes when an object is destroyed.
* **`__toString()`** → Can be used to trigger code execution via string conversion.

If a PHP application unserializes untrusted input, an attacker can inject a malicious object that triggers one of these methods.

#### **Example of PHP Object Injection Attack**

A vulnerable PHP application:

```php
phpCopiaModificaif(isset($_GET['data'])) {
    $obj = unserialize($_GET['data']);
}
```

An attacker can craft a malicious payload:

```php
phpCopiaModificaclass Malicious {
    public function __destruct() {
        system("whoami");
    }
}

$payload = serialize(new Malicious());
echo urlencode($payload); 
```

Example payload:

```
cssCopiaModificaO:9:"Malicious":0:{}
```

Sending this payload via `?data=O:9:"Malicious":0:{}` executes `whoami` on the server when the object is destroyed.

### **Mitigation Strategies**

* **Never use `unserialize()` on untrusted input.**
* **Use JSON instead of serialization.**

  ```php
  phpCopiaModifica$json = json_encode($object);
  $object = json_decode($json);
  ```
* **Implement allowlisting** to only accept expected classes:

  ```php
  phpCopiaModificaunserialize($data, ["allowed_classes" => ["SafeClass"]]);
  ```
* **Use Web Application Firewalls (WAFs)** to detect and block serialized attack payloads.
