10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Amazon LinuxでGeoIPを使って海外からの攻撃を遮断する方法

Last updated at Posted at 2016-10-05

概要

AWSの環境でmod_geoipというApacheモジュールを使って、海外のIPからのアタックを遮断する設定例です。

設定が簡単なので
海外からの攻撃を一刻も早く遮断したい!といった場合に、
ちゃんとした WAF, IPS/IDS ツールを導入するまでのつなぎとして使える小技です。

環境

EC2 (Amazon Linux AMI release 2016.03)
ELB (Classic)

GeoIP-1.4.8-1.5.amzn1.x86_64
httpd24-2.4.23-1.66.amzn1.x86_64
mod24_geoip-1.2.7-1.6.amzn1.x86_64

GeoIPとは?

maxmind社が提供しているIPアドレスから地理情報を確認することができるサービスです。
https://www.maxmind.com/

mod_geoipの設定

前提:Apache2.4がインストール済みであること(設定は割愛)。

mod_geoipのインストール

# yum install mod24_geoip

GeoIPデータベースの更新

# cd /usr/share/GeoIP

<<< データが古いので退避 >>>
# mv GeoIP.dat GeoIP.dat.org

<<< 最新のデータを取得 >>>
# wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCountry/GeoIP.dat.gz
# gunzip GeoIP.dat.gz

geoip.confの設定

日本国外からの接続を遮断する設定

/etc/httpd/conf.d/geoip.conf
<IfModule mod_geoip.c>
  GeoIPEnable On
  GeoIPDBFile /usr/share/GeoIP/GeoIP.dat
</IfModule>

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

反映

# service httpd restart

ApacheがELB配下にある場合

普通に設定するとアクセス元IPがELBのものになったり、ヘルスチェックが弾かれてしまったりしてうまく動作しません。
これらの問題を回避する為、以下の設定を追加します。

ELB経由でもallow fromで元IPをチェックできるようにする

/etc/httpd/conf/httpd.conf
# <<< 下記を追加 >>>
RemoteIPHeader X-Forwarded-For

# <<< LogFormat 設定を変更 %h -> %a >>>
    #
    # The following directives define some format nicknames for use with
    # a CustomLog directive (see below).
    #
    LogFormat "%a %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
    LogFormat "%a %l %u %t \"%r\" %>s %b" common

    <IfModule logio_module>
      # You need to enable mod_logio.c to use %I and %O
      LogFormat "%a %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
    </IfModule>

ELBのヘルスチェックIPをチェック対象から除外

ELBのSubnetからの接続を許可する設定を追加すればOK(この例はクラスB全部)

/etc/httpd/conf.d/geoip.conf
<IfModule mod_geoip.c>
  GeoIPEnable On
  GeoIPDBFile /usr/share/GeoIP/GeoIP.dat
</IfModule>

<DirectoryMatch />
SetEnvIf Remote_Addr "^172.(1[6-9]|2[0-9]|3[0-1])." AllowCountry <<<-- New!!
SetEnvIf GEOIP_COUNTRY_CODE JP AllowCountry
Order deny,allow
Deny from all
Allow from env=AllowCountry
</DirectoryMatch>

反映

# service httpd restart

以上。

参考サイト

GeoIP Legacy Apache Module ドキュメント 国の他に,大陸や地域ごとの制御も可能なようです。
CentOSでGeoIPを利用してHTTPアクセスを制御する

10
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?