ksaitoの日記

日々試したことの覚え書き

SSHブルートフォース攻撃が増加、SANSが紹介した対策をやってみる(その2)

移転しました。

自動的にリダイレクトします。

その2は、"SSHブルートフォース防止のためのツールを導入する"です。
どんなツールがあるか知りませんでしたがdenyhostsというのが良さそうなので試してみました。

SSHブルートフォース防止のためのツールを導入する

denyhostsは、aptパッケージになっているので導入は簡単です。

$ sudo aptitude install denyhosts

デフォルトでは、下記のような接続を拒否するようになっています。

$ grep \^DENY /etc/denyhosts.conf 
DENY_THRESHOLD_INVALID = 5
DENY_THRESHOLD_VALID = 10
DENY_THRESHOLD_ROOT = 1
DENY_THRESHOLD_RESTRICTED = 1
$ 

意味は、rootで1回でもログインに失敗したら接続を拒否、存在しないユーザで5回ログインに失敗したら接続を拒否、存在するユーザが10回ログインに失敗したら、これも拒否です。

実際に試してみる

rootでログインに失敗してみると、/etc/hosts.denyに"sshd: [IPアドレス]"が追加されて接続できなくなりました。

$ ssh -p 60022 root@ubuntu
root@ubuntu's password: 
Permission denied, please try again.
root@ubuntu's password: 
Permission denied, please try again.
root@ubuntu's password: 
Permission denied (publickey,password).
$ ssh -p 60022 root@ubuntu
ssh_exchange_identification: Connection closed by remote host
$ 

解除する

一度、接続拒否されるとデフォルト設定では、/etc/hosts.denyから1行削除しても、すぐに接続拒否されます。
解除するには、公式ホームページのFAQの手順が必要です。

  1. Stop DenyHosts
  2. Remove the IP address from /etc/hosts.deny
  3. Edit WORK_DIR/hosts and remove the lines containing the IP address. Save the file.
  4. Edit WORK_DIR/hosts-restricted and remove the lines containing the IP address. Save the file.
  5. Edit WORK_DIR/hosts-root and remove the lines containing the IP address. Save the file.
  6. Edit WORK_DIR/hosts-valid and remove the lines containing the IP address. Save the file.
  7. Edit WORK_DIR/user-hosts and remove the lines containing the IP address. Save the file.
  8. (optional) Consider adding the IP address to WORK_DIR/allowed-hosts
  9. Start DenyHosts

デフォルト設定でWORK_DIRは、下記の通り/var/lib/denyhostsです。

$ grep \^WORK_DIR /etc/denyhosts.conf 
WORK_DIR = /var/lib/denyhosts
$

手順通りに解除してみます。

$ sudo /etc/init.d/denyhosts stop
 * Stopping DenyHosts denyhosts
   ...done.
$ sudo su -
# for i in /var/lib/denyhosts/hosts* /var/lib/denyhosts/users-valid /etc/hosts.deny
> do
>  sed -i -e '/解除するIPアドレス/d' $i
> done
# /etc/init.d/denyhosts start
 * Starting DenyHosts denyhosts
   ...done.
# 

これで、接続できるようになりました。

考察

denyhostsは、なかなか良いツールです。
設定の中には、接続拒否したときにメールを通知したり、一定期間で接続解除を復旧させたりすることができます。
sshdのログのパターンマッチなので、ポートがデフォルトから変更されていても問題なく動作します。
sshd以外のサービスにも対応しているので応用範囲が広そうです。