防御暴力破解SSH攻击

托管在IDC的机器我们通常都用SSH方式来远程管理.但是经常可以发现log-watch的日志中有大量试探登录的

信息,为了我们的主机安全,有必要想个方法来阻挡这些可恨的”HACKER”

有很多办法来阻挡这些密码尝试 1 修改端口 2 健壮的密码 3 RSA公钥认证 4 使用iptables脚本 5 使用sshd日志过滤 6 使用tcp_wrappers过滤 7 使用knockd

1 vi /etc/ssh/sshd_config #Port 22 默认端口为22,为了避免被扫描,去掉#,改成一个其他的端口,比如45632 保存后重启sshd服务.service sshd restart

2没什么可说的,密码的复杂性可以增加破解的难度,大小写混合加上数字并且有足够的密码长度就比较安全

了,唯一的问题就是要牢记密码.

3.默认的登录方式是password,如果需要用RSA公钥登录,需要先创建RSA Key #ssh-keygen -t rsa -b 1024 会生成私钥/home/username/.ssh/id_rsa 同时生成公钥/home/username/.ssh/id_rsa.pub 输入一个加密短语(也可省略)

修改sshd 设置,编辑/etc/ssh/sshd_config ‘PasswordAuthentication no’ RSAAuthentication yes PubkeyAuthentication yes AuthorizedKeysFile .ssh/id_rsa.pub 将公钥下载到本地计算机,然后在ssh客户端软件Secure CRT中设置好,就可以登录了

4 iptbles脚本 此脚本允许每分钟3个连接.有白名单,并有日志纪录

iptables -A INPUT -p tcp –dport 22 -m state –state NEW -m recent –set –name SSH iptables -A INPUT -p tcp –dport 22 -m state –state NEW -j SSH_WHITELIST iptables -A INPUT -p tcp –dport 22 -m state –state NEW -m recent –update –seconds 60 –

hitcount 4 –rttl –name SSH -j ULOG –ulog-prefix SSH_brute_force iptables -A INPUT -p tcp –dport 22 -m state –state NEW -m recent –update –seconds 60 –

hitcount 4 –rttl –name SSH -j DROP iptables的版本需要>1.2.11 (1.2不支持 –rttl参数)

5使用sshd日志过滤 有几个软件(脚本)可以做到. sshfilter [url]http://www.csc.liv.ac.uk/~greg/sshdfilter/[/url] Fail2Ban [url]http://fail2ban.sourceforge.net/[/url] DenyHosts [url]http://denyhosts.sourceforge.net/[/url]

需要sshd支持tcp_wrappers此功能. [root@as4test include]# ldd /usr/sbin/sshd | grep libwrap libwrap.so.0 => /usr/lib64/libwrap.so.0 (0x0000002a9566c000) 如果有libwrap.so.0这个库说明支持此功能 另一种测试方法:在/etc/hosts.deny加入一行127.0.0.1 然后ssh localhost,如果无法连接,说明支持.

$ tar zxvf DenyHosts-2.6.tar.gz

$ cd DenyHosts-2.6

as root:

# python setup.py install

#cd /usr/share/denyhost

# cp denyhosts.cfg-dist denyhosts.cfg 配置文件 # cp daemon-control-dist daemon-control 启动脚本 # chown root daemon-control

# chmod 700 daemon-control

# cd /etc/init.d

# ln -s /usr/share/denyhosts/daemon-control denyhosts

# chkconfig –add denyhosts 添加到开机启动服务中

6 使用tcp_wrappers过滤 1 下载脚本[url]http://www.la-samhna.de/misc/sshblock.sh[/url] 2 设置可执行权限 chmod 755 /usr/local/bin/sshblock.sh 3 在/etc/hosts.allow中添加以下内容 #__START_SSHBLOCK__ #__END_SSHBLOCK__ sshd : ALL : spawn (/usr/local/bin/sshblock.sh %a)& 设置 DONTBLOCK 白名单 BURST_MAX=5 BURST_TIM=60 60秒内登录5次就封锁 PURGE_TIM=3600 3600秒后解冻

7 使用KNOCKD knockd 监视一个预定义模式在iptables的日志,例如一次击中端口6356,一次击中端口63356,两次击中端口

9356,这相当于敲一个关闭的门用一种特殊的暗码来被konckd识别,konckd 将使用iptables来打开一个预定

义端口例如ssh的22端口在一个预定定义时间.(比如一分钟),如果一个ssh session 在这个时间范围内打开,

这个端口会一直保留.直到预定义时间过期后ssh端口被knockd关掉.

缺点:比较复杂的方案,不适合普通人 需要客户端(knockd-client)来实现port knocking”,同时需要knockd-server来响应. 实际上,很容易检测到这种通讯模式,一旦攻击者可以监控你的通讯,这种解决方案无法提供安全防护针对本

地攻击者.