Insecure Deserialization

Insecure Deserialization in Java

Vulnerability: Insecure Deserialization

Vulnerable Code:

javaCopy codeObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.ser"));
Object obj = ois.readObject();

Reason for vulnerability: Deserializing untrusted data can lead to remote code execution or other security issues.

Fixed Code:

javaCopy codeObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.ser")) {
    @Override
    protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
        if (!allowedClasses.contains(desc.getName())) {
            throw new InvalidClassException("Unauthorized deserialization attempt", desc.getName());
        }
        return super.resolveClass(desc);
    }
};
Object obj = ois.readObject();

Reason for fix: Restricting the classes that can be deserialized prevents malicious code execution.


Insecure Deserialization in Python

Vulnerability: Insecure Deserialization

Vulnerable Code:

Reason for vulnerability: Deserializing untrusted data with pickle can lead to arbitrary code execution.

Fixed Code:

Reason for fix: Using json for deserialization instead of pickle prevents arbitrary code execution since json only handles basic data types.


Example 2: Python

Vulnerable Code:

Reason for vulnerability: Deserializing untrusted data, leading to insecure deserialization.

Fixed Code:

Reason for fix: Restrict the classes that can be deserialized.


Java Example

Vulnerable Code:

Reason for Vulnerability:

This code blindly deserializes user-provided data, which can lead to remote code execution if the User class or any of its members are not designed securely.

Fixed Code:

Reason for Fix:

The fixed code uses Jackson for JSON deserialization instead of Java's built-in serialization. This approach is generally safer and allows for fine-grained control over deserialization behavior.

Java Example

Vulnerable Code:

Reason for Vulnerability:

This code uses Apache Commons Collections' TransformedMap with InvokerTransformer, which can be exploited in deserialization attacks to execute arbitrary commands.

Fixed Code:

Reason for Fix:

The fixed code removes the use of potentially dangerous Apache Commons Collections classes and implements a safer way to execute commands with proper validation.

Python Example

Vulnerable Code:

Reason for Vulnerability:

This code uses Python's pickle module to deserialize data, which can lead to arbitrary code execution if an attacker controls the serialized data.

Fixed Code:

Reason for Fix:

The fixed code uses JSON for deserialization instead of pickle. JSON is a data-only format and doesn't allow for code execution, making it a safer choice for deserializing untrusted data.

Last updated