Mars's Blog

解决服务器被ssh暴力破解问题

2021-11-24

阅读

解决ssh暴力破解,方法有:

  • 改ssh端口
  • 禁止root登录,只能通过其他管理员或者用户登录(用户名和密码同时破解规模上升一个数量级)
  • 只能通过密钥登录
  • 多次登录错误ban ip
  • 工具:Fail2Ban 参考

安装:

1
2
3
4
5
sudo yum install epel-release
sudo yum install fail2ban
sudo systemctl enable fail2ban

vi /etc/fail2ban/jail.local
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
[DEFAULT]
# Ban hosts for 1 hour after they perform 3 failed login attempts within 10 minutes
# 600s内失败超过3次会ban3600s
bantime = 3600
findtime = 600
maxretry = 3

# Never ban the following space-separated IP addresses/masks
ignoreip = 127.0.0.1/8

# Override /etc/fail2ban/jail.d/00-firewalld.conf
# to ensure that iptables will be used for firewall configuration
banaction = iptables-multiport

# Choose what to do when issuing a ban:
# $(action_)s : [default]
# sets the OS firewall to reject all incoming calls
# from that IP address for the specified amount of time
# $(action_mw)s : same as above + send and alert e-mail
# $(action_mwl)s : same as above + adds relevant log lines to the e-mail
# action = $(action_)s

# Send fail2ban alerts & warnings to the following e-mail address
destemail = web@ryadel.com
sendername = Fail2Ban
mta = sendmail

[sshd]
# Enables the sshd jail
enabled = true

Cascading rules

It’s worth noting that the jail.conf file can also be overridden by any .conf file present in the/etc/fail2ban/jail.d/ folder: similarly, the jail.local file we just added can also be overridden by any .local file present in that same folder. Here’s the cascading order:

  1. /etc/fail2ban/jail.conf
  2. /etc/fail2ban/jail.d/*.conf (from first to last, sorted alphabetically)
  3. /etc/fail2ban/jail.local
  4. /etc/fail2ban/jail.d/*.local (from first to last, sorted alphabetically)

Regardless how you choose to configure it, be sure to restart the Fail2ban services after you change any of these files:

监控:

查看当前被封的ip:

1
sudo fail2ban-client status sshd

查看fail2ban日志:

1
sudo tail -F /var/log/fail2ban.log
Tags: Devops