# Code Smell 215 - Deserializing Object Vulnerability

> TL;DR: Don't allow remote code execution

# Problems

- Security

# Solutions

1. Validate and sanitize input

2. Avoid executing code. Input only data

3. Apply sandboxing or isolation

# Context

Deserializing objects from an untrusted source is indeed a security-sensitive operation. 

Suppose you have a web application that accepts serialized objects as input from user-submitted data, such as in an API endpoint or a file upload feature. 

The application deserializes these objects to reconstruct them into usable objects within the system.

If an attacker submits maliciously crafted serialized data to exploit vulnerabilities in the deserialization process. 

They might manipulate the serialized data to execute arbitrary code, escalate privileges, or perform unauthorized actions within the application or the underlying system. 

This type of attack is commonly known as "deserialization attacks" or "serialization vulnerabilities."

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/4b1c59db5f77bc9d29db5115c6516b46)
```python
import pickle  # Python's serialization module

def process_serialized_data(serialized_data):
    try:
        obj = pickle.loads(serialized_data)  
        # Deserialize the object
        # Process the deserialized object
        # ...

# User-submitted serialized data
user_data = b"\x80\x04\x95\x13\x00\x00\x00\x00\x00\x00\x00\x8c\x08os\nsystem\n\x8c\x06uptime\n\x86\x94."
# This code executes os.system("uptime") 

process_serialized_data(user_data)

```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/d6f86ea9959eb68e0604f6249afa8709)
```python
import json

def process_serialized_data(serialized_data):
    try:
        obj = json.loads(serialized_data)  
        # Deserialize the JSON object
        # Does not execute code
        # ...

user_data = '{"key": "value"}'

process_serialized_data(user_data)

```

# Detection

[X] Semi-Automatic 

Several linters warn about deserialization points.

# Tags

- Security

# Conclusion

Metaprogramming opens doors to abusers.

# Relations

%[https://maximilianocontieri.com/code-smell-189-not-sanitized-input]

# More Info

%[https://maximilianocontieri.com/laziness-i-meta-programming]

[Sonar Source](https://rules.sonarsource.com/php/RSPEC-4508)

# Disclaimer

Code Smells are my [opinion](https://maximilianocontieri.com/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned).

# Credits

Photo by [Towfiqu barbhuiya](https://unsplash.com/@towfiqu999999) on [Unsplash](https://unsplash.com/photos/em5w9_xj3uU)
    
* * *

> Whenever possible, steal code.

_Tom Duff_
 
%[https://maximilianocontieri.com/software-engineering-great-quotes]

* * *

This article is part of the CodeSmell Series.

%[https://maximilianocontieri.com/how-to-find-the-stinky-parts-of-your-code]
