很多场合,我们不得不在公网开启ssh 22端口,以CentOS6为例,下面的几个办法可以加固ssh连接
1、限制密码尝试次数(denyhosts)
1
2
3
|
yum install denyhosts --enablerepo=epel
chkconfig denyhosts on /etc/init .d /denyhosts start
|
2、除掉密码认证,采用ssh密钥登陆
修改/etc/ssh/sshd_config
1
|
PasswordAuthentication no |
3、禁止root登陆
修改 /etc/ssh/sshd_config
1
|
PermitRootLogin no |
4、限制连接频率
1
2
|
/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
|
也可以利用iptables recent模块搞另类一点的策略,默认关闭ssh端口,用ping来解锁。
1
2
3
4
5
6
7
8
9
10
11
|
iptables -A INPUT -p icmp --icmp- type 8 -m length --length 78 -j LOG --log-prefix "SSHOPEN: "
#记录日志,前缀SSHOPEN: iptables -A INPUT -p icmp --icmp- type 8 -m length --length 78 -m recent -- set --name sshopen --rsource -j ACCEPT
#linux默认ping包一般为56字节,加上IP头20字节,ICMP头部8字节,共84字节。我们这里指定78字节,回头用特定大小的ping包来解锁。 iptables -A INPUT -p tcp --dport 22 --syn -m recent --rcheck --seconds 15 --name sshopen --rsource -j ACCEPT #符合sshopen的IP才会放行22端口 ping -s 50 host #Linux下解锁
ping -l 50 host #Windows下解锁
|
5、限制IP来源
这个稍微复杂一点点,采用geoip数据库来识别IP来源,比如只允许中国的IP访问
写个脚本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
#!/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调用那个脚本
1
2
3
4
|
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
|
6、设置超时
ssh session 超时应该属于安全范畴,可以防止人离开后,终端被他人利用。
这里设置为1800秒(30分钟)
方法一、利用环境变量TMOUT
1
2
|
echo "export TMOUT=1800" > /etc/profile .d /timeout .sh
source /etc/profile .d /timeout .sh
|
方法二、修改sshd_config
1
2
|
ClientAliveInterval 60 ClientAliveCountMax 30 |
本文转自 紫色葡萄 51CTO博客,原文链接:http://blog.51cto.com/purplegrape/1630728,如需转载请自行联系原作者