CentOS7 - ipset + firewalld or iptables 国別アクセス制御
作業環境
hostnamectl status Static hostname: localhost.localdomain Icon name: computer-vm Chassis: vm ~ Virtualization: kvm Operating System: CentOS Linux 7 (Core) CPE OS Name: cpe:/o:centos:centos:7 Kernel: Linux 3.10.0-693.2.2.el7.x86_64 Architecture: x86-64
国別IPアドレスリストに取得
IPアドレスリストをダウンロード
shell> curl -O 'http://nami.jp/ipv4bycc/cidr.txt.gz'
ファイルを解凍
shell> gunzip cidr.txt.gz
ブラックリストの作成
ルールを作成
shell> ipset create -exist BLACKLIST hash:net
ブラックリストを初期化
shell> ipset flush BLACKLIST
US(アメリカ)をブラックリストに登録
shell> awk '$1 ~ /^US/ {print $2}' cidr.txt | xargs -i ipset -q add BLACKLIST {}
ブラックリストに登録済みのIPアドレス一覧を表示
shell> ipset list BLACKLIST
firewalld or iptablesにブラックリストのルールを追加
firewalld
shell> firewall-cmd --permanent --direct --add-rule ipv4 filter INPUT 1 -m set --match-set BLACKLIST src -j REJECT shell> firewall-cmd --direct --add-rule ipv4 filter INPUT 1 -m set --match-set BLACKLIST src -j REJECT
iptables
shell> iptables -I INPUT -m state --state NEW -p tcp --dport 22 -m set --match-set BLACKLIST src -j REJECT
ホワイトリストを作成
ルールを作成
shell> ipset create -exist WHITELIST hash:net
ホワイトリストを初期化
shell> ipset flush WHITELIST
JP(日本)をホワイトリストに登録
shell> awk '$1 ~ /^JP/ {print $2}' cidr.txt | xargs -i ipset -q add WHITELIST {}
firewalld or iptablesにホワイトリストのルールを追加
firewalld
shell> firewall-cmd --permanent --direct --add-rule ipv4 filter INPUT 0 -m set --match-set WHITELIST src -j ACCEPT shell> firewall-cmd --direct --add-rule ipv4 filter INPUT 0 -m set --match-set WHITELIST src -j ACCEPT
iptables
shell> iptables -I INPUT -m state --state NEW -p tcp --dport 22 -m set --match-set WHITELIST src -j ACCEPT
ホワイトリストにIPアドレスを追加/削除
ブラックリストに変更を加える場合は、「WHITELIST」を「BLACKLIST」置換するだけ
追加
shell> ipset -q add WHITELIST 1.1.1.1/32
削除
shell> ipset -q del WHITELIST 1.1.1.1/32