Profile picture

[Linux] Ubuntu 해외 IP 차단하기 (xtables)

JaehyoJJAng2023년 07월 05일

◾️ SSH 접속 시도 조회

$ sudo lastb -50

admin ssh:notty    x.x.x.x  Sun Feb 18 19:19 - 19:19  (00:00)
Admin ssh:notty    x.x.x.x  Sun Feb 18 19:30 - 19:30  (00:00)
User ssh:notty     x.x.x.x  Sun Feb 18 19:45 - 19:45  (00:00)
User01 ssh:notty   x.x.x.x  Sun Feb 18 19:47 - 19:47  (00:00)
jojo ssh:notty     x.x.x.x  Sun Feb 18 20:10 - 20:10  (00:00)
ami ssh:notty      x.x.x.x  Sun Feb 18 20:15 - 20:15  (00:00)
...

AWS 인스턴스를 생성하고 나고 몇 분 지나면 위처럼 수 많은 SSH 접속 시도가 들어온다.


◾️ xtables 설치

iptables에 geoip 모듈이 들어있는 xtables-addons-common 패키지 설치

$ sudo apt-get install -y xtables-addon-common
$ dkms status
xtables-addons/3.19, 5.15.0-94-generic, x86_64: installed

◾️ geoip 모듈 설정

iptables 설정을 백업하고 편집할 파일(iptables.geoip)을 생성

$ sudo iptables-save > /tmp/iptables.bak
$ cp -R /tmp/iptables.bak /tmp/iptables.geoip

iptables.geoip 파일을 아래와 같이 편집. 첫째줄이 한국(국가코드 KR) 이외에는 전부 리젝트. 둘째줄은 SSH가 사용하는 22번 포트를 허용
{% include codeHeader.html name="/tmp/iptables.geoip" %}

-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -m geoip ! --src-cc KR -j REJECT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT

편집한 iptables.geoip 적용

$ sudo iptables-apply /tmp/iptables.geoip  
Applying new iptables rules from './iptables.geoip'... iptables-restore: line 64 failed
failed.
Error: unknown error applying new iptables rules: ./iptables.geoip
Reverting to old iptables rules... done.

그러나 국가별 IP 리스트가 존재하지 않아 적용되지 않음!


◾️ 국가별 IP 리스트 작성

elmitash/geoup_krnic2dbip elmitash님의 깃허브 레포지토리에서 go로 작성한 IP 파일 리스트를 다운로드하고 변환하는 툴을 다운로드 받아 실행 권한을 부여해주자.

$ wget https://github.com/elmitash/geoip_krnic2dbip/raw/master/linux_amd64/krnic2dbip_linux_amd64
$ wget https://github.com/elmitash/geoip_krnic2dbip/raw/master/geoip.sh
$ chmod +x krnic2dbip_linux_* geoip.sh

#xt_geoip_build가 실행되면 없다고 하기 때문에 미리 인스톨(can't locate text/csv_xs.pm라는 에러가 나온다.)
$ sudo apt-get install -y libtext-csv-perl

위 파일들을 다운로드받고 실행 권한까지 부여해줬다면 geoip.sh 스크립트를 실행해주자.

$ sudo bash geoip.sh

geoip.sh에 내용은 KRNIC에서 국가별IP 할당정보를 받아오고, krnic2dbip_linux_* 실행파일이 db-ip.com에서 사용하는 형식으로 변환. db-ip.com 형식의 CSV 파일을 xt_geoip_build 에서 /usr/share/xt_geoip 디렉토리에 국가코드별로 정리해서 넣어준다.


다시 iptables.geoip 파일을 적용

$ sudo iptables-apply /tmp/iptables.geoip

Loading script...