Major Security Flaws in Mailcow: Inside the XSS and Path Traversal Exploits (CVE-2024-31204 and CVE-2024-30270)

Purple Teaming – All You Need to Know
July 2, 2024
Static Analysis of Android Application
Mitigate OWASP Top 10 Android Risks with Static Analysis
July 12, 2024

July 2, 2024

Summary

Mailcow’s XSS and file overwrite vulnerabilities allow attackers to inject code, hijack sessions, and execute commands, highlighting critical security risks.

Introduction

This analysis thoroughly examines the vulnerabilities within Mailcow’s codebase, particularly focusing on CVE-2024-31204 (XSS) and CVE-2024-30270 (path traversal). The report not only identifies these vulnerabilities but also provides detailed technical insights, impact evaluations, effective mitigation strategies, and actionable recommendations to strengthen Mailcow’s security posture.

An Introduction to Mailcow

Mailcow is a robust open-source mail server software suite designed to provide a comprehensive email hosting solution. Its feature-rich components include essential elements such as the Postfix mail transfer agent, Dovecot IMAP/POP3 server, ClamAV antivirus, and SpamAssassin spam filter, among others. 

With its resilient and adaptable framework, Mailcow caters to both organizations and individuals, gaining significant traction among those aiming to efficiently establish and manage their email infrastructure.

Details of the Vulnerabilities

CVE-2024-31204: XSS in the Admin Panel

This vulnerability arises from inadequate input sanitization within Mailcow’s admin panel, specifically in the jQuery-based notification library. The flaw allows attackers to inject malicious JavaScript payloads by manipulating API error messages, potentially leading to unauthorized code execution. 

The vulnerability stems from the absence of an HTML entity escaping in Mailcow’s jQuery-based notification library. When API errors occur and are displayed in the admin panel, the lack of proper sanitization enables attackers to inject JavaScript payloads. Successful exploitation allows attackers to execute arbitrary code within the admin panel, potentially compromising sensitive data and system integrity.

Attack Scenario:

An attacker crafts a malicious email embedded with a CSS background image loaded from a remote URL. This image points to the API endpoint with an XSS payload in the query parameter, triggering code execution when viewed by an admin user in the panel.

CVE-2024-30270: Arbitrary File Overwrite

This vulnerability stems from insufficient input validation in the rspamd_maps function, allowing attackers to overwrite arbitrary files on the server. Attackers can leverage this vulnerability to manipulate file paths and execute arbitrary commands, posing a substantial risk of complete system compromise. 

The vulnerability originates from inadequate input validation within Mailcow’s rspamd_maps function, enabling attackers to construct a file path using manipulated user input and overwrite files with malicious content. Successful exploitation grants attackers unauthorized access to critical system files, potentially resulting in data leakage, unauthorized system modifications, and additional avenues for exploitation. 

By addressing these vulnerabilities comprehensively and implementing recommended security measures, Mailcow can significantly enhance its resilience against potential threats and safeguard its users’ data and systems effectively.

Attack Scenario:

Attackers exploit the path traversal vulnerability by providing crafted input to the rspamd_maps function, enabling them to traverse directories and overwrite critical files.

Proof of Concept

Lab Setup

To set up this lab, we used Ubuntu 20.04.6 LTS in VMware Workstation Pro 17. Setting up Mailcow can be a complicated process, so we created an automation script in Bash that is compatible with all Linux distributions.

!/bin/bash
 Check if running as root
if [[ $EUID -ne 0 ]]; then
   echo "This script must be run as root"
   exit 1
fi
 Check if Docker and Docker Compose are installed
docker -v >/dev/null 2>&1
DOCKER_INSTALLED=$?
docker-compose -v >/dev/null 2>&1
DOCKER_COMPOSE_INSTALLED=$?
 Install Docker if not already installed
if [ $DOCKER_INSTALLED -ne 0 ]; then
    echo "Installing Docker..."
    curl -fsSL https://get.docker.com/ | CHANNEL=stable sh
    systemctl enable --now docker
    echo "Docker installed successfully!"
else
    echo "Docker is already installed"
fi
 Install Docker Compose if not already installed
if [ $DOCKER_COMPOSE_INSTALLED -ne 0 ]; then
    echo "Installing Docker Compose..."
    LATEST_COMPOSE=$(curl -Ls -w %{url_effective} -o /dev/null https://github.com/docker/compose/releases/latest) && LATEST_COMPOSE=${LATEST_COMPOSE/}
    curl -L https://github.com/docker/compose/releases/download/$LATEST_COMPOSE/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose
    chmod +x /usr/local/bin/docker-compose
    echo "Docker Compose installed successfully!"
else
    echo "Docker Compose is already installed"
fi
 Download and unzip specific version of Mailcow
echo "Downloading Mailcow version 2024-02..."
cd /opt
if [ ! -d "mailcow-dockerized" ]; then
    curl -L https://github.com/mailcow/mailcow-dockerized/archive/refs/tags/2024-02.zip -o mailcow-2024-02.zip
    unzip mailcow-2024-02.zip
    mv mailcow-dockerized-2024-02 mailcow-dockerized
    rm mailcow-2024-02.zip
fi
cd mailcow-dockerized
 Generate configuration file
echo "Generating configuration file..."
./generate_config.sh
echo "Configuration file generated successfully!"
 Start mailcow
echo "Starting mailcow..."
docker compose pull
docker compose up -d
echo "Mailcow version 2024-02 started successfully!"

Usage:

  • Save the script to a file, e.g., setup_mailcow.sh.
  • Make the script executable: chmod +x setup_mailcow.sh.
  • Run the script as root: sudo ./setup_mailcow.sh.

Once done, you can access Mailcow on your pre-configured IP, such as localhost, using your browser. Log in to Mailcow with the default credentials:

Username: admin
Password: moohoo

Configure SOGO and connect the example domain. After configuration, you will be able to log in to your SOGO account. Once completed, you can copy the URL and use it in an exploit.

Exploitation

To exploit this vulnerability, we created an exploit script. The details are as follows:

This script is designed to exploit vulnerabilities in a Mailcow instance using Cross-Site Scripting (XSS) and Remote Code Execution (RCE). The script aims to:

  • Inject an XSS payload into the Mailcow web interface.
  • Use the XSS payload to execute unauthorized actions.
  • Achieve RCE by overwriting a server template and executing commands.

Requirements

1. Python 3: Ensure Python 3 is installed on your machine. You can download it from the official website.

2. Requests Library: Install the requests library if it’s not already installed. You can do this by running: pip install requests

3. Target Mailcow Instance: You need access to a Mailcow instance where you have identified a potential XSS vulnerability.

Steps to Use the Script

1. Download the Script: Save the provided script in a Python file, e.g., exploit.py.

2. Run the Script: Execute the script in your terminal or command prompt. The script will prompt you for the target Mailcow instance URL.

python3 exploit.py

3. Provide Target URL: When prompted, enter the URL of the target Mailcow instance. For example:

bash
Copy code
Enter the target Mailcow instance URL (e.g., https://mail.mailcow.example): http://setted-domain/SOGo/so/[email protected]/Mail/view!/Mail/0/inbox

4.Monitor Output: The script will perform the following acti

  • Send a malicious email containing the XSS payload.
  • Wait for the victim to open the email.
  • Send an API request to overwrite the rspamd maps.
  • Trigger the execution of the malicious code.
  • Log responses and indicate the success or failure of each step.

Script Output Explanation

The script provides feedback on each step, indicating whether it was successful or if an error occurred. Here is an example of the expected output:

Enter the target Mailcow instance URL (e.g., https://mail.mailcow.example): http://setted-domain/SOGo/so/[email protected]/Mail/view!/Mail/0/inbox

Sending malicious email...

Waiting for the victim to open email.

Sending malicious API requests.

Response Status Code: 200

Response Text: 123
<!DOCTYPE html>
...
Template cache overwritten successfully!
Triggering malicious code execution...
Response Status Code: 200
Response Text: exploited
<!DOCTYPE html>
Malicious code executed successfully!
Command output: exploited
You can find the script here. https://github.com/Alchemist3dot14/CVE-2024-30270-PoC

Cause Analysis

The exploit strategy hinges on exploiting exceptions thrown by the system, particularly in cases where errors are converted into strings using functions like print_r(). Mailcow’s configuration includes attacker-controlled arguments in these error strings, providing an avenue for attackers to inject their own code. An exploitable function within Mailcow’s code, explode(), further exacerbates the issue. 

If an attacker sends unexpected input, such as an array, to explode(), it triggers an error. This error message then inadvertently includes the attacker’s malicious payload. Attackers leverage this vulnerability by crafting emails with payloads hidden in CSS background images. When recipients open these emails in Mailcow’s webmail client, the malicious code executes, allowing attackers to hijack sessions, manipulate settings, and compromise user accounts. 

Moreover, the CVE-2024-30270 vulnerability permits attackers to overwrite server files by exploiting flaws in file validation. This can lead to the replacement of critical files with malicious ones, potentially granting full control over the server. Despite Mailcow’s security measures like Docker containers and restricted permissions, attackers can still infiltrate by targeting cache directories where templates are stored. 

Injecting malicious code into these directories allows for execution upon loading specific pages. While some avenues for running malicious commands may be blocked, attackers circumvent these restrictions using functions like mail() to execute commands and cause further damage.

Patch Diffing

Let’s dive deeper into the technical details of the patches applied to address the XSS vulnerability (CVE-2024-31204) and the file write vulnerability (CVE-2024-30270) in Mailcow, along with the additional hardening measures implemented.

XSS Vulnerability (CVE-2024-31204) Patch

Since it is an open-source program, source files can be accessed (https://github.com/mailcow/mailcow-dockerized).

The patch for the XSS vulnerability involved encoding HTML special characters in the exception details before rendering them in the template. Here’s the technical breakdown:

php

- $message = strtr($log['msg'], ["\n" => '', "\r" => '', "\t" => '']);
+ $message = htmlspecialchars($log['msg'], ENT_QUOTES);
+ $message = strtr($message, ["\n" => '', "\r" => '', "\t" => '']);

Explanation

  • htmlspecialchars($log[‘msg’], ENT_QUOTES) encodes HTML special characters, preventing malicious JavaScript injection.
  • The subsequent strtr() function call ensures that newline, carriage return, and tab characters are properly handled.

 File Write Vulnerability (CVE-2024-30270) Patch

The fix for the file write vulnerability involved enhancing the validation logic to enforce an allowlist of permitted map types, thereby preventing unauthorized file writes. Here’s the technical breakdown:

- return false;
}
$maps = (array)$_data['map'];
+ $valid_maps = array();
foreach ($maps as $map) {
  foreach ($RSPAMD_MAPS as $rspamd_map_type) {
    if (!in_array($map, $rspamd_map_type)) {
        'log' => array(__FUNCTION__, $_action, '-'),
        'msg' => array('global_map_invalid', $map)
      );
-       continue;
+     } else {
+       array_push($valid_maps, $map);
     }
   }
+ }
+ foreach ($valid_maps as $map) {
   try {
     if (file_exists('/rspamd_custom_maps/' . $map)) {
       $map_content = trim($_data['rspamd_map_data']);

Explanation

– The code now checks if the map type is in the allowlist ($RSPAMD_MAPS) before processing it further.

– $valid_maps array is used to store valid map types, ensuring that only permitted map types are processed.

Additional Hardening Measures

In addition to the patches, Mailcow implemented extra security measures to mitigate potential exploits.

1. Checking Referer Header (Deprecated)

php
+ if (isset($_SERVER['HTTP_REFERER'])) {
+   if (strpos(strtolower($_SERVER['HTTP_REFERER']), '/sogo') !== false) {
+     header('HTTP/1.1 403 Forbidden');
+     exit;
+   }
+ }

2. Checking Sec-Fetch-Dest Header (Preferred)

php
- if (isset($_SERVER['HTTP_REFERER'])) {
-   if (strpos(strtolower($_SERVER['HTTP_REFERER']), '/sogo') !== false) {
-     header('HTTP/1.1 403 Forbidden');
-     exit;
-   }
+ if (isset($_SERVER['HTTP_SEC_FETCH_DEST']) && $_SERVER['HTTP_SEC_FETCH_DEST'] !== 'empty') {
+   header('HTTP/1.1 403 Forbidden');
+   exit;
  }

Explanation

– The Sec-Fetch-Dest header is now checked to ensure that API requests originate from expected sources, improving defense against potential exploitation attempts.

– This approach is more robust as it avoids relying solely on the Referer header, which can be manipulated or omitted by attackers.

These technical enhancements showcase Mailcow’s commitment to addressing vulnerabilities comprehensively and proactively fortifying its security posture.

 Final Thoughts

An analysis of the vulnerabilities in Mailcow revealed critical security gaps, especially with CVE-2024-31204 (XSS) and CVE-2024-30270 (Path Traversal) vulnerabilities. The in-depth investigation provided actionable insights, robust mitigation strategies, and emphasized the importance of proactive security measures in safeguarding systems against potential exploits and cyber threats.

 References

  • https://www.sonarsource.com/blog/remote-code-execution-in-mailcow-always-sanitize-error-messages/
  • https://docs.mailcow.email/interested-try-it-out-right-away
  • https://github.com/mailcow/mailcow-dockerized/blob/2024-02/data/web/inc/prerequisites.inc.phpL147-L167

Discover more from SecureLayer7 - Offensive Security, API Scanner & Attack Surface Management

Subscribe now to keep reading and get access to the full archive.

Continue reading