很多场合,我们不得不在公网开启ssh 22端口,以CentOS6为例,下面的几个办法可以加固ssh连接
1、限制密码尝试次数(denyhosts)
yum install denyhosts --enablerepo=epel chkconfig denyhosts on /etc/init.d/denyhosts start
2、除掉密码认证,采用ssh密钥登陆
修改/etc/ssh/sshd_config
PasswordAuthentication no
3、禁止root登陆
修改 /etc/ssh/sshd_config
PermitRootLogin no
4、限制连接频率
/sbin/iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set --name ssh --rsource /sbin/iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent ! --rcheck --seconds 60 --hitcount 2 --name ssh --rsource -j ACCEPT
5、限制IP来源
这个稍微复杂一点点,采用geoip数据库来识别IP来源,比如只允许中国的IP访问
写个脚本
#!/bin/bash # UPPERCASE space-separated country codes to ACCEPT ALLOW_COUNTRIES="CN" if [ $# -ne 1 ]; then echo "Usage: `basename $0` <ip>" 1>&2 exit 0 # return true in case of config issue fi COUNTRY=`/usr/bin/geoiplookup $1 | awk -F ": " ‘{ print $2 }‘ | awk -F "," ‘{ print $1 }‘ | head -n 1` [[ $COUNTRY = "IP Address not found" || $ALLOW_COUNTRIES =~ $COUNTRY ]] && RESPONSE="ALLOW" || RESPONSE="DENY" if [ $RESPONSE = "ALLOW" ]then exit 0 else logger "$RESPONSE sshd connection from $1 ($COUNTRY)" exit 1 fi
利用tcp_wrapper调用那个脚本
chmod 775 /usr/bin/sshfilter.sh echo "sshd: ALL" >>/etc/hosts.deny echo "sshd: 10.0.0.0/8" >>/etc/hosts.allow echo "sshd: ALL: aclexec /usr/bin/sshfilter.sh %a" >>/etc/hosts.allow
参考文章
http://www.axllent.org/docs/view/ssh-geoip/
时间: 2024-10-06 03:41:57