How to generate iptables rules for smtp.gmail.com

I wanted to add firewall rules to my router that would let my server email me via a gmail account using msmtp. But smtp.gmail.com servers can live on many different addresses, and they do change from time to time, as this Google support article explains. To keep the job of updating all possible relevant firewall rules simple, I wrote a little Bash script that will generate them for me.

It shouldn’t be difficult to adjust for your specific situation – just change the text to prepend and append in the final awk statement:

for i in `nslookup -q=TXT _spf.google.com 8.8.8.8 | tr " " "\n" | grep "include:" | cut -c 9-`; do nslookup -q=TXT $i | tr " " "\n" | grep "ip4:" | cut -c 5-; done | sort -g | awk '{print "iptables -A FORWARD -i eth3.3 -o eth3 -p tcp -d " $0 " --dport 587 -j ACCEPT"}'

Right now it generates following set of rules:

iptables -A FORWARD -i eth3.3 -o eth3 -p tcp -d 64.18.0.0/20 --dport 587 -j ACCEPT
iptables -A FORWARD -i eth3.3 -o eth3 -p tcp -d 64.233.160.0/19 --dport 587 -j ACCEPT
iptables -A FORWARD -i eth3.3 -o eth3 -p tcp -d 66.102.0.0/20 --dport 587 -j ACCEPT
iptables -A FORWARD -i eth3.3 -o eth3 -p tcp -d 66.249.80.0/20 --dport 587 -j ACCEPT
iptables -A FORWARD -i eth3.3 -o eth3 -p tcp -d 72.14.192.0/18 --dport 587 -j ACCEPT
iptables -A FORWARD -i eth3.3 -o eth3 -p tcp -d 74.125.0.0/16 --dport 587 -j ACCEPT
iptables -A FORWARD -i eth3.3 -o eth3 -p tcp -d 108.177.8.0/21 --dport 587 -j ACCEPT
iptables -A FORWARD -i eth3.3 -o eth3 -p tcp -d 108.177.96.0/19 --dport 587 -j ACCEPT
iptables -A FORWARD -i eth3.3 -o eth3 -p tcp -d 172.217.0.0/19 --dport 587 -j ACCEPT
iptables -A FORWARD -i eth3.3 -o eth3 -p tcp -d 173.194.0.0/16 --dport 587 -j ACCEPT
iptables -A FORWARD -i eth3.3 -o eth3 -p tcp -d 207.126.144.0/20 --dport 587 -j ACCEPT
iptables -A FORWARD -i eth3.3 -o eth3 -p tcp -d 209.85.128.0/17 --dport 587 -j ACCEPT
iptables -A FORWARD -i eth3.3 -o eth3 -p tcp -d 216.239.32.0/19 --dport 587 -j ACCEPT
iptables -A FORWARD -i eth3.3 -o eth3 -p tcp -d 216.58.192.0/19 --dport 587 -j ACCEPT
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s