Table of Contents
はじめに
Ubuntuのufwで海外からのアクセスをブロックする設定方法です。
ufwの設定
$ sudo vim /etc/ufw/before.rules# COMMIT前に以下を追記# :DROP_EXCEPT_JP - [0:0]# -A DROP_EXCEPT_JP -j ACCEPT# -A ufw-before-input -j DROP_EXCEPT_JP
$ sudo vim /etc/ufw/after.init# 以下を追記# start)# # typically required# /etc/ufw/after.init.drop_except_jp# ;;# stop)# # typically required# iptables -F DROP_EXCEPT_JP# ;;
# 権限付与$ chmod +x /etc/ufw/after.init
スクリプトの作成
格納フォルダを作成して移動
$ mkdir drop_except_jp$ cd drop_except_jp
drop_except_jp.shの作成
#!/bin/shIPTABLES=iptables# 接続を許可するポートをカンマ区切りで指定EXCLUDE_PORTS=80,443wget -q -N http://nami.jp/ipv4bycc/cidr.txt.gzgunzip -q -f -c cidr.txt.gz > cidr.txtif [ -f cidr.txt ]; then echo $IPTABLES -F DROP_EXCEPT_JP echo $IPTABLES -A DROP_EXCEPT_JP -p tcp -m multiport --dport $EXCLUDE_PORTS -m state --state NEW -j RETURN # 接続を許可したい国外IPアドレスがあれば以下に追加 echo $IPTABLES -A DROP_EXCEPT_JP -s 192.168.1.0/24 -j RETURN sed -n 's/^JP\t//p' cidr.txt | while read address; do echo $IPTABLES -A DROP_EXCEPT_JP -s $address -j RETURN done echo $IPTABLES -A DROP_EXCEPT_JP -j DROPfi
作成後、以下のコマンドを実行
$ sh drop_except_jp.sh > /etc/ufw/after.init.drop_except_jp$ chmod +x /etc/ufw/after.init.drop_except_jp
# ufw再起動$ systemctl restart ufw
jp_iplist_update.shの作成
cronで上記コマンドを実行するためのスクリプトです。
#!/bin/bashsh /root/drop_except_jp.sh > /etc/ufw/after.init.drop_except_jpsystemctl restart ufw
jp_iplist_update.sh
をcronに登録
$ sudo crontab -e# (例)毎日1時に実行# 0 1 * * * sh /home/ユーザー名/drop_except_jp/jp_iplist_update.sh >> /home/ユーザー名/drop_except_jp/cron.log 2>&1
参考
[Ubuntu] ファイアウォール ufw で海外からの接続をブロックする Ubuntuで国外からのアクセスをfirewallでブロックする