本記事では、firewalld + ipset で設定した
中国・韓国・ロシアのIPブロックを自動更新する方法を解説します。
■ 対象ipset
・cn(中国)
・kr(韓国)
・ru(ロシア)
■ なぜ必要か
IPアドレスは定期的に変わるため、手動設定のままだと
・新しいIPがブロックされない
・古いIPが残る
👉 自動更新が必要です
■ 前提
以下の記事の続きです
→ ipsetで特定の国だけ遮断する方法
■ ① スクリプト作成
sudo vi /usr/local/bin/update-ipset-country-block.sh
■ 内容(そのままコピペ)
#!/bin/bash
set -eu
APNIC_URL="https://ftp.apnic.net/apnic/stats/apnic/delegated-apnic-latest"
WORKDIR="/tmp/ipset-country-update"
APNIC_FILE="${WORKDIR}/delegated-apnic-latest"
LOG_FILE="/var/log/ipset-country-update.log"
mkdir -p "${WORKDIR}"
log() {
echo "[$(date '+%F %T')] $*" >> "${LOG_FILE}"
}
cleanup() {
rm -f "${WORKDIR}/"*.txt "${WORKDIR}/"*.add "${WORKDIR}/"*.del
}
trap cleanup EXIT
update_country_ipset() {
local COUNTRY="$1"
local IPSET_NAME="$2"
local NEW_FILE="${WORKDIR}/${IPSET_NAME}-new.txt"
local OLD_FILE="${WORKDIR}/${IPSET_NAME}-old.txt"
local ADD_FILE="${WORKDIR}/${IPSET_NAME}.add"
local DEL_FILE="${WORKDIR}/${IPSET_NAME}.del"
grep "|${COUNTRY}|" "${APNIC_FILE}" | grep '|ipv4|' | \
awk -F '|' '
function log2(x){ return log(x)/log(2) }
{
printf "%s/%d\n", $4, 32-log2($5)
}
' | sort -u > "${NEW_FILE}"
firewall-cmd --permanent --ipset="${IPSET_NAME}" --get-entries | sort -u > "${OLD_FILE}"
comm -13 "${OLD_FILE}" "${NEW_FILE}" > "${ADD_FILE}" || true
comm -23 "${OLD_FILE}" "${NEW_FILE}" > "${DEL_FILE}" || true
ADD_COUNT=$(wc -l < "${ADD_FILE}")
DEL_COUNT=$(wc -l < "${DEL_FILE}")
log "${IPSET_NAME}: add=${ADD_COUNT}, delete=${DEL_COUNT}"
if [ "${ADD_COUNT}" -gt 0 ]; then
while read -r entry; do
[ -n "${entry}" ] || continue
firewall-cmd --permanent --ipset="${IPSET_NAME}" --add-entry="${entry}"
done < "${ADD_FILE}"
fi
if [ "${DEL_COUNT}" -gt 0 ]; then
while read -r entry; do
[ -n "${entry}" ] || continue
firewall-cmd --permanent --ipset="${IPSET_NAME}" --remove-entry="${entry}"
done < "${DEL_FILE}"
fi
}
log "=== update start ==="
if ! curl -fsSL "${APNIC_URL}" -o "${APNIC_FILE}"; then
log "ERROR: failed to download APNIC data"
exit 1
fi
update_country_ipset "CN" "cn"
update_country_ipset "KR" "kr"
update_country_ipset "RU" "ru"
firewall-cmd --reload
log "firewalld reloaded"
log "=== update end ==="
exit 0
■ ② 実行権限
sudo chmod +x /usr/local/bin/update-ipset-country-block.sh
■ ③ 手動テスト
sudo /usr/local/bin/update-ipset-country-block.sh
■ ログ確認
sudo tail -n 50 /var/log/ipset-country-update.log
■ ④ cron登録
sudo crontab -e
■ 毎日3時
0 3 * * * /usr/local/bin/update-ipset-country-block.sh
■ ⑤ 確認
sudo firewall-cmd --get-ipsets
sudo firewall-cmd --permanent --ipset=cn --get-entries | head
sudo firewall-cmd --permanent --ipset=kr --get-entries | head
sudo firewall-cmd --permanent --ipset=ru --get-entries | head
■ よくあるトラブル
● ipsetが空になる
→ APNIC取得失敗
● cronで動かない
→ 実行権限確認
● 反映されない
→ firewall reload確認
■ 関連記事
→ ipsetで特定の国だけ遮断する方法
→ WordPressを日本IPのみ公開する方法
→ fail2ban設定

コメント