denyhosts配置详解

  用DenyHosts可以阻止试图猜测SSH登录口令,它会分析/var/log/secure等日志文件,当发现同一IP在进行多次SSH密码尝试时就会记录IP到/etc/hosts.deny文件,从而达到自动屏蔽该IP的目的。

PURGE_DENY: removed HOSTS_DENY entries that are older than this time  
            when DenyHosts is invoked with the --purge flag

      format is: i[dhwmy]

      Where 'i' is an integer (eg. 7) 
            'm' = minutes
            'h' = hours
            'd' = days
            'w' = weeks
            'y' = years

# yum install denyhosts -y
# cp denyhosts.cfg denyhosts.cfg.bak
# vi denyhosts.cfg

        ############ THESE SETTINGS ARE REQUIRED ############
SECURE_LOG = /var/log/secure    #sshd的日志文件  
HOSTS_DENY = /etc/hosts.deny   #将阻止IP写入到hosts.deny,所以这个工具只支持 支持tcp wrapper的协议  
PURGE_DENY = 4w   #过多久后清除已阻止的IP,即阻断恶意IP的时长  (4周)  
BLOCK_SERVICE  = sshd   #阻止服务名  
DENY_THRESHOLD_INVALID = 5   #允许无效用户登录失败的次数  
DENY_THRESHOLD_VALID = 10   #允许普通有效用户登录失败的次数  
DENY_THRESHOLD_ROOT = 1    #允许root登录失败的次数  
DENY_THRESHOLD_RESTRICTED = 1    #设定 deny host 写入到该资料夹  
WORK_DIR = /var/lib/denyhosts    #将deny的host或ip记录到work_dir中  
SUSPICIOUS_LOGIN_REPORT_ALLOWED_HOSTS=YES  
HOSTNAME_LOOKUP=YES    #是否做域名反解  
LOCK_FILE = /var/lock/subsys/denyhosts    #将DenyHost启动的pid记录到LOCK_FILE中,已确保服务正确启动,防止同时启动多个服务

        ############ THESE SETTINGS ARE OPTIONAL ############
ADMIN_EMAIL = root   #设置管理员邮件地址  
SMTP_HOST = localhost  
SMTP_PORT = 25  
SMTP_FROM = DenyHosts <nobody@localhost>  
SMTP_SUBJECT = DenyHosts Report from $[HOSTNAME]  
AGE_RESET_VALID=5d  
AGE_RESET_ROOT=25d  
AGE_RESET_RESTRICTED=25d  
AGE_RESET_INVALID=10d

        ######### THESE SETTINGS ARE SPECIFIC TO DAEMON MODE  ##########
DAEMON_LOG = /var/log/denyhosts   #denyhost服务日志文件

DAEMON_SLEEP = 30s  
DAEMON_PURGE = 1h      #该项与PURGE_DENY 设置成一样,也是清除hosts.deniedssh 用户的时间

  删除一个已经禁止的主机IP,并加入到允许主机例表,只在 /etc/hosts.deny 删除是没用的。需要进入 /var/lib/denyhosts 目录,进入以下操作:

1、停止DenyHosts服务:

$sudo service denyhosts stop

2、在 /etc/hosts.deny 中删除你想取消的主机IP
3、编辑 DenyHosts 工作目录的所有文件,通过

grep 192.168.1.1 /var/lib/denyhosts/*  

然后一个个删除文件中你想取消的主机IP所在的行:

*/var/lib/denyhosts/hosts
*/var/lib/denyhosts/hosts-restricted
*/var/lib/denyhosts/hosts-root
*/var/lib/denyhosts/hosts-valid
*/var/lib/denyhosts/users-hosts

4、 添加你想允许的主机IP地址到 /var/lib/denyhosts/allowed-hosts

vi  /var/lib/denyhosts/allowed-hostsps  
# We mustn't block localhost
127.0.0.1  
192.168.1.*  

5、启动DenyHosts服务: service denyhosts start
6、一个解除IP限制的脚本:

#!/bin/bash

HOST=$1  
if [ -z "${HOST}" ]; then  
    echo "Usage:$0 IP"
    exit 1
fi

/etc/init.d/denyhosts stop
echo '  
/etc/hosts.deny
/var/lib/denyhosts/hosts
/var/lib/denyhosts/hosts-restricted
/var/lib/denyhosts/hosts-root
/var/lib/denyhosts/hosts-valid
/var/lib/denyhosts/users-hosts
' | grep -v "^$" | xargs sed -i "/${HOST}/d"  
/etc/init.d/denyhosts start