Skip to content

Instantly share code, notes, and snippets.

@churnd
Last active May 11, 2020 16:48
Show Gist options
  • Save churnd/0ffd27a62f09a091b79abb4e450b96b5 to your computer and use it in GitHub Desktop.
Save churnd/0ffd27a62f09a091b79abb4e450b96b5 to your computer and use it in GitHub Desktop.
Create iptables block from Github IP ranges to integrate into existing firewall rules.
#!/bin/bash
# Configuration
IPTABLES_CONF=/etc/iptables/rules.v4
GITHUB_IPS=/var/tmp/github-ips
GITHUB_BEGIN="^# GITHUB BEGINS$"
GITHUB_END="^# GITHUB ENDS$"
if ! [ -x "$(command -v jq)" ]; then
echo "Cannot find 'jq' in your PATH, exiting..."
exit 1
fi
# Download .git, .api, & .hooks fields & filter out the IP ranges
curl -s https://api.github.com/meta | jq -r '.git, .api, .hooks | @sh' | tr -d "\'" > $GITHUB_IPS.new
# Check if old files exists & compare with the new one. Stop here if they're identical.
if [ -f $GITHUB_IPS ]; then
if diff -q $GITHUB_IPS $GITHUB_IPS.new >/dev/null 2>&1; then
echo "Old & new IPs are the same so no need to update"
exit 0
fi
else
mv -f $GITHUB_IPS.new $GITHUB_IPS
fi
# Generate temporary rules with timestamp
echo "# Last gen: `date`" > $GITHUB_IPS.rules
for IP_RANGE in $(cat $GITHUB_IPS); do
echo "-A INPUT -d $IP_RANGE -p tcp -m multiport --dport 80,443,8080 -j ACCEPT" >> $GITHUB_IPS.rules
done
# Insert new rules between begin/end markers
sed -e "/$GITHUB_BEGIN/,/$GITHUB_END/ {/$GITHUB_BEGIN/ {p; r $GITHUB_IPS.rules
}; /$GITHUB_END/p; d }" "$IPTABLES_CONF" > $IPTABLES_CONF.temp
# Replace iptables config with new one
cat $IPTABLES_CONF.temp > "$IPTABLES_CONF"
# Restart iptables service
systemctl restart netfilter-persistent.service
@churnd
Copy link
Author

churnd commented May 11, 2020

Useful if you need to firewall off traffic to allow Github only. Written for Debian & used on a Jenkins host.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment