fail2ban

cagylogicではwordpressをつかっているのだが、ここ何年か、163data.com.cnから大量のスパムコメントをもらっている。

もちろん、Akismetで弾いているのだが、この度、fail2banを導入してみたのでそのメモ。

参考文献 : Web覚書ノート FAIL2BANでWORDPRESSのコメントスパム対策

# apt-get install fail2ban

でインストール。fail2banはpythonで記述された、iptableを利用してネットワークの元からブロックするツール。

ということで、芋づる式にPythonもインストールされる。

インストールしたら、/etc/fail2ban/jail.confに

ignoreip = 127.0.0.1/8 192.168.XXX.0/24

XXXは伏せ字(意味ないけど)

を頭の部分に、

[wp-login]

enabled = true
port = http,https
filter = wp-login
logpath = /var/log/apache*/*access.log
maxretry = 5
findtime = 600
bantime = 172800

[wp-comment]

enabled = true
port = http,https
filter = wp-comment
logpath = /var/log/apache*/*access.log
maxretry = 5
findtime = 600
bantime = 172800

をapacheの設定の下辺りに追加。

これは、ignoreipにローカルからのアクセスがはじかれるのを防ぐための無視IPアドレスの定義と、600秒(10分)間に5回条件を満たしたら、172800秒(2日)間弾くという条件の定義。

wp-login, wp-commentは、/etc/fail2ban/filter.d/wp-login.conf, /etc/fail2ban/filter.d/wp-comment.confのフィルターファイルに対応する文字列。ここでのポイントは、この文字列をあんまり長くしないこと。

最初、なんも考えないで、apache-wordpress-loginと設定していたら、fail2banを起動したときに、内部でのiptableの呼び出しのところでエラーになって、頭を抱えた。

フィルターファイルは、/etc/fail2ban/filter.d/wp-login.confでは、

[Definition]
failregex = <HOST>.*] “POST /wp-login.php

/etc/fail2ban/filter.d/wp-comment.confでは、

[Definition]
failregex = <HOST>.*] “POST /wp-comments-post.php

と設定した。この2つのファイルは新しく作成する。これは、/etc/fail2ban/jail.conf のlogpathで設定したログファイルを監視して、failregexで表した正規表現にマッチした場合に弾くという意味。ということで、もしwordpressをルートではなくて、/wordpressなどにインストールしている場合は、/wordpress/wp-login.phpなどと書けばOK。ログをチェックして、どんな文字列が出ているのか確認するのが吉。

あとは、

# /etc/init.d/fail2ban restart

をすれば起動する。/var/log/fail2ban.logを確認してエラーが出ていないことと、

# iptables -L

を実行して、

Chain INPUT (policy ACCEPT)
target prot opt source destination
fail2ban-wp-comment tcp — anywhere anywhere multiport dports http,https
fail2ban-wp-login tcp — anywhere anywhere multiport dports http,https

Chain FORWARD (policy ACCEPT)
target prot opt source destination

Chain OUTPUT (policy ACCEPT)
target prot opt source destination

Chain fail2ban-wp-comment (1 references)
target prot opt source destination
RETURN all — anywhere anywhere

Chain fail2ban-wp-login (1 references)
target prot opt source destination
RETURN all — anywhere anywhere

のように、fail2ban-wp-commentなどのチェインができていることを確認する。

1-2日放置しておくと、/var/log/fail2ban.logには、

2014-04-23 11:30:31,028 fail2ban.actions: WARNING [wp-comment] Ban 110.85.101.16
2014-04-23 11:33:43,256 fail2ban.actions: WARNING [wp-comment] Ban 110.85.103.5
2014-04-23 17:42:19,040 fail2ban.actions: WARNING [wp-comment] Ban 76.164.234.26
2014-04-23 18:25:24,918 fail2ban.actions: WARNING [wp-comment] Ban 183.14.87.43
2014-04-23 19:03:02,459 fail2ban.actions: WARNING [wp-comment] Ban 116.25.32.91
2014-04-23 19:18:16,478 fail2ban.actions: WARNING [wp-comment] Ban 27.153.251.105

のようにちゃんとブロックされいていることを確認する。iptables -Lを実行しても、ブロックしていることが確認できると思う。

この後、あきらかに、akismetでブロックされたスパムコメントの量が減っているのが確認できた。

コメントを残す

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください