很多时候, 我们并不想更改SSH端口来避开攻击, 或者因为某些网络限制, 我们必须为服务器开22端口. 这时候可以使用Fail2ban来拦截未授权的访问者.
食用前请确保你的魔法主机是KVM/XEN, 某些Openvz的firewalld组件启动不完全, 会使Fail2ban失效. 已知hostus这家是无法使用fail2ban的
使用如下命令安装fail2ban
<div class="blockcode"> <div id="code_Xq7"> <ol> <li>yum install epel-release -y</li> <li>yum install fail2ban fail2ban-systemd -y</li> </ol> </div> </div>
复制文件
<div class="blockcode"> <div id="code_FuX"> <ol> <li>cp -pf /etc/fail2ban/jail.conf /etc/fail2ban/jail.local</li> </ol> </div> </div>
使用 vi /etc/fail2ban/jail.local , 并写入如下内容
[DEFAULT]
# # MISCELLANEOUS OPTIONS #
# “ignoreip” can be an IP address, a CIDR mask or a DNS host. Fail2ban will not # ban a host which matches an address in this list. Several addresses can be # defined using space separator. ignoreip = 127.0.0.1/8
# External command that will take an tagged arguments to ignore, e.g. <ip>, # and return true if the IP is to be ignored. False otherwise. # # ignorecommand = /path/to/command <ip> ignorecommand =
# “bantime” is the number of seconds that a host is banned. bantime = 864000
# A host is banned if it has generated “maxretry” during the last “findtime” # seconds. findtime = 3600
# “maxretry” is the number of failures before a host get banned. maxretry = 10
使用 vi /etc/fail2ban/jail.d/sshd.local , 并写入如下内容[sshd]
enabled = true port = ssh #action = firewallcmd-ipset logpath = %(sshd_log)s maxretry = 10 bantime = 864000
确保firewall已经打开
- systemctl enable firewalld
- systemctl start firewalld
启动fail2ban
<div class="blockcode"> <div id="code_uKz"> <ol> <li>systemctl enable fail2ban</li> <li>systemctl start fail2ban</li> </ol> </div> </div>
至此, 你已提升服务器的安全等级. 所有未授权的访问都会被拦截 使用如下命令可以查看攻击者IP
<div class="blockcode"> <div id="code_HxM"> <ol> <li>fail2ban-client status sshd</li> </ol> </div> </div>
设置开机启动
CentOS 7: systemctl enable fail2ban