【防御】防止SSH暴力破解

前言

通过IP地址黑白名单的方式,防止SSH暴力破解
配置完黑白名单后立即生效,无需重启
配置完黑白名单后,已经通过SSH连接的会话不会受到影响

查看SSH登录失败的IP地址和次数

1
cat /var/log/secure | awk '/Failed/{print $(NF-3)}' | sort | uniq -c | awk '{print $2" = "$1;}'

写入白名单

  • 白名单中出现的IP地址允许通过SSH连接

xx.xx.xx.xx:允许连接的IP地址

/etc/hosts.allow
1
2
3
4
5
6
7
8
9
10
11
#
# hosts.allow This file contains access rules which are used to
# allow or deny connections to network services that
# either use the tcp_wrappers library or that have been
# started through a tcp_wrappers-enabled xinetd.
#
# See 'man 5 hosts_options' and 'man 5 hosts_access'
# for information on rule syntax.
# See 'man tcpd' for information on tcp_wrappers
#
sshd:xx.xx.xx.xx:allow
  • 每当公网IP发生变化需要手动去云服务器控制台,登录云服务器命令行,将新的公网IP地址添加到白名单
1
echo "sshd:xx.xx.xx.xx:allow" >> /etc/hosts.allow

写入黑名单

  • 拒绝除了白名单以外的所有IP地址通过SSH连接

sshd:all:deny:拒绝所有IP地址

/etc/hosts.deny
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#
# hosts.deny This file contains access rules which are used to
# deny connections to network services that either use
# the tcp_wrappers library or that have been
# started through a tcp_wrappers-enabled xinetd.
#
# The rules in this file can also be set up in
# /etc/hosts.allow with a 'deny' option instead.
#
# See 'man 5 hosts_options' and 'man 5 hosts_access'
# for information on rule syntax.
# See 'man tcpd' for information on tcp_wrappers
#
sshd:all:deny

完成

  • 非白名单内的IP地址在通过SSH连接时将会被拒绝
1
2
kex_exchange_identification: Connection closed by remote host
Connection closed by xx.xx.xx.xx port 22

参考文献

博客园——RoyFans
CSDN——河边小咸鱼