# Unauthenticated Mongo DB

MongoDB by default does not enforce authentication. In many situations, this may allow anyone on the network to access all data within the database.

### PENTESTING MONGODB

The commands needed to verify connectivity are fairly straightforward. The mongo client (and server) can be installed with the apt package `mongodb`.

The following commands can be used to explore and read data from an unauthenticated MongoDB server:

* Connect to the server: `mongo 10.0.0.5:27017`
* List databases: `show dbs`
* Use database: `use <database>`
* List collections: `show collections`
* Search contents: `db.<collection>.find()`

Below shows an example:

```
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> use config
switched to db config
> show collections
system.sessions
> db.system.sessions.find()
> show dbs
admin   0.000GB
config  0.000GB
local   0.000GB
> use admin
switched to db admin
> show collections
system.version
> db.system.version.find()
{ "_id" : "featureCompatibilityVersion", "version" : "3.6" }

```

### CONFIGURING AUTHENTICATION

To secure a MongoDB server we’ll need to set a username and password. Once a user is created, the database needs to be shut down, and restarted with access control enabled.

#### 1. CREATING AN ADMIN USER

The following will create a basic admin user:

```
use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: "p@ssw0rd",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)
```

You should then see a response as follows:

![MongoDB Create User](https://www.virtuesecurity.com/wp-content/uploads/2021/09/mongo-create-user.png)

#### 2. ENABLE ACCESS CONTROL

In this example we are using ubuntu, so we will edit the `/etc/mongodb.conf`. We will find the following section:

```
# Turn on/off security.  Off is currently the default
#noauth = true
#auth = true
```

We will then uncomment `auth = true`.

#### 3. RESTART MONGODB

On Ubuntu we can restart the service with the following command:

```
sudo systemctl restart mongodb
```

We can then verify that access controls are enforced by reconnecting without credentials and running a query:

```
$ mongo 127.0.0.1:27017
MongoDB shell version v3.6.3
connecting to: mongodb://127.0.0.1:27017/test
MongoDB server version: 3.6.3
> show dbs
2021-09-08T02:09:59.898-0700 E QUERY    [thread1] Error: listDatabases failed:{
    "ok" : 0,
    "errmsg" : "not authorized on admin to execute command { listDatabases: 1.0, $db: \"admin\" }",
    "code" : 13,
    "codeName" : "Unauthorized"
} :

```

#### REFERENCES

<https://docs.mongodb.com/manual/tutorial/enable-authentication/>
