Deploy Replica Set With Keyfile Authentication

Overview

Enforcing access control on a replica set requires configuring:

For this tutorial, each member of the replica set uses the same internalauthentication mechanism and settings.

Enforcing internal authentication also enforces user access control. Toconnect to the replica set, clients like the mongo shell need touse a user account. SeeUsers and Authentication Mechanisms.

Cloud Manager and Ops Manager

If you are currently using or are planning to use Cloud Manager or OpsManager, see the Cloud Manager manual or the OpsManager manual forenforcing access control.

Considerations

Tip

When possible, use a logical DNS hostname instead of an ip address,particularly when configuring replica set members or sharded clustermembers. The use of logical DNS hostnames avoids configurationchanges due to ip address changes.

IP Binding

Changed in version 3.6.

Starting in MongoDB 3.6, mongod and mongosbind to localhost by default. If the members of your deployment arerun on different hosts or if you wish remote clients to connect toyour deployment, you must specify —bind_ip ornet.bindIp. For more information, seeLocalhost Binding Compatibility Changes.

Operating System

This tutorial primarily refers to the mongod process.Windows users should use the mongod.exe program instead.

Keyfile Security

Keyfiles are bare-minimum forms of security and are best suited for testing ordevelopment environments. For production environments we recommend usingx.509 certificates.

Users and Authentication Mechanisms

This tutorial covers creating the minimum number of administrativeusers on the admin database only. For the user authentication,the tutorial uses the default SCRAMauthentication mechanism. Challenge-response security mechanisms arebest suited for testing or development environments. For productionenvironments, we recommend using x.509certificates or LDAP Proxy Authentication(available for MongoDB Enterprise only) or Kerberos Authentication(available for MongoDB Enterprise only).

For details on creating users for specific authentication mechanism,refer to the specific authentication mechanism pages.

See Configure Role-Based Access Control for bestpractices for user creation and management.

Deploy New Replica Set with Keyfile Access Control

Tip

When possible, use a logical DNS hostname instead of an ip address,particularly when configuring replica set members or sharded clustermembers. The use of logical DNS hostnames avoids configurationchanges due to ip address changes.

Create a keyfile.

With keyfile authentication, eachmongod instances in the replica set uses the contents of the keyfile as theshared password for authenticating other members in the deployment. Onlymongod instances with the correct keyfile can join the replica set.

Note

Starting in MongoDB 4.2, keyfiles for internal membershipauthentication use YAML format to allow formultiple keys in a keyfile. The YAML format accepts content of:

  • a single key string (same as in earlier versions),
  • multiple key strings (each string must be enclosed in quotes), or
  • sequence of key strings.

The YAML format is compatible with the existing single-keykeyfiles that use the text file format.

A key’s length must be between 6 and 1024 characters and may onlycontain characters in the base64 set. All members of thereplica set must share at least one common key.

Note

On UNIX systems, the keyfile must not have group or worldpermissions. On Windows systems, keyfile permissions are not checked.

You can generate a keyfile using any method you choose. For example,the following operation uses openssl to generate a complexpseudo-random 1024 character string to use as a shared password. It thenuses chmod to change file permissions to provide readpermissions for the file owner only:

  1. openssl rand -base64 756 > <path-to-keyfile>
  2. chmod 400 <path-to-keyfile>

See Keyfiles for additional details and requirementsfor using keyfiles.

Copy the keyfile to each replica set member.

Copy the keyfile to each server hosting the replica set members.Ensure that the user running the mongod instances is the owner of thefile and can access the keyfile.

Avoid storing the keyfile on storage mediums that can be easilydisconnected from the hardware hosting the mongod instances, such as aUSB drive or a network attached storage device.

Start each member of the replica set with access control enabled.

For each member in the replica set, start the mongod witheither the security.keyFile configuration file setting orthe —keyFile command-line option. Running mongodwith the —keyFile command-line option or thesecurity.keyFile configuration file setting enforces bothInternal/Membership Authentication andRole-Based Access Control.

Configuration File

If using a configuration file, set

Include additional options as requiredfor your configuration. For instance, if you wish remote clients toconnect to your deployment or your deployment members are run ondifferent hosts, specify the net.bindIp setting. For moreinformation, see Localhost Binding Compatibility Changes.

  1. security:
  2. keyFile: <path-to-keyfile>
  3. replication:
  4. replSetName: <replicaSetName>
  5. net:
  6. bindIp: localhost,<hostname(s)|ip address(es)>

Start the mongod using the configuration file:

  1. mongod --config <path-to-config-file>

For more information on the configuration file, seeconfiguration options.

Command Line

If using the command line options, start the mongod with the following options:

  • —keyFile set to the keyfile’s path, and
  • —replSet set to the replica set name.

Include additional options as required for your configuration. Forinstance, if you wish remote clients to connect to your deploymentor your deployment members are run on different hosts, specify the—bind_ip. For more information, seeLocalhost Binding Compatibility Changes.

  1. mongod --keyFile <path-to-keyfile> --replSet <replicaSetName> --bind_ip localhost,<hostname(s)|ip address(es)>

Tip

When possible, use a logical DNS hostname instead of an ip address,particularly when configuring replica set members or sharded clustermembers. The use of logical DNS hostnames avoids configurationchanges due to ip address changes.

For more information on command-line options, see themongod reference page.

Connect to a member of the replica set over the localhost interface.

Connect a mongo shell to one of themongod instances over the localhostinterface. You must run the mongoshell on the same physical machine as the mongod instance.

The localhost interface is only availablesince no users have been created for the deployment. Thelocalhost interface closes after thecreation of the first user.

Initiate the replica set.

From the mongo shell, run the rs.initiate() method.

rs.initiate() can take an optional replica setconfiguration document. In thereplica set configuration document, include:

  • The _id field set to the replica set name specified ineither the replication.replSetName or the —replSetoption.
  • The members array with a document per each member of thereplica set.

The following example initates a three member replica set.

Important

Run rs.initiate() on just one and only onemongod instance for the replica set.

Tip

When possible, use a logical DNS hostname instead of an ip address,particularly when configuring replica set members or sharded clustermembers. The use of logical DNS hostnames avoids configurationchanges due to ip address changes.

  1. rs.initiate(
  2. {
  3. _id : <replicaSetName>,
  4. members: [
  5. { _id : 0, host : "mongo1.example.net:27017" },
  6. { _id : 1, host : "mongo2.example.net:27017" },
  7. { _id : 2, host : "mongo3.example.net:27017" }
  8. ]
  9. }
  10. )

rs.initiate() triggers an election andelects one of the members to be the primary.

Connect to the primary before continuing. Use rs.status() tolocate the primary member.

Create the user administrator.

Important

After you create the first user, the localhost exception is no longer available.

The first user must have privileges to create other users, suchas a user with the userAdminAnyDatabase. This ensuresthat you can create additional users after the Localhost Exceptioncloses.

If at least one user does not have privileges to create users,once the localhost exception closes you may be unable to createor modify users with new privileges, and therefore unable toaccess necessary operations.

Add a user using the db.createUser() method. The user shouldhave at minimum the userAdminAnyDatabase role on theadmin database.

You must be connected to the primary to create users.

The following example creates the user fred with theuserAdminAnyDatabase role on the admin database.

Important

Passwords should be random, long, and complex to ensure system securityand to prevent or delay malicious access.

Tip

Starting in version 4.2 of the mongo shell, you canuse the passwordPrompt() method in conjunction withvarious user authentication/management methods/commands to promptfor the password instead of specifying the password directly in themethod/command call. However, you can still specify the passworddirectly as you would with earlier versions of themongo shell.

  1. admin = db.getSiblingDB("admin")
  2. admin.createUser(
  3. {
  4. user: "fred",
  5. pwd: passwordPrompt(), // or cleartext password
  6. roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  7. }
  8. )

Enter the password when prompted.See Database User Roles for a full list of built-in roles andrelated to database administration operations.

Authenticate as the user administrator.

Authenticate to the admin database.

In the mongo shell, use db.auth() toauthenticate. For example, the following authenticate as the useradministrator fred:

Tip

Starting in version 4.2 of the mongo shell, you canuse the passwordPrompt() method in conjunction withvarious user authentication/management methods/commands to promptfor the password instead of specifying the password directly in themethod/command call. However, you can still specify the passworddirectly as you would with earlier versions of themongo shell.

  1. db.getSiblingDB("admin").auth("fred", passwordPrompt()) // or cleartext password

Alternatively, connect a new mongo shell to the primaryreplica set member using the -u <username>, -p <password>, andthe —authenticationDatabase parameters.

  1. mongo -u "fred" -p --authenticationDatabase "admin"

If you do not specify the password to the -pcommand-line option, the mongo shell prompts for thepassword.

Create the cluster administrator.

The clusterAdmin role grants access to replicationoperations, such as configuring the replica set.

Create a cluster administrator user and assign theclusterAdmin role in the admin database:

Tip

Starting in version 4.2 of the mongo shell, you canuse the passwordPrompt() method in conjunction withvarious user authentication/management methods/commands to promptfor the password instead of specifying the password directly in themethod/command call. However, you can still specify the passworddirectly as you would with earlier versions of themongo shell.

  1. db.getSiblingDB("admin").createUser(
  2. {
  3. "user" : "ravi",
  4. "pwd" : passwordPrompt(), // or cleartext password
  5. roles: [ { "role" : "clusterAdmin", "db" : "admin" } ]
  6. }
  7. )

Enter the password when prompted.

See Cluster Administration Roles for a full list of built-in roles related toreplica set and sharded cluster operations.

Create additional users (Optional).

Create users to allow clients to connect and interact with the replica set.See Database User Roles for basic built-in roles to use in creatingread-only and read-write users.

You may also want additional administrative users.For more information on users, see Users.

x.509 Internal Authentication

For details on using x.509 for internal authentication, seeUse x.509 Certificate for Membership Authentication.

To upgrade from keyfile internal authentication to x.509 internalauthentication, seeUpgrade from Keyfile Authentication to x.509 Authentication.