Skip to content

Instantly share code, notes, and snippets.

@amanjuman
Forked from stevejenkins/gwhitelist.sh
Created September 14, 2022 20:51
Show Gist options
  • Save amanjuman/273a045aa038c351e2e83ff20fe49896 to your computer and use it in GitHub Desktop.
Save amanjuman/273a045aa038c351e2e83ff20fe49896 to your computer and use it in GitHub Desktop.
Script for creating a Postfix whitelist for Gmail servers
#! /bin/sh
#
# Copyright (c) 2013 Mike Miller <[email protected]>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# a quick script to output the current list of google outbound smtp servers
# in a format suitable for Postfix's postscreen whitelist CIDR file.
#
# the list of CIDR-formatted addresses, each followed by the word "permit"
# is printed to stdout. It is up to you to mesh this output into your
# postscreen processing on a recurring basis.
#
# this page was used as a guide:
# http://support.google.com/a/bin/answer.py?hl=en&hlrm=de&answer=60764
#
# version history
# 20130519 1.0 mm - initial release
# 20130520 1.1 mm - added set -e error check
# 20151122 1.2 sj - added postfix reload at end of script and clean up spaces
# 20151125 1.3 sj - made postfix reload optional
# make sure the mktemp command syntax is appropriate for your OS.
# this works on FreeBSD 9.1 and Debian GNU/Linux 6.0.6
tmpBase=`basename $0`
tmpNetBlocks=`mktemp -q /tmp/${tmpBase}.XXXXXX`
if [ $? -ne 0 ]; then
echo "$0: Can't create temp file, exiting..."
exit 1
fi
# abort on any error
set -e
# obtain and format the netblocks for subsequent look-ups
spfString=`dig @8.8.8.8 _spf.google.com txt | grep ^_spf | cut -f5`
printf "%s\n" ${spfString} | grep "^include" | cut -c9- | \
sed s/^/' @8.8.8.8 '/ | sed s/$/' txt'/ > ${tmpNetBlocks}
# get the IP addresses from the netblocks
nbString=`dig -f ${tmpNetBlocks} | grep ^_netblock | cut -f5`
printf "%s\n" ${nbString} | grep "^ip" | cut -c5- | \
sed s/$/' permit'/
# clean up
test -e ${tmpNetBlocks} && rm ${tmpNetBlocks}
# Uncomment if you want this script to reload Postfix config
#/usr/sbin/postfix reload
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment