fail2ban安装后。默认的设置使用iptable防火墙,如果服务器启用了ufw,那么就要稍加调整,否则即使是fail2ban的日志显示已经baned的ip地址,但实际上由于iptables的顺序问题,根本不起作用。
首先,安装fail2ban:
sudo apt install fail2ban
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo vi /etc/fail2ban/jail.local
将
banaction = iptables-multiport
更改为
banaction = ufw
重新载入
sudo fail2ban-client reload
查看状态
sudo fail2ban-client status
测试filter可用性
sudo fail2ban-regex /var/log/auth.log /etc/fail2ban/filter.d/sshd.conf
我的测试结果如下:
sudo fail2ban-regex /var/log/auth.log /etc/fail2ban/filter.d/sshd.conf Running tests ============= Use failregex filter file : sshd, basedir: /etc/fail2ban Use maxlines : 1 Use datepattern : Default Detectors Use log file : /var/log/auth.log Use encoding : UTF-8 Results ======= Failregex: 73 total |- #) [# of hits] regular expression | 4) [24] ^Failed \b(?!publickey)\S+ for (?P<cond_inv>invalid user )?<F-USER>(?P<cond_user>\S+)|(?(cond_inv)(?:(?! from ).)*?|[^:]+)</F-USER> from <HOST>(?: port \d+)?(?: on \S+(?: port \d+)?)?(?: ssh\d*)?(?(cond_user): |(?:(?:(?! from ).)*)$) | 14) [23] ^pam_unix\(sshd:auth\):\s+authentication failure;\s*logname=\S*\s*uid=\d*\s*euid=\d*\s*tty=\S*\s*ruser=<F-USER>\S*</F-USER>\s*rhost=<HOST>\s.*(?: \[preauth\])?\s*$ | 20) [26] ^<F-MLFFORGET><F-NOFAIL>Accepted publickey</F-NOFAIL></F-MLFFORGET> for \S+ from <HOST>(?:\s|$) `- Ignoreregex: 0 total Date template hits: |- [# of hits] date format | [1177] {^LN-BEG}(?:DAY )?MON Day %k:Minute:Second(?:\.Microseconds)?(?: ExYear)? `- Lines: 1177 lines, 0 ignored, 73 matched, 1104 missed [processed in 0.31 sec] Missed line(s): too many to print. Use --print-all-missed to print all 1104 lines
默认状态下,fail2ban仅启用了sshd一个:
sudo fail2ban-client status
Status
|- Number of jail: 1
`- Jail list: sshd
启用其它filter过滤器或自定义过滤器,需要加入 enabled = true,例如:
[nginx-botsearch]
enabled = true
port = http,https
filter = nginx-botsearch
logpath = /var/log/nginx/access.log
maxretry = 2
findtime = 120
参考网址