MongoDB Pentesting

MongoDB is a NoSQL database program. Default ports are 27017, 27018.

Enumeration

nmap --script mongodb-info -p 27017 <target-ip>
nmap --script mongodb-databases -p 27017 <target-ip>

Brute Force Credentials

hydra -l username -P passwords.txt <target-ip> mysql
hydra -L usernames.txt -p password <target-ip> mysql


Connect

# Local
mongo
mongo --port 27017

# Remote
mongo --host <target-ip> --port 27017 -u username -p password
mongo "mongodb://<target-ip>:27017"
mongo "mongodb://username:password@<target-ip>:27017/?authSource=admin"


Basic Commands

# All databases
> show dbs
# Current database
> db
# Switch database if it exists, or create new if not exist
> use db_name
# Collections
> show collections
# Run javascript file
> load("example.js")

# List users in the current database
> show users
> db.admin.find()

# Create new collection in current database
> db.createCollection("users")

CRUD

# Create
> db.<collection_name>.insert({id: "1", username: "admin"})
# Read
> db.<collection_name>.find()
> db.<collection_name>.findOne({"username":"michael"})
# Update
> db.<collection_name>.update({id: "1"}, {$set: {username: "king"}})
# Delete
> db.<collection_name>.remove({"name": "Micael"})
# Delete all documents
> db.<collection_name>.remove({})

Operators

# $eq: equal
# ex. username is "admin"
db.<collection_name>.findOne({username: {"$eq": "admin"}})

# $ne: not equal
# ex. password is not "xyz"
db.<collection_name>.findOne({id: "1"}, {password: {"$ne": "xyz"}})

# $gt: greater than
# ex. id is greater than 2
db.<collection_name>.findOne({id: {"$gt": "2"}})

# $where:

# $exists:

# $regex: 

Operators (Aggregation)

# $match: filter the documents to pass only the documents that match the specified conditions to the next pipeline stage.
{$match: { username: "admin" }}

# $lookup: join to a collection in the same database to filter in documents from the "joined" collection for processing.
{
    $lookup:
        {
            from: "users",
            localField: "_id",
            foreignField: "_id",
            as: "test"
        }
}