Access Control
Enable Client Authentication – Enabling authentication on a MongoDB instance restricts access to the instance by requiring that users identify themselves when connecting. In this procedure, you enable authentication and then create the instance’s first user, which must be a user administrator. The user administrator grants further access to the instance by creating additional users. After enabling authentication and prior to creating the user administrator, you can access the instance only through the localhost exception, which allows access only through a local client. MongoDB disables this access after you create the user administrator. The consideration is, if you create the user administrator before enabling authentication, MongoDB disables the localhost exception. In that case, you must use the “Enable Authentication after Creating the User Administrator” procedure to enable authentication. The procedure is as
Start the MongoDB instance with authentication enabled – Start the mongod or mongos instance with the authorization or keyFile setting. Use authorization on a standalone instance. Use keyFile on an instance in a replica set or sharded cluster. For example, to start a mongod with authentication enabled and a key file stored in /private/var, first set the following option in the mongod‘s configuration file:
security:
keyFile: /private/var/key.pem
Then start the mongod and specify the config file. For example:
mongod –config /etc/mongodb/mongodb.conf
After you enable authentication, only the user administrator can connect to the MongoDB instance. The user administrator must log in and grant further access to the instance by creating additional users.
Connect to the MongoDB instance via the localhost exception – Connect to the MongoDB instance from a client running on the same system. This access is made possible by the localhost exception.
Create the system user administrator – Add the user with the userAdminAnyDatabase role, and only that role. The following example creates the user siteUserAdmin user on the admin database:
use admin
db.createUser(
{
user: “siteUserAdmin”,
pwd: “password”,
roles:
[ { role: “userAdminAnyDatabase”,db: “admin”
} ] } )
After you create the user administrator, the localhost exception is no longer available.
Create additional users – Login in with the user administrator’s credentials and create additional users.
Enable Authentication in a Sharded Cluster – It is new in version 2.0. When authentication is enabled on a sharded cluster every client that accesses the cluster must provide credentials. This includes MongoDB instances that access each other within the cluster. To enable authentication on a sharded cluster, you must enable authentication individually on each component of the cluster. This means enabling authentication on each mongos and each mongod, including each config server, and all members of a shard’s replica set. Authentication requires an authentication mechanism and, in most cases, a key file. The content of the key file must be the same on all cluster members. The procedure is as
Create a key file – Create the key file your deployment will use to authenticate servers to each other. To generate pseudo-random data to use for a keyfile, issue the following openssl command:
openssl rand -base64 741 > mongodb-keyfile
chmod 600 mongodb-keyfile
You may generate a key file using any method you choose. Always ensure that the password stored in the key file is both long and contains a high amount of entropy. Using openssl in this manner helps generate such a key.
Enable authentication on each component in the cluster – On each mongos and mongod in the cluster, including all config servers and shards, specify the key file using one of the following approaches:
Specify the key file in the configuration file – In the configuration file, set the keyFile option to the key file’s path and then start the component, as in the following example:
security:
keyFile: /srv/mongodb/keyfile
Specify the key file at runtime – When starting the component, set the –keyFile option, which is an option for both mongos instances and mongod instances. Set the –keyFile to the key file’s path. The keyFile setting implies the authorization setting, which means in most cases you do not need to set authorization explicitly.
Add users – While connected to a mongos, add the first administrative user and then add subsequent users.
Enable Authentication after Creating the User Administrator – Enabling authentication on a MongoDB instance restricts access to the instance by requiring that users identify themselves when connecting. In this procedure, you will create the instance’s first user, which must be a user administrator and then enable authentication. Then, you can authenticate as the user administrator to create additional users and grant additional access to the instance. This procedures outlines how enable authentication after creating the user administrator. The approach requires a restart. This section outlines a procedure for enabling authentication for MongoDB instance where you create the first user on an existing MongoDB system that does not require authentication before restarting the instance and requiring authentication. You can use the localhost exception to gain access to a system with no users and authentication enabled.
Start the MongoDB instance without authentication – Start the mongod or mongos instance without the authorization or keyFile setting. For example:
mongod –port 27017 –dbpath /data/db1
Create the system user administrator – Add the user with the userAdminAnyDatabase role, and only that role. The following example creates the user siteUserAdmin user on the admin database:
use admin
db.createUser(
{ user: “siteUserAdmin”,
pwd: “password”,
roles:
[ { role: “userAdminAnyDatabase”,db: “admin”
}
] }
)
Re-start the MongoDB instance with authentication enabled – Re-start the mongod or mongos instance with the authorization or keyFile setting. Use authorization on a standalone instance. Use keyFile on an instance in a replica set or sharded cluster. The following example enables authentication on a standalone mongod using the authorization command-line option:
mongod –auth –config /etc/mongodb/mongodb.conf
Create additional users – Login in with the user administrator’s credentials and create additional users.
Authenticate with x.509 Certificate – It is new in version 2.6. MongoDB supports x.509 certificate authentication for use with a secure SSL connection. The x.509 authentication allows clients to authenticate to servers with certificates instead of with username and password. The x.509 authentication also allows sharded cluster members and replica set members to use x.509 certificates to verify their membership to the cluster or the replica set instead of using keyfiles. The membership authentication is an internal process.
Use x.509 for Client Authentication – It involves
Client x.509 Certificate – The client certificate must have the following properties:
- A single Certificate Authority (CA) must issue the certificates for both the client and the server.
- Client certificates must contain the following fields:
keyUsage = digitalSignature
extendedKeyUsage = clientAuth
Configure MongoDB Server – Configure the MongoDB server from the command line, as in the following:
mongod –sslMode requireSSL –sslPEMKeyFile <path to SSL certificate and key PEM file> –sslCAFile <path to root CA PEM file>
You may also specify these options in the configuration file:
sslMode = requireSSL
sslPEMKeyFile = <path to SSL certificate and key PEM file>
sslCAFile = <path to the root CA PEM file>
Include any additional options, SSL or otherwise, that are required for your specific configuration.
Add x.509 Certificate subject as a User – To authenticate with a client certificate, you must first add the value of the subject from the client certificate as a MongoDB user. You can retrieve the subject from the client certificate with the following command:
openssl x509 -in <pathToClient PEM> -inform PEM -subject -nameopt RFC2253
The command returns the subject string as well as certificate:
subject= CN=myName,OU=myOrgUnit,O=myOrg,L=myLocality,ST=myState,C=myCountry
—–BEGIN CERTIFICATE—–
# …
—–END CERTIFICATE—–
Add the value of the subject, omitting the spaces, from the certificate as a user. For example, in the mongo shell, to add the user with both the readWrite role in the test database and the userAdminAnyDatabase role which is defined only in the admin database:
db.getSiblingDB(“$external”).runCommand(
{
createUser: “CN=myName,OU=myOrgUnit,O=myOrg,L=myLocality,ST=myState,C=myCountry”,
roles: [
{ role: ‘readWrite’, db: ‘test’ },
{ role: ‘userAdminAnyDatabase’, db: ‘admin’ }
],
writeConcern: { w: “majority” , wtimeout: 5000 }
}
)
In the above example, to add the user with the readWrite role in the test database, the role specification document specified ‘test’ in the db field. To add userAdminAnyDatabase role for the user, the above example specified ‘admin’ in the db field. Some roles are defined only in the admin database, including: clusterAdmin, readAnyDatabase, readWriteAnyDatabase, dbAdminAnyDatabase, and userAdminAnyDatabase. To add a user with these roles, specify ‘admin’ in the db.
Authenticate with a x.509 Certificate – To authenticate with a client certificate, you must first add a MongoDB user that corresponds to the client certificate. To authenticate, use the db.auth() method in the $external database, specifying “MONGODB-X509” for the mechanism field, and the user that corresponds to the client certificate for the user field. For example, if using the mongo shell, connect mongo shell to the mongod set up for SSL:
mongo –ssl –sslPEMKeyFile <path to CA signed client PEM file>
To perform the authentication, use the db.auth() method in the $external database. For the mechanism field, specify “MONGODB-X509”, and for the user field, specify the user, or the subject, that corresponds to the client certificate.
db.getSiblingDB(“$external”).auth(
{
mechanism: “MONGODB-X509”,
user: “CN=myName,OU=myOrgUnit,O=myOrg,L=myLocality,ST=myState,C=myCountry”
}
)
Use x.509 for Replica Set/Sharded Cluster Member Authentication
Member x.509 Certificate – The member certificate, used for internal authentication to verify membership to the sharded cluster or a replica set, must have the following properties:
- A single Certificate Authority (CA) must issue all the x.509 certificates for the members of a sharded cluster or a replica set.
- The member certificate’s subject, which contains the Distinguished Name (DN), must match the subject of the certificate on the other servers in the cluster, starting from and including the Organizational Unit (OU) of the certificate on the server.
- Either the Common Name (CN) or one of the Subject Alternative Name (SAN) entries must match the hostname of the server, used by the other members of the cluster.
For example, the certificates for a cluster could have the following subjects:
subject= CN=<myhostname1>,OU=Dept1,O=MongoDB,ST=NY,C=US
subject= CN=<myhostname2>,OU=Dept1,O=MongoDB,ST=NY,C=US
subject= CN=<myhostname3>,OU=Dept1,O=MongoDB,ST=NY,C=US
Configure Clusters – To specify the x.509 certificate for internal cluster member authentication, append the additional SSL options –clusterAuthMode and –sslClusterFile, as in the following example for a member of a replica set:
mongod –replSet <name> –sslMode requireSSL –clusterAuthMode x509 –sslClusterFile <path to membership certificate and key PEM file> –sslPEMKeyFile <path to SSL certificate and key PEM file> –sslCAFile <path to root CA PEM file>
Include any additional options, SSL or otherwise, that are required for your specific configuration. For instance, if the membership key is encrypted, set the –sslClusterPassword to the passphrase to decrypt the key or have MongoDB prompt for the passphrase. You may also specify these options in the configuration file, as in the following example:
sslMode = requireSSL
sslPEMKeyFile = <path to SSL certificate and key PEM file>
sslCAFile = <path to root CA PEM file>
clusterAuthMode = x509
sslClusterFile = <path to membership certificate and key PEM file>
Authenticate Using SASL and LDAP – MongoDB Enterprise provides support for proxy authentication of users. This allows administrators to configure a MongoDB cluster to authenticate users by proxying authentication requests to a specified Lightweight Directory Access Protocol (LDAP) service. MongoDB Enterprise for Windows does not include LDAP support for authentication. MongoDB does not support LDAP authentication in mixed sharded cluster deployments that contain both version 2.4 and version 2.6 shards.
Because the transmission of the username and password from the client to the MongoDB server, from the MongoDB server to saslauthd, and from saslauthd to the LDAP server uses SASL PLAIN mechanism, i.e. in plain text, you should, in general, use only on a trusted channel (VPN, SSL, trusted wired network). LDAP support for user authentication requires proper configuration of the saslauthd daemon process as well as the MongoDB server.
Specify the mechanism – On systems that configure saslauthd with the /etc/sysconfig/saslauthd file, such as Red Hat Enterprise Linux, Fedora, CentOS, and Amazon Linux AMI, set the mechanism MECH to ldap:
MECH=ldap
On systems that configure saslauthd with the /etc/default/saslauthd file, set the MECHANISMS option to ldap:
MECHANISMS=”ldap”
Adjust caching behavior – On certain Linux distributions, saslauthd starts with the caching of authentication credentials enabled. Until restarted or until the cache expires, saslauthd will not contact the LDAP server to re-authenticate users in its authentication cache. This allows saslauthd to successfully authenticate users in its cache, even in the LDAP server is down or if the cached users’ credentials are revoked. To set the expiration time (in seconds) for the authentication cache, use the -t option of saslauthd.
Configure with LDAP Options – If the saslauthd.conf file does not exist, create it. The saslauthd.conf file usually resides in the /etc folder. If specifying a different file path, use the -O option of saslauthd.
Configure for Use with Active Directory – To use with Active Directory, start saslauthd with the following configuration options set in the saslauthd.conf file:
ldap_servers: <ldap uri>
ldap_use_sasl: yes
ldap_mech: DIGEST-MD5
ldap_auth_method: fastbind
For the <ldap uri>, specify the uri of the ldap server. For example, ldap_servers: ldaps://ad.example.net.
Configure for Use with OpenLDAP – To connect to an OpenLDAP server, update the saslauthd.conf file with the following configuration options:
ldap_servers: <ldap uri>
ldap_search_base: <search base>
ldap_filter: <filter>
The ldap_servers specifies the uri of the LDAP server used for authentication. In general, for OpenLDAP installed on the local machine, you can specify the value ldap://localhost:389 or if using LDAP over SSL, you can specify the value ldaps://localhost:636. The ldap_search_base specifies distinguished name to which the search is relative. The search includes the base or objects below. The ldap_filter specifies the search filter. The values for these configuration options should correspond to the values specific for your test. For example, to filter on email, specify ldap_filter: (mail=%n) instead.
Test the saslauthd configuration – Use testsaslauthd utility to test the saslauthd configuration. For example:
testsaslauthd -u testuser -p testpassword -f /var/run/saslauthd/mux
Configure MongoDB
Add user to MongoDB for authentication.- Add the user to the $external database in MongoDB. To specify the user’s privileges, assign roles to the user. For example, the following adds a user with read-only access to the records database. Add additional principals as needed.
db.getSiblingDB(“$external”).createUser(
{
user : <username>,
roles: [ { role: “read”, db: “records” } ]
} )
Configure MongoDB server – To configure the MongoDB server to use the saslauthd instance for proxy authentication, start the mongod with the following options:
- –auth,
- authenticationMechanisms parameter set to PLAIN, and
- saslauthdPath parameter set to the path to the Unix-domain Socket of the saslauthd instance.
Configure the MongoDB server using either the command line option –setParameter or the configuration file. Specify additional configurations as appropriate for your configuration. Use specific saslauthd socket path. For socket path of /<some>/<path>/saslauthd, set the saslauthdPath to /<some>/<path>/saslauthd/mux, as in the following command line example:
mongod –auth –setParameter saslauthdPath=/<some>/<path>/saslauthd/mux –setParameter authenticationMechanisms=PLAIN
Or if using a configuration file, specify the following parameters in the file:
auth=true
setParameter=saslauthdPath=/<some>/<path>/saslauthd/mux
setParameter=authenticationMechanisms=PLAIN
Use default Unix-domain socket path – To use the default Unix-domain socket path, set the saslauthdPath to the empty string “”, as in the following command line example:
mongod –auth –setParameter saslauthdPath=”” –setParameter authenticationMechanisms=PLAIN
Or if using a configuration file, specify the following parameters in the file:
auth=true
setParameter=saslauthdPath=/<some>/<path>/saslauthd/mux
setParameter=authenticationMechanisms=PLAIN
Authenticate the user in the mongo shell – To perform the authentication in the mongo shell, use the db.auth() method in the $external database. Specify the value “PLAIN” in the mechanism field, the user and password in the user and pwd fields respectively, and the value false in the digestPassword field. You must specify false for digestPassword since the server must receive an undigested password to forward on to saslauthd, as in the following example:
db.getSiblingDB(“$external”).auth(
{
mechanism: “PLAIN”,
user: <username>,
pwd: <cleartext password>,
digestPassword: false
}
)
The server forwards the password in plain text. In general, use only on a trusted channel (VPN, SSL, and trusted wired network).
Deploy MongoDB with Kerberos Support on Linux – It is new in version 2.4. MongoDB Enterprise supports authentication using a Kerberos service. Kerberos is an industry standard authentication protocol for large client/server system. This section assumes you have configured a Kerberos service principal for each mongod and mongos instance in your MongoDB deployment, and you have a valid keytab file for each mongod and mongos instance. The following procedure outlines the steps to add a Kerberos user principal to MongoDB, configure a standalone mongod instance for Kerberos support, and connect using the mongo shell and authenticate the user principal.
Start mongod without Kerberos – For the initial addition of Kerberos users, start mongod without Kerberos support. If a Kerberos user is already in MongoDB and has the privileges required to create a user, you can start mongod with Kerberos support.
Connect to mongod – Connect via the mongo shell to the mongod instance. If mongod has –auth enabled, ensure you connect with the privileges required to create a user.
Add Kerberos Principal(s) to MongoDB – Add a Kerberos principal, <username>@<KERBEROS REALM> or <username>/<instance>@<KERBEROS REALM>, to MongoDB in the $external database. Specify the Kerberos realm in all uppercase. The $external database allows mongod to consult an external source (e.g. Kerberos) to authenticate. To specify the user’s privileges, assign roles to the user.
The following example adds the Kerberos principal application/[email protected] with read-only access to the records database:
use $external
db.createUser(
{
user: “application/[email protected]”,
roles: [ { role: “read”, db: “records” } ]
}
)
Add additional principals as needed. For every user you want to authenticate using Kerberos, you must create a corresponding user in MongoDB.
Start mongod with Kerberos support – To start mongod with Kerberos support, set the environmental variable KRB5_KTNAME to the path of the keytab file and the mongod parameter authenticationMechanisms to GSSAPI in the following form:
env KRB5_KTNAME=<path to keytab file> \
mongod \
–setParameter authenticationMechanisms=GSSAPI
<additional mongod options>
For example, the following starts a standalone mongod instance with Kerberos support:
env KRB5_KTNAME=/opt/mongodb/mongod.keytab \
/opt/mongodb/bin/mongod –auth \
–setParameter authenticationMechanisms=GSSAPI \
–dbpath /opt/mongodb/data
The path to your mongod as well as your keytab file may differ. Modify or include additional mongod options as required for your configuration. The keytab file must be only accessible to the owner of the mongod process.
With the official .deb or .rpm packages, you can set the KRB5_KTNAME in a environment settings file.
Connect mongo shell to mongod and authenticate – Connect the mongo shell client as the Kerberos principal application/[email protected]. Before connecting, you must have used Kerberos’s kinit program to get credentials for application/[email protected]. You can connect and authenticate from the command line.
mongo –authenticationMechanism=GSSAPI –authenticationDatabase=’$external’ \
–username application/[email protected]
Or, alternatively, you can first connect mongo to the mongod, and then from the mongo shell, use the db.auth() method to authenticate in the $external database.
use $external
db.auth( { mechanism: “GSSAPI”, user: “application/[email protected]” } )
Deploy MongoDB on Windows with Kerberos Authentication – It is new in version 2.6. MongoDB Enterprise supports authentication using a Kerberos service. Kerberos is an industry standard authentication protocol for large client/server system. Kerberos allows MongoDB and applications to take advantage of existing authentication infrastructure and processes. This section assumes have configured a Kerberos service principal for each mongod.exe and mongos.exe instance as well as initialize a credential cache for the mongo shell.
Start mongod.exe without Kerberos – For the initial addition of Kerberos users, start mongod.exe without Kerberos support. If a Kerberos user is already in MongoDB and has the privileges required to create a user, you can start mongod.exe with Kerberos support.
Connect to mongod – Connect via the mongo.exe shell to the mongod.exe instance. If mongod.exe has –auth enabled, ensure you connect with the privileges required to create a user.
Add Kerberos Principal(s) to MongoDB – Add a Kerberos principal, <username>@<KERBEROS REALM>, to MongoDB in the $external database. Specify the Kerberos realm in all uppercase. The $external database allows mongod.exe to consult an external source (e.g. Kerberos) to authenticate. To specify the user’s privileges, assign roles to the user. The following example adds the Kerberos principal [email protected] with read-only access to the records database:
use $external
db.createUser(
{
user: “[email protected]”,
roles: [ { role: “read”, db: “records” } ]
}
)
Add additional principals as needed. For every user you want to authenticate using Kerberos, you must create a corresponding user in MongoDB.
Start mongod.exe with Kerberos support – You must start mongod.exe as the service principal account. To start mongod.exe with Kerberos support, set the mongod.exe parameter authenticationMechanisms to GSSAPI:
mongod.exe –setParameter authenticationMechanisms=GSSAPI <additional mongod.exe options>
For example, the following starts a standalone mongod.exe instance with Kerberos support:
mongod.exe –auth –setParameter authenticationMechanisms=GSSAPI
Modify or include additional mongod.exe options as required for your configuration.
Connect mongo.exe shell to mongod.exe and authenticate – Connect the mongo.exe shell client as the Kerberos principal [email protected]. You can connect and authenticate from the command line.
mongo.exe –authenticationMechanism=GSSAPI –authenticationDatabase=’$external’ \
–username [email protected]
Or, alternatively, you can first connect mongo.exe to the mongod.exe, and then from the mongo.exe shell, use the db.auth() method to authenticate in the $external database.
use $external
db.auth( { mechanism: “GSSAPI”, user: “[email protected]” } )
Authenticate to a MongoDB Instance or Cluster – To authenticate to a running mongod or mongos instance, you must have user credentials for a resource on that instance. When you authenticate to MongoDB, you authenticate either to a database or to a cluster. Your user privileges determine the resource you can authenticate to. You authenticate to a resource either by:
- using the authentication options when connecting to the mongod or mongos instance, or
- connecting first and then authenticating to the resource with the authenticate command or the db.auth() method.
In general, always use a trusted channel (VPN, SSL, trusted wired network) for connecting to a MongoDB instance. You must have user credentials on the database or cluster to which you are authenticating.
Authenticate When First Connecting to MongoDB
Specify your credentials when starting the mongo instance – When using mongo to connect to a mongod or mongos, enter your username, password, and authenticationDatabase. For example:
mongo –username “prodManager” –password “cleartextPassword” –authenticationDatabase “products”
Close the session when your work is complete – To close an authenticated session, use the logout command.:
db.runCommand( { logout: 1 } )
Authenticate After Connecting to MongoDB
connect to a MongoDB instance – Connect to a mongod or mongos instance.
Switch to the database to which to authenticate –
use <database>
Authenticate – Use either the authenticate command or the db.auth() method to provide your username and password to the database. For example:
db.auth( “prodManager”, “cleartextPassword” )
Close the session when your work is complete – To close an authenticated session, use the logout command.:
db.runCommand( { logout: 1 } )
Generate a Key File – This section describes how to generate a key file to store authentication information. After generating a key file, specify the key file using the keyFile option when starting a mongod or mongos instance. A key’s length must be between 6 and 1024 characters and may only contain characters in the base64 set. The key file must not have group or world permissions on UNIX systems. Key file permissions are not checked on Windows systems. MongoDB strips whitespace characters (e.g. x0d, x09, and x20) for cross-platform convenience. As a result, the following operations produce identical keys:
echo -e “my secret key” > key1
echo -e “my secret key\n” > key2
echo -e “my secret key” > key3
echo -e “my\r\nsecret\r\nkey\r\n” > key4
Create a key file – Create the key file your deployment will use to authenticate servers to each other. To generate pseudo-random data to use for a keyfile, issue the following openssl command:
openssl rand -base64 741 > mongodb-keyfile
chmod 600 mongodb-keyfile
You may generate a key file using any method you choose. Always ensure that the password stored in the key file is both long and contains a high amount of entropy. Using openssl in this manner helps generate such a key.
Specify the key file when starting a MongoDB instance – Specify the path to the key file with the keyFile option.
Apply for MongoDB Certification Now!!
https://www.vskills.in/certification/databases/mongodb-server-administrator