Skip to content

Instantly share code, notes, and snippets.

Last active Sep 16, 2020
What would you like to do?
Linux iptables whitelist country for specific ports
# Run this to update the country whitelist chain in iptables
# This is confingured for New Zealand. Other CIDR ranges can be found at:
# To use this chain, configure iptables to redirect some traffic to it. Eg:
# iptables -v -A INPUT -p tcp --match multiport --dports 25,587,465 -j nz_only
# iptables -v -A INPUT -p tcp --dport 22 -j nz_only
CIDRS="$(curl $ALLOW_LIST_URL)" || exit 1
# Flush rules and delete custom chain
iptables -F nz_only
iptables -X nz_only
# Create a new chain for the country whitelist
iptables -N nz_only || exit 1
# Allow local connections
iptables -v -A nz_only -s -j ACCEPT
# Allow NZ IP ranges
for range in $CIDRS; do
iptables -v -A nz_only -s "$range" -j ACCEPT
# Drop other countries
iptables -v -A nz_only -j DROP
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment