Skip to content

Instantly share code, notes, and snippets.

@stecman
Last active September 16, 2020 05:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stecman/cedbbe434811cac2693f2650a86d50e2 to your computer and use it in GitHub Desktop.
Save stecman/cedbbe434811cac2693f2650a86d50e2 to your computer and use it in GitHub Desktop.
Linux iptables whitelist country for specific ports
#!/bin/bash
# Run this to update the country whitelist chain in iptables
#
# This is confingured for New Zealand. Other CIDR ranges can be found at:
#
# https://www.ipdeny.com/ipblocks/
#
# 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
#
ALLOW_LIST_URL=https://www.ipdeny.com/ipblocks/data/countries/nz.zone
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 127.0.0.1 -j ACCEPT
# Allow NZ IP ranges
for range in $CIDRS; do
iptables -v -A nz_only -s "$range" -j ACCEPT
done
# 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