본문 바로가기
Linux

GeoIP 모듈을 이용한 해외 IP 차단 관리하기

by 씨엔아이소프트 2022. 1. 18.
반응형
GeoIP 란 MaxMind 에서 제공하는 국가별로 IP를 확인할 수 있는 오픈소스 라이브러리로 이를 이용하여 서버에 접근 하는 아이피를 국가별로 관리할 수 있습니다.
 
테스트 OS : CentOS 5.9 64bit
 
1. Apache에 GeoIP 모듈 설치하기
 
​1-1. GeoIP C API 설치하기
​# cd /usr/local/src
# tar xvfz GeoIP-1.4.6.tar.gz
# cd GeoIP-1.4.6
#./configure --prefix=/usr/local/GeoIP
# make && make install
 
- GeoIP의 ip목록을 최신정보로 갱신하기 위하여 GeoIP.dat 을 다운받아 설치된 위치에 복사
: 국가 정보 다운로드
 
: 도시 정보 다운로드
 
# gzip -d GeoIP.dat.gz 
# gzip -d GeoLiteCity.dat.gz
 
- 해제된 파일을 GeoIP가 설치된 위치에 덮어쓰기
#cp -a GeoIP.dat /usr/local/GeoIP/share/GeoIP/
#cp -a GeoLiteCity.dat /usr/local/GeoIP/share/GeoIP/
 
​1-2. GeoIP 모듈을 아파치에 설치하기
-mod_geoip 다운
아파치 1.x 용
아파치 2.x 용
ex)아파치 2.x용 다운로드
 
 
# tar zxvf mod_geoip2_1.2.5.tar.gz
 
-> 해제된 위치로 이동 후 c 파일을 apxs 를 이용하여 설치
# cd mod_geoip2_1.2.5
 
# [아파치 apxs경로] -i -a -L [geoip 설치 디렉토리의 lib 경로] -I [geoip 설치 디렉토리의 include 경로] -l GeoIP -c [mod_geoip.c 경로]
----> 옵션 대소문자 주의 -l GeoIP = 소문자 엘로 시작
 
# /usr/local/apache/bin/apxs -i -a -L /usr/local/GeoIP/lib -I /usr/local/GeoIP/include -l GeoIP -c /usr/local/src/mod_geoip2_1.2.5/mod_geoip.c
 
# ls -al /usr/local/apache/modules/mod_geoip.so
# cat /usr/local/apache/conf/httpd.conf | grep geoip
 
- phpinfo 페이지의 Apache Environment 정보에 GEOIP_CONTINENT_CODE, GEOIP_COUNTRY_CODE, GEOIP_COUNTRY_NAME 항목 확인
 
# vi /usr/local/apache/conf/httpd.conf
특정 국가의 접근 차단
<IfModule mod_geoip.c>
    GeoIPEnable On
    GeoIPDBFile /usr/local/GeoIP/share/GeoIP/GeoIP.dat
    <Location /home>
           SetEnvIf GEOIP_COUNTRY_CODE CN go_out
           SetEnvIf GEOIP_COUNTRY_CODE RU go_out
           SetEnvIf GEOIP_COUNTRY_CODE TH go_out
           <Limit GET POST>
             Order allow,deny
             Allow from all
             Deny  from env=go_out
           </Limit>
    </Location>
</IfModule>
 
특정 국가에만 접근 허용
<IfModule mod_geoip.c>
    GeoIPEnable On
    GeoIPDBFile /usr/local/GeoIP/share/GeoIP/GeoIP.dat
    <Location /home>
          SetEnvIf GEOIP_COUNTRY_CODE KR go_in
           <Limit GET POST>
             Order Deny,Allow
             Deny from all
             Allow  from env=go_in
           </Limit>
    </Location>
</IfModule>
 
[cloudflare 적용시]
<IfModule mod_geoip.c>
    GeoIPEnable On
    GeoIPDBFile /usr/local/GeoIP/share/GeoIP/GeoIP.dat
</IfModule>  
 
<Directory /home/>
SetEnvIf GEOIP_COUNTRY_CODE KR AllowCountry
Allow from env=AllowCountry
allow from 103.21.244.0/22
allow from 103.22.200.0/22
allow from 103.31.4.0/22
allow from 104.16.0.0/12
allow from 108.162.192.0/18
allow from 131.0.72.0/22
allow from 141.101.64.0/18
allow from 162.158.0.0/15
allow from 172.64.0.0/13
allow from 173.245.48.0/20
allow from 188.114.96.0/20
allow from 190.93.240.0/20
allow from 197.234.240.0/22
allow from 198.41.128.0/17
allow from 199.27.128.0/21
Deny from all
</Directory> 
 
 
[참고]
Cannot load /usr/local/apache/libexec/mod_geoip.so into server: libGeoIP.so.1: cannot open shared object file: No such file or directory
에러 발생시 
/etc/ld.so.conf 파일에 
/usr/local/GeoIP/lib 라인 추가 후 
ldconfig 적용
===================================================================
 
 
* GeoIP에는 국가별 IP대역에 대한 database가 담겨 있습니다. 이를 각 패키지 모듈에 적재하여 여러 방법으로 접속제한 및 속도향상, 등 여러가지 재미있는 구성을 해 볼 수 있습니다. 이번 포스팅에는 iptables에 모듈 적재하여 국가별로 접속을 제한하는 방법에 대해 설명 해 보고자 합니다.
 
GeoIP의 경우 공식적인 모듈 업데이트가 몇년 전에 중단 된 것으로 알고 있어 구 버전 OS를 사용하는 경우가 있으나
이를 위해 최신 OS 커널에 작업을 해보겠습니다.
 
 
2. Iptables에 GeoIP 모듈 설치하기
 
 
 
2-1. patch-o-matic-ng 구버전을 받아 압축을 푼다. patch-o-matic-ng 최근 버전의 경우 커널과 iptables에 ipt_geoip가 아닌 xt_geoip 모듈이 추가되는데, 2.6.18.x 커널과 iptables 1.3.5 버전엔 맞지 않는 모듈이라고 한다. iptables의 경우 v1.4.3 이상이 설치되어 있어야 사용 가능하다고 합니다.
 
 
 
 
# cd /usr/src
# tar xvfz patch-o-matic-ng-20080521.tar.bz2
 
2-2. ​
rpm으로 설치된 iptables에 geoip extension을 추가하려면 iptables srpm을 받아 patch-o-matic-ng를 적용하고 리빌드하여 설치해야한다.
http://rpm.pbone.net 을 통해 iptables의 srpm을 다운받아 설치한다.
# cd /usr/src/redhat/SOURCE
->iptables-1.3.5.tar.bz 파일 생성
->압축풀기
# tar xvfj iptables-1.3.5.tar.bz2
 
 
 
# cd /usr/src
 
# ln -s /usr/src/redhat/SOURCE/iptables-1.3.5 /usr/src/iptables
# ln -s /usr/src/kernel/`uname -r` /usr/src/linux
-> 최신 커널 버전을 입력
*****************************
geoip update 스크립트 
*******************************
# cd /usr/src/patch-o-matic-ng-20080521
# ./runme --download    --> geoip 소스 가져오기
# ./runme geoip      --> kernel과 iptables에 geoip 모듈 소스가 설치
 
* 주의사항 : 위 두줄 명령어 실행시 kernel dir 과 iptables dir의 위치를 찾을 수 없다는 메세지가 나올 수 있으며 심볼릭 링크를 제대로 걸어준 상태라면 /usr/src/linux , /usr/src/iptables 를 입력후 엔터하면 제대로 넘어간다.
 
Welcome to Patch-o-matic ($Revision: 6736 $)! Kernel:   2.6.18, /usr/src/linux
Iptables: 1.3.5, /usr/src/iptables
Each patch is a new feature: many have minimal impact, some do not.
Almost every one has bugs, so don't apply what you don't need!
-------------------------------------------------------
Already applied:
Testing geoip... not applied
The geoip patch:
   Author: Samuel Jean <jix@bugmachine.ca>; Nicolas Bouliane <nib@bugmachine.ca>
   Status: Stable This patch makes possible to match a packet
by its source or destination country. GeoIP options:
        [!]   --src-cc, --source-country country[,country,country,...]                         Match packet coming from (one of)
                        the specified country(ies)         [!]   --dst-cc, --destination-country country[,country,country,...]                         Match packet going to (one of)
                        the specified country(ies)            NOTE: The country is inputed by its ISO3166 code. The only extra files you need is a binary db (geoipdb.bin) & its index file (geoipdb.idx).
for a quick HOWTO.
-----------------------------------------------------------------
Do you want to apply this patch [N/y/t/f/a/r/b/w/q/?] y
Excellent! Source trees are ready for compilation.
 
Recompile the kernel image (if there are non-modular netfilter modules).
Recompile the netfilter kernel modules.
Recompile the iptables binaries
​위에서 압푹 푼 iptables의 extensions 경로에 geoip 패치파일이 있는지 확인한다
[root@ns patch-o-matic-ng-20071231]# ls -l /usr/src/iptables/extensions | grep geoip
 
 
 
 
 
 
# cd /usr/src/i​ptables
# make   --> libipt_geoip.so 모듈 생성
# make install 또는​
# cd extensions
# cp libipt_geoip.so /lib64/i​ptables  -->  iptables 실행 준비 완료
* 주의사항 : extensions 디렉터리에서 모듈을 lib에 복사하지 않으면 다음과 같은 에러 때문에  iptables에 geoip 모듈을 적용할 수 없다.
iptables v1.3.5: Couldn't load match `geoip':/lib/iptables/libipt_geoip.so: cannot open shared object file: No such file or directory
 
이 에러는 iptables의 geoip extension이 없어서 발생하는 문제 입니다. 이 글을 iptables의 geoip extension을 알아서 준비하셨거나 하실 거라고 가정을 하고, geoip kernel netfilter module을 빌드하기 위한 방법을 적은 것입니다.
 
즉, iptables 를 geoip extension을 넣어서 새로 빌드 하셔야 한다는 얘기 입니다. geoip extension은 patch-o-matics 에서 찾으실 수 있는데, 요즘 geoip extension이 있는 사이트가 죽은 모양인지 연결이 안되서, 인터넷을 뒤져야 할 수도 있을 것 같습니다. ^^;
 
즉, iptables에서 geoip를 사용하기 위해서는 ipbltales geoip extension과 kernel netfilter iptables module 이 필요하고, 이 글은 후자(kernel module)을 빌드하기 위한 글 입니다. (즉, iptblaes에서 geoip를 사용하기 위한 전반적인 내용을 담고 있는 것이 아닙니다.)
 
========================================================
 
 
 
2-3. 커널 작업
# cd /usr/​src/linux
# make oldconfig
 
...(중략)...
geoip match support (IP_NF_MATCH_GEOIP) [N/m/?] (NEW)
# make modules_prepare
 
# mv net/ip​v4/netfilter/Makefile net/ipv4/netfilter/Makefile.orig
# vi net/ipv4/netfilter/Makefile
obj-m := ipt_geoip.o
KDIR := /lib/modules/$(shell uname -r)/build
PWD   := $(shell pwd)
default:
    $(MAKE) -C $(KDIR) M=$(PWD) modules
# make M=net/ipv4/netfilter
​# cp net/ipv4/netfilter/ipt_geoip.ko /lib/modules/최신커널버전/kernel/net/ipv4/netfilter/
# chmod 744 /lib/modules/최신커널버전/kernel/net/ipv4/netfilter/ipt_geoip.ko
# depmod -a
# ls -l /lib/modules/2.6.18-164.el5/kernel/net/ipv4/netfilter | grep geoip
# modprobe ipt_geoip
# lsmod | grep geoip     --> module 로딩 되었는지 확인 
 
 
​# yum install GeoIP GeoIP-devel
 
 
# mkdir /var/geoip
# cd /var/geoip
# tar xvfz csv2bin-20041103.tar.gz
# cd csv2bin
# make 
--->cvs2bin 툴을 이용하여 매월1일 업데이트 되는 geoip database를 생성
 
 
---------------------------------------------------------------------------------------
국가별 DB 다운 받는다. 매달 정기적인 업데이트를 위해 쉘 형태로 만들어 보았다.
#>geoip_csv_update
#!/bin/bash
cd /var/geoip/
unzip GeoIPCountryCSV.zip
mv GeoIPCountryWhois.csv csv2bin/
cd /var/geoip/csv2bin/
chmod 755 GeoIPCountryWhois.csv
./csv2bin GeoIPCountryWhois.csv
cp geoipdb* /var/geoip -f
rm -f /var/geoip/GeoIPCountryCSV.zip 
 
 
# ./geoip_csv_update
-> 쉘 실행
 
 
----------------------------------------------------------------------------
3. iptables 룰 적용
***** 주의 : 체인 적용 할 때 INPUT 체인 대신 따른 체인을 사용한다면 꼭 적용되는 지 테스트 해 볼 것 -> 구글 크롭 Zenmate 사용
 
# iptables -I INPUT -p tcp -m geoip ! --src-cc KR -j DROP
# iptables -I OUTPUT -p tcp -m geoip ! --dst-cc KR -j DROP
 
  1) 예로 국내를 제외한 모든 해외로부터의 시스템 접근 차단하기 
        iptables -A INPUT -m geoip ! --src-cc KR -j DROP 
 
  2) 중국 IP 대역으로부터 들어오는 ssh 접근 차단하기 
        iptables -A INPUT -p tcp --dport 22 -m geoip --src-cc CN -j DROP
​-A RH-Firewall-1-INPUT -p tcp --dport 80 -m geoip ! --src-cc KR,AU,VN,JP,US -j DROP
-A RH-Firewall-1-INPUT -p tcp --dport 22 -m geoip ! --src-cc KR -j DROP
또는
# vi /etc/sysconfig/iptables 에 등록
# /etc/init.d/iptables restart
# iptables -L
확인
 
 
반응형

댓글