Our Blog

Mail in the Middle – A tool to automate spear phishing campaigns

Reading time ~15 min

Context

In the chilly month of December 2023, my colleagues Jason (@BreakerOfSigns), Szymon (@TH3_GOAT_FARM3R), and myself (@felmoltor) were on a red team. This one was tough, but we had fun. We had to be a bit more creative than I am used to and two interesting things were done that are worth sharing: 

  1. Szymon and Jason physically broke into the client’s facilities. At a branch office, they left an implant using Rogan’s “Slimjim” device and it proved to be a solid and production ready project. Try it out and let us know how it goes. 
  2. I developed a tool that we named Mail-in-the-Middle (Maitm for short). You can find it in our Github repository here: https://github.com/sensepost/mail-in-the-middle

I cannot speak in first person about the physical breakin beyond praising the excellent social engineering skills of both of my colleagues, but I can talk about Mail-in-the-Middle. 

First, let me explain what is Mail-in-the-Middle and how we approached it. 

What is Maitm? 

The idea is simple; take advantage of the typos that people make when they enter email addresses. If we positioned ourselves in between the sender of an email (be it a person or a system) and the legitimate recipient, we may be able to capture plenty of information about the business, including personally identifiable information, email verification processes, etc. This scenario is effectively a Person-in-the-Middle (PiTM), but for email communications.

Some examples of how being positioned in the middle of email communications could be useful include: 

  • A vendor or third party would like to send out an invoice to the finance department of the target but they typo’d the domain. An attacker who owns the typo’d domain would receive these mails disclosing whatever information was contained within. This provides the attacker with a good pretext for a social engineering attack.
  • Let’s say an administrator sets up a service to monitor performance of their servers, and proceeded to configure notifications / alarms to be sent to an email address where there was a typo within the domain. An attacker would receive those notifications which might disclose useful information about their internal infrastructure (for instance, software used, hostnames, IP addresses, etc.).
  • Or perhaps an employee, from HR, registered an account on a third party service used to manage candidates applying for a job. But this was done using an email address where the domain was typo’d. Should the third party service send an email to that account, it would land in the hands of the attackers. An attacker could potentially perform an account takeover by requesting a password reset.
  • What if an attacker finds that they were receiving OTP’s for an account registration. In this scenario, they could take advantage of this by actively forwarding on these emails on to the corrected target. This would give the attacker the ability to hijack the account later on should the victim user complete the registration process using the forwarded OTP.
  • A more active approach could be taken by tainting all the emails coming in and forwarding them on to the legitimate recipient. Links can be modified to point to a phishing page, UNC paths can also be injected as images on the email or mail headers (see CVE-2023-35636) to exfiltrate NetNTLM hashes, or attachments can be injected to deliver your malicious payload. 

In summary, doing this would be similar to receiving an Amazon package wrongly delivered to you, swapping the Rolex inside the package with the Casio, repackaging it, and leaving the parcel on your neighbours doorstep (hoping they don’t notice).  

The original idea of doing this mail interception manually was not ours (Szymon, Jason, or Felipe), but it was rather passed down from previous generations of SensePost to us (thank you Willem), and probably has been by many others out there. What we are presenting here is an improvement on the process and the automation of it.  

Back to the point, to achieve a Mail-in-the-Middle position, there are three basic steps: 

  1. Register a good number of typos of the target’s domain
  2. Configure the DNS with the MX record pointing to an attacker-controlled mail server
  3. Configure a catch-all email address to read all these “Stranded Emails”.

I like to call these “Stranded Emails”, just because I am a fan of Death Stranding and I am not a native English speaker, so I just make up words to sound like an intellectual. 

The architecture of this setup is illustrated in the diagram below:

The green envelope is the original email sent to the wrong domain (mircosoft.com). The handsome hacker would catch that email, extract any sensitive information, if any or modify it and forward on.  

All this sounds a bit cumbersome to do manually. Hence, this is where the tool Mail-in-the-Middle can help you, which automates this process.  

Let’s dig into how to set up the environment and use the tool. 

Infrastructure Preparation

As I’ve mentioned before, registering domains that are typo’s of the target’s domain (mostly domains that you would type if you fat-fingered an email address) is key. There are tools, such as dnstwist that can help you with discovering good domains to look at. For example, if the target was mydomain.com, you would register domains like mydoain.com,  mydomian.com or mdyomian.com. 

Once we have registered a good number of these domains, we set the MX DNS records of all these domains to point to our mailbox. Following on our earlier example, querying the MX records of the domain using dig would return something like the following (a good tip to check for this if you are on the blue team and suspect something weird is going on!): 

$ dig mydoain.com mx +short
10 mail.attacker.com. 

Now, configure a catch-all rule on the server to forward any email coming to a non-existent recipient to another trap email, for example to blackhole@attacker.com

With a catch-all configured, if I go to our servers webmail, I often see plenty of rubbish and spam clogging my inbox. This is a good sign, the catch-all rule is working. You could expect like 5% of these emails to be useful (aka: not spam). 

Meeting invite including a passcode and details about the agenda
Invoice for SAP sent to the wrong recipient

Automation

The objective of Maitm is to reduce my workload by automating the delivery of the spear-phishing style campaigns at scale. 

The main ingredients of my tool were a handful of imap-tools, a pinch of discord-webhook and a spoonful of BeautifulSoup4. We mix all this magic in a hot pot and now the attacker can rely on a script to do automatic email modification and forwarding to intended users, all while they are relaxing: 

Simply put, the script is an infinite loop with the following logic: 

Depending on the configuration you have set, the flow should be similar to the following: 

  1. Login to a mailbox via SMTP and IMAP (defined in auth.yml).
  2. List emails, new or all (defined by the CLI argument -n).
  3. Filter emails you want (defined in filter.yml) 
  4. Inject a tracking URL (if defined in injections.yml) 
  5. Inject a UNC path as image to exfiltrate NetNTLM hashes (if defined injections.yml)
  6. Replace/Inject attached files (if defined in injections.yml)
  7. Replace legitimate links with attacker-controlled links (if defined in injections.yml)
  8. Fix typos on the destination(s) email address(es) (defined in typos.yml) 
  9. Forward the email to the corrected email address (defined by the CLI argument -f).
    • The source of the email can be defined in misc.yml, e.g. security@mircosoft.com.
    • The destination can be set to a fixed address in case you want to test before going to production in misc.yml.
  10. Notify the Discord/Teams channel (defined in notifications.yml)
  11. Repeat the process again with new emails.

Now that you know the general flow and functionality of Maitm, you just need it to run.

Running Maitm

The usage of the script requires you to tweak the yaml formatted configuration file (config/config.yml). This file contains the name of other files with a subset of configurations, such as “auth.yml”, “filter.yml”, “typos.yml”, “injections.yml”, etc. By editing these configuration files you would be able to adapt the tool to your needs as described before. For the full details of how to configure and run the tool, refer to the github project README

Once configured, there are two ways you can run the tool, either by creating the virtual environment with pipenv or running it via Docker. Using it via Docker would be as easy as executing: 

docker build -t maitm .       # Build 
docker run --rm -ti maitm -h # To get help 
docker run --rm -ti maitm -c config/config.yml -f –n

Results

When you run Maitm on your server, you should see something like this in the console: 

Running Maitm

When an email is forwarded and you have configured Discord or Teams, you will receive a message like this when some activity happens: 

Discord notifications of forwarded emails with a summary of the result

I also created another script to report a hit from a tracking pixel via Discord. For it to work you need to install the Apache mod forensics module and modify the path of your log file (variable LOG_FILE) where the script watching. You also need to create an .env file containing the discord webhook URL in the DISCORD_WEBHOOK variable. 

Leave this script running in background and when a recipient receives a email (and if the user allowed remote content to be displayed in the email client) you should get a hit on your tracking pixel and will be notified like this: 

Discord notification of a tracking pixel injected in a forwarded email being rendered in the target’s mail client.

If you are lucky, after every one of these notifications, you will receive a NetNTLM hash on your server and, hoping the recipient has executed your attachment (assuming you’ve configured that), a new agent connection to your C2 infrastructure.

Target’s point of view when opening our mail with the UNC path injected 
NetNTLM hashes exfiltrated via UNC path injected in the tainted email

Conclusions 

When we think about the security implications of typo’d domains, we immediately think of phishing sent from that domain to our business, but we forget about the implications of the emails sent to that typo’d domain.  

Setting up infrastructure that catches “stranded emails” as an attacker is a powerful attack piivimite. The emails sent to these domains often contain a trove of sensitive data, which could include Personally Identifiable Information (PII), business infrastructure information, business meeting invites, bills, etc. Attackers can take advantage of this to great effect by performing many actions such as completing employee enrolments or password resets on specific business-owned platforms, effectively leading to account takeovers. In my last Red Team we had good success with this, and almost surely you can put it in practice in yours as well.

Having a tool deal with “stranded email” monitoring, link and attachment replacement and more takes a significant workload off your shoulders, leaving you with more time to focus on other aspects of your testing. That, and sometimes when email delivery is fast (right after clicking that password reset button), it’s less suspicious :)

Recommendations 

Mitigating these kinds of attacks, from a business perspective, requires a multi-faceted approach. It’s not always possible to prevent human errors when typing email addresses or registering people in third-party web applications linked with your business. Some procedures and mechanisms to consider include: 

  • Frequent validation of data, specifically email address, of registered employees on third-party applications. Consider having a procedure for administrators of applications that describes that responsibility. 
  • Implement domain and user impersonation protection mechanisms on your email provider. For example, Microsoft has specific settings in their anti-phishing for user and domain impersonation
  • All the recommendations that apply to typo squatting, also apply here: 
    • Monitor domains similar to yours. For this attack, if an attacker defined an MX record for a similar domain, they are most likely receiving emails you were supposed to be receiving! Request a take-down of that domain. 
    • There are plenty of open-source projects on github to help with monitoring, as well as commercial solutions.
    • Register and park domains similar to yours, keeping them to prevent attackers from registering these themselves. Costs may be a concern, so focus only on the few most likely to be mistyped.  
  • The longer your business domain is, the higher the chance of a typo. An obvious mitigation would be to have a shorter domain name. Of course, this is hard to apply in hindsight. You are not going to change the name of your company just because you want a shorter domain name, or the company brand policy prevents this. Instead, an alternative option would be to register a shorthand for your domain for email communications. For example, registering ms.com for microsoft.com and encouraging using the shorter version for email communications and user registration in third-party provider applications.  
  • Usual recommendations to protect your business against spear phishing campaigns also apply here. These range from continuous phishing simulation campaigns, employee awareness training, and clear procedures and mechanisms to report real phishing to the security team internally.

Use the tool in your engagements and let me know how it goes.  

Happy hunting!