Webアプリケーションファイアウォールの仕組みとModSecurity実践ガイド

Webアプリケーションファイアウォール(WAF)は、SQLインジェクションやクロスサイトスクリプティング(XSS)などの攻撃からアプリケーションを守るための重要なセキュリティ層です。ここでは、その動作原理と代表的なオープンソース実装であるModSecurityを用いた具体的な設定手順を解説します。

WAFの基本アーキテクチャ

  • 処理レイヤ:HTTP/HTTPSトラフィックを解析するアプリケーション層(OSI第7層)で動作
  • 検知方式
    • シグネチャベース:既知の攻撃パターン(例:UNION SELECT)との照合
    • 正規表現マッチング:悪意あるパラメータ構造の検出
    • 異常行動分析:リクエスト頻度やサイズの逸脱を検知
  • 対応アクション:許可(Allow)、遮断(Block)、ログ記録(Log)、リダイレクト(Redirect)など

主なデプロイ形態

形態特徴利用例
リバースプロキシ型全トラフィックがWAFを経由Nginx + ModSecurity
透過プロキシ型ネットワーク側でトラフィックを迂回専用ハードウェア機器
埋め込み型Webサーバにモジュールとして統合Apache mod_security

ModSecurity環境の構築手順

Ubuntu 22.04上でNginxと連携させる場合のセットアップ例:

# 必要パッケージのインストール
sudo apt update
sudo apt install -y git build-essential libpcre3-dev libssl-dev libtool autoconf automake

# ModSecurity v3のビルド
git clone --depth 1 -b v3/master https://github.com/SpiderLabs/ModSecurity
cd ModSecurity
git submodule update --init
./build.sh && ./configure && make -j$(nproc) && sudo make install
# Nginx用コネクタのコンパイル
NGINX_VERSION=$(nginx -v 2>&1 | cut -d'/' -f2)
wget http://nginx.org/download/nginx-${NGINX_VERSION}.tar.gz
tar xzf nginx-${NGINX_VERSION}.tar.gz
git clone https://github.com/SpiderLabs/ModSecurity-nginx.git

cd nginx-${NGINX_VERSION}
./configure --with-compat --add-dynamic-module=../ModSecurity-nginx
make modules
sudo cp objs/ngx_http_modsecurity_module.so /usr/lib/nginx/modules/

設定ファイルの作成

Nginx設定(/etc/nginx/nginx.conf):

load_module modules/ngx_http_modsecurity_module.so;

http {
    modsecurity on;
    modsecurity_rules_file /etc/nginx/modsec/main.conf;
    
    server {
        listen 80;
        location / {
            proxy_pass http://localhost:8080;
        }
    }
}

ルール設定(/etc/nginx/modsec/main.conf):

Include /etc/nginx/modsec/modsecurity.conf
Include /etc/nginx/modsec/crs-setup.conf
Include /etc/nginx/modsec/rules/*.conf

OWASP CRSの導入

cd /etc/nginx/modsec
sudo git clone https://github.com/coreruleset/coreruleset.git rules
sudo cp rules/crs-setup.conf.example crs-setup.conf
sudo cp /usr/local/modsecurity/modsecurity.conf-recommended modsecurity.conf

modsecurity.conf内の主要パラメータ:

SecRuleEngine On
SecAuditLog /var/log/modsec_audit.log
SecDebugLogLevel 0

動作確認テスト

# XSS攻撃のシミュレーション
curl "http://localhost/?input=<script>alert('test')</script>"

# SQLインジェクションのシミュレーション
curl "http://localhost/search?term=' OR 1=1--"

正常に動作していれば、両方とも403 Forbiddenが返却され、ログファイルにブロック記録が残ります。

運用時のチューニングポイント

  • 誤検知対策:特定URIに対してルールIDを除外
    location /api/public {
            modsecurity_rules '
                SecRuleRemoveById 942100
                SecRuleRemoveById 942260
            ';
        }
  • パフォーマンス最適化:不要なボディ検査を無効化(ただしリスクあり)
    SecRequestBodyAccess Off
  • ログ管理:logrotateによる自動ローテーション設定推奨

代替オープンソースWAF比較

名称特徴向いている用途
Coraza (Go製)軽量・高速・Kubernetes対応マイクロサービス環境
NAXSI低遅延・学習モード搭載高トラフィックAPIゲートウェイ
OpenResty + Lua柔軟なカスタムルール記述可能特殊なセキュリティ要件

WAFは包括的なセキュリティ対策の一部にすぎません。安全な開発プロセス、定期的な脆弱性診断、侵入検知システムとの連携によって初めて有効な防御体制が構築されます。

タグ: ModSecurity OWASP-CRS WAF nginx Webセキュリティ

5月31日 06:30 投稿