MongoDB - Port 27017, 27018

Basic info

MongoDB has become one of the most popular NoSQL databases in modern application development, powering everything from startups to Fortune 500 companies. However, its flexibility and rapid deployment capabilities often lead to significant security misconfigurations. This comprehensive guide walks through the complete methodology for penetration testing MongoDB installations, from initial reconnaissance to post-exploitation.

Why MongoDB is a Prime Target

  • Default Configurations: Many MongoDB instances ship with authentication disabled by default

  • Internet Exposure: Thousands of MongoDB instances are directly exposed to the internet

  • Sensitive Data: MongoDB often stores user credentials, API keys, PII, and business-critical information

  • Quick Deployment: DevOps teams frequently prioritize speed over security during deployment

Key Ports

Port
Service
Description

27017

MongoDB Primary Port

Default port for client connections

27018

MongoDB Shard Port

Used in sharded cluster configurations

27019

MongoDB Config Server

Configuration server in replica sets

28017

HTTP Status Interface

Web-based status interface (deprecated in newer versions)


MongoDB Architecture & Security Overview <a name="architecture"></a>

Database Structure

MongoDB uses a hierarchical structure:

Default Databases

Understanding default databases is crucial for pentesting:

  • admin: Administrative database containing user credentials and system information

  • config: Stores configuration data for sharded clusters

  • local: Stores data specific to a single server (replica set data)

  • test: Default database for testing (often left with data)

Authentication Mechanisms

MongoDB supports multiple authentication methods:

  1. SCRAM (Default): Salted Challenge Response Authentication Mechanism

  2. x.509 Certificate Authentication: Certificate-based authentication

  3. LDAP: External LDAP server integration

  4. Kerberos: Enterprise authentication

  5. AWS IAM: For MongoDB Atlas

Authorization Model

MongoDB uses Role-Based Access Control (RBAC):

Built-in Roles:

  • read: Read data from all non-system collections

  • readWrite: Read and modify data

  • dbAdmin: Database administration tasks

  • userAdmin: Create and modify users and roles

  • clusterAdmin: Cluster management operations

  • root: Superuser access (combine all privileges)


Reconnaissance & Information Gathering

1. Network Scanning

Basic Port Discovery

Expected Output:

Advanced Scanning with NSE Scripts

2. OSINT & Shodan Reconnaissance

Shodan Queries

Finding exposed MongoDB instances globally:

Censys Queries

3. Fingerprinting MongoDB Version

Different methods to identify MongoDB version:

Using Python

Using Mongo Shell

4. Banner Grabbing


Enumeration Techniques

1. Checking Authentication Requirements

Method 1: Configuration File Analysis (Post-Access)

Method 2: Direct Connection Test

2. Database Enumeration

Complete Enumeration Script

3. Targeted Collection Queries

4. Searching for Sensitive Data


Authentication & Authorization Testing

1. Default Credentials Testing

Common MongoDB default scenarios:

2. Brute Force Attacks

Using Hydra

Using Nmap NSE Script

Custom Python Brute Force Script

3. Authentication Bypass Techniques

NoSQL Injection in Login Forms

When MongoDB is used with web applications, login forms may be vulnerable to NoSQL injection:

Vulnerable code example:

Exploitation:

This bypasses authentication because {$ne: null} matches any document where username and password are not null.

Other injection payloads:

JavaScript Injection via $where

4. Privilege Escalation

From Read-Only to Read-Write

If you have read access to the admin database, you can enumerate users and attempt to:

Exploiting Weak Role Assignments


Exploitation Techniques

1. Data Exfiltration

Full Database Dump

Programmatic Dump

2. Malicious Data Injection

Inserting Backdoor Accounts

Web Shell Upload via GridFS

3. Server-Side JavaScript Execution

MongoDB allows executing JavaScript on the server side:

Note: db.eval() is deprecated and disabled by default in MongoDB 3.0+, but may still work on older installations.

MapReduce Code Execution

4. Denial of Service Attacks

Resource Exhaustion

Crash via Malformed Queries


Post-Exploitation

1. Persistence Mechanisms

Creating Hidden Admin User

Scheduled Backup Exfiltration

Create a cron job to periodically dump and exfiltrate data:

2. Lateral Movement

Discovering Other Databases/Hosts

3. Pivoting Through MongoDB

Using MongoDB as a Proxy

If MongoDB server has network access to internal resources:


Critical Vulnerabilities

1. CVE-2025-14847: MongoBleed (Memory Disclosure)

MongoBleed is a critical unauthenticated memory disclosure vulnerability affecting MongoDB versions 3.6 through 8.2 when zlib compression is enabled.

Vulnerability Details

The vulnerability exists in how MongoDB handles the OP_COMPRESSED protocol message:

  1. Attacker sends: OP_COMPRESSED message with maliciously large uncompressedSize value

  2. Server allocates: Buffer based on attacker-controlled size

  3. Decompression: Small compressed payload decompresses into much smaller data

  4. Memory leak: Remaining buffer contains uninitialized heap data

  5. Exploitation: Omit BSON null terminator, causing parser to scan leaked memory

  6. Data exfiltration: Error messages echo both malicious document and leaked heap bytes

What can be leaked:

  • Authentication credentials from other connections

  • API keys and tokens

  • Session tokens

  • WiredTiger cache contents

  • /proc filesystem data

  • Data from concurrent connections

Affected Versions

  • MongoDB 3.6.x (all versions)

  • MongoDB 4.0.x (all versions)

  • MongoDB 4.2.x (all versions)

  • MongoDB 4.4.0 - 4.4.29

  • MongoDB 5.0.0 - 5.0.31

  • MongoDB 6.0.0 - 6.0.26

  • MongoDB 7.0.0 - 7.0.27

  • MongoDB 8.0.0 - 8.0.16

  • MongoDB 8.2.0 - 8.2.2

Checking if Instance is Vulnerable

Exploitation

Using Public PoC:

Manual exploitation concept:

Detection

Network-based detection:

Log-based detection:

Cortex XQL detection query:

Mitigation

  1. Immediate: Upgrade to patched versions

    • MongoDB 4.4.30+

    • MongoDB 5.0.32+

    • MongoDB 6.0.27+

    • MongoDB 7.0.28+

    • MongoDB 8.0.17+

    • MongoDB 8.2.3+

  2. Temporary: Disable zlib compression

  1. Network segmentation: Restrict MongoDB access

  2. Monitoring: Implement connection rate monitoring

2. CVE-2020-7928: Privilege Escalation

Affects MongoDB Server 4.2.x before 4.2.3:

3. MongoDB Injection Vulnerabilities

Where Clause Injection

Operator Injection

4. ObjectId Prediction (IDOR)

MongoDB ObjectIds are predictable:

Structure: [4-byte timestamp][5-byte random][3-byte counter]

Example: 5f2459ac9fa6dc2500314019

  • 5f2459ac = Timestamp (1596217772 = July 31, 2020 17:49:32)

  • 9fa6dc = Machine ID

  • 2500 = Process ID

  • 314019 = Counter

Exploitation

Using mongo-objectid-predict tool:


Defense & Hardening

1. Authentication & Authorization

Enable Authentication

Implement Role-Based Access Control

2. Network Security

Bind to Specific Interface

Firewall Rules

Enable TLS/SSL

3. Encryption

Encryption at Rest

Encryption in Transit

Always use TLS for client-server and server-server communication:

4. Disable Dangerous Features

5. Auditing & Logging

6. Regular Security Practices

Keep MongoDB Updated

Regular Backups

Security Monitoring

7. Configuration Hardening Checklist


Practical Lab Scenarios <a name="lab-scenarios"></a>

Scenario 1: Unauthenticated MongoDB

Setup:

Exploitation Steps:

  1. Discovery

  1. Connection

  1. Enumeration

  1. Data Exfiltration

  1. Backdoor Creation

Scenario 2: NoSQL Injection

Vulnerable Application:

Exploitation:

Scenario 3: Privilege Escalation

Initial Access: Read-only user on app database

Scenario 4: MongoBleed Exploitation

Testing Environment:

Exploitation:


Conclusion

MongoDB security requires a multi-layered approach:

  1. Never expose MongoDB directly to the internet

  2. Always enable authentication and use strong passwords

  3. Implement role-based access control with least privilege

  4. Enable TLS/SSL for all connections

  5. Disable JavaScript execution unless absolutely necessary

  6. Keep MongoDB updated to the latest stable version

  7. Regular security audits and penetration testing

  8. Monitor logs for suspicious activity

  9. Implement network segmentation and firewall rules

  10. Regular backups and disaster recovery planning

Remember: Security is not a one-time configuration but an ongoing process. Stay informed about new vulnerabilities, apply patches promptly, and regularly review your security posture.


Additional Resources

Tools

  • NoSQLMap: Automated NoSQL injection and exploitation

  • mongoaudit: MongoDB security audit tool

  • MongoDB Compass: Official GUI for MongoDB exploration

  • Studio 3T: Advanced MongoDB IDE with security features

circle-check

Last updated