> For the complete documentation index, see [llms.txt](https://greenhat.gitbook.io/interview-bank/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://greenhat.gitbook.io/interview-bank/web/code-review.md).

# Code Review

So here is a code that uses a Flask web server with routes to set and get values stored in a Redis database. The values retrieved from Redis are unserialized using Python `pickle` module.

**Spot the vulnerability in this code snippet!**

<figure><img src="https://4157702631-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FslGw3ZF0EFGfkPZZ1EMu%2Fuploads%2FyaiiCr0fYj811KMD1fQx%2Fcode_challenge.png?alt=media&amp;token=a3c51f5d-284f-4191-8c11-af1898b77aa1" alt=""><figcaption><p>Code Review Challenge</p></figcaption></figure>

**Are you able to find the vulnerability?**

The vulnerability code: `data = pickle.loads(value)`

`Pickle` is a powerful module for serializing and deserializing objects in Python. **However**, it is infamously insecure when used with untrusted data! The vulnerability lies in `pickle.loads()` which can execute arbitrary code contained within the data it is attempting to unserialize.

This is known as **Insecure Deserialization** where user-controlled data is deserialized by a website. **Deserialization** is the process of restoring this byte stream to a fully functional replica of the original object.

<figure><img src="https://4157702631-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FslGw3ZF0EFGfkPZZ1EMu%2Fuploads%2FhtGcjkjNK3WtGe6RMkip%2FScreenshot%202024-03-26%20at%201.35.20%E2%80%AFPM.png?alt=media&amp;token=1b1d607a-0a4d-4d24-be86-025eb4a1776a" alt=""><figcaption><p>Process of Serialization and Deserialization. Credits: Portswigger</p></figcaption></figure>

If an attacker can store malicious data in the Redis cache, he/she could craft a payload that leads to remote code execution.

**So, how can we fix this vulnerability?**

For starters, we should not use `pickle` to unserialize data coming from an untrusted or controllable source. We can use a safer format like JSON which does not allow code execution

<figure><img src="https://4157702631-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FslGw3ZF0EFGfkPZZ1EMu%2Fuploads%2FP4FWCpcpnRKYvUCxcjdV%2Fcode_solution.png?alt=media&amp;token=a772562a-ead7-463a-92b7-c5b84ba99678" alt=""><figcaption><p>A possible code solution</p></figcaption></figure>

## Author

* [Isaac](https://github.com/frostsg)
