Як використовувати MySQL без пароля (і ризиків для безпеки)

Як використовувати MySQL без пароля (і ризиків для безпеки)

Кажуть, що найкращий пароль – той, який не треба запам'ятовувати. У випадку з MySQL це реально завдяки плагіну auth_socket та його версії для MariaDB unix_socket.

Обидві ці плагіни — зовсім не нові, про них багато говорилося в цьому ж блозі, наприклад у статті про те, як змінювати паролі MySQL 5.7, використовуючи плагін auth_socket. Однак, розбираючи, що новенького в MariaDB 10.4, я виявив, що unix_socket тепер встановлюється за умовчанням і є одним з методів аутентифікації («одним з», тому що в MariaDB 10.4 одному користувачеві для аутентифікації є більше одного плагіна, що пояснюється в документі "Аутентифікація" від MariaDB 10.04).

Як я вже сказав, це не новини, і коли встановлюєш MySQL, використовуючи підтримувані командою Debian пакети .deb, користувач з root-правами створюється під аутентифікацію через сокет. Це справедливо як MySQL, так MariaDB.

root@app:~# apt-cache show mysql-server-5.7 | grep -i maintainers
Original-Maintainer: Debian MySQL Maintainers <[email protected]>
Original-Maintainer: Debian MySQL Maintainers <<a href="mailto:[email protected]">[email protected]</a>>

З пакетами Debian для MySQL, root користувач автентифікується так:

root@app:~# whoami
root=
root@app:~# mysql
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 4
Server version: 5.7.27-0ubuntu0.16.04.1 (Ubuntu)

Copyright (c) 2000, 2019, 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> select user, host, plugin, authentication_string from mysql.user where user = 'root';
+------+-----------+-------------+-----------------------+
| user | host      | plugin | authentication_string |
+------+-----------+-------------+-----------------------+
| root | localhost | auth_socket |                       |
+------+-----------+-------------+-----------------------+
1 row in set (0.01 sec)

Те саме і у випадку з пакетом .deb для MariaDB:

10.0.38-MariaDB-0ubuntu0.16.04.1 Ubuntu 16.04

MariaDB [(none)]> show grants;
+------------------------------------------------------------------------------------------------+
| Grants for root@localhost                                                                      |
+------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED VIA unix_socket WITH GRANT OPTION |
| GRANT PROXY ON ''@'%' TO 'root'@'localhost' WITH GRANT OPTION                                  |
+------------------------------------------------------------------------------------------------+
2 rows in set (0.00 sec)

Пакети .deb з офіційного репозиторію Percona також налаштовують автентифікацію користувача з root-правами під auth-socket та Percona Server. Наведемо приклад з Percona Server for MySQL 8.0.16-7 та Ubuntu 16.04:

root@app:~# whoami
root
root@app:~# mysql
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 9
Server version: 8.0.16-7 Percona Server (GPL), Release '7', Revision '613e312'

Copyright (c) 2009-2019 Percona LLC and/or its affiliates
Copyright (c) 2000, 2019, 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> select user, host, plugin, authentication_string from mysql.user where user ='root';
+------+-----------+-------------+-----------------------+
| user | host      | plugin | authentication_string |
+------+-----------+-------------+-----------------------+
| root | localhost | auth_socket |                       |
+------+-----------+-------------+-----------------------+
1 row in set (0.00 sec)

То в чому ж магія? Плагін перевіряє, що користувач Linux відповідає користувачеві MySQL, використовуючи сокет-опцію SO_PEERCRED - щоб зібрати інформацію про користувача, що запускає програму клієнта. Таким чином, плагін можна використовувати тільки на системах, що підтримують опцію SO_PEERCRED, на зразок тієї ж Linux. Сокет-опція SO_PEERCRED дозволяє дізнаватися uid пов'язаного із сокетом процесу. А потім він вже отримує пов'язане з цим uid ім'я користувача.

Наведемо приклад з користувачем vagrant:

vagrant@mysql1:~$ whoami
vagrant
vagrant@mysql1:~$ mysql
ERROR 1698 (28000): Access denied for user 'vagrant'@'localhost'

Оскільки в MySQL немає користувача vagrant, у доступі нам відмовлено. Створимо такого користувача та повторимо спробу:

MariaDB [(none)]> GRANT ALL PRIVILEGES ON *.* TO 'vagrant'@'localhost' IDENTIFIED VIA unix_socket;
Query OK, 0 rows affected (0.00 sec)

vagrant@mysql1:~$ mysql
Welcome to the MariaDB monitor.  Commands end with ; or g.
Your MariaDB connection id is 45
Server version: 10.0.38-MariaDB-0ubuntu0.16.04.1 Ubuntu 16.04
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or 'h' for help. Type 'c' to clear the current input statement.

MariaDB [(none)]> show grants;
+---------------------------------------------------------------------------------+
| Grants for vagrant@localhost                                                    |
+---------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'vagrant'@'localhost' IDENTIFIED VIA unix_socket |
+---------------------------------------------------------------------------------+
1 row in set (0.00 sec)

Вийшло!

Ну а як щодо не-Debian дистрибутива, де це не передбачено за замовчуванням? Спробуємо Percona Server for MySQL 8, встановлений на CentOS 7:

mysql> show variables like '%version%comment';
+-----------------+---------------------------------------------------+
| Variable_name   | Value                                   |
+-----------------+---------------------------------------------------+
| version_comment | Percona Server (GPL), Release 7, Revision 613e312 |
+-----------------+---------------------------------------------------+
1 row in set (0.01 sec)

mysql> CREATE USER 'percona'@'localhost' IDENTIFIED WITH auth_socket;
ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded

Облом. Чого ж не вистачило? Плагін не завантажений:

mysql> pager grep socket
PAGER set to 'grep socket'
mysql> show plugins;
47 rows in set (0.00 sec)

Додамо в процес плагін:

mysql> nopager
PAGER set to stdout
mysql> INSTALL PLUGIN auth_socket SONAME 'auth_socket.so';
Query OK, 0 rows affected (0.00 sec)

mysql> pager grep socket; show plugins;
PAGER set to 'grep socket'
| auth_socket                     | ACTIVE | AUTHENTICATION | auth_socket.so | GPL     |
48 rows in set (0.00 sec)

Тепер ми маємо все необхідне. Спробуємо ще раз:

mysql> CREATE USER 'percona'@'localhost' IDENTIFIED WITH auth_socket;
Query OK, 0 rows affected (0.01 sec)
mysql> GRANT ALL PRIVILEGES ON *.* TO 'percona'@'localhost';
Query OK, 0 rows affected (0.01 sec)

Тепер можна увійти до системи під логіном «percona».

[percona@ip-192-168-1-111 ~]$ whoami
percona
[percona@ip-192-168-1-111 ~]$ mysql -upercona
Welcome to the MySQL monitor.  Commands end with ; or g.
Your MySQL connection id is 19
Server version: 8.0.16-7 Percona Server (GPL), Release 7, Revision 613e312

Copyright (c) 2009-2019 Percona LLC and/or its affiliates
Copyright (c) 2000, 2019, 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> select user, host, plugin, authentication_string from mysql.user where user ='percona';
+---------+-----------+-------------+-----------------------+
| user    | host   | plugin   | authentication_string |
+---------+-----------+-------------+-----------------------+
| percona | localhost | auth_socket |                       |
+---------+-----------+-------------+-----------------------+
1 row in set (0.00 sec)

І знову вийшло!

Питання: чи вийде у систему під тим самим логіном percona, але з іншого ользователя?

[percona@ip-192-168-1-111 ~]$ logout
[root@ip-192-168-1-111 ~]# mysql -upercona
ERROR 1698 (28000): Access denied for user 'percona'@'localhost'

Ні, не вийде.

Висновок

MySQL досить гнучка в кількох аспектах, один з яких – метод аутентифікації. Як видно з цієї посади, доступ можна отримати без паролів на основі користувачів ОС. Це може бути корисно за певних сценаріїв, і один із них — коли мігруєте з RDS/Aurora на звичайну MySQL, користуючись автентифікацією бази даних IAM, щоб продовжувати отримувати доступ, але без паролів.

Джерело: habr.com

Додати коментар або відгук