![見出し画像](https://assets.st-note.com/production/uploads/images/168575486/rectangle_large_type_2_323b2fee265fc26ef98b251ac926fb44.jpeg?width=1200)
WAF(Web Application Firewall)を作ってみた
はじめに
自分でつくった公開Webサイト。しばらく運用しているけど、もしかして何か外部から攻撃を受けているかも? 特にSQLインジェクションやDDoS攻撃といったよくある攻撃が心配だ。 まず、どんな攻撃をうけてるのか知りたい。よし、Googleで調べよう。という事で以下を発見。
ふむふむ。無料で攻撃を検知してくれるようだ。試しにやってみよう。何か攻撃を受けてますやん!!!!
![](https://assets.st-note.com/img/1735952603-PIwxicNslUj95zmobeYyaS2W.png?width=1200)
さてどうするか。WAFを導入したいがお金をかけたくない。なら自作するか。といわけで……。
やり方
1.iLogScannerでXML形式で出力( reporttype=xmlで出力可能)
2.XMLを解析して攻撃元IPアドレスを抽出(xmllint※というツールを利用)
※xmllint はXMLファイルを解析するためのツールで、抽出した攻撃元IPアドレスを取り出すために利用します。
3.FWでブロック(firewall-cmdを利用。既に登録されていればスキップ)
4.1~3を1分ごとに繰り返す
というわけでコードは以下(環境はCentOS7.9、Apache 2.4.57)
cd "$(dirname "$0")"
#iLogScannerを実行。
./iLogScanner.sh mode=cui logtype=apache accesslog=/var/log/httpd/access_log outdir=./ level=detail reporttype=xml
rm result.xml
rm find_ip.txt
mv iLogScanner_*.xml result.xml
#XMLを解析してIPを抜き出す
echo "cat /AnalysisReport/Detail/AttackDetections/AttackDetection/SourceLog/Line" | xmllint --shell result.xml | grep "Line No" | grep -oE "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b" | grep -v "120\.0\.0\.0" | sort -u > find_ip.txt
mapfile -t ip_addresses < find_ip.txt
file_name="firewall_ip.txt"
#抽出したIPアドレスに対してループ処理
for ip_address in "${ip_addresses[@]}"; do
#ファイル内でIPアドレスが見つかるか確認
if grep -q "$ip_address" "$file_name"; then
echo "IPアドレス $ip_address はファイル内に存在します"
else
#未登録の場合はFWに登録
current_date=$(date +"%Y%m%d%H%M%S")
echo "$current_date : IPアドレス $ip_address をブロックします" >> log.txt
firewall-cmd --permanent --add-rich-rule="rule family='ipv4' source address=$ip_address reject"
echo "$ip_address" >> "$file_name"
firewall-cmd --reload
mv result.xml ${current_date}_result.xml
fi
done
rm result.xml
rm find_ip.txt
#firewall-cmd --reload
そこそこブロックされている様子。今できるのはこれくらいかな。あとは実際に拒否されたログを見て確認してみる予定。
![](https://assets.st-note.com/img/1735952636-OHFdXhDzM6yAf5J3T08mkGP7.png?width=1200)