如何在CentOS 8上安装Fail2Ban ?

  1. 使用ssh登录到CentOS 8服务器
  2. 在CentOS 8上启用和安装EPEL存储库,运行: sudo yum install epel-release
  3. 安装Fail2Ban,运行 sudo yum install fail2ban
  4. 配置Fail2ban
  5. 启用Fail2ban服务 sudo systemctl enable fail2ban && sudo systemctl start fail2ban

在CentOS 8上使用Fail2Ban保护SSH

首先在CentOS 8上启用和安装EPEL Repo,运行:

sudo yum update
sudo yum install epel-release
sudo yum update

在CentOS 8上安装Fail2ban

使用yum命令按如下方式安装Fail2ban:

sudo yum install fail2ban

在系统启动时启用fail2ban服务

sudo systemctl enable fail2ban

配置Fail2ban设置

文件/etc/fail2ban/jail.local默认会覆盖/etc/fail2ban/boot.conf文件中的设置。
所以我们可以新建一个jail.local来进行设置

sudo vi /etc/fail2ban/jail.local

jail.local

[DEFAULT]
# Ban IP/hosts for 24 hour ( 24h*3600s = 86400s):
## 禁IP24小时
bantime = 86400
 
# An ip address/host is banned if it has generated "maxretry" during the last "findtime" seconds.
## 如果在600秒内尝试3次失败,则禁掉此ip
findtime = 600
maxretry = 3
 
# "ignoreip" can be a list of IP addresses, CIDR masks or DNS hosts. Fail2ban
# will not ban a host which matches an address in this list. Several addresses
# can be defined using space (and/or comma) separator. For example, add your 
# static IP address that you always use for login such as 103.1.2.3
# 设置IP白名单。 它们不会被禁
#ignoreip = 127.0.0.1/8 ::1 103.1.2.3
 
# Call iptables to ban IP address
## 使用iptables防火墙来禁IP连接
banaction = iptables-multiport
 
# Enable sshd protection
[sshd]
enabled = true

改完配置需要重启服务

sudo systemctl start fail2ban
sudo systemctl status fail2ban

如何启动/停止/重启fail2ban服务?

sudo systemctl start fail2ban
sudo systemctl stop fail2ban
sudo systemctl restart fail2ban
sudo systemctl status fail2ban

如何查看登录失败和被禁止的IP地址

sudo fail2ban-client status
sudo fail2ban-client status sshd

哪里查看ssh登录失败的日志

查看文件/var/log/secure:

tail -f /var/log/secure
grep 'sshd.*Failed password for' /var/log/secure

原因

通常服务器的SSH端口22会暴露在互联网上。因此,有许多机器人和攻击者会尝试随机密码或者密码字典登录到您的服务器。或者有的使用暴力攻击进行破解。

这时我们可以修改掉ssh的端口,并安装 Fail2Ban 来保护ssh。它能够在几次ssh登录不成功后禁止掉攻击者的IP地址。

如何在CentOS 8 Linux服务器上使用fail2ban保护ssh?

linux如何防止ssh被暴力尝试登陆

Fail2ban过滤器

在目录/etc/fail2ban/filter.d中,你可以看到所有的过滤器
例如sshd.conf是openssh过滤器

sudo cat /etc/fail2ban/filter.d/sshd.conf

不建议直接修改这个文件,而是应该修改(创建)文件/etc/fail2ban/jail.d/sshd.conf.local

获取更多关于被禁止的IP地址和日志文件的信息

tail -f /var/log/fail2ban.log
grep IP-address /var/log/fail2ban.log
sudo iptables -L -n -v
sudo iptables -L f2b-sshd -n -v
sudo iptables -S | f2b-sshd

问题描述

ssh的日志文件显示有很多尝试登陆失败记录。

There are 2003 failed login attempts since the last successful login
日期:2019-04-29 03:18:00 来源:oir作者:oir