A Deep Dive into RabbitMQ Security: From CVEs to Exploitation

Author: Pentester Date: November 06, 2025

Introduction

RabbitMQ is a powerful and widely adopted open-source message broker that enables applications to communicate with each other through a messaging queue system. It is a critical component in many modern, distributed architectures, from microservices to large-scale enterprise systems. However, its central role also makes it a high-value target for attackers. A compromised message broker can lead to data breaches, service disruption, and unauthorized access to the broader network. Understanding its security landscape is not just beneficial; it is essential for developers, system administrators, and security professionals.

This article provides a comprehensive overview of RabbitMQ security, grounded in publicly available vulnerability data and established penetration testing techniques. We will explore its default configurations, common misconfigurations, a history of Common Vulnerabilities and Exposures (CVEs) from recent years back to 2016, and the methods attackers use to exploit them. The focus will be on providing defensive knowledge to help organizations harden their RabbitMQ instances against these threats, covering everything from initial reconnaissance and exploitation to privilege escalation and post-exploitation persistence.

Understanding the Default Attack Surface

Out of the box, RabbitMQ is designed for ease of use, which can sometimes be at odds with security. The default configuration presents a known attack surface that must be addressed before any production deployment.

Port Service Default Exposure Security Risk
5672 AMQP (Client Connections) Unencrypted Eavesdropping on credentials and message content.
15672 Management Plugin UI & API HTTP (Unencrypted) Brute-force attacks, credential sniffing, Cross-Site Scripting (XSS).
25672 Erlang Distribution (Clustering) Internal Remote Code Execution if the Erlang cookie is compromised.
4369 Erlang Port Mapper Daemon (epmd) Internal Facilitates node discovery for clustering; exposure can leak cluster information.

One of the most well-known aspects of a default RabbitMQ installation is the guest user. This user is created with the password guest and is granted full administrative privileges on the default virtual host (/). In modern versions of RabbitMQ, this user is restricted to localhost connections only, a critical security improvement. However, a common and dangerous misconfiguration is to remove this restriction, exposing the instance to trivial compromise from remote attackers [1].

Common Misconfigurations and Hardening

Many successful attacks against RabbitMQ are not the result of sophisticated zero-day exploits, but rather the exploitation of common security misconfigurations. Hardening a RabbitMQ instance involves a systematic review of its configuration to eliminate these weaknesses.

A production system should almost never expose its RabbitMQ ports to the public Internet. Access should be restricted via firewalls to a set of known hosts (application servers). Management UI and API must be protected by both a firewall and TLS. [2]

Key Hardening Steps:

  1. Manage Users and Credentials: The guest user should be deleted immediately in a production environment. New administrative and application-specific users should be created with strong, generated passwords. The principle of least privilege must be applied, granting each user only the permissions necessary for their function.

  2. Enforce Encrypted Transport (TLS/SSL): All communication with RabbitMQ should be encrypted. This includes client connections over AMQP (using port 5671) and access to the management plugin (using port 15671). Unencrypted ports (5672, 15672) should be disabled or firewalled.

  3. Secure the Management Plugin: The management UI is a powerful tool and a significant attack surface. It should never be exposed to the public internet. Access should be restricted to a trusted internal network or VPN, and always over HTTPS.

  4. Protect the Erlang Cookie: The Erlang cookie is a shared secret that allows nodes in a cluster to communicate and execute remote commands. If an attacker obtains this cookie, they can achieve full remote code execution on the cluster. The cookie file must be protected with restrictive file permissions (e.g., 400) and should be a long, randomly generated string [3].

  5. Use Virtual Hosts for Isolation: Virtual hosts provide logical separation of resources within a single RabbitMQ instance. Use different virtual hosts for different applications or tenants to prevent one compromised application from affecting others.

A History of Vulnerabilities: CVE Deep Dive

Over the years, numerous vulnerabilities have been discovered in RabbitMQ. Analyzing these CVEs provides insight into recurring weaknesses and informs a robust defensive strategy. The following table summarizes key vulnerabilities from 2025 back to 2016.

CVE ID CVSS 3.1 Score Summary Affected Versions Type
CVE-2025-50200 6.7 Medium Logs Basic Auth credentials in plaintext (base64 encoded) from API requests. [4] <= 3.13.7 Information Disclosure (CWE-532)
CVE-2025-30219 6.1 Medium XSS in management UI error message when a virtual host fails to start. [5] < 4.0.3 Cross-Site Scripting (CWE-79)
CVE-2023-46118 4.9 Medium Denial of Service via large messages published over the HTTP API, causing an out-of-memory error. [6] < 3.11.24, < 3.12.7 Denial of Service
CVE-2022-31008 5.5 Medium Predictable encryption key used for URI obfuscation in Shovel and Federation plugins. [6] < 3.10.2, < 3.9.18 Cryptographic Weakness
CVE-2021-22117 7.8 High Windows Local Privilege Escalation due to insecure plugin directory permissions. [7] Windows < 3.8.16 Privilege Escalation (Insecure Permissions)
CVE-2021-22116 7.5 High Denial of Service due to improper input validation in the AMQP 1.0 plugin. [6] < 3.8.16 Denial of Service
CVE-2020-5419 6.7 Medium Windows-specific binary planting vulnerability allowing arbitrary code execution. [8] 3.8.x < 3.8.7 Arbitrary Code Execution (CWE-427)
CVE-2019-11291 4.8 Medium XSS in the federation and shovel management UI endpoints via vhost or node name fields. [6] 3.7.x < 3.7.20 Cross-Site Scripting (CWE-79)
CVE-2018-11087 5.9 Medium Man-in-the-middle in the Java client due to lack of hostname validation. [6] Spring AMQP < 1.7.10 Man-in-the-Middle
CVE-2016-9877 9.8 Critical MQTT plugin allows authentication with a valid username but no password. [9] < 3.6.6 Authentication Bypass

Pentesting and Red Teaming RabbitMQ

An effective defense requires understanding the offense. Pentesting RabbitMQ involves a methodical approach to discover and exploit weaknesses.

Reconnaissance and Enumeration

The first step is to identify RabbitMQ instances and fingerprint them. This is typically done through port scanning and banner grabbing.

# Scan for default RabbitMQ ports
nmap -p 4369,5672,15672,25672 -sV <target>

# Enumerate users, vhosts, and queues via the management API
# (Requires credentials, but try guest:guest first)
curl -u guest:guest http://<target>:15672/api/overview
curl -u guest:guest http://<target>:15672/api/users
curl -u guest:guest http://<target>:15672/api/queues

Tools like rabbitmqadmin can also be used to enumerate the target if valid credentials are known or obtained [10].

Common Attack Vectors

  • Default Credentials: The simplest and often most effective attack is trying the guest:guest credential pair, especially on older or misconfigured systems.
  • Brute-Force Attacks: The management UI login page is a prime target for password spraying and brute-force attacks using tools like Hydra.
  • Message Interception and Injection: With valid credentials, an attacker can connect to the broker, consume messages from queues to steal sensitive data, and publish malicious messages to poison downstream applications.
  • Management API Abuse: If an attacker gains administrative access, they can create backdoor users, modify permissions, and use plugins like Shovel to exfiltrate data to an attacker-controlled server.

Privilege Escalation: From Local User to SYSTEM

Privilege escalation vulnerabilities are particularly severe as they allow an attacker with a low-privileged foothold to gain complete control of the system. RabbitMQ has had notable LPE vulnerabilities, especially on Windows.

Case Study: CVE-2021-22117 This vulnerability allows any local user on a Windows machine to escalate their privileges to NT AUTHORITY\SYSTEM. The RabbitMQ installer for Windows (prior to version 3.8.16) failed to set secure permissions on its installation directory. The RabbitMQ service runs as LocalSystem, and it loads plugin files (.ez files) from this insecure directory. An attacker could simply write a malicious plugin to this directory, which the service would then execute, granting the attacker code execution with the highest level of privilege on the host [7].

Another powerful vector for privilege escalation and remote code execution is the Erlang cookie. If an attacker can read this file from the filesystem, they can impersonate another node, join the cluster, and execute arbitrary Erlang code. This highlights the critical importance of filesystem security on the broker nodes themselves.

Post-Exploitation

Once an attacker has compromised a RabbitMQ instance, their goal is to maintain persistence and pivot to other parts of the network.

  • Persistence: This can be achieved by creating hidden administrative accounts, installing malicious plugins that act as backdoors, or using the Shovel plugin to continuously exfiltrate messages.
  • Lateral Movement: Messages in the queues often contain credentials, API keys, or connection strings for other services like databases and internal APIs. By consuming these messages, an attacker can gather the intelligence needed to move laterally across the network.

Conclusion

RabbitMQ is a robust and reliable message broker, but like any complex software, it requires careful security configuration and ongoing maintenance. The most significant risks often stem not from exotic vulnerabilities, but from failing to move away from insecure defaults. Deleting the guest user, enforcing TLS on all connections, protecting the management interface, and securing the Erlang cookie are fundamental steps to building a secure RabbitMQ deployment.

By understanding the historical vulnerabilities and the techniques used by attackers, organizations can adopt a proactive, defense-in-depth security posture. Regular patching, continuous monitoring, and adherence to security best practices are paramount to ensuring that your message broker remains a trusted and secure component of your infrastructure.


References

[1]: RabbitMQ Documentation: Access Control [2]: RabbitMQ Documentation: Production Checklist [3]: Exploit-DB: Erlang Cookie - Remote Code Execution [4]: NVD: CVE-2025-50200 [5]: Red Hat Customer Portal: CVE-2025-30219 [6]: OpenCVE: RabbitMQ Vulnerabilities [7]: AttackIQ: Local Privilege Escalation in RabbitMQ on Windows (CVE-2021-22117) [8]: NVD: CVE-2020-5419 [9]: NVD: CVE-2016-9877 [10]: Hackviser: RabbitMQ Pentesting

RabbitMQ Vulnerability Detection Toolkit

Overview

This guide provides comprehensive detection methods and scripts to identify RabbitMQ installations vulnerable to CVE-2021-22117 and other common security issues. The vulnerability allows local privilege escalation to SYSTEM on Windows installations of RabbitMQ prior to version 3.8.16.

CVE-2021-22117 Details

CVE ID: CVE-2021-22117
CVSS Score: 7.8 (High)
Attack Vector: Local
Privileges Required: Low
User Interaction: None
Impact: Complete system compromise (SYSTEM privileges)

Vulnerability Description

RabbitMQ installers on Windows prior to version 3.8.16 fail to properly secure the plugin directory permissions. The RabbitMQ service runs as NT AUTHORITY\SYSTEM, and when it loads plugin files (.ez files) from the installation directory, it does so with elevated privileges. Due to insecure default permissions (BUILTIN\Users with write access), any local user can place malicious plugin files in this directory, which will then be executed with SYSTEM privileges.

Affected Versions

All RabbitMQ versions on Windows prior to 3.8.16 are vulnerable.

Patched Versions

RabbitMQ 3.8.16 and later have hardened plugin directory permissions.

Detection Scripts

This package includes three detection scripts for different environments:

1. PowerShell Script (Windows)

File: detect_cve_2021_22117.ps1

Purpose: Local detection on Windows systems

Features: - Automatically discovers RabbitMQ installations via registry, common paths, and services - Extracts version information from multiple sources - Checks plugin directory ACL permissions for insecure configurations - Identifies if BUILTIN\Users group has write access - Provides detailed vulnerability assessment

Usage:

# Basic scan
.\detect_cve_2021_22117.ps1

# Verbose output
.\detect_cve_2021_22117.ps1 -Verbose

# Run as Administrator for complete detection
# Right-click PowerShell → Run as Administrator
.\detect_cve_2021_22117.ps1

Requirements: - Windows PowerShell 5.1 or later - Administrator privileges recommended (not required, but provides more accurate results)

Output Example:

=== CVE-2021-22117 Detection Script ===
Scanning for vulnerable RabbitMQ installations on Windows...

[*] Found 1 RabbitMQ installation(s)

----------------------------------------
[*] Analyzing: C:\Program Files\RabbitMQ Server
[*] Version: 3.8.14
[!] Version is VULNERABLE (< 3.8.16)
[!] CRITICAL: Insecure plugin directory permissions detected!
    Path: C:\Program Files\RabbitMQ Server\rabbitmq_server-3.8.14\plugins
    Identity: BUILTIN\Users
    Rights: Modify, Write

[!] This installation is VULNERABLE to CVE-2021-22117!
[!] Local users can escalate privileges to SYSTEM!

2. Python Script (Cross-Platform)

File: detect_cve_2021_22117.py

Purpose: Local detection on Windows, Linux, and macOS

Features: - Cross-platform compatibility - Automatic installation discovery - Version extraction and vulnerability assessment - Permission checking (Windows ACL and Unix permissions) - Colored terminal output - Verbose mode for detailed diagnostics

Usage:

# Basic scan
python3 detect_cve_2021_22117.py

# Verbose output
python3 detect_cve_2021_22117.py --verbose

# On Windows (requires pywin32 for detailed ACL checks)
pip install pywin32
python detect_cve_2021_22117.py

Requirements: - Python 3.6 or later - Optional: pywin32 package for detailed Windows ACL analysis - Administrator/root privileges recommended

Installation:

# Install dependencies (optional, for enhanced Windows ACL checking)
pip install pywin32

3. Bash Script (Remote Network Scanning)

File: scan_rabbitmq_vulnerabilities.sh

Purpose: Remote vulnerability scanning via RabbitMQ Management API

Features: - Remote network-based scanning - Port accessibility checks - Version detection via Management API - Default credential testing - User and virtual host enumeration - TLS/SSL configuration verification - Multiple CVE detection (CVE-2021-22117, CVE-2022-31008, CVE-2023-46118, etc.) - Comprehensive security assessment

Usage:

# Make script executable
chmod +x scan_rabbitmq_vulnerabilities.sh

# Basic scan with default credentials
./scan_rabbitmq_vulnerabilities.sh 192.168.1.100

# Scan with custom credentials
./scan_rabbitmq_vulnerabilities.sh example.com -u admin -p secretpassword

# Scan with custom port
./scan_rabbitmq_vulnerabilities.sh 10.0.0.50 -P 15672 -u admin -p password

# Verbose output
./scan_rabbitmq_vulnerabilities.sh target.com -v

Requirements: - Bash 4.0 or later - curl command-line tool - Network access to target RabbitMQ management port (default: 15672) - Valid credentials (tries guest:guest by default)

Output Example:

╔════════════════════════════════════════════════════════════╗
║         RabbitMQ Vulnerability Scanner                    ║
║         CVE Detection & Security Assessment                ║
╚════════════════════════════════════════════════════════════╝

[i] Target: 192.168.1.100
[i] Management Port: 15672
[i] Username: guest

[*] Port Accessibility Check
[!] AMQP port 5672 is accessible
[!] Management UI port 15672 is accessible
[+] Erlang distribution port 25672 is not accessible

[*] Default Credentials Check
[-] Default credentials (guest:guest) are ACTIVE!

[*] Version Detection
[i] Detected version: 3.8.14
[-] Vulnerable to CVE-2021-22117 (Windows LPE)
[-] Vulnerable to CVE-2021-22116 (DoS)

Detection Methodology

Local Detection (Windows)

The local detection process follows these steps:

  1. Installation Discovery
  2. Search common installation directories
  3. Query Windows Registry for installation paths
  4. Check Windows Services for RabbitMQ service
  5. Enumerate all discovered installations

  6. Version Extraction

  7. Parse version from directory names
  8. Read version from rabbitmqctl output
  9. Extract version from service configuration

  10. Vulnerability Assessment

  11. Compare version against known vulnerable versions (< 3.8.16)
  12. If vulnerable version detected, proceed to permission check

  13. Permission Analysis

  14. Locate plugin directory (typically plugins subdirectory)
  15. Retrieve Access Control List (ACL) using Windows API
  16. Check if BUILTIN\Users or similar groups have write permissions
  17. Identify specific dangerous permissions (Write, Modify, FullControl)

  18. Risk Determination

  19. If version is vulnerable AND permissions are insecure: CRITICAL
  20. If version is vulnerable but permissions are secure: WARNING (still recommend upgrade)
  21. If version is patched: SAFE

Remote Detection (Network)

The remote detection process includes:

  1. Port Scanning
  2. Test connectivity to AMQP port (5672)
  3. Test connectivity to Management UI (15672)
  4. Test connectivity to Erlang distribution port (25672) - should NOT be accessible
  5. Test connectivity to TLS ports (5671, 15671)

  6. Authentication Testing

  7. Attempt authentication with default credentials (guest:guest)
  8. Test provided credentials against Management API

  9. Version Fingerprinting

  10. Query /api/overview endpoint for version information
  11. Parse RabbitMQ version from JSON response
  12. Cross-reference version against CVE database

  13. Configuration Assessment

  14. Enumerate users and check for guest account
  15. List virtual hosts
  16. Identify enabled plugins
  17. Check TLS/SSL configuration

  18. Vulnerability Mapping

  19. Map detected version to known CVEs
  20. Report all applicable vulnerabilities
  21. Provide remediation recommendations

Remediation Steps

If a vulnerable installation is detected, follow these steps immediately:

1. Upgrade RabbitMQ

The primary remediation is to upgrade to a patched version.

Windows:

# Download latest version from official site
# https://www.rabbitmq.com/install-windows.html

# Stop RabbitMQ service
Stop-Service RabbitMQ

# Run new installer (will upgrade in place)
# Start installer and follow prompts

# Start RabbitMQ service
Start-Service RabbitMQ

# Verify version
& "C:\Program Files\RabbitMQ Server\rabbitmq_server-3.x.x\sbin\rabbitmqctl.bat" status

Linux (via package manager):

# Ubuntu/Debian
sudo apt update
sudo apt install --only-upgrade rabbitmq-server

# RHEL/CentOS
sudo yum update rabbitmq-server

# Verify version
sudo rabbitmqctl status

2. Harden Plugin Directory Permissions (Temporary Mitigation)

If immediate upgrade is not possible, harden permissions as a temporary mitigation:

Windows:

# Navigate to RabbitMQ installation
cd "C:\Program Files\RabbitMQ Server\rabbitmq_server-3.x.x"

# Remove Users group write access
icacls plugins /remove:g "BUILTIN\Users"

# Grant read-only access to Users
icacls plugins /grant "BUILTIN\Users:(RX)"

# Verify permissions
icacls plugins

3. Audit for Compromise

Check for signs of exploitation:

# Check for suspicious .ez files in plugins directory
Get-ChildItem "C:\Program Files\RabbitMQ Server\rabbitmq_server-*\plugins" -Filter *.ez | 
    Select-Object Name, CreationTime, LastWriteTime | 
    Sort-Object LastWriteTime -Descending

# Review RabbitMQ logs for suspicious activity
Get-Content "C:\Users\<RabbitMQ_User>\AppData\Roaming\RabbitMQ\log\*.log" | 
    Select-String -Pattern "plugin|error|failed"

# Check for unauthorized user accounts
Get-LocalUser | Where-Object {$_.Enabled -eq $true}

# Review scheduled tasks for persistence
Get-ScheduledTask | Where-Object {$_.State -eq "Ready"}

4. Security Hardening

Implement additional security measures:

  • Delete Guest User: bash rabbitmqctl delete_user guest

  • Create Strong Admin User: bash rabbitmqctl add_user admin $(openssl rand -base64 32) rabbitmqctl set_user_tags admin administrator rabbitmqctl set_permissions -p / admin ".*" ".*" ".*"

  • Enable TLS: Configure TLS for AMQP and Management UI in rabbitmq.conf

  • Restrict Network Access: Use firewall rules to limit access to trusted networks only

Integration with Security Tools

Nmap NSE Script

You can use Nmap to detect RabbitMQ and check for default credentials:

# Detect RabbitMQ and enumerate version
nmap -p 15672 --script http-title,http-headers <target>

# Test for default credentials
nmap -p 15672 --script http-auth --script-args http-auth.path=/api/overview <target>

Metasploit Module

Check for auxiliary modules:

msfconsole
search rabbitmq
use auxiliary/scanner/rabbitmq/rabbitmq_auth_bruteforce

Vulnerability Scanners

  • Nessus: Plugin ID 198217 detects CVE-2021-22117
  • OpenVAS: Includes RabbitMQ vulnerability checks
  • Qualys: Detects outdated RabbitMQ versions

Continuous Monitoring

Implement ongoing detection:

1. Scheduled Scanning

Windows Task Scheduler:

# Create scheduled task to run detection weekly
$action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File C:\Scripts\detect_cve_2021_22117.ps1"
$trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Monday -At 2am
Register-ScheduledTask -Action $action -Trigger $trigger -TaskName "RabbitMQ CVE Check" -Description "Weekly RabbitMQ vulnerability scan"

Linux Cron:

# Add to crontab (weekly scan)
0 2 * * 1 /usr/local/bin/detect_cve_2021_22117.py --verbose > /var/log/rabbitmq_cve_scan.log 2>&1

2. SIEM Integration

Export scan results to your SIEM:

# Run scan and output JSON
./scan_rabbitmq_vulnerabilities.sh target.com | tee -a /var/log/siem/rabbitmq_scan.log

3. Alerting

Set up alerts for vulnerable installations:

# PowerShell example with email alert
$result = & .\detect_cve_2021_22117.ps1
if ($result -match "VULNERABLE") {
    Send-MailMessage -To "security@company.com" -From "scanner@company.com" -Subject "ALERT: Vulnerable RabbitMQ Detected" -Body $result -SmtpServer "smtp.company.com"
}

False Positives and Limitations

Known Limitations

  1. Version Detection: If RabbitMQ is installed in a non-standard location or the version cannot be determined, manual verification may be required.

  2. Permission Checks: The scripts check for common insecure permission patterns, but custom ACL configurations may require manual review.

  3. Remote Scanning: The bash script requires network access to the Management API. If the API is disabled or firewalled, local scanning is necessary.

  4. Platform-Specific: CVE-2021-22117 only affects Windows installations. Linux/Unix systems are not vulnerable to this specific CVE.

False Negative Prevention

To minimize false negatives:

  • Run scripts with elevated privileges (Administrator/root)
  • Ensure all RabbitMQ installation paths are checked
  • Manually verify version if automatic detection fails
  • Review ACLs manually using icacls or Get-Acl on Windows

References

  1. CVE-2021-22117: https://nvd.nist.gov/vuln/detail/CVE-2021-22117
  2. Security Advisory: https://www.attackiq.com/2021/06/09/dsa-lpe-rabbitmq-win/
  3. RabbitMQ Security: https://www.rabbitmq.com/docs/access-control
  4. Production Checklist: https://www.rabbitmq.com/docs/production-checklist

Support and Contributions

For issues, questions, or contributions related to these detection scripts, please ensure you're using them in accordance with your organization's security policies and applicable laws.

Disclaimer: These scripts are provided for defensive security purposes only. Use them responsibly and only on systems you own or have explicit permission to test.


Last Updated: November 06, 2025
Version: 1.0
Author: Pentester

PowerShell Detection Script

<#
.SYNOPSIS
    Detection script for CVE-2021-22117 - RabbitMQ Windows Local Privilege Escalation

.DESCRIPTION
    This script checks if a Windows system has a vulnerable RabbitMQ installation
    that is susceptible to CVE-2021-22117 (Local Privilege Escalation via insecure
    plugin directory permissions).

    CVE-2021-22117 affects RabbitMQ versions prior to 3.8.16 on Windows.

.NOTES
    Author: Pentester
    Date: November 06, 2025
    CVE: CVE-2021-22117
    CVSS: 7.8 (High)

.EXAMPLE
    .\detect_cve_2021_22117.ps1

.EXAMPLE
    .\detect_cve_2021_22117.ps1 -Verbose
#>

[CmdletBinding()]
param()

function Write-ColorOutput {
    param(
        [string]$Message,
        [string]$Color = "White"
    )
    Write-Host $Message -ForegroundColor $Color
}

function Get-RabbitMQInstallation {
    Write-Verbose "Searching for RabbitMQ installations..."

    $installations = @()

    # Check common installation paths
    $commonPaths = @(
        "C:\Program Files\RabbitMQ Server",
        "C:\Program Files (x86)\RabbitMQ Server",
        "C:\tools\RabbitMQ",
        "${env:ProgramFiles}\RabbitMQ Server",
        "${env:ProgramFiles(x86)}\RabbitMQ Server"
    )

    foreach ($path in $commonPaths) {
        if (Test-Path $path) {
            $installations += $path
            Write-Verbose "Found RabbitMQ at: $path"
        }
    }

    # Check Windows Registry for installation path
    try {
        $regPaths = @(
            "HKLM:\SOFTWARE\VMware, Inc.\RabbitMQ Server",
            "HKLM:\SOFTWARE\WOW6432Node\VMware, Inc.\RabbitMQ Server",
            "HKLM:\SOFTWARE\Pivotal\RabbitMQ Server"
        )

        foreach ($regPath in $regPaths) {
            if (Test-Path $regPath) {
                $installPath = (Get-ItemProperty -Path $regPath -ErrorAction SilentlyContinue).Install_Dir
                if ($installPath -and (Test-Path $installPath)) {
                    if ($installPath -notin $installations) {
                        $installations += $installPath
                        Write-Verbose "Found RabbitMQ via registry: $installPath"
                    }
                }
            }
        }
    } catch {
        Write-Verbose "Registry check failed: $_"
    }

    # Check for RabbitMQ service
    try {
        $service = Get-Service -Name "RabbitMQ" -ErrorAction SilentlyContinue
        if ($service) {
            Write-Verbose "Found RabbitMQ service: $($service.DisplayName)"
            # Try to get path from service
            $servicePath = (Get-WmiObject Win32_Service -Filter "Name='RabbitMQ'" -ErrorAction SilentlyContinue).PathName
            if ($servicePath) {
                $serviceDir = Split-Path (Split-Path $servicePath -Parent) -Parent
                if ($serviceDir -and (Test-Path $serviceDir) -and ($serviceDir -notin $installations)) {
                    $installations += $serviceDir
                    Write-Verbose "Found RabbitMQ via service: $serviceDir"
                }
            }
        }
    } catch {
        Write-Verbose "Service check failed: $_"
    }

    return $installations
}

function Get-RabbitMQVersion {
    param([string]$InstallPath)

    Write-Verbose "Checking RabbitMQ version at: $InstallPath"

    # Try to find version from directory name
    if ($InstallPath -match "rabbitmq_server-(\d+\.\d+\.\d+)") {
        return $matches[1]
    }

    # Try to find version from sbin directory
    $sbinPath = Join-Path $InstallPath "sbin"
    if (Test-Path $sbinPath) {
        $versionDirs = Get-ChildItem $sbinPath -Directory -Filter "rabbitmq_server-*" -ErrorAction SilentlyContinue
        if ($versionDirs) {
            $dirName = $versionDirs[0].Name
            if ($dirName -match "rabbitmq_server-(\d+\.\d+\.\d+)") {
                return $matches[1]
            }
        }
    }

    # Try to get version from rabbitmqctl
    $rabbitmqctl = Join-Path $InstallPath "sbin\rabbitmqctl.bat"
    if (Test-Path $rabbitmqctl) {
        try {
            $versionOutput = & $rabbitmqctl status 2>&1 | Select-String "RabbitMQ version"
            if ($versionOutput -match "(\d+\.\d+\.\d+)") {
                return $matches[1]
            }
        } catch {
            Write-Verbose "Could not execute rabbitmqctl: $_"
        }
    }

    return "Unknown"
}

function Test-VersionVulnerable {
    param([string]$Version)

    if ($Version -eq "Unknown") {
        return $null  # Cannot determine
    }

    try {
        $versionParts = $Version.Split('.')
        $major = [int]$versionParts[0]
        $minor = [int]$versionParts[1]
        $patch = [int]$versionParts[2]

        # Vulnerable if version < 3.8.16
        if ($major -lt 3) {
            return $true
        } elseif ($major -eq 3 -and $minor -lt 8) {
            return $true
        } elseif ($major -eq 3 -and $minor -eq 8 -and $patch -lt 16) {
            return $true
        } else {
            return $false
        }
    } catch {
        Write-Verbose "Error parsing version: $_"
        return $null
    }
}

function Test-PluginDirectoryPermissions {
    param([string]$InstallPath)

    Write-Verbose "Checking plugin directory permissions..."

    # Find plugins directory
    $pluginsPaths = @(
        (Join-Path $InstallPath "plugins"),
        (Join-Path $InstallPath "rabbitmq_server-*\plugins")
    )

    foreach ($pluginsPath in $pluginsPaths) {
        $resolvedPaths = Resolve-Path $pluginsPath -ErrorAction SilentlyContinue

        foreach ($resolvedPath in $resolvedPaths) {
            if (Test-Path $resolvedPath) {
                Write-Verbose "Found plugins directory: $resolvedPath"

                try {
                    $acl = Get-Acl $resolvedPath

                    # Check if BUILTIN\Users or Users group has write permissions
                    foreach ($access in $acl.Access) {
                        $identity = $access.IdentityReference.Value
                        $rights = $access.FileSystemRights

                        # Check for dangerous permissions
                        if (($identity -match "BUILTIN\\Users" -or $identity -match "Users") -and 
                            ($access.AccessControlType -eq "Allow") -and
                            ($rights -match "Write|Modify|FullControl|CreateFiles|AppendData")) {

                            Write-Verbose "VULNERABLE: Users group has write access to plugins directory"
                            return @{
                                Vulnerable = $true
                                Path = $resolvedPath
                                Identity = $identity
                                Rights = $rights
                            }
                        }
                    }
                } catch {
                    Write-Verbose "Error checking ACL: $_"
                }
            }
        }
    }

    return @{
        Vulnerable = $false
        Path = $null
    }
}

# Main execution
Write-ColorOutput "`n=== CVE-2021-22117 Detection Script ===" "Cyan"
Write-ColorOutput "Scanning for vulnerable RabbitMQ installations on Windows...`n" "Cyan"

# Check if running on Windows
if ($PSVersionTable.Platform -and $PSVersionTable.Platform -ne "Win32NT") {
    Write-ColorOutput "[!] This script is designed for Windows systems only." "Yellow"
    Write-ColorOutput "[!] CVE-2021-22117 only affects Windows installations." "Yellow"
    exit 0
}

# Check if running with appropriate privileges
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
if (-not $isAdmin) {
    Write-ColorOutput "[!] Warning: Not running as Administrator. Some checks may be limited." "Yellow"
    Write-ColorOutput "[!] For complete detection, run this script as Administrator.`n" "Yellow"
}

# Find RabbitMQ installations
$installations = Get-RabbitMQInstallation

if ($installations.Count -eq 0) {
    Write-ColorOutput "[+] No RabbitMQ installations found on this system." "Green"
    Write-ColorOutput "[+] System is NOT vulnerable to CVE-2021-22117.`n" "Green"
    exit 0
}

Write-ColorOutput "[*] Found $($installations.Count) RabbitMQ installation(s)`n" "White"

$vulnerableCount = 0

foreach ($installPath in $installations) {
    Write-ColorOutput "----------------------------------------" "Gray"
    Write-ColorOutput "[*] Analyzing: $installPath" "White"

    # Get version
    $version = Get-RabbitMQVersion -InstallPath $installPath
    Write-ColorOutput "[*] Version: $version" "White"

    # Check if version is vulnerable
    $isVersionVulnerable = Test-VersionVulnerable -Version $version

    if ($isVersionVulnerable -eq $null) {
        Write-ColorOutput "[?] Could not determine if version is vulnerable" "Yellow"
        Write-ColorOutput "[!] Manual verification required" "Yellow"
    } elseif ($isVersionVulnerable) {
        Write-ColorOutput "[!] Version is VULNERABLE (< 3.8.16)" "Red"

        # Check permissions
        $permCheck = Test-PluginDirectoryPermissions -InstallPath $installPath

        if ($permCheck.Vulnerable) {
            Write-ColorOutput "[!] CRITICAL: Insecure plugin directory permissions detected!" "Red"
            Write-ColorOutput "    Path: $($permCheck.Path)" "Red"
            Write-ColorOutput "    Identity: $($permCheck.Identity)" "Red"
            Write-ColorOutput "    Rights: $($permCheck.Rights)" "Red"
            Write-ColorOutput "`n[!] This installation is VULNERABLE to CVE-2021-22117!" "Red"
            Write-ColorOutput "[!] Local users can escalate privileges to SYSTEM!" "Red"
            $vulnerableCount++
        } else {
            Write-ColorOutput "[*] Plugin directory permissions appear secure" "Yellow"
            Write-ColorOutput "[!] However, version is still outdated and should be upgraded" "Yellow"
        }
    } else {
        Write-ColorOutput "[+] Version is PATCHED (>= 3.8.16)" "Green"
        Write-ColorOutput "[+] This installation is NOT vulnerable to CVE-2021-22117" "Green"
    }

    Write-ColorOutput ""
}

# Summary
Write-ColorOutput "========================================" "Cyan"
Write-ColorOutput "DETECTION SUMMARY" "Cyan"
Write-ColorOutput "========================================" "Cyan"
Write-ColorOutput "Total installations found: $($installations.Count)" "White"
Write-ColorOutput "Vulnerable installations: $vulnerableCount" "$(if ($vulnerableCount -gt 0) { 'Red' } else { 'Green' })"

if ($vulnerableCount -gt 0) {
    Write-ColorOutput "`n[!] ACTION REQUIRED:" "Red"
    Write-ColorOutput "    1. Upgrade RabbitMQ to version 3.8.16 or later" "Yellow"
    Write-ColorOutput "    2. Review and harden plugin directory permissions" "Yellow"
    Write-ColorOutput "    3. Audit system for signs of compromise" "Yellow"
    Write-ColorOutput "    4. Review user accounts for unauthorized privilege escalation" "Yellow"
    Write-ColorOutput "`nReferences:" "White"
    Write-ColorOutput "  - CVE-2021-22117: https://nvd.nist.gov/vuln/detail/CVE-2021-22117" "Gray"
    Write-ColorOutput "  - Security Advisory: https://www.attackiq.com/2021/06/09/dsa-lpe-rabbitmq-win/" "Gray"
} else {
    Write-ColorOutput "`n[+] No vulnerable installations detected." "Green"
}

Write-ColorOutput ""

Python Detection Script

#!/usr/bin/env python3
"""
CVE-2021-22117 Detection Script
================================

This script detects RabbitMQ installations vulnerable to CVE-2021-22117
(Windows Local Privilege Escalation via insecure plugin directory permissions).

Author: Pentester
Date: November 06, 2025
CVE: CVE-2021-22117
CVSS: 7.8 (High)

Usage:
    python3 detect_cve_2021_22117.py
    python3 detect_cve_2021_22117.py --verbose
"""

import os
import sys
import re
import subprocess
import argparse
from pathlib import Path
from typing import List, Dict, Optional, Tuple

# Color codes for terminal output
class Colors:
    RED = '\033[91m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    BLUE = '\033[94m'
    CYAN = '\033[96m'
    WHITE = '\033[97m'
    GRAY = '\033[90m'
    RESET = '\033[0m'
    BOLD = '\033[1m'

def print_color(message: str, color: str = Colors.WHITE):
    """Print colored message to terminal"""
    print(f"{color}{message}{Colors.RESET}")

def is_windows() -> bool:
    """Check if running on Windows"""
    return sys.platform.startswith('win')

def is_admin() -> bool:
    """Check if script is running with admin privileges"""
    if not is_windows():
        return os.geteuid() == 0

    try:
        import ctypes
        return ctypes.windll.shell32.IsUserAnAdmin() != 0
    except:
        return False

def find_rabbitmq_installations() -> List[str]:
    """Find RabbitMQ installations on the system"""
    installations = []

    if is_windows():
        # Common Windows installation paths
        common_paths = [
            r"C:\Program Files\RabbitMQ Server",
            r"C:\Program Files (x86)\RabbitMQ Server",
            r"C:\tools\RabbitMQ",
        ]

        # Add environment variable paths
        program_files = os.environ.get('ProgramFiles', '')
        program_files_x86 = os.environ.get('ProgramFiles(x86)', '')

        if program_files:
            common_paths.append(os.path.join(program_files, 'RabbitMQ Server'))
        if program_files_x86:
            common_paths.append(os.path.join(program_files_x86, 'RabbitMQ Server'))

        for path in common_paths:
            if os.path.exists(path):
                installations.append(path)

        # Try to find via registry (Windows only)
        try:
            import winreg
            reg_paths = [
                (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\VMware, Inc.\RabbitMQ Server"),
                (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\WOW6432Node\VMware, Inc.\RabbitMQ Server"),
                (winreg.HKEY_LOCAL_MACHINE, r"SOFTWARE\Pivotal\RabbitMQ Server"),
            ]

            for hkey, subkey in reg_paths:
                try:
                    key = winreg.OpenKey(hkey, subkey)
                    install_dir, _ = winreg.QueryValueEx(key, "Install_Dir")
                    winreg.CloseKey(key)
                    if install_dir and os.path.exists(install_dir):
                        if install_dir not in installations:
                            installations.append(install_dir)
                except WindowsError:
                    pass
        except ImportError:
            pass
    else:
        # Linux/Unix paths
        common_paths = [
            "/usr/lib/rabbitmq",
            "/opt/rabbitmq",
            "/usr/local/rabbitmq",
        ]

        for path in common_paths:
            if os.path.exists(path):
                installations.append(path)

    return installations

def get_rabbitmq_version(install_path: str) -> str:
    """Get RabbitMQ version from installation"""

    # Try to extract from directory name
    match = re.search(r'rabbitmq_server-(\d+\.\d+\.\d+)', install_path)
    if match:
        return match.group(1)

    # Try to find version in sbin directory
    sbin_path = os.path.join(install_path, 'sbin')
    if os.path.exists(sbin_path):
        for item in os.listdir(sbin_path):
            match = re.search(r'rabbitmq_server-(\d+\.\d+\.\d+)', item)
            if match:
                return match.group(1)

    # Try to execute rabbitmqctl
    rabbitmqctl = os.path.join(install_path, 'sbin', 'rabbitmqctl')
    if is_windows():
        rabbitmqctl += '.bat'

    if os.path.exists(rabbitmqctl):
        try:
            result = subprocess.run(
                [rabbitmqctl, 'status'],
                capture_output=True,
                text=True,
                timeout=10
            )
            match = re.search(r'RabbitMQ version[:\s]+(\d+\.\d+\.\d+)', result.stdout)
            if match:
                return match.group(1)
        except Exception:
            pass

    return "Unknown"

def is_version_vulnerable(version: str) -> Optional[bool]:
    """Check if version is vulnerable to CVE-2021-22117"""
    if version == "Unknown":
        return None

    try:
        major, minor, patch = map(int, version.split('.'))

        # Vulnerable if version < 3.8.16
        if major < 3:
            return True
        elif major == 3 and minor < 8:
            return True
        elif major == 3 and minor == 8 and patch < 16:
            return True
        else:
            return False
    except Exception:
        return None

def check_plugin_directory_permissions(install_path: str) -> Dict:
    """Check if plugin directory has insecure permissions"""

    # Find plugins directory
    plugins_paths = [
        os.path.join(install_path, 'plugins'),
    ]

    # Also check subdirectories
    try:
        for item in os.listdir(install_path):
            item_path = os.path.join(install_path, item)
            if os.path.isdir(item_path) and 'rabbitmq_server' in item:
                plugins_paths.append(os.path.join(item_path, 'plugins'))
    except Exception:
        pass

    for plugins_path in plugins_paths:
        if os.path.exists(plugins_path):
            if is_windows():
                return check_windows_permissions(plugins_path)
            else:
                return check_unix_permissions(plugins_path)

    return {'vulnerable': False, 'path': None, 'details': 'Plugins directory not found'}

def check_windows_permissions(path: str) -> Dict:
    """Check Windows ACL permissions"""
    try:
        import win32security
        import ntsecuritycon as con

        # Get security descriptor
        sd = win32security.GetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION)
        dacl = sd.GetSecurityDescriptorDacl()

        if dacl is None:
            return {'vulnerable': True, 'path': path, 'details': 'No DACL (NULL DACL - everyone has full access)'}

        # Check each ACE in the DACL
        for i in range(dacl.GetAceCount()):
            ace = dacl.GetAce(i)
            ace_type, ace_flags, permissions, sid = ace

            try:
                account, domain, type = win32security.LookupAccountSid(None, sid)
                identity = f"{domain}\\{account}" if domain else account

                # Check if Users group has write permissions
                if 'Users' in identity or 'BUILTIN\\Users' in identity:
                    # Check for dangerous permissions
                    dangerous_perms = [
                        con.FILE_WRITE_DATA,
                        con.FILE_APPEND_DATA,
                        con.FILE_ADD_FILE,
                        con.FILE_ADD_SUBDIRECTORY,
                        con.GENERIC_WRITE,
                        con.GENERIC_ALL,
                        con.FILE_ALL_ACCESS
                    ]

                    for perm in dangerous_perms:
                        if permissions & perm:
                            return {
                                'vulnerable': True,
                                'path': path,
                                'identity': identity,
                                'permissions': hex(permissions),
                                'details': f'Users group has write access ({hex(perm)})'
                            }
            except Exception:
                pass

        return {'vulnerable': False, 'path': path, 'details': 'Permissions appear secure'}

    except ImportError:
        # pywin32 not available, try icacls
        try:
            result = subprocess.run(
                ['icacls', path],
                capture_output=True,
                text=True,
                timeout=5
            )

            # Check if Users group has write permissions in icacls output
            if 'BUILTIN\\Users' in result.stdout or 'Users:' in result.stdout:
                for line in result.stdout.split('\n'):
                    if 'Users' in line and any(perm in line for perm in ['(W)', '(M)', '(F)', 'WD', 'AD']):
                        return {
                            'vulnerable': True,
                            'path': path,
                            'details': f'Users group has write permissions: {line.strip()}'
                        }

            return {'vulnerable': False, 'path': path, 'details': 'Permissions appear secure'}
        except Exception as e:
            return {'vulnerable': None, 'path': path, 'details': f'Could not check permissions: {e}'}
    except Exception as e:
        return {'vulnerable': None, 'path': path, 'details': f'Error checking permissions: {e}'}

def check_unix_permissions(path: str) -> Dict:
    """Check Unix file permissions"""
    try:
        stat_info = os.stat(path)
        mode = stat_info.st_mode

        # Check if others have write permission (world-writable)
        if mode & 0o002:
            return {
                'vulnerable': True,
                'path': path,
                'details': f'Directory is world-writable (permissions: {oct(mode)[-3:]})'
            }

        # Check if group has write permission and group is not restricted
        if mode & 0o020:
            return {
                'vulnerable': True,
                'path': path,
                'details': f'Directory is group-writable (permissions: {oct(mode)[-3:]})'
            }

        return {'vulnerable': False, 'path': path, 'details': 'Permissions appear secure'}
    except Exception as e:
        return {'vulnerable': None, 'path': path, 'details': f'Error checking permissions: {e}'}

def main():
    parser = argparse.ArgumentParser(description='Detect CVE-2021-22117 vulnerability in RabbitMQ')
    parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose output')
    args = parser.parse_args()

    print_color("\n=== CVE-2021-22117 Detection Script ===", Colors.CYAN + Colors.BOLD)
    print_color("Scanning for vulnerable RabbitMQ installations...\n", Colors.CYAN)

    # Check platform
    if not is_windows():
        print_color("[!] Note: CVE-2021-22117 specifically affects Windows installations.", Colors.YELLOW)
        print_color("[!] This script will still check for outdated versions.\n", Colors.YELLOW)

    # Check privileges
    if not is_admin():
        print_color("[!] Warning: Not running with administrator privileges.", Colors.YELLOW)
        print_color("[!] Some checks may be limited. Run as admin for complete detection.\n", Colors.YELLOW)

    # Find installations
    installations = find_rabbitmq_installations()

    if not installations:
        print_color("[+] No RabbitMQ installations found on this system.", Colors.GREEN)
        print_color("[+] System is NOT vulnerable to CVE-2021-22117.\n", Colors.GREEN)
        return 0

    print_color(f"[*] Found {len(installations)} RabbitMQ installation(s)\n", Colors.WHITE)

    vulnerable_count = 0

    for install_path in installations:
        print_color("----------------------------------------", Colors.GRAY)
        print_color(f"[*] Analyzing: {install_path}", Colors.WHITE)

        # Get version
        version = get_rabbitmq_version(install_path)
        print_color(f"[*] Version: {version}", Colors.WHITE)

        # Check if version is vulnerable
        is_vulnerable = is_version_vulnerable(version)

        if is_vulnerable is None:
            print_color("[?] Could not determine if version is vulnerable", Colors.YELLOW)
            print_color("[!] Manual verification required", Colors.YELLOW)
        elif is_vulnerable:
            print_color("[!] Version is VULNERABLE (< 3.8.16)", Colors.RED)

            # Check permissions
            perm_check = check_plugin_directory_permissions(install_path)

            if args.verbose:
                print_color(f"[*] Permission check details: {perm_check.get('details', 'N/A')}", Colors.GRAY)

            if perm_check.get('vulnerable') is True:
                print_color("[!] CRITICAL: Insecure plugin directory permissions detected!", Colors.RED + Colors.BOLD)
                print_color(f"    Path: {perm_check.get('path')}", Colors.RED)
                if 'identity' in perm_check:
                    print_color(f"    Identity: {perm_check.get('identity')}", Colors.RED)
                if 'permissions' in perm_check:
                    print_color(f"    Permissions: {perm_check.get('permissions')}", Colors.RED)
                print_color("\n[!] This installation is VULNERABLE to CVE-2021-22117!", Colors.RED + Colors.BOLD)
                print_color("[!] Local users can escalate privileges to SYSTEM!", Colors.RED + Colors.BOLD)
                vulnerable_count += 1
            elif perm_check.get('vulnerable') is False:
                print_color("[*] Plugin directory permissions appear secure", Colors.YELLOW)
                print_color("[!] However, version is still outdated and should be upgraded", Colors.YELLOW)
            else:
                print_color("[?] Could not verify plugin directory permissions", Colors.YELLOW)
                print_color("[!] Manual verification recommended", Colors.YELLOW)
        else:
            print_color("[+] Version is PATCHED (>= 3.8.16)", Colors.GREEN)
            print_color("[+] This installation is NOT vulnerable to CVE-2021-22117", Colors.GREEN)

        print()

    # Summary
    print_color("========================================", Colors.CYAN)
    print_color("DETECTION SUMMARY", Colors.CYAN + Colors.BOLD)
    print_color("========================================", Colors.CYAN)
    print_color(f"Total installations found: {len(installations)}", Colors.WHITE)

    if vulnerable_count > 0:
        print_color(f"Vulnerable installations: {vulnerable_count}", Colors.RED + Colors.BOLD)
        print_color("\n[!] ACTION REQUIRED:", Colors.RED + Colors.BOLD)
        print_color("    1. Upgrade RabbitMQ to version 3.8.16 or later", Colors.YELLOW)
        print_color("    2. Review and harden plugin directory permissions", Colors.YELLOW)
        print_color("    3. Audit system for signs of compromise", Colors.YELLOW)
        print_color("    4. Review user accounts for unauthorized privilege escalation", Colors.YELLOW)
        print_color("\nReferences:", Colors.WHITE)
        print_color("  - CVE-2021-22117: https://nvd.nist.gov/vuln/detail/CVE-2021-22117", Colors.GRAY)
        print_color("  - Security Advisory: https://www.attackiq.com/2021/06/09/dsa-lpe-rabbitmq-win/", Colors.GRAY)
        return 1
    else:
        print_color(f"Vulnerable installations: {vulnerable_count}", Colors.GREEN)
        print_color("\n[+] No vulnerable installations detected.", Colors.GREEN)
        return 0

if __name__ == '__main__':
    try:
        sys.exit(main())
    except KeyboardInterrupt:
        print_color("\n\n[!] Scan interrupted by user.", Colors.YELLOW)
        sys.exit(130)
    except Exception as e:
        print_color(f"\n[!] Error: {e}", Colors.RED)
        sys.exit(1)

Bash Detection Script

#!/bin/bash

################################################################################
# RabbitMQ Vulnerability Scanner
# 
# This script performs remote vulnerability scanning of RabbitMQ installations
# to detect various CVEs and misconfigurations.
#
# Author: Pentester
# Date: November 06, 2025
#
# Usage:
#   ./scan_rabbitmq_vulnerabilities.sh <target_host> [options]
#
# Options:
#   -u, --user <username>       Username for authentication (default: guest)
#   -p, --password <password>   Password for authentication (default: guest)
#   -P, --port <port>          Management UI port (default: 15672)
#   -v, --verbose              Enable verbose output
#   -h, --help                 Show this help message
#
# Examples:
#   ./scan_rabbitmq_vulnerabilities.sh 192.168.1.100
#   ./scan_rabbitmq_vulnerabilities.sh example.com -u admin -p password
################################################################################

set -euo pipefail

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
GRAY='\033[0;90m'
BOLD='\033[1m'
NC='\033[0m' # No Color

# Default values
TARGET=""
USERNAME="guest"
PASSWORD="guest"
MGMT_PORT="15672"
VERBOSE=false

# Vulnerability tracking
VULN_COUNT=0
FINDINGS=()

################################################################################
# Helper Functions
################################################################################

print_banner() {
    echo -e "${CYAN}${BOLD}"
    echo "╔════════════════════════════════════════════════════════════╗"
    echo "║         RabbitMQ Vulnerability Scanner                    ║"
    echo "║         CVE Detection & Security Assessment                ║"
    echo "╚════════════════════════════════════════════════════════════╝"
    echo -e "${NC}"
}

print_section() {
    echo -e "\n${CYAN}${BOLD}[*] $1${NC}"
}

print_success() {
    echo -e "${GREEN}[+] $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}[!] $1${NC}"
}

print_error() {
    echo -e "${RED}[-] $1${NC}"
}

print_info() {
    echo -e "${BLUE}[i] $1${NC}"
}

print_verbose() {
    if [ "$VERBOSE" = true ]; then
        echo -e "${GRAY}[v] $1${NC}"
    fi
}

add_finding() {
    local severity=$1
    local message=$2
    FINDINGS+=("[$severity] $message")
    ((VULN_COUNT++))
}

usage() {
    echo "Usage: $0 <target_host> [options]"
    echo ""
    echo "Options:"
    echo "  -u, --user <username>       Username for authentication (default: guest)"
    echo "  -p, --password <password>   Password for authentication (default: guest)"
    echo "  -P, --port <port>          Management UI port (default: 15672)"
    echo "  -v, --verbose              Enable verbose output"
    echo "  -h, --help                 Show this help message"
    echo ""
    echo "Examples:"
    echo "  $0 192.168.1.100"
    echo "  $0 example.com -u admin -p password"
    exit 1
}

################################################################################
# Parsing Arguments
################################################################################

if [ $# -eq 0 ]; then
    usage
fi

TARGET=$1
shift

while [[ $# -gt 0 ]]; do
    case $1 in
        -u|--user)
            USERNAME="$2"
            shift 2
            ;;
        -p|--password)
            PASSWORD="$2"
            shift 2
            ;;
        -P|--port)
            MGMT_PORT="$2"
            shift 2
            ;;
        -v|--verbose)
            VERBOSE=true
            shift
            ;;
        -h|--help)
            usage
            ;;
        *)
            echo "Unknown option: $1"
            usage
            ;;
    esac
done

################################################################################
# Vulnerability Checks
################################################################################

check_port_accessibility() {
    print_section "Port Accessibility Check"

    # Check AMQP port (5672)
    if timeout 3 bash -c "cat < /dev/null > /dev/tcp/$TARGET/5672" 2>/dev/null; then
        print_warning "AMQP port 5672 is accessible"
        add_finding "MEDIUM" "Unencrypted AMQP port 5672 is accessible from external network"
    else
        print_verbose "AMQP port 5672 is not accessible"
    fi

    # Check Management UI port (15672)
    if timeout 3 bash -c "cat < /dev/null > /dev/tcp/$TARGET/$MGMT_PORT" 2>/dev/null; then
        print_warning "Management UI port $MGMT_PORT is accessible"
        add_finding "MEDIUM" "Management UI port $MGMT_PORT is accessible from external network"
    else
        print_error "Management UI port $MGMT_PORT is not accessible"
        print_info "Cannot perform further checks without management API access"
        exit 1
    fi

    # Check Erlang distribution port (25672)
    if timeout 3 bash -c "cat < /dev/null > /dev/tcp/$TARGET/25672" 2>/dev/null; then
        print_error "Erlang distribution port 25672 is accessible!"
        add_finding "CRITICAL" "Erlang distribution port 25672 is exposed to external network - RCE risk if cookie is compromised"
    else
        print_success "Erlang distribution port 25672 is not accessible"
    fi
}

check_version() {
    print_section "Version Detection"

    local response
    response=$(curl -s -u "$USERNAME:$PASSWORD" "http://$TARGET:$MGMT_PORT/api/overview" 2>/dev/null)

    if [ -z "$response" ]; then
        print_error "Failed to retrieve version information"
        return 1
    fi

    local version
    version=$(echo "$response" | grep -oP '"rabbitmq_version"\s*:\s*"\K[^"]+' 2>/dev/null)

    if [ -z "$version" ]; then
        print_warning "Could not extract version from API response"
        return 1
    fi

    print_info "Detected version: $version"

    # Check for known vulnerable versions
    check_version_vulnerabilities "$version"
}

check_version_vulnerabilities() {
    local version=$1
    local major minor patch

    # Parse version
    IFS='.' read -r major minor patch <<< "$version"

    # CVE-2021-22117 (< 3.8.16)
    if [ "$major" -lt 3 ] || ([ "$major" -eq 3 ] && [ "$minor" -lt 8 ]) || ([ "$major" -eq 3 ] && [ "$minor" -eq 8 ] && [ "$patch" -lt 16 ]); then
        print_error "Vulnerable to CVE-2021-22117 (Windows LPE)"
        add_finding "HIGH" "CVE-2021-22117: Version $version is vulnerable to Windows Local Privilege Escalation"
    fi

    # CVE-2021-22116 (< 3.8.16)
    if [ "$major" -lt 3 ] || ([ "$major" -eq 3 ] && [ "$minor" -lt 8 ]) || ([ "$major" -eq 3 ] && [ "$minor" -eq 8 ] && [ "$patch" -lt 16 ]); then
        print_error "Vulnerable to CVE-2021-22116 (DoS)"
        add_finding "HIGH" "CVE-2021-22116: Version $version is vulnerable to Denial of Service via AMQP 1.0"
    fi

    # CVE-2022-31008 (< 3.10.2, < 3.9.18, < 3.8.32)
    if [ "$major" -lt 3 ] || \
       ([ "$major" -eq 3 ] && [ "$minor" -lt 8 ]) || \
       ([ "$major" -eq 3 ] && [ "$minor" -eq 8 ] && [ "$patch" -lt 32 ]) || \
       ([ "$major" -eq 3 ] && [ "$minor" -eq 9 ] && [ "$patch" -lt 18 ]) || \
       ([ "$major" -eq 3 ] && [ "$minor" -eq 10 ] && [ "$patch" -lt 2 ]); then
        print_error "Vulnerable to CVE-2022-31008 (Credential Exposure)"
        add_finding "MEDIUM" "CVE-2022-31008: Version $version has predictable URI obfuscation in Shovel/Federation"
    fi

    # CVE-2023-46118 (< 3.11.24, < 3.12.7)
    if [ "$major" -lt 3 ] || \
       ([ "$major" -eq 3 ] && [ "$minor" -lt 11 ]) || \
       ([ "$major" -eq 3 ] && [ "$minor" -eq 11 ] && [ "$patch" -lt 24 ]) || \
       ([ "$major" -eq 3 ] && [ "$minor" -eq 12 ] && [ "$patch" -lt 7 ]); then
        print_error "Vulnerable to CVE-2023-46118 (DoS)"
        add_finding "MEDIUM" "CVE-2023-46118: Version $version is vulnerable to DoS via large HTTP API messages"
    fi

    # CVE-2025-50200 (<= 3.13.7)
    if [ "$major" -lt 3 ] || \
       ([ "$major" -eq 3 ] && [ "$minor" -lt 13 ]) || \
       ([ "$major" -eq 3 ] && [ "$minor" -eq 13 ] && [ "$patch" -le 7 ]); then
        print_error "Vulnerable to CVE-2025-50200 (Credential Logging)"
        add_finding "MEDIUM" "CVE-2025-50200: Version $version logs Basic Auth credentials in plaintext"
    fi

    # CVE-2025-30219 (< 4.0.3)
    if [ "$major" -lt 4 ] || ([ "$major" -eq 4 ] && [ "$minor" -eq 0 ] && [ "$patch" -lt 3 ]); then
        print_error "Vulnerable to CVE-2025-30219 (XSS)"
        add_finding "MEDIUM" "CVE-2025-30219: Version $version is vulnerable to XSS in management UI"
    fi
}

check_default_credentials() {
    print_section "Default Credentials Check"

    local response
    response=$(curl -s -u "guest:guest" "http://$TARGET:$MGMT_PORT/api/whoami" 2>/dev/null)

    if echo "$response" | grep -q "guest"; then
        print_error "Default credentials (guest:guest) are ACTIVE!"
        add_finding "CRITICAL" "Default guest:guest credentials are enabled and accessible remotely"
    else
        print_success "Default credentials are not accessible remotely"
    fi
}

check_users() {
    print_section "User Enumeration"

    local response
    response=$(curl -s -u "$USERNAME:$PASSWORD" "http://$TARGET:$MGMT_PORT/api/users" 2>/dev/null)

    if [ -z "$response" ]; then
        print_error "Failed to enumerate users (authentication failed or insufficient permissions)"
        return 1
    fi

    local user_count
    user_count=$(echo "$response" | grep -o '"name"' | wc -l)

    print_info "Found $user_count user(s)"

    # Check for guest user
    if echo "$response" | grep -q '"name":"guest"'; then
        print_warning "Guest user exists on the system"
        add_finding "LOW" "Guest user account still exists (should be deleted in production)"
    fi

    # List admin users
    local admin_users
    admin_users=$(echo "$response" | grep -B2 '"administrator"' | grep -oP '"name"\s*:\s*"\K[^"]+' || true)

    if [ -n "$admin_users" ]; then
        print_info "Administrator users: $admin_users"
    fi
}

check_vhosts() {
    print_section "Virtual Hosts Check"

    local response
    response=$(curl -s -u "$USERNAME:$PASSWORD" "http://$TARGET:$MGMT_PORT/api/vhosts" 2>/dev/null)

    if [ -z "$response" ]; then
        print_error "Failed to enumerate virtual hosts"
        return 1
    fi

    local vhost_count
    vhost_count=$(echo "$response" | grep -o '"name"' | wc -l)

    print_info "Found $vhost_count virtual host(s)"

    # Check if only default vhost exists
    if [ "$vhost_count" -eq 1 ] && echo "$response" | grep -q '"name":"/"'; then
        print_warning "Only default virtual host (/) exists"
        print_info "Consider using separate vhosts for multi-tenant environments"
    fi
}

check_tls_configuration() {
    print_section "TLS/SSL Configuration Check"

    # Check if HTTPS is available on management port
    if timeout 3 bash -c "echo | openssl s_client -connect $TARGET:15671 2>/dev/null" | grep -q "CONNECTED"; then
        print_success "HTTPS is available on port 15671"
    else
        print_warning "HTTPS does not appear to be configured on port 15671"
        add_finding "MEDIUM" "Management UI is not configured with HTTPS"
    fi

    # Check if AMQPS is available
    if timeout 3 bash -c "echo | openssl s_client -connect $TARGET:5671 2>/dev/null" | grep -q "CONNECTED"; then
        print_success "AMQPS is available on port 5671"
    else
        print_warning "AMQPS does not appear to be configured on port 5671"
        add_finding "MEDIUM" "AMQP is not configured with TLS encryption"
    fi
}

check_plugins() {
    print_section "Enabled Plugins Check"

    local response
    response=$(curl -s -u "$USERNAME:$PASSWORD" "http://$TARGET:$MGMT_PORT/api/overview" 2>/dev/null)

    if [ -z "$response" ]; then
        print_error "Failed to retrieve plugin information"
        return 1
    fi

    # Check for management plugin (obviously enabled if we got here)
    print_info "Management plugin is enabled"

    # Check for potentially risky plugins
    if echo "$response" | grep -q "rabbitmq_federation"; then
        print_warning "Federation plugin is enabled"
        print_info "Ensure federation URIs are properly secured (CVE-2022-31008)"
    fi

    if echo "$response" | grep -q "rabbitmq_shovel"; then
        print_warning "Shovel plugin is enabled"
        print_info "Monitor shovel configurations for data exfiltration"
    fi
}

################################################################################
# Main Execution
################################################################################

main() {
    print_banner

    print_info "Target: $TARGET"
    print_info "Management Port: $MGMT_PORT"
    print_info "Username: $USERNAME"
    echo ""

    # Run checks
    check_port_accessibility
    check_default_credentials
    check_version
    check_users
    check_vhosts
    check_tls_configuration
    check_plugins

    # Print summary
    echo ""
    echo -e "${CYAN}${BOLD}╔════════════════════════════════════════════════════════════╗${NC}"
    echo -e "${CYAN}${BOLD}║                    SCAN SUMMARY                            ║${NC}"
    echo -e "${CYAN}${BOLD}╚════════════════════════════════════════════════════════════╝${NC}"
    echo ""

    if [ $VULN_COUNT -eq 0 ]; then
        print_success "No critical vulnerabilities detected"
    else
        print_error "Found $VULN_COUNT security issue(s):"
        echo ""
        for finding in "${FINDINGS[@]}"; do
            echo -e "  ${RED}•${NC} $finding"
        done
        echo ""
        print_warning "RECOMMENDATIONS:"
        echo "  1. Upgrade RabbitMQ to the latest stable version"
        echo "  2. Remove or disable the guest user account"
        echo "  3. Enable TLS/SSL for all connections"
        echo "  4. Restrict network access to RabbitMQ ports"
        echo "  5. Implement strong authentication and authorization"
        echo "  6. Regular security audits and monitoring"
    fi

    echo ""
    print_info "Scan completed at $(date)"
    echo ""
}

# Run main function
main

Comments

Popular posts from this blog

Tutorial: Build an AI Penetration Tester with Claude (MCP + Burp)

InfluxDB TCP 8086 (Default) — Authentication Bypass & Pentest Notes

Mastering PowerShell Execution Policy Bypass