LoginSignup
1
0

nftablesを用いたIPアドレス制限(国別)

Last updated at Posted at 2024-04-12

nftablesを用いたIPアドレス制限

国ごとに割り振られているIPアドレス一覧を取得する

IPアドレスの一覧を APINIC1 で公開されているものを取得する。

curl -LO http://ftp.apnic.net/stats/apnic/delegated-apnic-latest

指定した国家のIPアドレスを取り出す

ip_by_country.awk
BEGIN{
    FS="|"
    ipv4="country_whitelist_ipv4"
    ipv6="country_whitelist_ipv6"
    stderr="/dev/stderr"
    print "define country_whitelist_ipv4 = {" > ipv4
    print "define country_whitelist_ipv6 = {" > ipv6
}
{
    if ($2 ~ country) {
        if ($3=="ipv4") {
            ip=$4
            if(and($5,$5-1) == 0) {
                mask=32-log($5)/log(2)
                if (!a[ip,mask]++) print ip"/"mask"," >> ipv4
            } else {
                print "Something is wrong with netmask(CIDR range).\n" ip " / " $5 > stderr
            }
        } else if ($3=="ipv6") {
            ip=$4
            prefix=$5
            if (!b[ip,prefix]++) print ip"/"prefix"," >> ipv6
        }
    }
}
END{
    print "}">> ipv4
    print "}">> ipv6
}

上記スクリプトは、カレントディレクトリにcountry_whitelist_ipv4,country_whitelist_ipv6を作成します。

日本のみ

awk -v country="JP" -f ip_by_country.awk delegated-apnic-latest

複数の国を指定する場合

awk -v country="JP|US|RU" -f ip_by_country.awk delegated-apnic-latest

nftables.confの設定例(抜粋)

/etc/nftablesにコピーしておきます

mkdir -p /etc/nftables
sudo cp country_whitelist_ipv4 /etc/nftables/
sudo cp country_whitelist_ipv6 /etc/nftables/

nftables.confでincludeする。

sshのポートが22の場合の例。

#!/usr/bin/nft -f
# vim:set ts=2 sw=2 et:

include "/etc/nftables/country_whitelist_ipv4"
include "/etc/nftables/country_whitelist_ipv6"

table inet filter {
    set country_accept_ipv4 {
        type ipv4_addr; flags interval;
        elements = $country_whitelist_ipv4
    }
    set country_accept_ipv6 {
        type ipv6_addr; flags interval;
        elements = $country_whitelist_ipv6
    }
        ct state new tcp dport 22 ip saddr @country_accept_ipv4 counter accept
        ct state new tcp dport 22 ip6 saddr @country_accept_ipv6 counter accept

参考サイト

  1. http://ftp.apnic.net/stats/apnic/delegated-apnic-latest

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