Authentication plugin caching sha2 password reported error authentication requires secure connection

MySQL version - 8.0.23 on RDS I am replicating my local database to AWS RDS MySQL instance. But I am getting this error: 2021-11-11T22:43:09.091947Z 378 [ERROR] [MY-010584] [Repl] Slave I/O for cha...

MySQL version — 8.0.23 on RDS
I am replicating my local database to AWS RDS MySQL instance. But I am getting this error:

2021-11-11T22:43:09.091947Z 378 [ERROR] [MY-010584] [Repl] Slave I/O for channel '': error connecting to master 'replicator@localhost:3306' - retry-time: 60 retries: 1 message: Authentication plugin 'caching_sha2_password' reported error: Authentication requires secure connection. Error_code: MY-002061

My RDS slave status:

*************************** 1. row ***************************
               Slave_IO_State: Connecting to master
                  Master_Host: localhost
                  Master_User: replicator
                  Master_Port: 3306
                Connect_Retry: 60
              Master_Log_File: DESKTOP-7DL3FOM-bin.000010
          Read_Master_Log_Pos: 700
               Relay_Log_File: relaylog.000001
                Relay_Log_Pos: 4
        Relay_Master_Log_File: DESKTOP-7DL3FOM-bin.000010
             Slave_IO_Running: Connecting
            Slave_SQL_Running: Yes
              Replicate_Do_DB:
          Replicate_Ignore_DB:
           Replicate_Do_Table:
       Replicate_Ignore_Table: innodb_memcache.cache_policies,innodb_memcache.config_options,mysql.plugin,mysql.rds_configuration,mysql.rds_history,mysql.rds_monitor,mysql.rds_replication_status,mysql.rds_sysinfo
      Replicate_Wild_Do_Table:
  Replicate_Wild_Ignore_Table:
                   Last_Errno: 0
                   Last_Error:
                 Skip_Counter: 0
          Exec_Master_Log_Pos: 700
              Relay_Log_Space: 1166
              Until_Condition: None
               Until_Log_File:
                Until_Log_Pos: 0
           Master_SSL_Allowed: No
           Master_SSL_CA_File:
           Master_SSL_CA_Path:
              Master_SSL_Cert:
            Master_SSL_Cipher:
               Master_SSL_Key:
        Seconds_Behind_Master: NULL
Master_SSL_Verify_Server_Cert: No
                Last_IO_Errno: 2061
                Last_IO_Error: error connecting to master 'replicator@localhost:3306' - retry-time: 60 retries: 1 message: Authentication plugin 'caching_sha2_password' reported error: Authentication requires secure connection.
               Last_SQL_Errno: 0
               Last_SQL_Error:
  Replicate_Ignore_Server_Ids:
             Master_Server_Id: 0
                  Master_UUID:
             Master_Info_File: mysql.slave_master_info
                    SQL_Delay: 0
          SQL_Remaining_Delay: NULL
      Slave_SQL_Running_State: Slave has read all relay log; waiting for more updates
           Master_Retry_Count: 86400
                  Master_Bind:
      Last_IO_Error_Timestamp: 211111 23:08:40
     Last_SQL_Error_Timestamp:
               Master_SSL_Crl:
           Master_SSL_Crlpath:
           Retrieved_Gtid_Set:
            Executed_Gtid_Set:
                Auto_Position: 0
         Replicate_Rewrite_DB:
                 Channel_Name:
           Master_TLS_Version:
       Master_public_key_path:
        Get_master_public_key: 0
            Network_Namespace:

I have tried changing my master db user password format to mysql native password. But it is not helping. What should I do to get through this problem?

I am moving from our web sites to a new host. Our database cluster (PCS) now runs MySQL 8. We have two database servers (active and failover) with a floating virtual IP that we connect to MySQL to.

We also have replication running from the cluster to another server (using binary logs). I have setup the replication in the same manner as when we were using MySQL 5.x, including using SSL with self-signed CA and certificates.

Once the certificates are made, I use this configuration on the master:

ssl
ssl-ca=/var/lib/mysql/ssl/ca.pem
ssl-cert=/var/lib/mysql/ssl/server-cert.pem
ssl-key=/var/lib/mysql/ssl/server-key.pem

Replication is now running fine on the slave. However, when I try to connect to the mysql cluster on the command line (from the active DB server) I get the following error:

ERROR 2061 (HY000): Authentication plugin 'caching_sha2_password' reported error: Authentication requires secure connection.

From reading up on this, I thought it was due to the fact that caching_sha2_password is now the default and the docs say that a secure connection is needed. I tried the following:

mysql --ssl-mode=DISABLED

and that didn’t make any difference. I also tried to change the user:

mysql> ALTER USER 'root'@'db-01' IDENTIFIED WITH mysql_native_password BY 'passwordhere'

and that didn’t work either. So far, the only way I’ve been able to login to MySQL is by removing SSL. I found that I can get this to connect like so:

mysql --get-server-public-key

I’m not sure if this is the best solution though.

What is the best way to make my connections work properly in MySQL 8 when using SSL in this manner? There will be a number of accounts from both the DB servers that make up the cluster, on the web servers on the same internal network and from externally (such as replication and remote db management).

If you have installed MySQL version 8.0 or later and tried to establish a connection to its database, you might run into this error:

Authentication plugin 'caching_sha2_password' cannot be loaded: dlopen(/usr/local/mysql/lib/plugin/caching_sha2_password.so, 2): image not found

What is caching_sha2_password Authentication Plugin?

caching_sha2_password is MySQL’s latest authentication plugin which brings some major advancements to the connection encryption, compared to the other authentication mechanisms. The first is, an in-memory cache for faster authentication. Next is a RSA-based password exchange that is independent of the SSL library against which MySQL is linked. And finally, it supports Unix socket-files and shared-memory protocols.

You can read more about its features here.

Why I can’t connect to MySQL 8.0?

The reason for this is while MySQL 8.0 uses caching_sha2_password as the default authentication plugin, your MySQL client hasn’t been compatible with it yet. It uses the older versions of libmysqlclient which do not support this caching_sha2_password plugin. Thus it failed to connect.

For example, Sequel Pro users have been experiencing this due to the fact that Sequel Pro hasn’t supported MySQL 8 (issue #2699) and the caching_sha2_password
plugin is missing (issue 3037).

Note from the Sequel Pro team on Jun 20:

Side note: Support for caching_sha2_password will probably not happen anytime soon.
Sequel Pro currently uses the 5.5 MySQL client library and this plugin is only included with the most recent 8.0 library.
Since there may be internal changes between those versions and we made some customizations ourselves, we have to go 5.5 -> 5.6 -> 5.7 -> 8.0 and check compatibility at each step.
But not even the switch to 5.6 is scheduled for the next release.

Well, that sucks!

Guess I'll wait


Until now, there are a couple solutions for this:

1. Change to legacy password for MySQL Server:
  • Go to System Preferences -> MySQL
  • From Instance tab, choose Initialize Database
  • Choose Use legacy Password Encryption
  • Restart the Server

Use legacy password encryption

Now you might be able to connect to the database again.

2. Use mysql_native_password

You can use the ALTER command to change the encryption of the password to mysql_native_password instead of the latest authentication plugin caching_sha2_password

ALTER USER 'username'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
3. Roll back to the earlier version of MySQL

Back to MySQL 5.7 for example:

But those are just temporary solutions. It’s not recommended if you want to use the latest encryption method.

4. Use another GUI Client which supports MySQL 8
  1. Download TablePlus here or update the TablePlus app to the latest version.
  2. Connect to any version of MySQL, even it requires two-step authentication.
  3. Enjoy coding!

TablePlus is a modern, native client with intuitive GUI tools to create, access, query & edit multiple relational databases: MySQL, PostgreSQL, SQLite, Microsoft SQL Server, Amazon Redshift, MariaDB, CockroachDB, Vertica, Cassandra, Oracle, and Redis.

It’s native, beautiful, and available for free.

Use legacy password encryption

Nov 24, 2021

Summary

You have installed MySQL 8 and are unable to connect your database using your MySQL client (Sequel Pro, HeidiSQL etc). Every attempt to connect using your MySQL client results in the following error

Authentication plugin ‘caching_sha2_password’ cannot be loaded: dlopen(/usr/local/mysql/lib/plugin/caching_sha2_password.so, 2): image not found

or

Authentication plugin ‘caching_sha2_password’ cannot be loaded. The specific module can not be found

Reason

As of MySQL 8.0, caching_sha2_password is now the default authentication plugin rather than mysql_native_password which was the default in previous versions. This means that clients (Sequel Pro, HeidiSQL etc) that rely on the mysql_native_password won’t be able to connect because of this change.

Resolution

1) You can, at a server level, revert to the mysql_native_password mechanism by adding the following to your MySQL configuration files

[mysqld]
default_authentication_plugin=mysql_native_password

2) You can, at a user level, revert to the mysql_native_password mechanism via the following process

Open a terminal window and connect to your MySQL instance via the command line

mysql -u [USERNAME] -p

Enter your MySQL password and press enter and you should be logged into your MySQL instance.

Now run the following SQL command, replacing [USERNAME], [PASSWORD] and [HOST] as appropriate.

Note: [HOST] can be the IP address of your computer which would allow access from your computer only or, in the case of a local development environment, you can use % to allow from any host.

ALTER USER '[USERNAME]'@'[HOST]' 
  IDENTIFIED WITH mysql_native_password 
  BY '[PASSWORD]';

or

ALTER USER '[USERNAME]'@'%' 
  IDENTIFIED WITH mysql_native_password 
  BY '[PASSWORD]';

Now you should be able to go back to your MySQL client and connect as normal.

References

  • 2.11.4 Changes in MySQL 8.0 — https://dev.mysql.com/doc/refman/8.0/en/upgrading-from-previous-series.html
  • 6.4.1.2 Caching SHA-2 Pluggable Authentication — https://dev.mysql.com/doc/refman/8.0/en/caching-sha2-pluggable-authentication.html

Originally published at https://chrisshennan.com/blog/fixing-authentication-plugin-cachingsha2password-cannot-be-loaded-errors

Subscribe to my newsletter…

… and get the ramblings of a wannabe #indiehacker straight in your inbox once a month.

Ramblings will cover a variety of topics including Web Development, DevOps, Startups, Bootstrapping, #buildinpublic, SEO, opinion and personal experience.

I won’t send you spam and you can unsubscribe at any time.

Получили ли вы сообщение об ошибке unable to load authentication plugin ‘caching_sha2_password’ при попытке подключиться к экземпляру базы данных MySQL в контейнере Docker ?. Начиная с MySQL 8.0 плагин аутентификации по умолчанию был изменен на caching_sha2_password с mysql_native_password. Если вы используете более старый клиент MySQL, он может не подключиться к серверу базы данных с сообщением об ошибке “unable to load authentication plugin ‘caching_sha2_password’”.

Чтобы продемонстрировать это, мы создадим контейнер Docker с экземпляром сервера базы данных MySQL 8. Я выполняю эту операцию на сервере Linux Ubuntu 20.04, но можно использовать любую другую ОС. Я начну с установки Docker CE, а затем с создания контейнеров докеров MySQL 8.

Установите Docker CE на Ubuntu

Начну с установки Docker CE на Ubuntu. Используйте последний индекс пакета приложений:

sudo apt -y update
sudo apt -y install apt-transport-https ca-certificates curl gnupg-agent software-properties-common

Импортировать ключ GPG из репозитория Docker:

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

Добавьте репозиторий Docker CE в Ubuntu:

sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"

Наконец, установите Docker CE на Ubuntu:

sudo apt update
sudo apt -y install docker-ce docker-ce-cli containerd.io

Добавьте свою учетную запись пользователя в группу докеров.

sudo usermod -aG docker $USER
newgrp docker

Проверьте установку, проверив версию Docker:

$ docker version
Client: Docker Engine - Community
 Version:           19.03.14
 API version:       1.40
 Go version:        go1.13.15
 Git commit:        5eb3275d40
 Built:             Tue Dec  1 19:20:26 2020
 OS/Arch:           linux/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          19.03.14
  API version:      1.40 (minimum version 1.12)
  Go version:       go1.13.15
  Git commit:       5eb3275d40
  Built:            Tue Dec  1 19:18:53 2020
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.3.9
  GitCommit:        ea765aba0d05254012b0b9e595e995c09186427f
 runc:
  Version:          1.0.0-rc10
  GitCommit:        dc9208a3303feef5b3839f4323d9beb36df0a9dd
 docker-init:
  Version:          0.18.0
  GitCommit:        fec3683

Запустить экземпляр базы данных MySQL в Docker

Теперь мы можем создать контейнер Docker на основе базового образа MySQL 8. Создадим каталог данных:

mkdir ~/mysql_data

Запуск экземпляра базы данных:

docker run -d 
--name mysql8 
-p 3306:3306 
-v ~/mysql_data:/var/lib/mysql 
-e MYSQL_ROOT_PASSWORD='RootUserPssw0rd' 
-e MYSQL_USER=app1 
-e MYSQL_PASSWORD='app1Password' 
-e MYSQL_DATABASE=app1db 
mysql:8

Подтверждаем, что контейнер запущен:

$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                 NAMES
368b02d943ad        mysql:8             "docker-entrypoint.s…"   51 seconds ago      Up 50 seconds       3306/tcp, 33060/tcp   mysql8

Установите клиентские инструменты MariaDB.

sudo apt install mariadb-client

Попробуйте подключиться к экземпляру сервера базы данных как пользователь root.

$ mysql -uroot -p'RootUserPssw0rd' -h 127.0.0.1
ERROR 1045 (28000): Plugin caching_sha2_password could not be loaded: /usr/lib/x86_64-linux-gnu/mariadb19/plugin/caching_sha2_password.so: cannot open shared object file: No such file or directory

Мы можем подтвердить ошибку “Plugin caching_sha2_password could not be loaded“.

С более новой версией клиента MySQL, например 8, у вас не должно возникнуть такой проблемы.

$ mysql --version
mysql  Ver 8.0.22-0ubuntu0.20.04.3 for Linux on x86_64 ((Ubuntu))

# mysql -uroot -p'RootUserPssw0rd' -h 127.0.0.1
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 10
Server version: 8.0.22 MySQL Community Server - GPL

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>

Исправление невозможности загрузить плагин аутентификации  ‘caching_sha2_password’

Проверьте работающие контейнеры, чтобы выбрать контейнер MySQL.

$ docker ps
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                               NAMES
72d48298731e        mysql:8             "docker-entrypoint.s…"   10 minutes ago      Up 10 minutes       0.0.0.0:3306->3306/tcp, 33060/tcp   mysql8

Подключиться к оболочке контейнера.

$ docker exec -ti mysql8 bash
root@72d48298731e:/#

Подключитесь к оболочке MySQL с паролем, переданным в переменной среды во время выполнения.

root@72d48298731e:/# mysql -uroot -p'RootUserPssw0rd'
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: 8.0.22 MySQL Community Server - GPL

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>

Обновите плагин аутентификации.

Для пользователя корневой базы данных

mysql> ALTER USER 'root'@'%' IDENTIFIED WITH mysql_native_password BY 'RootUserPssw0rd';
Query OK, 0 rows affected (0.01 sec)

mysql> q
Bye

root@72d48298731e:/# exit
exit

Подтвердите подключение:

$ mysql -uroot -p'RootUserPssw0rd' -h 127.0.0.1
Welcome to the MariaDB monitor.  Commands end with ; or g.
Your MySQL connection id is 11
Server version: 8.0.22 MySQL Community Server - GPL

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

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

MySQL [(none)]>

Для любых других пользователей базы данных

Для любого другого пользователя базы данных используйте синтаксис команды:

ALTER USER 'dbusername' IDENTIFIED WITH mysql_native_password BY 'DBUserPassword';
# OR
ALTER USER 'dbusername'@'ip_address' IDENTIFIED WITH mysql_native_password BY 'DBUserPassword';

См. Пример ниже, где мы обновляем плагин аутентификации для пользователя базы данных, который мы создали ранее.

mysql> ALTER USER 'app1'@'%' IDENTIFIED WITH mysql_native_password BY 'app1Password';
Query OK, 0 rows affected (0.00 sec)

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

mysql> q
Bye

root@07164b718a3f:/# exit
exit

Повторите команду для подключения к экземпляру MySQL.

$ mysql -u app1 -papp1Password -h 127.0.0.1
Welcome to the MariaDB monitor.  Commands end with ; or g.
Your MySQL connection id is 9
Server version: 8.0.22 MySQL Community Server - GPL

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

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

MySQL [(none)]> SHOW DATABASES;
+--------------------+
| Database           |
+--------------------+
| app1db             |
| information_schema |
+--------------------+
2 rows in set (0.008 sec)

MySQL [(none)]> q
Bye


MySQL provides two authentication plugins that implement SHA-256 hashing for user account passwords:

  • sha256_password: Implements basic SHA-256 authentication.

  • caching_sha2_password: Implements SHA-256 authentication (like sha256_password), but uses caching on the server side for better performance and has additional features for wider applicability. (In MySQL 5.7, caching_sha2_password is implemented only on the client side, as described later in this section.)

This section describes the caching SHA-2 authentication plugin, available as of MySQL 5.7.23. For information about the original basic (noncaching) plugin, see Section 6.4.1.5, “SHA-256 Pluggable Authentication”.

Important

In MySQL 5.7, the default authentication plugin is mysql_native_password. As of MySQL 8.0, the default authentication plugin is changed to caching_sha2_password. To enable MySQL 5.7 clients to connect to 8.0 and higher servers using accounts that authenticate with caching_sha2_password, the MySQL 5.7 client library and client programs support the caching_sha2_password client-side authentication plugin. This improves MySQL 5.7 client connect-capability compatibility with respect to MySQL 8.0 and higher servers, despite the differences in default authentication plugin.

Limiting caching_sha2_password support in MySQL 5.7 to the client-side plugin in the client library has these implications compared to MySQL 8.0:

  • The caching_sha2_password server-side plugin is not implemented in MySQL 5.7.

  • MySQL 5.7 servers do not support creating accounts that authenticate with caching_sha2_password.

  • MySQL 5.7 servers do not implement system and status variables specific to caching_sha2_password server-side support: caching_sha2_password_auto_generate_rsa_keys , caching_sha2_password_private_key_path , caching_sha2_password_public_key_path , Caching_sha2_password_rsa_public_key .

In addition, there is no support for MySQL 5.7 replication slaves to connect to MySQL 8.0 replication masters using accounts that authenticate with caching_sha2_password. That would involve a master replicating to a slave with a version number lower than the master version, whereas masters normally replicate to slaves having a version equal to or higher than the master version.

Important

To connect to a MySQL 8.0 or higher server using an account that authenticates with the caching_sha2_password plugin, you must use either a secure connection or an unencrypted connection that supports password exchange using an RSA key pair, as described later in this section. Either way, the caching_sha2_password plugin uses MySQL’s encryption capabilities. See Section 6.3, “Using Encrypted Connections”.

Note

In the name sha256_password, sha256 refers to the 256-bit digest length the plugin uses for encryption. In the name caching_sha2_password, sha2 refers more generally to the SHA-2 class of encryption algorithms, of which 256-bit encryption is one instance. The latter name choice leaves room for future expansion of possible digest lengths without changing the plugin name.

The caching_sha2_password plugin has these advantages, compared to sha256_password:

  • On the server side, an in-memory cache enables faster reauthentication of users who have connected previously when they connect again. (This server-side behavior is implemented only in MySQL 8.0 and higher.)

  • Support is provided for client connections that use the Unix socket-file and shared-memory protocols.

The following table shows the plugin name on the client side.

Table 6.10 Plugin and Library Names for SHA-2 Authentication

Plugin or File Plugin or File Name
Client-side plugin caching_sha2_password
Library file None (plugin is built in)

The following sections provide installation and usage information specific to caching SHA-2 pluggable authentication:

  • Installing SHA-2 Pluggable Authentication

  • Using SHA-2 Pluggable Authentication

  • Cache Operation for SHA-2 Pluggable Authentication

For general information about pluggable authentication in MySQL, see Section 6.2.13, “Pluggable Authentication”.

Installing SHA-2 Pluggable Authentication

In MySQL 5.7, the caching_sha2_password plugin exists in client form. The client-side plugin is built into the libmysqlclient client library and is available to any program linked against libmysqlclient.

Using SHA-2 Pluggable Authentication

In MySQL 5.7, the caching_sha2_password client-side plugin enables connecting to MySQL 8.0 or higher servers using accounts that authenticate with the caching_sha2_password server-side plugin. The discussion here assumes that an account named 'sha2user'@'localhost' exists on the MySQL 8.0 or higher server. For example, the following statement creates such an account, where password is the desired account password:

CREATE USER 'sha2user'@'localhost'
IDENTIFIED WITH caching_sha2_password BY 'password';

caching_sha2_password supports connections over secure transport. caching_sha2_password also supports encrypted password exchange using RSA over unencrypted connections if these conditions are satisfied:

  • The MySQL 5.7 client library and client programs are compiled using OpenSSL, not yaSSL. caching_sha2_password works with distributions compiled using either package, but RSA support requires OpenSSL.

    Note

    It is possible to compile MySQL using yaSSL as an alternative to OpenSSL only prior to MySQL 5.7.28. As of MySQL 5.7.28, support for yaSSL is removed and all MySQL builds use OpenSSL.

  • The MySQL 8.0 or higher server to which you wish to connect is configured to support RSA (using the RSA configuration procedure given later in this section).

RSA support has these characteristics, where all aspects that pertain to the server side require a MySQL 8.0 or higher server:

  • On the server side, two system variables name the RSA private and public key-pair files: caching_sha2_password_private_key_path and caching_sha2_password_public_key_path . The database administrator must set these variables at server startup if the key files to use have names that differ from the system variable default values.

  • The server uses the caching_sha2_password_auto_generate_rsa_keys system variable to determine whether to automatically generate the RSA key-pair files. See Section 6.3.3, “Creating SSL and RSA Certificates and Keys”.

  • The Caching_sha2_password_rsa_public_key status variable displays the RSA public key value used by the caching_sha2_password authentication plugin.

  • Clients that are in possession of the RSA public key can perform RSA key pair-based password exchange with the server during the connection process, as described later.

  • For connections by accounts that authenticate with caching_sha2_password and RSA key pair-based password exchange, the server does not send the RSA public key to clients by default. Clients can use a client-side copy of the required public key, or request the public key from the server.

    Use of a trusted local copy of the public key enables the client to avoid a round trip in the client/server protocol, and is more secure than requesting the public key from the server. On the other hand, requesting the public key from the server is more convenient (it requires no management of a client-side file) and may be acceptable in secure network environments.

    • For command-line clients, use the --server-public-key-path option to specify the RSA public key file. Use the --get-server-public-key option to request the public key from the server. The following programs support the two options: mysql, mysqladmin, mysqlbinlog, mysqlcheck, mysqldump, mysqlimport, mysqlpump, mysqlshow, mysqlslap, mysqltest.

    • For programs that use the C API, call mysql_options() to specify the RSA public key file by passing the MYSQL_SERVER_PUBLIC_KEY option and the name of the file, or request the public key from the server by passing the MYSQL_OPT_GET_SERVER_PUBLIC_KEY option.

    In all cases, if the option is given to specify a valid public key file, it takes precedence over the option to request the public key from the server.

For clients that use the caching_sha2_password plugin, passwords are never exposed as cleartext when connecting to the MySQL 8.0 or higher server. How password transmission occurs depends on whether a secure connection or RSA encryption is used:

  • If the connection is secure, an RSA key pair is unnecessary and is not used. This applies to TCP connections encrypted using TLS, as well as Unix socket-file and shared-memory connections. The password is sent as cleartext but cannot be snooped because the connection is secure.

  • If the connection is not secure, an RSA key pair is used. This applies to TCP connections not encrypted using without TLS and named-pipe connections. RSA is used only for password exchange between client and server, to prevent password snooping. When the server receives the encrypted password, it decrypts it. A scramble is used in the encryption to prevent repeat attacks.

  • If a secure connection is not used and RSA encryption is not available, the connection attempt fails because the password cannot be sent without being exposed as cleartext.

As mentioned previously, RSA password encryption is available only if MySQL 5.7 was compiled using OpenSSL. The implication for clients from MySQL 5.7 distributions compiled using yaSSL is that, to use SHA-2 passwords, clients must use an encrypted connection to access the server. See Section 6.3.1, “Configuring MySQL to Use Encrypted Connections”.

Assuming that MySQL 5.7 has been compiled using OpenSSL, use the following procedure to enable use of an RSA key pair for password exchange during the client connection process.

Important

Aspects of this procedure that pertain to server configuration must be done on the MySQL 8.0 or higher server to which you wish to connect using MySQL 5.7 clients, not on your MySQL 5.7 server.

  1. Create the RSA private and public key-pair files using the instructions in Section 6.3.3, “Creating SSL and RSA Certificates and Keys”.

  2. If the private and public key files are located in the data directory and are named private_key.pem and public_key.pem (the default values of the caching_sha2_password_private_key_path and caching_sha2_password_public_key_path system variables), the server uses them automatically at startup.

    Otherwise, to name the key files explicitly, set the system variables to the key file names in the server option file. If the files are located in the server data directory, you need not specify their full path names:

    [mysqld]
    caching_sha2_password_private_key_path=myprivkey.pem
    caching_sha2_password_public_key_path=mypubkey.pem

    If the key files are not located in the data directory, or to make their locations explicit in the system variable values, use full path names:

    [mysqld]
    caching_sha2_password_private_key_path=/usr/local/mysql/myprivkey.pem
    caching_sha2_password_public_key_path=/usr/local/mysql/mypubkey.pem
  3. Restart the server, then connect to it and check the Caching_sha2_password_rsa_public_key status variable value. The value will differ from that shown here, but should be nonempty:

    mysql> SHOW STATUS LIKE 'Caching_sha2_password_rsa_public_key'G
    *************************** 1. row ***************************
    Variable_name: Caching_sha2_password_rsa_public_key
            Value: -----BEGIN PUBLIC KEY-----
    MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDO9nRUDd+KvSZgY7cNBZMNpwX6
    MvE1PbJFXO7u18nJ9lwc99Du/E7lw6CVXw7VKrXPeHbVQUzGyUNkf45Nz/ckaaJa
    aLgJOBCIDmNVnyU54OT/1lcs2xiyfaDMe8fCJ64ZwTnKbY2gkt1IMjUAB5Ogd5kJ
    g8aV7EtKwyhHb0c30QIDAQAB
    -----END PUBLIC KEY-----

    If the value is empty, the server found some problem with the key files. Check the error log for diagnostic information.

After the server has been configured with the RSA key files, accounts that authenticate with the caching_sha2_password plugin have the option of using those key files to connect to the server. As mentioned previously, such accounts can use either a secure connection (in which case RSA is not used) or an unencrypted connection that performs password exchange using RSA. Suppose that an unencrypted connection is used. For example:

shell> mysql --ssl-mode=DISABLED -u sha2user -p
Enter password: password

For this connection attempt by sha2user, the server determines that caching_sha2_password is the appropriate authentication plugin and invokes it (because that was the plugin specified at CREATE USER time). The plugin finds that the connection is not encrypted and thus requires the password to be transmitted using RSA encryption. However, the server does not send the public key to the client, and the client provided no public key, so it cannot encrypt the password and the connection fails:

ERROR 2061 (HY000): Authentication plugin 'caching_sha2_password'
reported error: Authentication requires secure connection.

To request the RSA public key from the server, specify the --get-server-public-key option:

shell> mysql --ssl-mode=DISABLED -u sha2user -p --get-server-public-key
Enter password: password

In this case, the server sends the RSA public key to the client, which uses it to encrypt the password and returns the result to the server. The plugin uses the RSA private key on the server side to decrypt the password and accepts or rejects the connection based on whether the password is correct.

Alternatively, if the client has a file containing a local copy of the RSA public key required by the server, it can specify the file using the --server-public-key-path option:

shell> mysql --ssl-mode=DISABLED -u sha2user -p --server-public-key-path=file_name
Enter password: password

In this case, the client uses the public key to encrypt the password and returns the result to the server. The plugin uses the RSA private key on the server side to decrypt the password and accepts or rejects the connection based on whether the password is correct.

The public key value in the file named by the --server-public-key-path option should be the same as the key value in the server-side file named by the caching_sha2_password_public_key_path system variable. If the key file contains a valid public key value but the value is incorrect, an access-denied error occurs. If the key file does not contain a valid public key, the client program cannot use it.

Client users can obtain the RSA public key two ways:

  • The database administrator can provide a copy of the public key file.

  • A client user who can connect to the server some other way can use a SHOW STATUS LIKE 'Caching_sha2_password_rsa_public_key' statement and save the returned key value in a file.

Cache Operation for SHA-2 Pluggable Authentication

On the server side, the caching_sha2_password plugin uses an in-memory cache for faster authentication of clients who have connected previously. For MySQL 5.7, which supports only the caching_sha2_password client-side plugin, this server-side caching thus takes place on the MySQL 8.0 or higher server to which you connect using MySQL 5.7 clients. For information about cache operation, see Cache Operation for SHA-2 Pluggable Authentication , in MySQL 8.0 Reference Manual .

Понравилась статья? Поделить с друзьями:
  • Authentication error scp secret laboratory
  • Authentication error right click on forts
  • Attempt to call global a nil value ошибка
  • Authentication error occurred wifi
  • Attempt 1 at connecting failed connection error proxy connection timed out 10