在 CentOS 7 上安装 Fail2Ban

什么是 Fail2Ban?

Fail2ban 是一款开源软件,它实时主动扫描服务器日志文件以查找任何暴力登录尝试,如果发现,则使用服务器防火墙软件(firewalld 或 iptables)立即阻止攻击。 Fail2Ban 作为后台进程运行,并持续扫描日志文件以查找异常登录模式和安全漏洞尝试。

安装

为了在 CentOS 7 上安装 Fail2Ban,我们首先需要启用 EPEL(企业 Linux 的额外软件包)存储库。 以下命令将以 root 用户身份运行。

[root@host ~]# yum install epel-release
[root@host ~]# yum install fail2ban fail2ban-systemd

我们还可以 安装 Fail2ban 通过从 GitHub 克隆软件。

配置

一旦安装了fail2ban,我们需要使用更新的jail.local 配置文件来配置和调整软件。 附带说明一下,fail2ban 软件将其配置文件存储在 /etc/fail2ban 文件夹中。 jail.local 文件取代了 jail.conf 文件,通常用于验证您的自定义更新是否安全。

首先,我们将复制“jail.conf”文件并使用名称“jail.local”重新保存它:

[root@host ~]# cp -pf /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

接下来,我们需要使用以下命令在 Vim 中编辑 jail.local 文件。


[root@host ~]# vim /etc/fail2ban/jail.local
[DEFAULT]

# "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

# Override /etc/fail2ban/jail.d/00-firewalld.conf:
banaction = iptables-multiport

# "bantime" is the number of seconds that a host is banned.
bantime  = 600

# A host is banned if it has generated "maxretry" during the last "findtime"
# seconds.
findtime  = 600

# "maxretry" is the number of failures before a host get banned.
maxretry = 5

将您的本地 IP 地址添加到 忽略ip 线。

添加监狱文件以保护 SSH 访问

接下来,我们需要在 Vim 中创建和编辑一个名为 sshd.local 的新文件。

[root@host ~]# touch /etc/fail2ban/jail.d/sshd.local && chmod +x /etc/fail2ban/jail.d/sshd.local

[root@host ~]# vim /etc/fail2ban/jail.d/sshd.local

在此之后,我们添加以下代码行。

[sshd]
enabled = true
port = ssh
#action = firewallcmd-ipset
logpath = %(sshd_log)s
maxretry = 5
bantime = 86400

确保参数“启用”设置为“真”。 要启用保护,请设置为 True,要禁用保护,请将其设置为 False。 jail.conf 文件中第 167 行的过滤器参数

filter = %(__name__)s[mode=%(mode)s]

根据位于路径 /etc/fail2ban/filter.d/sshd.conf 中的此设置检查 sshd 配置文件。

此参数的操作用于定义需要使用 /etc/fail2ban/action.d/firewallcmd-ipset.conf 文件中可用的过滤器禁止的 IP 地址。

此外,可以将 SSH 端口参数修改为新值以匹配您的 SSH 设置。 如果您使用端口 22,则无需更改此参数。 其他参数包括:

  • Logpath:Logpath 定义了将存储日志文件的路径。 此日志文件由 Fail2Ban 扫描。
  • Maxretry:Maxetry 用于定义失败登录条目的最大限制。
  • Bantime:bantime 参数用于定义主机将被禁止的秒数。

Fail2Ban 服务

如果您没有运行 CentOS 防火墙 (firewalld),请启用它:

[root@host ~]# systemctl enable firewalld
[root@host ~]# systemctl start firewalld

运行以下命令在服务器上启用和启动 Fail2Ban 软件。

[root@host ~]# systemctl enable fail2ban
[root@host ~]# systemctl start fail2ban

Fal2Ban 状态

要检查 Fail2Ban 监狱的状态,请运行以下命令:

[root@host ~]# fail2ban-client status

结果应该与此类似:

[root@host ~]# fail2ban-client status
Status
|- Number of jail: 1
`- Jail list: sshd

解禁 IP 地址

要从禁止列表中手动删除 IP 地址,请使用以下命令:

[root@host ~]# fail2ban-client set sshd unbanip IPADDRESS

这将删除IP。

有限的可用率!
立刻行动!

您是否担心服务器的安全性?
您是否在登录服务器时看到多次登录尝试? Liquid Web 有几个最先进的安全包可用于确保您的数据受到保护。