2022-05-11 12:43:18 -04:00
#!/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.
#
#
2023-06-06 18:56:44 -04:00
# Updates FirewallD when my home IP address changes.
2022-05-11 12:43:18 -04:00
#
# Define variables
2023-06-06 18:56:44 -04:00
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
}
2022-05-11 12:43:18 -04:00
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
2023-06-06 18:56:44 -04:00
if [ " $ip " = " $1 " ] ; then
2022-05-11 12:43:18 -04:00
found = true
fi
done
if [ " $found " = false ] ; then
2023-06-06 18:56:44 -04:00
echo " Error: IP ' $1 ' not found in firewall entries. "
echo "Info: Updating IP in firewall."
add_ip $HOME_IP
2022-05-11 12:43:18 -04:00
fi
}
2023-06-06 18:56:44 -04:00
# Get home ip
get_home_ip
2022-05-11 12:43:18 -04:00
# Check if we have cache IP
if test -f $CACHE_IP_FILE ; then
CACHE_IP = $( cat $CACHE_IP_FILE )
2023-06-06 18:56:44 -04:00
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
2022-05-11 12:43:18 -04:00
fi
else
2023-06-06 18:56:44 -04:00
update_firewall $HOME_IP
write_ip_cache $HOME_IP
2022-05-11 12:43:18 -04:00
fi
exit 0