背景
Fail2Ban已经加固了SSH了,但发现开放的mysql,也需要这个,免得被暴力破解,或者说,不停的有黑客去试密码,浪费服务器资源,在此记录下,当某个客户端连接MySQL3次失败后,封那个客户端IP地址24小时。
这里我的MySQL版本是5.7,端口是33056。
操作
搭建好:fail2ban,具体可参考,此篇
Centos安全加固-There were 1085 failed login attempts since the last successful login.
在fail.d中新增mysql.conf
bash
vim /etc/fail2ban/jail.d/mysql.conf
内容如下:
bash
[mysqld-auth]
enabled = true
filter = mysqld-auth
port = 33056
logpath = /var/log/mysqld.log
maxretry = 3
bantime = 86400
findtime = 300
ignoreip = xxx.xxx.xxx.xxx
banaction = iptables-multiport
xxx.xxx.xxx.xxx:为公网IP地址。
重启fail2ban
bash
systemctl restart fail2ban
查看fail2ban的状态:
bash
[root@iZuf6hz8ygv8i1uq8mno2hZ ~]# fail2ban-client status
Status
|- Number of jail: 3
`- Jail list: mysqld-auth, sshd-invalid-user, sshd-root-fail
此时随便找一个工具去登录3次失败mysql。比如我用的sqlyog,前3次登陆失败:

第四次登录失败:

查看下mysqld-auth状态:
bash
[root@iZuf6hz8ygv8i1uq8mno2hZ ~]# fail2ban-client status mysqld-auth
Status for the jail: mysqld-auth
|- Filter
| |- Currently failed: 0
| |- Total failed: 6
| `- File list: /var/log/mysqld.log
`- Actions
|- Currently banned: 1
|- Total banned: 2
`- Banned IP list: 122.192.15.55
[root@iZuf6hz8ygv8i1uq8mno2hZ ~]#
查看对应的iptables:
bash
[root@iZuf6hz8ygv8i1uq8mno2hZ ~]# iptables -L INPUT -nv
Chain INPUT (policy ACCEPT 80 packets, 5245 bytes)
pkts bytes target prot opt in out source destination
164K 36M f2b-mysqld-auth tcp -- * * 0.0.0.0/0 0.0.0.0/0 multiport dports 33056
473K 947M f2b-sshd-root-fail tcp -- * * 0.0.0.0/0 0.0.0.0/0 multiport dports 0:65535
473K 947M f2b-sshd-invalid-user tcp -- * * 0.0.0.0/0 0.0.0.0/0 multiport dports 0:65535
495K 29M tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:22 state NEW recent: SET name: ssh_strict side: source mask: 255.255.255.255
217K 13M DROP tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:22 state NEW recent: UPDATE seconds: 1 hit_count: 2 name: ssh_strict side: source mask: 255.255.255.255
[root@iZuf6hz8ygv8i1uq8mno2hZ ~]#
原理就是fail2Ban去匹配mysqld.log中的字符串
bash
grep "Access denied" /var/log/mysqld.log
最终将测试的ip地址放出来
bash
[root@iZuf6hz8ygv8i1uq8mno2hZ ~]# fail2ban-client set mysqld-auth unbanip 122.192.15.55
1
[root@iZuf6hz8ygv8i1uq8mno2hZ ~]# fail2ban-client status mysqld-auth
Status for the jail: mysqld-auth
|- Filter
| |- Currently failed: 0
| |- Total failed: 6
| `- File list: /var/log/mysqld.log
`- Actions
|- Currently banned: 0
|- Total banned: 2
`- Banned IP list:
[root@iZuf6hz8ygv8i1uq8mno2hZ ~]#