openssh 加固

很多场合,我们不得不在公网开启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 # 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,如需转载请自行联系原作者

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值