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