중국 IP address 차단

리눅스 등에서 특정 대역을 차단하기는 어렵진 않다. 다만, 버전마다 조금씩 다르다. 여기서는 CentOS 6.4, 6.5 기준으로 여러 가지 방법 중 단순 무식한 방법을 하나 적어보자.

먼저 xtables-addons 가 필요하다. http://sourceforge.net/projects/xtables-addons/files/Xtables-addons/ 에서 아무거나 다운로드 받자. 우리에게 중요한 건 저 소스코드 자체보다는 거기에 딸려 있는 geoip 가 필요하다. 일단 최신버전인 2.5 를 다운로드 받자.

xtables-addons-2.5.tar.xz 파일을 적당한 곳에 풀자. 하지만, 계속해서 사용해야 하니, /usr/src 에다가 복사하고

xz -d xtables-addons-2.5.tar.xz
tar xvf xtables-addons-2.5.tar

cd xtables-addons-2.5
cd geoip
ls -al

합계 52
drwxr-xr-x 2 root root  4096 2014-04-19 02:16 .
drwxr-xr-x 8 root root  4096 2014-04-19 02:16 ..
-rw-r--r-- 1 root root    81 2014-04-19 02:14 .gitignore
-rw-r--r-- 1 root root   112 2014-04-19 02:14 Makefile.am
-rw-r--r-- 1 root root 16821 2014-04-19 02:16 Makefile.in
-rwxr-xr-x 1 root root  2930 2014-04-19 02:14 xt_geoip_build
-rw-r--r-- 1 root root  1303 2014-04-19 02:14 xt_geoip_build.1
-rwxr-xr-x 1 root root   287 2014-04-19 02:14 xt_geoip_dl
-rw-r--r-- 1 root root   582 2014-04-19 02:14 xt_geoip_dl.1

[root@akpil geoip]#./xt_geoip_dl

[root@akpil geoip]# ls -al
합계 10888
drwxr-xr-x 2 root root    4096 2014-04-21 18:51 .
drwxr-xr-x 8 root root    4096 2014-04-19 02:16 ..
-rw-r--r-- 1 root root      81 2014-04-19 02:14 .gitignore
-rw-r--r-- 1 root root 1393192 2014-04-03 03:17 GeoIPCountryCSV.zip
-rw-r--r-- 1 root root 6807147 2014-04-03 03:16 GeoIPCountryWhois.csv
-rw-r--r-- 1 root root 2888764 2014-04-03 03:17 GeoIPv6.csv
-rw-r--r-- 1 root root     112 2014-04-19 02:14 Makefile.am
-rw-r--r-- 1 root root   16821 2014-04-19 02:16 Makefile.in
-rwxr-xr-x 1 root root    2930 2014-04-19 02:14 xt_geoip_build
-rw-r--r-- 1 root root    1303 2014-04-19 02:14 xt_geoip_build.1
-rwxr-xr-x 1 root root     287 2014-04-19 02:14 xt_geoip_dl
-rw-r--r-- 1 root root     582 2014-04-19 02:14 xt_geoip_dl.1
[root@akpil geoip]#



다시 정리하면 xtables-addons-2.5 디렉터리로 들어가서 다시 geoip 디렉터리로 들어간 다음에 ./xt_geoip_dl 명령을 내리면 국가별 IP 데이터를 가져와서 압축을 풀고, 그 파일들은 다음과 같다. 파일 크기는 업데이트 되기 떄문에 계속 변한다.

-rw-r--r-- 1 root root 1393192 2014-04-03 03:17 GeoIPCountryCSV.zip
-rw-r--r-- 1 root root 6807147 2014-04-03 03:16 GeoIPCountryWhois.csv
-rw-r--r-- 1 root root 2888764 2014-04-03 03:17 GeoIPv6.csv

간단한 스크립트를 하나 짜자, /opt/bin/china-ip.sh 파일 정도면 된다. 물론 퍼미션은 chmod 700 이나 755 로 주면 된다.

/opt/bin/china-ip.sh
#!/bin/sh
DATA=/usr/src/xtables-addons-2.5/geoip/GeoIPCountryWhois.csv
IPT=/sbin/iptables

cd /usr/src/xtables-addons-2.5/geoip/
/usr/src/xtables-addons-2.5/geoip/xt_geoip_dl

for IPRANGE in `egrep "China" $DATA | cut -d, -f1,2 | sed -e 's/"//g' | sed -e 's/,/-/g'`
do
        $IPT -A INPUT -p all -m iprange --src-range $IPRANGE -j DROP
done

이렇게 한 다음에 /etc/cron.d/china-ip 파일을 하나 만들자.

/etc/cron.d/china-ip
0 1 * * * root /opt/bin/china-ip.sh

이렇게 하면 매일 새벽 1시에 geoip 자료를 다운로드 받아서 자동으로 iptables 로 업데이트를 해준다. 저렇게 설정한 뒤에 iptables-save 명령을 실행시켜보면 뭔가 쭉 올라간다. 중국 ip address 가 차단된 거다.

스크립트에 China 부분을 다른 걸로 바꾸면 해당 국가도 마찬가지로 차단할 수 있다.