A brief discussion on the matching rules of host and user when Mysql connects to the database

A brief discussion on the matching rules of host and user when Mysql connects to the database

--When connecting to the database, the matching rules of host and user

Official documentation: https://dev.mysql.com/doc/refman/5.7/en/connection-access.html

--The matching rules for host and user are as follows:

--If the host is clear, it will be matched first. If the host is ambiguous with % it will be matched last. However, if the host is '' (empty), it will be matched after %.

--When the hosts are the same, the user with a clear name will be matched first, and the user with '' (empty) will be matched last

--When the host and user are the same, the sorting is uncertain

When multiple matches are possible, the server must determine which of them to use. It resolves this issue as follows: 
Whenever the server reads the user table into memory, it sorts the rows. 
When a client attempts to connect, the server looks through the rows in sorted order. 
The server uses the first row that matches the client host name and user name. 
The server uses sorting rules that order rows with the most-specific Host values ​​first. Literal host names and IP addresses are the most specific. (The specificity of a literal IP address is not affected by whether it has a netmask, so 198.51.100.13 and 198.51.100.0/255.255.255.0 are considered equally specific.) The pattern '%' means "any host" and is least specific. The empty string '' also means "any host" but sorts after '%'. Rows with the same Host value are ordered with the most-specific User values ​​first (a blank User value means "any user" and is least specific). For rows with equally-specific Host and User values, the order is nondeterministic.

--Check the current host and user information matching order, first host order matching, then user order matching

mysql> SELECT authentication_string, host, user,account_locked FROM mysql.USER ORDER BY host desc ,user desc;
+-------------------------------------------+--------------+---------------+----------------+
| authentication_string | host | user | account_locked |
+-------------------------------------------+--------------+---------------+----------------+
| *511C0A408C5065XXEC90D60YYA1AB9437281AF28 | localhost | root | N |
| *THISISNOTAVALIXXASSWORDYYATCANBEUSEDHERE | localhost | mysql.sys | Y |
| *THISISNOTAVALIXXASSWORDYYATCANBEUSEDHERE | localhost | mysql.session | Y |
| *485CE31BA547A4XXC047659YY10DF200F361CD4E | localhost | bkpuser | N |
| *7B502777D8FF69XX4B56BC2YY2867F4B47321BA8 | 192.168.56.% | repl | N |
| *AECCE73463829AXX3968838YYF6F85E43C3F169C | % | flyremote | N |
| *566AC8467DAAAEXXE247AE7YY0A770E9B97D9FB0 | | flylocal | N |
+-------------------------------------------+--------------+---------------+----------------+
8 rows in set (0.00 sec)
 

--Let me give you a special example.

--Create two special users as follows, one with username '' (empty), and one with username and host both '' (empty)

mysql> create user ''@'localhost' identified by "Kong123$";
Query OK, 0 rows affected (0.00 sec) 
mysql> create user ''@'' identified by "doubleKong123$";   
Query OK, 0 rows affected (0.00 sec)

--Check the current host and user information matching order, first host order matching, then user order matching

mysql> SELECT authentication_string, host, user,account_locked FROM mysql.USER ORDER BY host desc ,user desc;
+-------------------------------------------+--------------+---------------+----------------+
| authentication_string | host | user | account_locked |
+-------------------------------------------+--------------+---------------+----------------+
| *511C0VVV8C5065CBEC90D6TTTT1AB9437281AF28 | localhost | root | N |
| *THISIVVVTAVALIDPASSWORTTTTTCANBEUSEDHERE | localhost | mysql.sys | Y |
| *THISIVVVTAVALIDPASSWORTTTTTCANBEUSEDHERE | localhost | mysql.session | Y |
| *485CEVVVA547A48CC04765TTTT0DF200F361CD4E | localhost | bkpuser | N |
| *256D7VVV91F7363EBDADEFTTTTB74B2B318746FC | localhost | | N |
| *7B502VVVD8FF69164B56BCTTTT867F4B47321BA8 | 192.168.56.% | repl | N |
| *AECCEVVV63829A5F396883TTTT6F85E43C3F169C | % | flyremote | N |
| *566ACVVV7DAAAE79E247AETTTTA770E9B97D9FB0 | | flylocal | N |
| *AE162VVV68403D1D98A4C9TTTT50A508B8C56F3F | | | N |
+-------------------------------------------+--------------+---------------+----------------+
9 rows in set (0.00 sec)

--In this way, an error will be reported when logging in to the flyremote user locally, because in the above order, the user with host localhost and user '' (empty) is matched first, rather than the flyremote user (because the user with user '' (empty) can match any user name)

[root@hostmysql-m mysql]# mysql -uflyremote -pFlyremote123$
mysql: [Warning] Using a password on the command line interface can be insecure.
ERROR 1045 (28000): Access denied for user 'flyremote'@'localhost' (using password: YES)

--That is to say, when you log in to the flyremote user locally, you can log in normally with the matched host as localhost, user as '' (empty) and password Kong123$

[root@hostmysql-m mysql]# mysql -uflyremote -pKong123$
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 15
Server version: 5.7.23-log MySQL Community Server (GPL) 
Copyright (c) 2000, 2018, 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.

--View the current user connection method and current user authentication method

mysql> select user(),CURRENT_USER();
+---------------------+----------------+
| user() | CURRENT_USER() |
+---------------------+----------------+
| flyremote@localhost | @localhost |
+---------------------+----------------+
1 row in set (0.06 sec)

--There is no problem when logging in to the flyremote user by importing the ip, the ip matches % and the user matches flyremote

[root@hostmysql-m mysql]# mysql -uflyremote -pFlyremote123$ -h127.11.22.33 
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 12
Server version: 5.7.23-log MySQL Community Server (GPL) 
Copyright (c) 2000, 2018, 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>

--View the current user connection method and current user authentication method

mysql> select user(),CURRENT_USER();
+------------------------+----------------+
| user() | CURRENT_USER() |
+------------------------+----------------+
| [email protected] | flyremote@% |
+------------------------+----------------+
1 row in set (0.00 sec)

--Any user, any host, as long as the password matches the password of the second empty user and empty host "doubleKong123$" created, you can enter mysql

--Test a non-existent user hahaha

[root@hostmysql-m ~]# mysql -uhahaha -pdoubleKong123$ -h127.11.22.33
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 6
Server version: 5.7.23-log MySQL Community Server (GPL) 
Copyright (c) 2000, 2018, 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>

--View the current user connection method and current user authentication method

mysql> select user(),CURRENT_USER();
+---------------------+----------------+
| user() | CURRENT_USER() |
+---------------------+----------------+
| [email protected] | @ |
+---------------------+----------------+
1 row in set (0.01 sec)

--Solution:

1. Manually delete empty users and empty host users to ensure security

or

2. Use mysql_secure_installation for security configuration

--The security configuration is as follows, which includes the operation of deleting anonymous users

This program enables you to improve the security of your MySQL installation in the following ways:
 You can set a password for root accounts.
 You can remove root accounts that are accessible from outside the local host.
 You can remove anonymous-user accounts.
 You can remove the test database (which by default can be accessed by all users, even anonymous users), and privileges that permit anyone to access databases with names that start with test_.

--Delete the anonymous user source code mysql_secure_installation.cc as follows:

 //Remove anonymous users
 remove_anonymous_users(); 
/**
 Removes all the anonymous users for better security.
*/
void remove_anonymous_users()
{
 int reply;
 reply = get_response((const char *) "By default, a MySQL installation has an "
      "anonymous user,\nallowing anyone to log "
      "into MySQL without having to have\na user"
      "account created for them. This is intended "
      "only for\ntesting, and to make the "
      "installation go a bit smoother.\nYou should"
      "remove them before moving into a production\n"
      "environment.\n\nRemove anonymous users? "
      "(Press y|Y for Yes, any other key for No) : ", 'y');
 
 if (reply == (int) 'y' || reply == (int) 'Y')
 {
 const char *query;
 query = "SELECT USER, HOST FROM mysql.user WHERE USER = ''";
 if (!execute_query(&query, strlen(query)))
  DBUG_PRINT("info", ("query success!"));
 MYSQL_RES *result = mysql_store_result(&mysql);
 if (result)
  drop_users(result);
 mysql_free_result(result);
 fprintf(stdout, "Success.\n\n");
 }
 else
 fprintf(stdout, "\n ... skipping.\n\n");
}

Supplement: Matching rules for multiple hosts in MySQL user table

The host field of the user table in the MySQL database is used to control the user's "permission" to access the database.

You can use "%" to indicate all network segments;

You can also use a specific IP address, which means that only clients with that IP address can log in to the MySQL server.

You can also use "_" for fuzzy matching, indicating that clients in a certain network segment can log in to the MySQL server.

If there are two records with different host values ​​for a user in the user table, how does the MySQL server match the user's permissions?

The strategy used by mysql is that when the server reads the user table, it first sorts by the most specific host value (host name and IP number are the most specific). Entries with the same Host value are matched first with the most specific User.

Example:

As shown below, there are two root users, so only the root client of localhost can log in to the mysql server.

| root | localhost | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B |
| root | % | *81F5E21E35407D884A6CD4A731AEBFB6AF209E1B |

The above is my personal experience. I hope it can give you a reference. I also hope that you will support 123WORDPRESS.COM. If there are any mistakes or incomplete considerations, please feel free to correct me.

You may also be interested in:
  • How to set and get the number of Mysql connections
  • Three ways to connect PHP to MySQL database
  • How to remotely connect to MySQL database with Navicat Premium
  • Detailed steps to use IDEA to configure Tomcat and connect to MySQL database (JDBC)
  • Detailed explanation of DBeaver connecting to MySQL version 8 and above and solving possible problems
  • Solution to failure in connecting to mysql in docker
  • Solve the problem of error 10038 when connecting to MySQL remotely in Navicat
  • Php common code for connecting, reading and writing mysql database
  • Detailed explanation of remote connection to MySQL authorization method
  • How to connect to MySql database in C#
  • The unreasonable MaxIdleConns of MySQL will cause short connections

<<:  HTML table markup tutorial (29): cell light border color attribute BORDERCOLORLIGHT

>>:  Docker time zone issue and data migration issue

Recommend

Understanding and application scenarios of enumeration types in TypeScript

Table of contents 1. What is 2. Use Numeric Enume...

Introduction to the common API usage of Vue3

Table of contents Changes in the life cycle react...

Vue/react single page application back without refresh solution

Table of contents introduction Why bother? Commun...

2 reasons why html-css tag style setting does not work

1 CSS style without semicolon ";" 2 Tags...

Bootstrap 3.0 study notes page layout

This time we will mainly learn about layout, whic...

HTML5+CSS3 coding standards

The Golden Rule No matter how many people are wor...

VUE+Canvas realizes the whole process of a simple Gobang game

Preface In terms of layout, Gobang is much simple...

MySQL database index order by sorting detailed explanation

Table of contents The cause of the incident Anato...

Get the calculated style in the CSS element (after cascading/final style)

To obtain the calculated style in a CSS element (t...

Analysis of the process of simply deploying nginx in Docker container

1. Deploy nginx service in container The centos:7...

Solution to forgetting mysql password under linux

The problem is as follows: I entered the command ...

Workerman writes the example code of mysql connection pool

First of all, you need to understand why you use ...

Ideas for creating wave effects with CSS

Previously, I introduced several ways to achieve ...