天天看點

Linux 安裝DenyHost防止ssh被暴力破解

DenyHosts介紹

    當你的linux伺服器暴露在外網當中時,伺服器就極有可能會遭到網際網路上的掃描軟體進行掃描,然後試圖連接配接ssh端口進行暴力破解(窮舉掃描)。如果遇到這個問題,一款非常有用的工具DenyHosts可以阻止試圖猜測SSH登入密碼。DenyHosts是用Python寫的一個程式,它會分析SSHD的日志檔案(Redhat為/var/log/secure等),當發現同一IP在進行多次SSH密碼嘗試時就會記錄IP到/etc/hosts.deny檔案,進而達到自動屏蔽該IP的目的。

DenyHost的官方網址為http://denyhosts.sourceforge.net/ 官方的介紹如下:

What is DenyHosts?

DenyHosts is a Python script that analyzes the sshd server log messages to determine what hosts are attempting to hack into your system. It also determines what user accounts are being targeted. It keeps track of the frequency of attempts from each host.

Additionally, upon discovering a repeated attack host, the /etc/hosts.deny file is updated to prevent future break-in attempts from that host.

An email report can be sent to a system admin.

<b>DenyHosts安裝</b>

1:下載下傳DenyHosts安裝包。

2:解壓DenyHosts安裝包

[root@mylnx04 ~]# tar -zxvf DenyHosts-2.6.tar.gz

3:開始DenyHosts的安裝

安裝DenyHosts前必須安裝Python,當然現在絕大部分Linux主機應該都預設安裝了Python。

[root@mylnx04 ~]# cd DenyHosts-2.6/

[root@mylnx04 DenyHosts-2.6]# python setup.py install

<b>DenyHosts配置</b>

<b></b>

1:複制配置檔案denyhosts.cfg

[root@mylnx04 DenyHosts-2.6]# cp /usr/share/denyhosts/denyhosts.cfg-dist /usr/share/denyhosts/denyhosts.cfg

2:設定/usr/share/denyhosts/denyhosts.cfg相關參數.下面對主要的參數做一些介紹。

SECURE_LOG

sshd日志檔案,如下所示,配置檔案裡面都有詳細介紹。根本不用做詳細介紹。

如果是Redhat/Fedora Core系統,記錄sshd日志資訊的是/var/log/secure日志檔案。

如果是Mandrake, FreeBSD, OpenBSD系統,記錄sshd 日志資訊的是/var/log/auth.log日志檔案

如果是SuSE系統,記錄sshd日志資訊的是/var/log/messages日志檔案

.........................................

<a href="http://images2015.cnblogs.com/blog/73542/201703/73542-20170307122644875-678284319.png"></a>

HOSTS_DENY = /etc/hosts.deny

控制使用者登陸的檔案(記錄屏蔽的IP檔案)。大部分作業系統為/etc/hosts.deny BSD Unix為/etc/hosts.allow

<a href="http://images2015.cnblogs.com/blog/73542/201703/73542-20170307122647984-692319876.png"></a>

3: 從模闆copydaemon-control并授予相關權限,然後設定Denyhosts開機自啟動

4:啟動或重新開機DenyHosts服務

如果事态緊急,啟動服務前建議執行指令:echo "" &gt; /var/log/secure &amp;&amp; service rsyslog restart 清空以前的日志并重新開機一下rsyslog 。否則,如果日志裡面有大量記錄的話,你要等非常久才能啟動服務。

5:檢查DenyHosts是否啟動

[root@mylnx04 ~]# ps -ef | grep deny

下面是我遇到一台被人SSH掃描的主機,/etc/hosts.deny檔案裡面記錄的資訊。

<a href="http://images2015.cnblogs.com/blog/73542/201703/73542-20170307122650047-637034364.png"></a>

<b></b> 

<b>DenyHosts測試</b>

測試中也遇到一些小問題:

1: 設定PURGE_DENY = 5m,但是5分鐘後,/etc/hosts.deny中的ip記錄并沒有被清除。其實這個也受參數DAEMON_PURGE影響。因為DAEMON_PURGE預設為1h,而DenyHosts在daemon mode的時候,解禁IP的時間以DAEMON_PURGE為準,預設是1小時。是以你最好将PURGE_DENY和DAEMON_PURGE設定成一緻,另外你測試的值可能受DAEMON_SLEEP的影響,有所偏差。當然預設情況下DAEMON_SLEEP的值是很小的。

<b>測試總結歸納</b>

在實際環境中測試、驗證了一下DenyHost。确實非常有效,但是使用DenyHost防止主機sshd被人爆破也是一個非常被動的方法,其實有更好的方法解決問題。例如配置堡壘機跳闆機,隻允許從堡壘機 跳闆機通過ssh通路伺服器。

<b>參考資料:</b>

<a href="https://www.vpser.net/security/denyhosts.html">https://www.vpser.net/security/denyhosts.html</a>

<a href="http://denyhosts.sourceforge.net/faq.html">http://denyhosts.sourceforge.net/faq.html</a>