
AWS WAFのratebaseやShield, Route53, Fail2banを利用したり、スケーリング対応などなど・・・色々とDoSへの対応はあると思いますが、今回はApacheのDoS対策モジュールを利用します。
mod_dosdetectorの大きな動作はリクエスト数の閾値を超えたら環境変数に値をセットし、その変数を見てmod_rewriteに処理させるといったものなので、既存構成に大きな影響を与えることなくカジュアルに対応出来ます。
環境
- Amazon Linux2
- ALB配下のEC2
Apache DoS対策の流れ
- mod_dosdetectorでDoSを検知したら環境変数にセットする
- mod_rewriteで対象IPに対してルールを適用する
503を返したり、リダイレクトでどっかに飛ばしたり・・・!
mod_dosdetectorをインストールしよう
# yum install git httpd-devel gcc
# httpd -M | grep rewrite rewrite_module (shared)
cd /usr/local/src/ git clone https://github.com/stanaka/mod_dosdetector.git cd mod_dosdetector/ make install
コマンドの場所を確認
# which apxs /usr/bin/apxs
コマンドが/usr/sbin/apxsでないとインストールでこけるからリンクを張る
# ln -s /usr/bin/apxs /usr/sbin/apxs
インストール
# make install
ログにALB配下でクライアントのIPを取ってくるように設定
# vi /etc/httpd/conf.d/GlobalSetting.conf
# ALB利用中に接続元IPを取得してログへ
LogFormat "%{X-Forwarded-For}i %h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
mod_dosdetectorの設定
今回は下記となるように設定
- 5秒間100リクエストでDoS判定
- DoSと判定したら503を返す
# vi /etc/httpd/conf.d/mod_dosdetector.conf
LoadModule dosdetector_module /usr/lib64/httpd/modules/mod_dosdetector.so
<IfModule mod_dosdetector.c>
DoSDetection on
# DoS攻撃判定計測時間
DoSPeriod 5
# DOS攻撃の嫌疑をかける判定計測時間の閾値 閾値を超えると変数SuspectDoSが1になる
DoSThreshold 100
# DOS攻撃と確定するアクセスカウント 変数SuspectHardDoSが1になる
DoSHardThreshold 100
# アクセス禁止時間
DoSBanPeriod 60
# 嫌疑をかけるIPの最大保存数
DoSTableSize 100
# X-Forwarded-For headerをIPとして扱うかどうかのチェック
DoSForwarded on
# ホワイトリスト
DoSIgnoreContentType ^(image/|application/|text/javascript|text/css)
</IfModule>
## リライトルール -------------------
RewriteEngine On
# for DoS attack
RewriteCond %{ENV:SuspectDoS} .+ [OR]
RewriteCond %{ENV:SuspectHardDoS} .+
# クラスAのローカルIPアドレス帯を全て除外
RewriteCond %{REMOTE_ADDR} !^(10\.[0-9]+\.[0-9]\.[0-9])$
# クラスBのローカルIPアドレス帯を全て除外
RewriteCond %{REMOTE_ADDR} !^(172\.(1[6-9]|2[0-9]|3[0-1])\.[0-9]+\.[0-9]+)$
# クラスCのローカルIPアドレス帯を全て除外
RewriteCond %{REMOTE_ADDR} !^(192\.168\.[0-9]+\.[0-9]+)$
# 対クローラー排除
RewriteCond %{HTTP_USER_AGENT} !(google|yahoo|msn|bing) [NC]
RewriteRule .* - [R=503,L]
反映を行いましょ~!
# httpd -t # systemctl restart httpd
WEBサーバ当てにふわっと迷惑にならない程度にF5攻撃でも行います。
60リクエストを超えると503が返されました。
正常動作していますね。
ログを見る
# tail -f /var/log/httpd/error_log | grep dosdetector [Mon Feb 18 15:01:39.414772 2019] [so:warn] [pid 3996] AH01574: module dosdetector_module is already loaded, skipping [Mon Feb 18 15:01:53.625046 2019] [:notice] [pid 3997] dosdetector: 'xxx.xxx.xxx.xxx' is suspected as DoS attack! (counter: 16) [Mon Feb 18 15:01:54.458100 2019] [:notice] [pid 4045] dosdetector: 'xxx.xxx.xxx.xxx' is suspected as Hard DoS attack! (counter: 21)
お疲れ様です。
