I recently installed UFW on the VPS. Opening ports to allow certain services to work (such as HTTPS access) or limiting access to a port for a given IP is simple.
In my VPS I will install some services on certain ports, to which I want to limit access to my IP only. However, there is a problem: in my internet access at home I don’t have a fixed IP. How can I configure UFW to configure access to these ports for my IP that will change over time?
There are several solutions, some more complicated than the others, but I found a post that helped me find a simple solution.
The idea is to use a dynamic IP service (which I had previously configured) and at regular intervals to resolve this DNS entry and update the rule on the firewall. This should be done automatically, for example at every 5 minutes.
The steps to do this are as follows:
1 – Configure a dynamic DNS service
If you have not already done so, create an account with a dynamic DNS service. There are several such services, such as No-IP or ChangeIP.
2 – Create a script
Create a script to be executed at regular intervals. This script is what will do the job.
sudo vim /etc/update_firewall.bash
I’m using vim to create the file, but you can use any other editor.
3 – Edit the script
The content of the script should be as follows:
#!/bin/bash
HOSTNAME=my.dynamic-ip.com
PORT=123
if [[ $EUID -ne 0 ]]; then
echo "This script must be run as root"
exit 1
fi
new_ip=$(host $HOSTNAME | head -n1 | cut -f4 -d ' ')
old_ip=$(/usr/sbin/ufw status | grep $HOSTNAME | head -n1 | tr -s ' ' | cut -f3 -d ' ')
if [ "$new_ip" = "$old_ip" ] ; then
echo IP address has not changed
else
if [ -n "$old_ip" ] ; then
/usr/sbin/ufw delete allow from $old_ip to any port $PORT
fi
/usr/sbin/ufw allow from $new_ip to any port $PORT comment $HOSTNAME
echo iptables have been updated
fi
In the script, you must replace HOSTNAME and PORT with your own dynamic DNS and port.
4 – Change script attributes
It may be necessary to change the attributes of the script so that it can be executed. This is done as follows.
sudo chmod 766 /etc/update_firewall.bash
5 – Run the script at regular intervals
The script must now be executed automatically at regular intervals. For that we have to create an entry in the crontab file (cron is a process that executes commands at specific dates and times). The entry must be created in the /etc/crontab file and should look like this:
*/5 * * * * root /etc/update_firewall.bash > /dev/null 2>&1
The contents of the file should look something like this (with the new line at the end):
Now, every 5 minutes the script will resolve the IP for the specified dynamic DNS entry. If there is an IP change, the rule on the firewall will be updated.