hacktricks/network-services-pentesting/pentesting-imap.md

9.8 KiB

143,993 - Pentesting IMAP

Aprende hacking en AWS de cero a héroe con htARTE (Experto en Red Team de AWS de HackTricks)!

Otras formas de apoyar a HackTricks:

Encuentra vulnerabilidades que importan más para que puedas solucionarlas más rápido. Intruder rastrea tu superficie de ataque, ejecuta escaneos proactivos de amenazas, encuentra problemas en toda tu pila tecnológica, desde APIs hasta aplicaciones web y sistemas en la nube. Pruébalo gratis hoy.

{% embed url="https://www.intruder.io/?utm_campaign=hacktricks&utm_source=referral" %}


Protocolo de Acceso a Mensajes de Internet

El Protocolo de Acceso a Mensajes de Internet (IMAP) está diseñado con el propósito de permitir a los usuarios acceder a sus mensajes de correo electrónico desde cualquier ubicación, principalmente a través de una conexión a Internet. En esencia, los correos electrónicos se mantienen en un servidor en lugar de ser descargados y almacenados en el dispositivo personal de un individuo. Esto significa que cuando se accede o lee un correo electrónico, se hace directamente desde el servidor. Esta capacidad permite la conveniencia de revisar correos electrónicos desde múltiples dispositivos, asegurando que no se pierda ningún mensaje independientemente del dispositivo utilizado.

Por defecto, el protocolo IMAP funciona en dos puertos:

  • Puerto 143 - este es el puerto IMAP no encriptado por defecto
  • Puerto 993 - este es el puerto que debes usar si deseas conectarte utilizando IMAP de forma segura
PORT    STATE SERVICE REASON
143/tcp open  imap    syn-ack

Obtención de banner

nc -nv <IP> 143
openssl s_client -connect <IP>:993 -quiet

NTLM Auth - Divulgación de información

Si el servidor admite la autenticación NTLM (Windows) puedes obtener información sensible (versiones):

root@kali: telnet example.com 143
* OK The Microsoft Exchange IMAP4 service is ready.
>> a1 AUTHENTICATE NTLM
+
>> TlRMTVNTUAABAAAAB4IIAAAAAAAAAAAAAAAAAAAAAAA=
+ TlRMTVNTUAACAAAACgAKADgAAAAFgooCBqqVKFrKPCMAAAAAAAAAAEgASABCAAAABgOAJQAAAA9JAEkAUwAwADEAAgAKAEkASQBTADAAMQABAAoASQBJAFMAMAAxAAQACgBJAEkAUwAwADEAAwAKAEkASQBTADAAMQAHAAgAHwMI0VPy1QEAAAAA

O automatizar esto con el plugin nmap imap-ntlm-info.nse

Fuerza bruta de IMAP

Sintaxis

Ejemplos de comandos IMAP de aquí:

Login
A1 LOGIN username password
Values can be quoted to enclose spaces and special characters. A " must then be escape with a \
A1 LOGIN "username" "password"

List Folders/Mailboxes
A1 LIST "" *
A1 LIST INBOX *
A1 LIST "Archive" *

Create new Folder/Mailbox
A1 CREATE INBOX.Archive.2012
A1 CREATE "To Read"

Delete Folder/Mailbox
A1 DELETE INBOX.Archive.2012
A1 DELETE "To Read"

Rename Folder/Mailbox
A1 RENAME "INBOX.One" "INBOX.Two"

List Subscribed Mailboxes
A1 LSUB "" *

Status of Mailbox (There are more flags than the ones listed)
A1 STATUS INBOX (MESSAGES UNSEEN RECENT)

Select a mailbox
A1 SELECT INBOX

List messages
A1 FETCH 1:* (FLAGS)
A1 UID FETCH 1:* (FLAGS)

Retrieve Message Content
A1 FETCH 2 body[text]
A1 FETCH 2 all
A1 UID FETCH 102 (UID RFC822.SIZE BODY.PEEK[])

Close Mailbox
A1 CLOSE

Logout
A1 LOGOUT

Evolución

apt install evolution

CURL

La navegación básica es posible con CURL, pero la documentación es escasa en detalles, por lo que se recomienda revisar la fuente para obtener detalles precisos.

  1. Listar buzones de correo (comando imap LIST "" "*")
curl -k 'imaps://1.2.3.4/' --user user:pass
  1. Listando mensajes en un buzón de correo (comando IMAP SELECT INBOX y luego SEARCH ALL)
curl -k 'imaps://1.2.3.4/INBOX?ALL' --user user:pass```

The result of this search is a list of message indicies.

Its also possible to provide more complex search terms. e.g. searching for drafts with password in mail body:

```plaintext
curl -k 'imaps://1.2.3.4/Drafts?TEXT contraseña' --user usuario:contraseña

A nice overview of the search terms possible is located [here](https://www.atmail.com/blog/imap-commands/).

3.  Downloading a message (imap command `SELECT Drafts` and then `FETCH 1 BODY[]`)

```bash
```plaintext
curl -k 'imaps://1.2.3.4/Drafts;MAILINDEX=1' --user user:pass

curl -k 'imaps://1.2.3.4/Borradores;MAILINDEX=1' --user usuario:contraseña

The mail index will be the same index returned from the search operation.

It is also possible to use `UID` (unique id) to access messages, however it is less conveniant as the search command needs to be manually formatted. E.g.

```bash
```html
curl -k 'imaps://1.2.3.4/INBOX' -X 'UID SEARCH ALL' --user user:pass
curl -k 'imaps://1.2.3.4/INBOX;UID=1' --user user:pass

Also, possible to download just parts of a message, e.g. subject and sender of first 5 messages (the `-v` is required to see the subject and sender):

```bash
```plaintext
$ curl -k 'imaps://1.2.3.4/INBOX' -X 'FETCH 1:5 BODY[HEADER.FIELDS (SUBJECT FROM)]' --user user:pass -v 2>&1 | grep '^<'

Although, its probably cleaner to just write a little for loop:

```bash
```bash
for m in {1..5}; do
echo $m
curl "imap://1.2.3.4/INBOX;MAILINDEX=$m;SECTION=HEADER.FIELDS%20(SUBJECT%20FROM)" --user user:pass
done

## Shodan

* `port:143 CAPABILITY`
* `port:993 CAPABILITY`

## HackTricks Automatic Commands

Protocol_Name: IMAP    #Protocol Abbreviation if there is one.
Port_Number:  143,993     #Comma separated if there is more than one.
Protocol_Description: Internet Message Access Protocol         #Protocol Abbreviation Spelled out

Entry_1:
Name: Notas
Description: Notas para WHOIS
Note: |
El Protocolo de Acceso a Mensajes de Internet (IMAP) está diseñado con el propósito de permitir a los usuarios acceder a sus mensajes de correo electrónico desde cualquier ubicación, principalmente a través de una conexión a Internet. En esencia, los correos electrónicos se mantienen en un servidor en lugar de ser descargados y almacenados en el dispositivo personal de un individuo. Esto significa que cuando se accede o lee un correo electrónico, se hace directamente desde el servidor. Esta capacidad permite la conveniencia de revisar correos electrónicos desde múltiples dispositivos, asegurando que no se pierda ningún mensaje independientemente del dispositivo utilizado.

https://book.hacktricks.xyz/pentesting/pentesting-imap

Entry_2:
Name: Banner Grab
Description: Banner Grab 143
Command: nc -nv {IP} 143

Entry_3:
Name: Secure Banner Grab
Description: Banner Grab 993
Command: openssl s_client -connect {IP}:993 -quiet

Entry_4:
Name: enumeración de mfs sin consolas
Description: Enumeración IMAP sin la necesidad de ejecutar msfconsole
Note: obtenido de https://github.com/carlospolop/legion
Command: msfconsole -q -x 'use auxiliary/scanner/imap/imap_version; set RHOSTS {IP}; set RPORT 143; run; exit'

<figure><img src="/.gitbook/assets/image (675).png" alt=""><figcaption></figcaption></figure>

Find vulnerabilities that matter most so you can fix them faster. Intruder tracks your attack surface, runs proactive threat scans, finds issues across your whole tech stack, from APIs to web apps and cloud systems. [**Try it for free**](https://www.intruder.io/?utm\_source=referral\&utm\_campaign=hacktricks) today.

{% embed url="https://www.intruder.io/?utm_campaign=hacktricks&utm_source=referral" %}


<details>

<summary><strong>Learn AWS hacking from zero to hero with</strong> <a href="https://training.hacktricks.xyz/courses/arte"><strong>htARTE (HackTricks AWS Red Team Expert)</strong></a><strong>!</strong></summary>

Other ways to support HackTricks:

* If you want to see your **company advertised in HackTricks** or **download HackTricks in PDF** Check the [**SUBSCRIPTION PLANS**](https://github.com/sponsors/carlospolop)!
* Get the [**official PEASS & HackTricks swag**](https://peass.creator-spring.com)
* Discover [**The PEASS Family**](https://opensea.io/collection/the-peass-family), our collection of exclusive [**NFTs**](https://opensea.io/collection/the-peass-family)
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@carlospolopm**](https://twitter.com/hacktricks_live)**.**
* **Share your 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>