scripts/update_firewall.sh

87 lines
1.9 KiB
Bash
Executable File

#!/usr/bin/env bash
# Copyright (C) 2021 by LHProjects <copyright@lhpmail.us>
#
# Permission is granted to use, copy, modify, and/or distribute this work for any purpose with or without fee. This work is offered as-is, with absolutely no warranty whatsoever. The author is not responsible for any damages that result from using this work.
#
#
# Updates FirewallD when my home IP address changes.
#
# Define variables
CACHE_IP_FILE=/var/cache/update_firewall.cache
get_home_ip () {
tmpfile=$(mktemp)
for i in {1..5};
do
host fwgw.lhprojects.net 1.1.1.1 > $tmpfile && s=0 && break || s=1 && sleep 3;
done
if [ $s -eq 0 ]; then
HOME_IP=$(cat $tmpfile | cut -d ' ' -f 4 | xargs)
else
echo "Error: Can't resolve fwgw.lhprojects.net"
rm $tmpfile
exit 1
fi
rm $tmpfile
}
remove_ip () {
# remove old entry
firewall-cmd --permanent --ipset=node_ips --remove-entry=$1 &> /dev/null
# reload firewall
firewall-cmd --reload &> /dev/null
}
add_ip () {
# add new entry
firewall-cmd --permanent --ipset=node_ips --add-entry=$1 &> /dev/null
# reload firewall
firewall-cmd --reload &> /dev/null
}
write_ip_cache () {
echo "$1" > $CACHE_IP_FILE
}
update_firewall () {
# check if cache IP is in the ipset entries
ipset_entries=$(firewall-cmd --ipset=node_ips --get-entries 2> /dev/null)
found=false
for ip in $ipset_entries; do
if [ "$ip" = "$1" ]; then
found=true
fi
done
if [ "$found" = false ]; then
echo "Error: IP '$1' not found in firewall entries."
echo "Info: Updating IP in firewall."
add_ip $HOME_IP
fi
}
# Get home ip
get_home_ip
# Check if we have cache IP
if test -f $CACHE_IP_FILE; then
CACHE_IP=$(cat $CACHE_IP_FILE)
if [ -z "$CACHE_IP" ]; then
update_firewall $HOME_IP
write_ip_cache $HOME_IP
elif [ "$HOME_IP" != "$CACHE_IP" ]; then
remove_ip $CACHE_IP
update_firewall $HOME_IP
write_ip_cache $HOME_IP
fi
else
update_firewall $HOME_IP
write_ip_cache $HOME_IP
fi
exit 0