3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【2024年10月版】Ubuntu 20.04 〜 24.04 で日本国内IPからのアクセスのみに絞る、IPフィルタリング【ufw, iptable】

Last updated at Posted at 2022-07-05

はじめに

2024/10/07 Ubuntu20.04, Ubuntu22.04, Ubuntu24.04 でも動作することを確認して記事を更新しました。

環境

  • Ubuntu 20.04
  • Ubuntu 22.04
  • Ubuntu 24.04

設定

概要

  • 以下のように、新しいチェーンを作成して、日本のIPアドレスは、RETURN して、そのほかは DROP するように設定する。そのためにスクリプトや設定編集を実行する。
iptables -F DROP_EXCEPT_JP
iptables -A DROP_EXCEPT_JP -s AAA.AAA.AAA.AAA/16 -j RETURN
iptables -A DROP_EXCEPT_JP -s BBB.BBB.BBB.BBB/24 -j RETURN
      :
      :
iptables -A DROP_EXCEPT_JP -j DROP

作業

  • /etc/ufw/before.rules を編集して、以下の3行を COMMIT とコメントの前に追加する
:DROP_EXCEPT_JP - [0:0]
-A DROP_EXCEPT_JP -j ACCEPT
-A ufw-before-input -j DROP_EXCEPT_JP
# don't delete the 'COMMIT' line or these rules won't be processed
COMMIT
  • /etc/ufw/after.init の start) と stop) を編集する
start)
    # typically required
    /etc/ufw/after.init.drop_except_jp
    ;;
stop)
    # typically required
    iptables -F DROP_EXCEPT_JP
    ;;
  • /etc/ufw/after.init に実行権限を付加する
sudo chmod +x /etc/ufw/after.init
  • 以下のスクリプトを作成する。場所はどこでも良い。 {self subnet} に自分のサブネットを入れる
  • 自分のIPのサブネットは {self subnet} に入れる、不必要ならコメントアウト
#!/bin/sh
IPTABLES=iptables
#EXCLUDE_PORTS=80,443,25
wget -q -N http://nami.jp/ipv4bycc/cidr.txt.gz
gunzip -q -f -c cidr.txt.gz > cidr.txt
if [ -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
    # 次の行は必要に応じて
    echo $IPTABLES -A DROP_EXCEPT_JP -s {self subnet} -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 DROP
fi    
  • スクリプトを実行して日本のIPアドレスを記載したファイルを作成する
sudo sh drop_except_jp.sh > after.init.drop_except_jp
sudo cp after.init.drop_except_jp /etc/ufw/after.init.drop_except_jp
sudo chmod +x /etc/ufw/after.init.drop_except_jp
  • ufw を再起動する
sudo ufw reload
sudo systemctl restart ufw
sudo systemctl status ufw

おわりに

  • かんたんでしたね、簡単になるように公開してくださっている記事に感謝

参考記事

3
0
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
3
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?