# DenyHosts

### 利用DenyHosts防止暴力破解

DenyHosts由Phil Schwartz编写，其官方网站是<http://denyhosts.sourceforge.net。>

DenyHosts是使用Python开发的，它通过监控系统安全日志（例如，/var/log/secure）来分析是否存在对OpenSSH的暴力破解行为。如发现暴力破解，则其从该系统安全日志中分析出来源IP地址，然后通过在/etc/hosts.deny中加入相应的条目来使用TCP Wrappers禁止该IP地址的后续连接尝试。

### DenyHosts的安装和启动脚本

```
wget https://nchc.dl.sourceforge.net/project/denyhosts/denyhosts/2.6/DenyHosts-2.6.tar.gz
# 官网下载包安装
[root@www ~]# tar zxvf DenyHosts-2.6.tar.gz
[root@www ~]# cd DenyHosts-2.6
[root@www DenyHosts-2.6]# apt install python -y
[root@www DenyHosts-2.6]# python setup.py install
[root@www DenyHosts-2.6]# cd /usr/share/denyhosts/   
[root@www denyhosts]# cp denyhosts.cfg-dist denyhosts.cfg      //配置文件
[root@www denyhosts]# cp daemon-control-dist daemon-control    //启动文件
[root@www denyhosts]# chown root daemon-control
[root@www denyhosts]# chmod 700 daemon-control
[root@www denyhosts]# ln daemon-control /etc/init.d/           #创建硬链接
[root@www denyhosts]# /etc/init.d/daemon-control start         #以Daemon形式启动DenyHosts


```

### 配置文件详细解读

```
SECURE_LOG = /var/log/auth.log   # ssh日志文件  
HOSTS_DENY = /etc/hosts.deny    # 将阻止IP写入到hosts.deny
PURGE_DENY =     # 过多久后清除已经禁止的，空代表永不解禁 其中w代表周，d代表天，h代表小时，s代表秒，m代表分钟
BLOCK_SERVICE = sshd   # 阻止服务名
DENY_THRESHOLD_INVALID = 5  # 允许无效用户（在/etc/passwd未列出）登录失败次数,允许无效用户登录失败的次数.
DENY_THRESHOLD_VALID = 5  #  允许普通用户登录失败的次数
DENY_THRESHOLD_ROOT = 5  #  允许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=no  # 是否做域名反解
LOCK_FILE = /run/denyhosts.pid  # 将DenyHOts启动的pid纪录到LOCK_FILE中，已确保服务正确启动，防止同时启动多个服务。
IPTABLES = /sbin/iptables  # 防火墙脚本文件
ADMIN_EMAIL = youremailaddress@domain.com  # 设置接收通知邮件的地址 多个 ,分隔
SMTP_HOST = localhost  # SMTP服务器地址
SMTP_PORT = 25  # 端口
SMTP_USERNAME = senderemailaddress@domain.com  # 接收的邮箱看到的发送者邮箱地址
SMTP_PASSWORD= password   # 使用第三方邮箱的服务一般都有授权码 不是邮箱的密码哦
SMTP_FROM = DenyHosts senderemailaddress@domain.com  # 显示发件人是谁 
SMTP_SUBJECT = DenyHosts Report  # 邮件主题
AGE_RESET_VALID=1d  # 有效用户登录失败计数归零的时间
AGE_RESET_ROOT=1d  # root用户登录失败计数归零的时间
AGE_RESET_RESTRICTED=5d  # 用户的失败登录计数重置为0的时间
AGE_RESET_INVALID=10d  # 无效用户登录失败计数归零的时间
DAEMON_LOG = /var/log/denyhosts  自己的日志文件
DAEMON_SLEEP = 30s
DAEMON_PURGE = 5m  # 该项与PURGE_DENY 设置成一样，也是清除hosts.deniedssh 用户的时间

```

### 相关命令

```
$ sudo service denyhosts start  
$ sudo service denyhosts stop
$ sudo service denyhosts restart
$ sudo service denyhosts status   # 如果启动失败可以查看错误信息
$ sudo dpkg -l|grep denyhost   # 查看是否安装了 denyhost
$ sudo apt-get purge denyhost  # 卸载denyhost
```
