数据库如何防止暴力破解

前言

​ 一般来说,数据库作为数据存储工具是很敏感的,特别需要安全防护和容灾备份。在生产环境中数据库是在内网下才能进行连接,外网是不允许连接的,因为外网连接下很有可能被暴力破解。但有些时候又不得不开放外网连接,这时候就需要重视暴力破解了,而MySQL官方中提供了一个缓解暴力破解数据库的方法:当用户错误登陆次数达到一定次数时,在一段时间内禁止再次请求登录,从而避免了数据库被暴力破解。以下是官方文档的原文描述:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
As of MySQL 5.7.17, MySQL Server includes a plugin library that enables
administrators to introduce an increasing delay in server response to
connection attempts after a configurable number of consecutive failed attempts.
This capability provides a deterrent that slows down brute force attacks
against MySQL user accounts. The plugin library contains two plugins:

CONNECTION_CONTROL checks incoming connection attempts and adds a delay
to server responses as necessary.
This plugin also exposes system variables that enable its operation to be
configured and a status variable that provides rudimentary monitoring information.

The CONNECTION_CONTROL plugin uses the audit plugin interface
(see Writing Audit Plugins). To collect information, it subscribes
to the MYSQL_AUDIT_CONNECTION_CLASSMASK event class, and processes
MYSQL_AUDIT_CONNECTION_CONNECT and MYSQL_AUDIT_CONNECTION_CHANGE_USER
subevents to check whether the server should introduce a delay before
responding to connection attempts.

CONNECTION_CONTROL_FAILED_LOGIN_ATTEMPTS implements an INFORMATION_SCHEMA
table that exposes more detailed monitoring information for failed
connection attempts.

安装Connection-Control插件

1、通过命令行安装
在不影响MySQL对外提供服务的情况下安装插件,可在MySQL命令行执行以下语句:

1
2
INSTALL PLUGIN CONNECTION_CONTROL SONAME 'connection_control.so';
INSTALL PLUGIN CONNECTION_CONTROL_FAILED_LOGIN_ATTEMPTS SONAME 'connection_control.so';

​ 如果需要卸载则可以执行语句:

1
2
UNINSTALL PLUGIN CONNECTION_CONTROL;
UNINSTALL PLUGIN CONNECTION_CONTROL_FAILED_LOGIN_ATTEMPTS;

​ 查询插件安装信息

1
select plugin_name, plugin_status, plugin_type, plugin_library load_option from information_schema.plugins where plugin_name like '%CONTROL%'

2、通过配置文件安装

1
2
[mysqld]
plugin-load-add=connection_control.so

​ 为了避免插件的功能被删除,我们可以在MySQL的my.cnf配置文件中声明强制启用Connection-Control插件,从而避免被删除。

1
2
connection-control=FORCE_PLUS_PERMANENT
connection-control-failed-login-attempts=FORCE_PLUS_PERMANENT

​ 当尝试卸载时,MySQL给出错误提示

​ 配置完后需要重启MySQL服务

1
systemctl restart mysql

参数设置

connection_control_failed_connections_threshold的意义:

​ 1、登陆失败次数限制

​ 2、当有任何一次登录成功后,累计失败的值将重新从0开始累计统计。

​ 3、如果这个值设置为0,则表示禁用统计失败的功能。

connection_control_min_connection_delay的意义:

​ 查过失败次数后,再登录的时候,最小的重试间隔,单位为毫秒

通过命令行设置

1
2
SET GLOBAL connection_control_failed_connections_threshold = 3;
SET GLOBAL connection_control_min_connection_delay = 5000;

通过配置文件设置

1
2
connection_control_failed_connections_threshold=3
connection_control_min_connection_delay=4000

注意:在命令行中设置参数的优先级比配置文件的参数设置高,即在命令行设置参数会覆盖掉配置文件的参数,但服务重启后会加载配置文件的参数

测试效果

​ 由于我们设置失败限制登陆次数为3,延迟为5000毫秒,故效果如下

坚持原创技术分享,您的支持将鼓励我继续创作!

欢迎关注我的其它发布渠道