Linux-MySQL users and permissions

MySQL users and permissions

PS: This article is a document written for mysql5.7.32! ! !

mysql> select version();
+-----------+
| version() |
+-----------+
| 5.7.32    |
+-----------+
1 row in set (0.00 sec)

1. Knowledge overview

PS: If the number of user queries or connections exceeds the resource control limit within one hour, the user will be locked, and the corresponding operation can be performed here until the next hour. But you can use the GRANT statement to update the values ​​of these fields.

1. User column

	user表的用户列包括 Host、 User、password(在5.7.32中password叫authentication_string),分别表示主机名、用户名和密码。其中 user和 Host为user表的联合主踺。当用户与服务器之间建立连接时,输入的账户信息中的用户名称、主机名和密码必须匹配user表中对应的字段,只有3个值都匹配的时候,才允许连接的建立。这3 个字段的值就是创建账户时保存的账户信息。修改用户密码时,实际就是修改user表的password字段的值。

2. Permission column

​ The field of the permission column determines the user's permissions and describes the operations allowed on the data and database in the global scope. Including general permissions such as query permissions, modification permissions, and advanced permissions such as shutting down the server, super permissions, and loading users. Common permissions are used to manipulate the database; advanced permissions are used for database management. The corresponding permissions in the user table are for all user databases. The type of these field values ​​is ENUM, and the available values ​​can only be Y and N. Y means that the user has corresponding permissions; N means that the user does not have corresponding permissions. Looking at the structure of the user table, you can see that the values ​​of these fields are all N by default. If you want to modify the permissions, you can use the GRANT statement or UPDATE statement to change these fields of the user table to modify the user's corresponding permissions.

3. Safety column

​ The security column has only 6 fields, two of which are related to SSI, two are related to x509, and the other two are related to authorized plug-ins. SSI is used for encryption; X509 standard can be used to identify users: The Plugin field identifies the plug-in that can be used to verify the user's identity. If the field is empty, the server uses the built-in authorization verification mechanism to verify the user's identity. You can use the SHOW VARIABLES LIKE'have_openssl' statement to query whether the server supports the SSI function.

4. Resource control column

The fields in the resource control column are used to limit the resources used by the user. It contains 4 fields, namely:

  • Max_questions—The number of query operations the user is allowed to perform per hour.
  • Max_updates is the number of update operations that a user is allowed to perform per hour.
  • Max_connections—the number of connection operations the user is allowed to perform per hour.
  • Max_user_connections—The number of connections the user is allowed to establish at the same time.

5.Db table and Host table

​ The db table and host table are very important permission tables in MYSQL data. The db table stores the user's operating authority for a certain database, and determines which database the user can access from which host. The host table stores the operation authority of a certain host on the database, and cooperates with the db authority table to control the database-level operation authority on a given host in more detail. This permission table is not affected by the GRANT and REVOKE statements. The db table is commonly used, and the host table is rarely used. The structure of the db table and the host table are similar, and the fields can be roughly divided into two categories: user column and permission column

Two, create a user

grammar:

mysql> help create user
Name: 'CREATE USER'
Description:
Syntax:
CREATE USER [IF NOT EXISTS]
    user [auth_option] [, user [auth_option]] ...
    [REQUIRE {NONE | tls_option [[AND] tls_option] ...}]
    [WITH resource_option [resource_option] ...]
    [password_option | lock_option] ...

......
  • User: indicates the name of the created user;
  • host: indicates the host name of the user allowed to log in;
  • IDENTIFIED BY: indicates the password used to set the user;
  • [PASSWORD]: Means to use hash value to set password;
  • 'password': indicates the normal plaintext password used when the user logs in;
  • IDENTIFIED WITH: indicates that the user specifies an authentication plug-in;
  • auth_plugin: is the name of the plug-in;
  • 'auth_string': is an optional string that explains the meaning of the plug-in. View MySQL users

Method 1: Use the CREATE USER statement to create a new user

#带密码创建
mysql> create user 'tom'@'localhost' identified by '123.com';
Query OK, 0 rows affected (0.10 sec)

#不带密码创建
mysql> create user 'zhangsan'@'localhost';
Query OK, 0 rows affected (0.00 sec)

#利用哈希加密创建用户
mysql> select password('123.com');
+-------------------------------------------+
| password('123.com')                       |
+-------------------------------------------+
| *AC241830FFDDC8943AB31CBD47D758E79F7953EA |
+-------------------------------------------+
1 row in set, 1 warning (0.04 sec)

mysql> create user 'wangwu'@'localhost' identified by password '*AC241830FFDDC8943AB311CBD47D758E79F7953EA';
Query OK, 0 rows affected, 1 warning (0.00 sec)

#查询mysql库user表中User字段为tom的列
mysql> select * from mysql.user where user='tom'\G;
*************************** 1. row ***************************
                  Host: localhost
                  User: tom
#以下是权限,“N”表示没有对应的权限,“Y”表示拥有对应的权限-	
           Select_priv: N
           Insert_priv: N
           Update_priv: N
           Delete_priv: N
           Create_priv: N
             Drop_priv: N
           Reload_priv: N
         Shutdown_priv: N
          Process_priv: N
             File_priv: N
            Grant_priv: N
       References_priv: N
            Index_priv: N
            Alter_priv: N
          Show_db_priv: N
            Super_priv: N
 Create_tmp_table_priv: N
      Lock_tables_priv: N
          Execute_priv: N
       Repl_slave_priv: N
      Repl_client_priv: N
      Create_view_priv: N
        Show_view_priv: N
   Create_routine_priv: N
    Alter_routine_priv: N
      Create_user_priv: N
            Event_priv: N
          Trigger_priv: N
Create_tablespace_priv: N
              ssl_type: 
            ssl_cipher: 
           x509_issuer: 
          x509_subject: 
         max_questions: 0
           max_updates: 0
       max_connections: 0
  max_user_connections: 0
                plugin: mysql_native_password
 authentication_string: *AC241830FFDDC8943AB31CBD47D758E79F7953EA      #经过哈希加密过的密码
      password_expired: N
 password_last_changed: 2021-01-05 15:05:20
     password_lifetime: NULL
        account_locked: N
1 row in set (0.10 sec)

ERROR: 
No query specified

Method 2: Use the Grant statement to create a new user

#创建用户lisi
mysql> grant select,update on *.* to 'lisi'@'localhost' identified by '123.com';
Query OK, 0 rows affected, 1 warning (0.01 sec)

#查询mysql库user表中User字段为lisi的列:以下是权限,“N”表示没有对应的权限,“Y”表示拥有对应的权限-	
mysql> select host,user,select_priv,update_priv from mysql.user where user='lisi';
+-----------+------+-------------+-------------+
| host      | user | select_priv | update_priv |
+-----------+------+-------------+-------------+
| localhost | lisi | Y           | Y           |
+-----------+------+-------------+-------------+
1 row in set (0.00 sec)

#新添加的用户还无法使用账号和密码登陆MySQL,需要使用FLUSH告诉服务器重新加载授权
mysql>  FLUSH privileges;
Query OK, 0 rows affected (0.00 sec)

Extension: verify whether the created user has the corresponding permissions

#用lisi用户登录
[root@mysql ~]# mysql -ulisi  -p123.com
#查看有哪些数据库
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| sys                |
| test               |
+--------------------+
#查看test数据库
mysql> show tables from test;
+----------------+
| Tables_in_test |
+----------------+
| test           |
+----------------+
1 row in set (0.00 sec)
#查看test库下test表
mysql> select * from test.test;
+------+------+------+
| a    | b    | c    |
+------+------+------+
|    1 | a    |  100 |
|    2 | b    |  100 |
+------+------+------+
2 rows in set (0.00 sec)
#更新数据
mysql> update test.test set c=1000 where a=1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0
#查看更新数据
mysql> select * from test.test;
+------+------+------+
| a    | b    | c    |
+------+------+------+
|    1 | a    | 1000 |
|    2 | b    |  100 |
+------+------+------+
2 rows in set (0.00 sec)

**Summary:** The reason why lisi users can view is because select and update permissions are given when creating lisi users! ! !

Three, delete users

1. Use the DROP USER statement to delete

mysql> drop user zhangsan@localhost;
Query OK, 0 rows affected (0.00 sec)

2. Use the DELETE statement to delete users

#查看mysql中user表有哪些用户!!!
mysql> SELECT host,user,authentication_string FROM mysql.user;
+-----------+---------------+-------------------------------------------+
| host      | user          | authentication_string                     |
+-----------+---------------+-------------------------------------------+
| localhost | root          | *6BB4837EB74329105EE4568DDA7DC67ED2CA2AD9 |
| localhost | mysql.session | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| localhost | mysql.sys     | *THISISNOTAVALIDPASSWORDTHATCANBEUSEDHERE |
| localhost | tom           | *AC241830FFDDC8943AB31CBD47D758E79F7953EA |
| localhost | zhangsan      |                                           |
| localhost | wangwu        | *AC241830FFDDC8943AB31CBD47D758E79F7953EA |
| localhost | lisi          | *AC241830FFDDC8943AB31CBD47D758E79F7953EA |
| localhost | testUser      | *AC241830FFDDC8943AB31CBD47D758E79F7953EA |
+-----------+---------------+-------------------------------------------+
8 rows in set (0.01 sec)

#删除
mysql> delete from mysql.user where host='localhost' and user ='tom';
Query OK, 1 row affected (0.32 sec)

Four, modify user

1. Root users modify their own password

1.1 Use mysqladmin command

[root@mysql ~]# mysqladmin  -u root -p password "123.com"
Enter password:   #填写root用户旧密码
mysqladmin: [Warning] Using a password on the command line interface can be insecure.
Warning: Since password will be sent to server in plain text, use ssl connection to ensure password safety.

1.2 Modify the user table of the mysql database

mysql> update mysql.user set authentication_string=password("123456") where user="root" and host="localhost";
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 1

mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)

1.3 Use the SET statement to modify the password of the root user

mysql> SET PASSWORD=PASSWORD("123.com");
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

2. Root users modify ordinary user passwords

2.1 Use the SET statement to modify the password of an ordinary user

mysql>  SET PASSWORD FOR 'testUser'@'localhost'=PASSWORD("newped");
Query OK, 0 rows affected, 1 warning (0.00 sec)

2.2 Use the UPDATE statement to modify the ordinary user password

mysql> UPDATE mysql.user SET authentication_string=password("mima") where user='testUser' and host='localhost';
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 1

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.00 sec)

2.3 Use GRANT statement to modify ordinary user password

mysql> GRANT USAGE ON *.* TO 'testUser'@'localhost' IDENTIFIED BY '123.com';
Query OK, 0 rows affected, 1 warning (0.00 sec)

3. Ordinary users modify their own passwords

#普通用户修改密码 先登录
[root@mysql ~]# mysql -utestUser -p123.com
#修改密码
mysql> SET PASSWORD=PASSWORD("newped");
Query OK, 0 rows affected, 1 warning (0.00 sec)
#退出
mysql> exit
Bye
#使用新密码登录
[root@mysql ~]# mysql -utestUser -pnewped
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 16
Server version: 5.7.32 Source distribution

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

4...Solution to Root User Password Loss

3.1 Use the --skip-grant-tables option to start the mysql service

[root@mysql ~]# systemctl stop mysqld.service
[root@mysql ~]#  mysqld -uroot --skip-grant-tables

#无密码可登录
[root@mysql ~]# mysql -u root
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 2
Server version: 5.7.32 Source distribution

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

#更加mysql.user修改密码
mysql> update mysql.user set authentication_string=password('123') where user='root' and host='localhost';
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 1

#刷新一下
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)


mysql> exit
Bye
#重启mysql服务,使用新密码登录
[root@mysql ~]# systemctl  restart  mysqld
[root@mysql ~]# mysql -uroot -p123
mysql: [Warning] Using a password on the command line interface can be insecure.
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.32 Source distribution

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

Five, authority management

​ Permission management is mainly to verify the permissions of users who log in to MySQL. The permissions of all users are stored in the MySQL permission table. Unreasonable permission planning brings security risks to the MySQL server. The main function of the MySQL permission system is to verify the user connected to a given host and grant the user SELECT\INSERT\UPDATE and DELETE permissions on the database. Account permission information is stored in the user, db, tables_priv, columns_priv and procs_priv tables of the MySQL database. When MySQL starts, the server reads the content of the permission information in these database tables into memory.

Authority

  • CREATE and DROP permissions, you can create new databases and tables, or delete (remove) existing databases and tables. If the DROP permission in the MySQL database is granted to a user, the user can delete the database saved with the MySQL access permission.
  • SELECT, INSERT, UPDATE, and DELETE permissions allow operations to be performed on existing tables in a database.
  • SELECT permissions are only used when they actually retrieve rows from a table.
  • INDEX permission allows to create or delete indexes, INDEX is applicable to own tables. If you have CREATE permission for a table, you can include the index definition in the CREATE TABLE statement.
  • ALTER permission, you can use ALTER TABLE to change the structure of the table and rename the table.
  • CREATE ROUTINE permission is used to create saved programs (functions and programs), ALTER ROUTINE permission is used to modify and delete saved programs, and EXECUTE permission is used to execute saved programs.
  • RANT permissions allow authorization to other users. Can be used in databases, tables and saved programs.
  • FILE permissions give users the use of LOAD DATA INFILE and SELECT... INTO OUTFILE statements to read or write files on the server, and any user granted FILE permissions can read or write any file on the MySQL server. (It means that users can read files in any database directory because the server can access these files). FILE permission allows users to create new files in a directory with write permission on the MySQL server, but cannot overwrite their own files.

Authorization

Authorization is to grant permissions to a user. Reasonable authorization can ensure the security of the database. In MySQL, you can use the GRANT statement to grant permissions to users. The permissions granted can be divided into multiple levels:

  • Global level global permissions apply to all databases in a given server. These permissions are stored in the mysql.user table. GRANT ALL ON and REVOKE ALL ON only grant and revoke global permissions.
  • Database level database permissions apply to all targets in a given database. These permissions are stored in the mysql.db and mysql.host tables. GRANT ALL ON db_name and REVOKE ALL ON db_name.* only grant and revoke database permissions.
  • Table-level table permissions apply to all columns in a given table. These permissions are stored in the mysql.tables_priv table. GRANT ALL ON db_name.tb1_name and REVOKE ALL ON db_name.tb1_name only grant and revoke table permissions.
  • Column-level column permissions apply to a single column in a given table. These permissions are stored in the mysql.columns_priv table. When using REVOKE, you must specify the same column as the authorized column.
  • The subroutine level CREATE ROUTINE, ALTER ROUTINE, EXCUTE and GRANT permissions apply to stored subroutines. These permissions can be granted to the global level and the database level. Moreover, in addition to CREATE ROUTINE, these permissions can be granted to the subroutine level and stored in the mysql.procs_priv table. In MySQL, a user with GRANT privileges can execute GRANT statements. To use GRANT or REVOKE, you must have GRANT OPTION permissions, and must be used for the permissions being granted or revoked.

The syntax of GRANT is as follows:

mysql> help grant
Name: 'GRANT'
Description:
Syntax:
GRANT
    priv_type [(column_list)]
      [, priv_type [(column_list)]] ...
    ON [object_type] priv_level
    TO user [auth_option] [, user [auth_option]] ...
    [REQUIRE {NONE | tls_option [[AND] tls_option] ...}]
    [WITH {GRANT OPTION | resource_option} ...]

GRANT PROXY ON user
    TO user [, user] ...
    [WITH GRANT OPTION]

object_type: {
    TABLE
  | FUNCTION
  | PROCEDURE
}

priv_level: {
    *
  | *.*
  | db_name.*
  | db_name.tbl_name
  | tbl_name
  | db_name.routine_name
}

user:
    (see https://dev.mysql.com/doc/refman/5.7/en/account-names.html)

  • Privileges: indicates the type of permissions granted to the user;
  • db.table: Represents the table in the database that the user's permissions act on;
  • The identified by keyword is used to set the password;
  • The password of the'password' user; [with grant option] is optional, which means granting GRANT permissions to the newly created user.

GRANT OPTION has 5 values, meaning:

  • GRANT OPTION: Grant your own authority to other users.
  • |MAX_QUERIES_PER_HOUR count: set count queries can be executed per hour
  • |MAX_UPDATE_PER_HOUR count: Set up count updates per hour
  • |MAX_CONNECTIONS_PER_HOUR count: Set up count connections per hour
  • |MAX_USER_PER_HOUR count: Set that a single user can establish count connection creation permissions and view at the same time

Create permissions

mysql> GRANT SELECT,INSERT ON *.* TO 'masan'@'localhost' IDENTIFIED BY 'grantpwd';
Query OK, 0 rows affected, 1 warning (0.00 sec)

mysql> SELECT Host,User,Select_priv,Insert_priv,Grant_priv from mysql.user where user='masan';
+-----------+-------+-------------+-------------+------------+
| Host      | User  | Select_priv | Insert_priv | Grant_priv |
+-----------+-------+-------------+-------------+------------+
| localhost | masan | Y           | Y           | N          |
+-----------+-------+-------------+-------------+------------+
1 row in set (0.01 sec)


Withdraw permission

​ Withdrawal of permissions is to cancel certain permissions that have been granted to the user. Recovering unnecessary user permissions can ensure the security of the system to a certain extent. MySQL uses the REVOKE statement to cancel certain permissions of the user. After using REVOKE to recover the permissions, the user account records will be deleted from the db, host, user, tables_priv and columns_priv tables, but the user account records are still stored in the user table (delete user For account records in the table, use the DROP USER statement) The REVOKE statement has two uses. The first grammar is to withdraw all permissions from all users. This grammar is used to cancel all global levels, database levels, and table levels for the named user. And column-level permissions.

mysql> REVOKE INSERT ON *.* FROM 'masan'@'localhost';
Query OK, 0 rows affected (0.00 sec)

#查看用户权限
mysql> SELECT Host,User,Select_priv,Insert_priv,Grant_priv from mysql.user where user='masan';
+-----------+-------+-------------+-------------+------------+
| Host      | User  | Select_priv | Insert_priv | Grant_priv |
+-----------+-------+-------------+-------------+------------+
| localhost | masan | Y           | N           | N          |
+-----------+-------+-------------+-------------+------------+
1 row in set (0.00 sec)

mysql>  SHOW GRANTS FOR 'masan'@'localhost'\G
*************************** 1. row ***************************
Grants for masan@localhost: GRANT SELECT ON *.* TO 'masan'@'localhost'
1 row in set (0.00 sec)

Guess you like

Origin blog.csdn.net/weixin_45191791/article/details/112251687