LoginSignup
39
41

More than 5 years have passed since last update.

EC2でnginxの過剰な404|403に対しfail2banをかける

Last updated at Posted at 2015-03-13

nginxで404を発生させる攻撃が増えてきたため、いくつかのセキュリティ対策しました。
そのうちの一つとして、fail2banを使って404を過剰に発生させるホストについては一時的に受付ないようにします。

まずはインストール

#インストール
yum install fail2ban

#起動時に自動起動
chkconfig --add fail2ban
chkconfig fail2ban on

log設定

vim /etc/fail2ban/fail2ban.conf
fail2ban.conf
# logtarget = SYSLOG  # ←これをコメントアウト
logtarget = /var/log/fail2ban/fail2ban.log # ←これを追加
mkdir /var/log/fail2ban/

filterを追加する

vim /etc/fail2ban/filter.d/nginx-404.conf
[Definition]
failregex =  ^<HOST>.*"(GET|POST).*" (403|404) .*$
ignoreregex =

404か403の時に評価する

banする設定

vim /etc/fail2ban/jail.local
jail.local
[nginx-404]
enabled = true
port = http,https
filter = nginx-404
logpath = /var/log/nginx*/*access.log
action = iptables-multiport[name=404, port="http,https", protocol=tcp]
maxretry = 5
findtime = 30
bantime = 7200

「30秒の間に5回404出したら、7200秒BANする」という意味です。

※注意:どのくらいの閾値かは、一概には言えません。特に今回のシステムでのaccess.logは画像やjs,cssなどのログを吐かない設定にしてあります。もし画像やcssなどもアクセスログとして履いている場合、気づかない404が正しいユーザーにも発生して、BANしてしまうリスクがあります。この辺はちゃんと理解し、テストした上でやりましょう。

logrotateの設定

vim /etc/logrotate.d/fail2ban
fail2ban
/var/log/fail2ban/fail2ban.log {
    missingok
    notifempty
    weekly
    rotate 5
    compress
    dateext
    create 0644 root root
    postrotate
        /usr/bin/fail2ban-client set logtarget /var/log/fail2ban/fail2ban.log 2> /dev/null || true
    endscript
}

準備完了。開始!

service fail2ban start

必要があればホワイトリストを設定する

vim /etc/fail2ban/jail.conf
jail.conf
ignoreip = 127.0.0.1/8 xxx.xxx.0.0/16
39
41
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
39
41