The full Python crawler

Bitter experience

MongoDB, as the most popular database at present, its security verification is also essential, otherwise an unverified database is exposed, anyone can operate at will, which will be very dangerous. Please see the following painful experience of the netizens, you will understand.

The reason why these attacks occur is that the security of MongoDB database is not high, and security authentication and data backup are not done well. But in reverse, it also means that these attacks can be easily prevented with a few simple steps. The most effective way to prevent this type of attack is to enable authentication, deny remote access, or add IP access restrictions. Let’s learn how to use authentication to access MongoDB to solve these problems.

Manage MongoDB users and permissions

Commonly used permissions

permissions instructions
read Allows the user to read the specified database.
readWrite Allows users to read and write from the specified database.
userAdmin Allows users to write to the system.users collection. Users can be created, deleted, and managed in the specified database.
dbAdmin Allows users to perform administrative functions such as index creation, deletion, viewing statistics, or accessing system.profile in a specified database.
clusterAdmin Must be defined in the admin database to give users administrative rights to all sharding and replication set-related functions.
readAnyDatabase Must be defined in the admin database to give the user read permission on all databases.
readWriteAnyDatabase Must be defined in the admin database to give users read and write permissions to all databases.
userAdminAnyDatabase Must be defined in the admin database to give the user the userAdmin permission for all databases.
dbAdminAnyDatabase Must be defined in the admin database to give the user the dbAdmin permission for all databases.
root Must be defined in the admin database, super account, super permission.

Creating administrative Users

MongoDB has a user management mechanism, which is simply described as managing user groups. The users in this group are specially designed for managing ordinary users, and they are called administrators for the time being.

Administrators usually do not have read and write permissions to the database, but only the permissions of the operating user. We only need to assign the userAdminAnyDatabase role to the administrator. In addition, the administrator account must be created in the admin database.

Since the user can only log in to the database in which the user is created, all users are created in the admin database. This way we don’t need to log in frequently when switching databases.

Use admin to log in to the admin database, and then use another database. The second use does not need to be logged in again. When MongoDB sets the use of the second database, if the login user has high permission, the user can directly operate the second database without login.

Switching databases

The administrator needs toadminDatabase, so we need to switch to admin database first.

To view the user

Use the db.system.users.find() function to view information about all users in the admin database.

Create a user

You can create a user in MongoDB using the db.createUser({user information}) function.

db.createUser({ 
    user: "<name>",
    pwd: "<cleartext password>",
    customData: { <any information> },
    roles: [
        { role: "<role>", db: "<database>" } | "<role>",
        ...
    ]
});
Copy the code
  • userUser name:
  • pwdPassword:
  • customData: Stores user – defined data. This property can also be ignored
  • roles: Specifies an array type to configure user permissions
db.createUser({ 
    user: "<name>",
    pwd: "<cleartext password>",
    customData: { <any information> },
    roles: [
        { role: "<role>", db: "<database>" } | "<role>",
        ...
    ]
});
Copy the code

The following is an example:

db.createUser({user:"uaad",pwd:"uaad",roles:[{role:"userAdminAnyDatabase",db:"admin"}]})
Copy the code

Restart the service

After the administrator account is created, restart MongoDB and enable the identity authentication function.

Through the firstdb.shutdownServer()Function to close the service.

This article started MongoDB by specifying a configuration file, so modify the configuration, enable authentication, and restart the service. The complete configuration information is as follows:

#Directory for storing data files
dbpath = /usr/local/mongodb/data/db
#Directory for storing log files
logpath = /usr/local/mongodb/logs/mongodb.log
#Records logs in append mode
logappend = true
#The default port number is 27017
port = 27017
#Enabled as a daemon, that is, running in the background
fork = true
#Access to IP addresses is not restrictedBind_ip = 0.0.0.0#Enabling authentication
auth = true
Copy the code

The identity authentication

After the service is restarted, switch to the admin database and pass this command againdb.system.users.find()Function orshow usersTo viewadminAll user information in the database, the following information is returned.

Using authentication functionsDb.auth (" username ", "Password ")Perform identity authentication. If 1 is returned, the authentication succeeds. If 0 is returned, the authentication fails.

After a successful login, the user can perform other operations corresponding to the rights of the role, for exampleshow usersView all user information again.

Creating a Common User

Requirements: Create a test database and add a user named testuser and password 123456 to the database. Grant the user the read and write permission to the test database.

Logging In to the Database as an administrator

A common user must be created by an administrator. Therefore, log in to the database as an administrator first.

> use admin
switched to db admin
> db.auth("uaad"."uaad")
1
Copy the code

Creating a database

MongoDB does not have a specific syntax for creating a database. When using use to switch over a database, if the corresponding database does not exist, you can directly create and switch over the database.

> use test
switched to db test
Copy the code

Create a user

> db.createUser({user:"testuser".pwd:"123456",roles:[{role:"readWrite",db:"test"}]})
Successfully added user: {
	"user" : "testuser",
	"roles" : [
		{
			"role" : "readWrite",
			"db" : "test"
		}
	]
}
Copy the code

The identity authentication

Open a new client connection, switch to the test database, and execute the document insert statement. The following information is returned:

> use test
switched to db test
> db.user.insert({"name": "zhangsan"})
WriteCommandError({
	"ok" : 0,
	"errmsg" : "command insert requires authentication",
	"code" : 13,
	"codeName" : "Unauthorized"
})
Copy the code

The operation of the document will be explained in detail in the following articles, but please focus on the user’s operation here.

Use the authentication function db.auth(” username “, “password “) for identity authentication. If 1 is returned, the authentication succeeds. If 0 is returned, the authentication fails.

> db.auth("testuser"."123456")
1
Copy the code

After a successful login, you can perform other operations corresponding to the role permissions of the user. Run the following statement to check whether the user has read and write permissions.

> db.user.insert({"name": "zhangsan"})
WriteResult({ "nInserted" : 1 })
> db.user.find()
{ "_id" : ObjectId("5f9128f3b60db22aa1b9d7c1"), "name" : "zhangsan" }
Copy the code

Update user

Update the role

If we need to change the role of an existing user, we can use the db.updateUser() function to update the user role. Note: To execute this function, the current user needs to have either the userAdmin or userAdminAnyDatabse or root roles.

The updateUser (" username ", {" roles ": [{" role" : "character name," db: "database"}, {" update item 2 ":" update "}]})Copy the code

For example, add readWriteAnyDatabase and dbAdminAnyDatabase permissions to the uAAD user.

> db.updateUser("uaad", {"roles": [{"role":"userAdminAnyDatabase",db:"admin"},{role:"readWriteAnyDatabase",db:"admin"},{role:"dbAdminAnyDatabase",db:"admin"}]})
> show users
{
	"_id" : "admin.uaad",
	"userId" : UUID("def949fa-f89a-41b6-9df7-2aa7e4158466"),
	"user" : "uaad",
	"db" : "admin",
	"roles" : [
		{
			"role" : "userAdminAnyDatabase",
			"db" : "admin"
		},
		{
			"role" : "readWriteAnyDatabase",
			"db" : "admin"
		},
		{
			"role" : "dbAdminAnyDatabase",
			"db" : "admin"
		}
	],
	"mechanisms" : [
		"SCRAM-SHA-1",
		"SCRAM-SHA-256"
	]
}
Copy the code

Update the password

You can change a user password in either of the following ways: Switch to the database where the user resides. Note: You need to execute using a user with the userAdmin or userAdminAnyDatabse or root role:

  • useDb.updateuser (" username ", {" PWD ":" new password "})Function update password
  • useDb.changeuserpassword (" username ", "New Password ")Function update password

Delete user

The db.dropuser () function can be used to delete a specified user, and returns true on success. To delete a user, switch to the database where the user resides. Note: You need to use a user with the userAdmin or userAdminAnyDatabse or root role to delete another user.

[root @ localhost mongo] # bin/mongo mongo shell version v4.4.1 connecting to: mongo: / / 127.0.0.1:27017 /? compressors=disabled&gssapiServiceName=mongodb Implicit session: session { "id" : UUID(" 893992a6-de62-4624-ADEB-136ef2a92525 ")} MongoDB server version: 4.4.1> use admin
switched to db admin
> db.auth("uaad"."uaad")
1
> use test
switched to db test
> show users
{
	"_id" : "test.testuser",
	"userId" : UUID("6ed48451-c1a4-4831-888a-bd80d5697103"),
	"user" : "testuser",
	"db" : "test",
	"roles" : [
		{
			"role" : "readWrite",
			"db" : "test"
		}
	],
	"mechanisms" : [
		"SCRAM-SHA-1",
		"SCRAM-SHA-256"
	]
}
> db.dropUser("testuser")
true
> show users
> 
Copy the code

The above is all the content about MongoDB users and permission management. After learning this article, please enable the identity authentication function for MongoDB of your company to prevent the risk of being blackmailed by bitcoin. Below we will first introduce some MongoDB GUI visual client management tools, make a handy tool first. Then learn about MongoDB databases, collections, documents, indexes, built-in functions, and more.