LoginSignup
24

Apache向けfail2banの簡易構築手順

Last updated at Posted at 2016-11-16

Apacheのアクセスログに国外からの大量の403と404のリクエストエラーが出力されていたため、過剰なアクセスへの対策を施す事にしました。

以下は対策の元ネタにさせて頂いた記事

EC2でnginxの過剰な404|403に対しfail2banをかける
http://qiita.com/osamu1203/items/e7b1718caf4fa59dca4f

403と404を過剰に発生させているIPについては以下のルールを用いて一時的に受付けないようにします。

「30秒の間に10回403のリクエストエラーを発生させたら、1800秒BANする」
「30秒の間に10回404のリクエストエラーを発生させたら、1800秒BANする」

以下、fail2banの簡易構築手順です。

事前準備

[root@localhost ~]# cat /etc/sysconfig/iptables # iptablesの現在のコンフィグを確認
[root@localhost ~]# /etc/init.d/iptables status # iptablesの有効化を確認
[root@localhost ~]# iptables -L                 # iptablesの現在適用されているルールを確認
[root@localhost ~]# mkdir /var/log/fail2ban     # ログディレクトリを新規作成

インストール

[root@localhost ~]# rpm -Uvh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
[root@localhost ~]# yum install --enablerepo=epel fail2ban

fail2ban.confの編集

/etc/fail2ban/fail2ban.conf
# logtarget = SYSLOG                       # コメントアウト
logtarget = /var/log/fail2ban/fail2ban.log # 追加

jail.localの新規作成

/etc/fail2ban/jail.local
[apache-403]
enabled = true
filter = apache-403                  # フィルター名
logpath = /var/log/httpd/*access_log # ログファイルパス
action = iptables-multiport[name="403", port="http,https", protocol="tcp"]
maxretry = 10  # 最大リトライ値
findtime = 30  # 監視間隔(秒)
bantime = 1800 # アクセス禁止時間(秒)

[apache-404]
enabled = true
filter = apache-404                  # フィルター名
logpath = /var/log/httpd/*access_log # ログファイルパス
action = iptables-multiport[name="404", port="http,https", protocol="tcp"]
maxretry = 10  # 最大リトライ値
findtime = 30  # 監視間隔(秒)
bantime = 1800 # アクセス禁止時間(秒)

403フィルター新規作成

/etc/fail2ban/filter.d/apache-403.conf
[Definition]
failregex =  ^<HOST>.*"(GET|POST).*" 403 .*$                      # フィルター
ignoreregex = 127.0.0.0/8 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 # ホワイトリスト

404フィルター新規作成

/etc/fail2ban/filter.d/apache-404.conf
[Definition]
failregex =  ^<HOST>.*"(GET|POST).*" 404 .*$                      # フィルター
ignoreregex = 127.0.0.0/8 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 # ホワイトリスト

logrotateの設定

/etc/logrotate.d/fail2ban
# /etc/logrotate.d/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
}

fail2banのサービス起動および自動起動設定

[root@localhost ~]# /etc/init.d/fail2ban start  # fail2banのサービス起動
[root@localhost ~]# /etc/init.d/fail2ban status # fail2banのサービス起動確認
[root@localhost ~]# chkconfig --add fail2ban    # fail2banのサービス自動起動追加
[root@localhost ~]# chkconfig fail2ban on       # fail2banのサービス自動起動設定
[root@localhost ~]# chkconfig --list fail2ban   # fail2banのサービス自動起動確認

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
24