CentOS ssh加固:更改默认端口、限制IP和用户登录失败次数

283 阅读1分钟

CentOS ssh加固:更改默认端口、限制IP和用户登录失败次数

为什么要做限制?

服务器开放外网ssh登录端口就会有被攻击的风险,攻击者会采用暴力破解的方法,不断对服务器发送连接请求尝试登录。

本文核心是采用Linux的PAM框架来实现。

查看登录失败日志:

grep "Failed" /var/log/secure

一、更改默认端口

vim /etc/ssh/sshd_config
修改Port 22

二、限制IP

原理:IP白名单/etc/hosts.allow 黑名单/etc/hosts.deny 因此,只需要定时从登录失败日志中提取登录失败的IP,并加入到黑名单中即可实现限制这个IP登录。

脚本如下:

#! /bin/bash
cat /var/log/secure|awk '/Failed/{print $(NF-3)}'|sort|uniq -c|awk '{print $2"="$1;}' > /home/hhr/script/black.list
for i in `cat  /home/hhr/script/black.list`
do
  IP=`echo $i |awk -F= '{print $1}'`
  NUM=`echo $i|awk -F= '{print $2}'`
  echo $IP=$NUM
  if [ $NUM -gt 3 ]; then
    grep $IP /etc/hosts.deny > /dev/null
    if [ $? -gt 0 ];then
      echo "sshd:$IP:deny" >> /etc/hosts.deny
    fi
  fi
done

然后将其加入到crontab中即可实现自动执行(每十分钟)。

$ crontab -e
*/10 * * * *  sh /home/hhr/script/secure_ssh.sh > /home/hhr/script/secure_ssh.log &

三、限制用户

Linux中关于ssh登录的配置文件有如下:

/etc/pam.d/login 管理终端对应的配置文件

/etc/pam.d/sshd ssh远程登陆对应的配置文件

/etc/pam.d/system-auth 全局配置文件

/etc/pam.d/sshd 中加入以下配置:

auth required pam_tally2.so deny=3 unlock_time=3600 even_deny_root root_unlock_time=20

# deny=3 代表尝试登录的次数,超过设定次数后会执行后续的动作。

# even_deny_root 代表root用户也适用于此规则。

# unlock_time=3600 表示账户被锁后,3600秒后自动解锁。

# root_unlock_time=20 表示如果是 root 用户被锁定,则锁定 20 秒。

查看用户是否被锁定

pam_tally2 -u [username] -r # -r:清除被锁定的用户