====== Fail2Ban ======
> Fail2ban scans log files (e.g. /var/log/apache/error_log) and bans IPs that show the malicious signs -- too many password failures, seeking for exploits, etc.
[[http://www.fail2ban.org/wiki/index.php/Main_Page|Fail2Ban]]是一个通过扫描日志文件ban恶意ip的软件,推荐在你所有管理的主机上都安装一个。
===== Install =====
Ubuntu/debian:
sudo apt-get update
sudo apt-get install fail2ban
sudo service fail2ban start
Centos7:
sudo yum install epel-release
sudo yum install fail2ban
sudo systemctl enable fail2ban
sudo systemctl start fail2ban
安装''pyinotify''以提升程序效率:
sudo yum install python-inotify // centos
sudo apt-get install python-pyinotify // ubuntu/debian
===== Configuration =====
''/etc/fail2ban/fail2ban.conf''是程序的各种基本配置,例如socket和log文件的路径;
''/etc/fail2ban/jail.conf''为具体的各种ban ip规则
Fail2Ban依照以下顺序读取jail规则,后面的配置会覆盖前面的配置:
- ''/etc/fail2ban/jail.conf''
- ''/etc/fail2ban/jail.d/*.conf''
- ''/etc/fail2ban/jail.local''
- ''/etc/fail2ban/jail.d/*.local''
如果想override掉默认的配置,建议先将此文件先复制一份放到''jail.local'',然后编辑''jail.local'',这样软件包更新时配置就不会被覆盖掉:
sudo cp /etc/fail2ban/jail.{conf,local}
一般来说启用''sshd''的保护即可,其他按需求启用:
# /etc/fail2ban/jail.local
[DEFAULT]
# Ban hosts for one hour:
bantime = 3600
usedns = no
ignoreip = 127.0.0.1/8 192.168.0.0/24
[sshd]
enabled = true
可以使用以下命令查看当前的''Fail2Ban''状态:
sudo fail2ban-client status
sudo fail2ban-client status ssh
===== Usage =====
==== Check fail2ban status ====
fail2ban-client status
fail2ban-client status [jail-name]
==== Unban ip ====
fail2ban-client set [jail-name] unbanip [ip]
==== Test filter rule ====
fail2ban-regex 'string' /etc/fail2ban/filter.d/rule.conf
fail2ban-regex /path/to/access.log /etc/fail2ban/filter.d/rule.conf
===== Ban ip by specified nginx rule =====
新增规则限制 ''nginx'' 某个接口访问(例如短信),避免被恶意使用
[nginx-sms]
enabled = true
port = http,https
filter = nginx-sms
logpath = /path/to/access.log
maxtry = 9
findtime = 86400
bantime = 21600
[Definition]
failregex = ^ - - .* \"POST /path/to HTTP/1.1\" .*$
ignoreregex =
====== Reference ======
* [[https://www.digitalocean.com/community/tutorials/how-to-protect-ssh-with-fail2ban-on-ubuntu-14-04|How To Protect SSH with Fail2Ban on Ubuntu 14.04]]
* [[https://www.digitalocean.com/community/tutorials/how-to-protect-ssh-with-fail2ban-on-centos-7|How To Protect SSH With Fail2Ban on CentOS 7]]
* [[https://www.digitalocean.com/community/tutorials/how-to-protect-an-nginx-server-with-fail2ban-on-ubuntu-14-04|How To Protect an Nginx Server with Fail2Ban on Ubuntu 14.04]]