Harada's Diary

GeoIPを使用してWebサーバのアクセスを国内だけに制限する

※覚書用に作成したサイトですがクローリング設定は無効で、検索経由で来ることはありませんが、外部からもアクセスされるため対策します。海外からの攻撃的なアクセスが多いため、GeoIP で国内のみ許可します。


GeoIP について

GeoIP は MaxMind が提供する IP アドレスの地理判定サービス。
無償版と有償版があり、国別判定のみなら無償で十分。

👉 https://www.maxmind.com/


1. 作業環境

  • CentOS 6.8
  • Apache 2.2.15

2. Yum リポジトリ追加

yum install epel-release

3. パッケージインストール

yum install mod_geoip GeoIP GeoIP-devel GeoIP-data zlib-devel

これにより以下がインストールされる:

  • IP 判別 DB: /usr/share/GeoIP/GeoIP.dat(古いデータ)
  • ユーティリティ: geoiplookup, geoiplookup6, geoipupdate
  • Apache モジュール: modules/mod_geoip.so
  • 設定ファイル: /etc/httpd/conf.d/geoip.conf

4. GeoIP データベース更新

更新は月 1 回(おそらく 2 日頃)、更新しないと誤判定の原因に。

更新スクリプト例:

vi /root/geoipupdate.sh
#!/bin/sh # geoipupdate.sh # 無償の GeoLiteCountry を利用 GEOIP_URL=http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz GEOIP_PATH=/usr/share/GeoIP/GeoIP.dat GEOIP_TEMP=/usr/share/GeoIP/GeoIP.dat.temp curl -f $GEOIP_URL | zcat > $GEOIP_TEMP if [ $? -ne 0 ]; then exit 1 fi if [ -s $GEOIP_TEMP ]; then mv -f $GEOIP_TEMP $GEOIP_PATH exit 1 fi exit 0 

実行権付与:

chmod +x /root/geoipupdate.sh

geoipupdate コマンドでも更新可


5. Apache の設定

vi /etc/httpd/conf.d/geoip.conf

設定例(海外拒否):

LoadModule geoip_module modules/mod_geoip.so <IfModule mod_geoip.c> GeoIPEnable On GeoIPDBFile /usr/share/GeoIP/GeoIP.dat Standard </IfModule> # 海外からのアクセスを拒否 <DirectoryMatch "/"> SetEnvIf GEOIP_COUNTRY_CODE JP AllowCountry Order deny,allow Deny from all Allow from env=AllowCountry </DirectoryMatch> 

6. Apache 再起動

/etc/rc.d/init.d/httpd restart

これで完了。


検証(AWS 海外リージョンから)

設定前:アクセス可能
設定後:403 で遮断
→ 意図通り動作


Cron に登録(推奨)

crontab -e

例:

00 09 02 * * root /root/bin/geoipupdate.sh

📌 設定サンプル


🇯🇵 日本からのアクセスを拒否

<DirectoryMatch "/"> SetEnvIf GEOIP_COUNTRY_CODE JP BlockCountry Order allow,deny Allow from all Deny from env=BlockCountry </DirectoryMatch> 

🌍 多国アクセス許可(米/日 + 各大陸)

<DirectoryMatch "/"> SetEnvIf GEOIP_COUNTRY_CODE US AllowCountry SetEnvIf GEOIP_COUNTRY_CODE JP AllowCountry SetEnvIf GEOIP_CONTINENT_CODE SA AllowContinent SetEnvIf GEOIP_CONTINENT_CODE EU AllowContinent SetEnvIf GEOIP_CONTINENT_CODE NA AllowContinent SetEnvIf GEOIP_CONTINENT_CODE OC AllowContinent Order deny,allow Deny from all Allow from env=AllowCountry Allow from env=AllowContinent </DirectoryMatch> 

🇨🇳🇷🇺 中国+ロシア拒否

<DirectoryMatch "/"> SetEnvIf GEOIP_COUNTRY_CODE CN BlockCountry SetEnvIf GEOIP_COUNTRY_CODE RU BlockCountry Order allow,deny Allow from all Deny from env=BlockCountry </DirectoryMatch> 

参考リンク