- Update Sharded Cluster to Keyfile Authentication
- Overview
- Considerations
- Procedures
- Enforce Keyfile Internal Authentication on Existing Sharded Cluster Deployment
- Create a keyfile.
- Copy the keyfile to each component in the sharded cluster.
- Disable the Balancer.
- Shut down all mongos instances for the sharded cluster.
- Shut down config server mongod instances.
- Shut down shard replica set mongod instances.
- Enforce Access Control on the Config Servers.
- Enforce Access Control for each Shard in the Sharded Cluster.
- Create a Shard-Local User Administrator (Optional).
- Enforce Access Control for the mongos servers.
- Connect to the mongos instance over the localhost interface.
- Create the user administrator.
- Authenticate as the user administrator.
- Create Administrative User for Cluster Management
- Authenticate as cluster admin.
- Start the balancer.
- Create additional users (Optional).
- Enforce Keyfile Internal Authentication on Existing Sharded Cluster Deployment
- x.509 Internal Authentication
Update Sharded Cluster to Keyfile Authentication
Overview
Enforcing access control on a sharded cluster requires configuring:
- Security between components of the cluster usingInternal Authentication.
- Security between connecting clients and the cluster usingRole-Based Access Control.
For this tutorial, each member of the sharded cluster must use the sameinternal authentication mechanism and settings. This means enforcing internalauthentication on each mongos
and mongod
in the cluster.
The following tutorial uses a keyfile toenable internal authentication.
Enforcing internal authentication also enforces user access control. Toconnect to the replica set, clients like the mongo
shell need touse a user account. SeeAccess Control.
CloudManager and OpsManager
If Cloud Manager or Ops Manager is managing your deployment, internalauthentication is automatically enforced.
To configure Access Control on amanaged deployment, see: Configure Access Control for MongoDB Deployments
in the Cloud Manager manualor in the Ops Manager manual.
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 with MongoDB 3.6, MongoDB binaries, mongod
andmongos
, bind to localhost
by default.From MongoDB versions 2.6 to 3.4, only the binaries from theofficial MongoDB RPM (Red Hat, CentOS, Fedora Linux, and derivatives)and DEB (Debian, Ubuntu, and derivatives) packages would bind tolocalhost
by default. To learn more about this change, 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.
Access Control
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.
Users
In general, to create users for a sharded clusters, connect to themongos
and add the sharded cluster users.
However, some maintenance operations require direct connections tospecific shards in a sharded cluster. To perform these operations, youmust connect directly to the shard and authenticate as a shard-localadministrative user.
Shard-local users exist only in the specific shard and should only beused for shard-specific maintenance and configuration. You cannotconnect to the mongos
with shard-local users.
See the Users security documentation for moreinformation.
Downtime
Upgrading a sharded cluster to enforce access control requires downtime.
Procedures
Enforce Keyfile Internal Authentication on Existing Sharded Cluster Deployment
Create a keyfile.
With keyfile authentication, eachmongod
or mongos
instances in the sharded cluster uses the contents of the keyfile as theshared password for authenticating other members in the deployment. Onlymongod
or mongos
instances with the correct keyfile can join the sharded cluster.
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 thesharded cluster 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:
- openssl rand -base64 756 > <path-to-keyfile>
- chmod 400 <path-to-keyfile>
See Keyfiles for additional details and requirementsfor using keyfiles.
Copy the keyfile to each component in the sharded cluster.
Every server hosting a mongod
or mongos
componentof the sharded cluster must contain a copy of the keyfile.
Copy the keyfile to each server hosting the sharded cluster members.Ensure that the user running the mongod
or mongos
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
or mongos
instances, such as aUSB drive or a network attached storage device.
Disable the Balancer.
Connect a mongo
shell to a mongos
.
- sh.stopBalancer()
The balancer may not stop immediately if a migration is in progress.The sh.stopBalancer()
method blocks the shell until thebalancer stops.
Starting in MongoDB 4.2, sh.stopBalancer()
also disablesauto-splitting for the sharded cluster.
Use sh.getBalancerState()
to verify that the balancer hasstopped.
- sh.getBalancerState()
Important
Do not proceed until the balancer has stopped running.
See Manage Sharded Cluster Balancer for tutorials onconfiguring sharded cluster balancer behavior.
Shut down all mongos instances for the sharded cluster.
Connect a mongo
shell to each mongos
and shutthem down.
Use the db.shutdownServer()
method on the admin
databaseto safely shut down the mongos
:
- db.getSiblingDB("admin").shutdownServer()
Repeat until all mongos
instances in the clusterare offline.
Once this step is complete, all mongos
instances in the clustershould be offline.
Shut down config server mongod instances.
Connect a mongo
shell to each mongod
in theconfig server deployment and shut them down.
For replica set config server deployments, shut down the primarymember last.
Use the db.shutdownServer()
method on the admin
databaseto safely shut down the mongod
:
- db.getSiblingDB("admin").shutdownServer()
Repeat until all config servers are offline.
Shut down shard replica set mongod instances.
For each shard replica set, connect a mongo
shell to eachmongod
member in the replica set and shut them down. Shut downthe primary member last.
Use the db.shutdownServer()
method on the admin
databaseto safely shut down the mongod
:
- db.getSiblingDB("admin").shutdownServer()
Repeat this step for each shard replica set until all mongod
instances in all shard replica sets are offline.
Once this step is complete, the entire sharded cluster should be offline.
Enforce Access Control on the Config Servers.
Start eachmongod
in the config server replica set.Include the keyFile
setting. The keyFile
setting enforcesboth Internal/Membership Authentication andRole-Based Access Control.
You can specify the mongod
settings either via aconfiguration file or the command line.
Configuration File
If using a configuration file, for a config server replicaset, set security.keyFile
to the keyfile’s path,sharding.clusterRole
to configsvr
, andreplication.replSetName
to the name of the configserver replica set.
- security:
- keyFile: <path-to-keyfile>
- sharding:
- clusterRole: configsvr
- replication:
- replSetName: <setname>
- storage:
- dbpath: <path>
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.
Start the mongod
specifying the —config
option and thepath to the configuration file.
- mongod --config <path-to-config>
Command Line
If using the command line parameters, for a config server replicaset, start the mongod
with the -keyFile
,—configsvr
, and —replSet
parameters.
- mongod --keyFile <path-to-keyfile> --configsvr --replSet <setname> --dbpath <path>
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.
For more information on command line options, see themongod
reference page.
Make sure to use the original replica set name when restarting eachmember. You cannot change the name of a replica set.
Enforce Access Control for each Shard in the Sharded Cluster.
Running a mongod
with the keyFile
parameter enforces bothInternal/Membership Authentication andRole-Based Access Control.
Start eachmongod
in the replica set using eithera configuration file or the command line.
Configuration File
If using a configuration file, set thesecurity.keyFile
option to the keyfile’s path and thereplication.replSetName
option to the original nameof the replica set.
- security:
- keyFile: <path-to-keyfile>
- replication:
- replSetName: <setname>
- storage:
- dbPath: <path>
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.
Start the mongod
specifying the —config
option and thepath to the configuration file.
- mongod --config <path-to-config-file>
Command Line
If using the command line parameters, start the mongod
andspecify the —keyFile
and —replSet
parameters.
- mongod --keyfile <path-to-keyfile> --replSet <setname> --dbpath <path>
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.
For more information on startup parameters,see the mongod
reference page.
Make sure to use the original replica set name when restarting eachmember. You cannot change the name of a replica set.
Repeat this step until all shards in the cluster are online.
Create a Shard-Local User Administrator (Optional).
Important
The Localhost Exception allows clients connected over thelocalhost interface to create users on a mongod
enforcing access control. After creating the first user,the Localhost Exception closes.
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 certain functions or operations.
For each shard replica set in the cluster, connect a mongo
shell to the primary member over the localhostinterface. You must run the mongo
onthe same machine as the target mongod
to use the localhostinterface.
Create a user with the userAdminAnyDatabase
role on the admin
database. This user can createadditional users for the shard replica set as necessary.Creating this user also closes the Localhost Exception.
The following example creates the shard-local user fred
on theadmin
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.
- admin = db.getSiblingDB("admin")
- admin.createUser(
- {
- user: "fred",
- pwd: passwordPrompt(), // or cleartext password
- roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
- }
- )
Enforce Access Control for the mongos servers.
Running a mongod
with the keyFile
parameter enforces bothInternal/Membership Authentication andRole-Based Access Control.
Start eachmongos
in the replica set using eithera configuration file or the command line.
Configuration File
If using a configuration file, set thesecurity.keyFile
to the keyfile`s path and thesharding.configDB
to the replica set name and at leastone member of the replica set in <replSetName>/<host:port>
format.
- security:
- keyFile: <path-to-keyfile>
- sharding:
- configDB: <configReplSetName>/cfg1.example.net:27019,cfg2.example.net:27019,...
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.
Start the mongos
specifying the —config
option and thepath to the configuration file.
- mongos --config <path-to-config-file>
Command Line
If using command line parameters start the mongos
and specifythe —keyFile
and —configdb
parameters.
- mongos --keyFile <path-to-keyfile> --configdb <configReplSetName>/cfg1.example.net:27019,cfg2.example.net:27019,...
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.
At this point, the entire sharded cluster is back online and cancommunicate internally using the keyfile specified. However, externalprograms like the mongo
shell need to use a correctlyprovisioned user in order to read or write to the cluster.
Connect to the mongos instance over the localhost interface.
Connect a mongo
shell to one of themongos
instances over the localhostinterface. You must run the mongo
shell on the same physical machine as the mongos
instance.
The localhost interface is only availablesince no users have been created for the deployment. Thelocalhost interface closes after thecreation of the first user.
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 cannot createor modify users, and therefore may be unable toperform necessary operations.
Add a user using the db.createUser()
method. The user shouldhave at minimum the userAdminAnyDatabase
role on theadmin
database.
Important
Passwords should be random, long, and complex to ensure system securityand to prevent or delay malicious access.
The following example creates the user fred
on theadmin
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.
- admin = db.getSiblingDB("admin")
- admin.createUser(
- {
- user: "fred",
- pwd: passwordPrompt(), // or cleartext password
- roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
- }
- )
See Database User Roles for a full list of built-in roles andrelated to database administration operations.
Authenticate as the user administrator.
Use db.auth()
to authenticate as the user administratorto create additional users:
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.
- db.getSiblingDB("admin").auth("fred", passwordPrompt()) // or cleartext password
Enter the password when prompted.
Alternatively, connect a new mongo
shell to the targetreplica set member using the -u <username>
, -p <password>
, andthe —authenticationDatabase "admin"
parameters. You must usethe Localhost Exception to connect to the mongos
.
- mongo -u "fred" -p --authenticationDatabase "admin"
If you do not specify the password to the -p
command-line option, the mongo
shell prompts for thepassword.
Create Administrative User for Cluster Management
The cluster administrator user has the clusterAdmin
rolefor the sharded cluster and not the shard-local clusteradministrator.
The following example creates the user ravi
on the admin
database.
Important
Passwords should be random, long, and complex to ensure systemsecurity and 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.
- db.getSiblingDB("admin").createUser(
- {
- "user" : "ravi",
- "pwd" : passwordPrompt(), // or cleartext password
- roles: [ { "role" : "clusterAdmin", "db" : "admin" } ]
- }
- )
See Cluster Administration Roles for a full list of built-in roles related toreplica set and sharded cluster operations.
Authenticate as cluster admin.
To perform sharding operations, authenticate as aclusterAdmin
user with either thedb.auth()
method or a new mongo
shell with theusername
, password
, and authenticationDatabase
parameters.
Note
This is the cluster administrator for the sharded cluster and _not_the shard-local cluster administrator.
Start the balancer.
Start the balancer.
- sh.startBalancer()
Starting in MongoDB 4.2, sh.startBalancer()
also enablesauto-splitting for the sharded cluster.
Use the sh.getBalancerState()
to verify the balancer has started.
See Manage Sharded Cluster Balancer for tutorials onthe sharded cluster balancer.
Create additional users (Optional).
Create users to allow clients to connect and access thesharded cluster. See Database User Roles for available built-inroles, such as read
and readWrite
.You may also want additional administrative users.For more information on users, see Users.
To create additional users, you must authenticate as a user withuserAdminAnyDatabase
or userAdmin
roles.
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.
See also