iptables ASN sets
I previously wrote about using iptables to restrict access based on a country. Please refer to that article for implementing these ipsets.
At times, you may want to restrict (or open) access to a particular network that may have many IP ranges. The most common use cases would be to whitelist access from a corporate network or a specific ISP.
If you don't know the ASN you will be working with, I suggest using bgp.he.net to look it up.
Here is a quick bash script to create an ipset for a particular ASN.
#!/bin/bash
if [ ! -x "/usr/bin/whois" ]; then
echo "whois must be installed at /usr/bin/whois"
exit 2
elif [ $# -ne 1 ]; then
echo "Usage $0 [ASN #]"
exit 1
elif ! [ $1 -eq $1 ] 2> /dev/null; then
echo "ASN must be a number"
exit 1
fi
setname="as$1"
echo "create $setname hash:net family inet hashsize 1024 maxelem 2048" > "$setname.ipset"
/usr/bin/whois -h whois.radb.net -i origin AS$1 | /bin/grep -Eo '([0-9.]+){4}/[0-9]+' | sed "s/^/add $setname /" >> "$setname.ipset"
lines=`wc -l < $setname.ipset`
if (($lines < 2)); then
echo "ASN $1 not found or no routes found"
rm -f "$setname.ipset"
exit
elif (($lines > 2049)); then
echo "More than 2048 records found, adjust maxelem for set"
fi