If you want to test/use it, I’ve made a script to do the task.
When the script is executed the first time, it will create a new rule for the dyn host. If the dyn host ip changes, the script will add a new rule for the new ip and also will remove the rule for the old ip.
To install the script:
sudo su -
mkdir -p /var/lib/add_fw_rule_dyn/bin/
cd /var/lib/add_fw_rule_dyn/bin/
curl -sSL https://7j.gg/addfwdyn -o add_fw_rule_dyn
chmod +x add_fw_rule_dyn
The script needs 2 arguments the dyn host that you want to resolve and the port you want to open.
Example:
/var/lib/add_fw_rule_dyn/bin/add_fw_rule_dyn dyn.example.com 3306
To create a cron job that runs every 5 minutes, will check the ip of dyn.example.com and will open port 3306 (remember to replace the host and port with the actual data).
sudo su -
(crontab -l 2>/dev/null; echo "*/5 * * * * /var/lib/add_fw_rule_dyn/bin/add_fw_rule_dyn dyn.example.com 3306") | crontab -
Just in case, this is the script:
#!/usr/bin/env bash
set -o pipefail
if [[ $EUID -ne 0 ]]; then
echo "Script must be executed as root user" >&2
exit 1
fi
BIN="/usr/local/hestia/bin"
basedir="/var/lib/add_fw_rule_dyn"
host="$1"
port="$2"
iplist="$basedir/${host}_${port}.iplist"
cur_ip=""
saved_ip=""
if [[ -z $host ]]; then
echo "Usage $0 domainname port"
exit 1
fi
if [[ -z $port ]]; then
echo "Usage $0 domainname port"
exit 1
fi
if [[ ! -d $basedir ]]; then
mkdir -p "$basedir"
fi
if ! cur_ip="$(dig +short "$host" | tail -n1)"; then
echo "Error resolving domain $host"
exit 2
fi
if [[ -z $cur_ip ]]; then
echo "Error, host $host is not resolving"
exit 3
fi
if [[ -f $iplist ]]; then
saved_ip="$(head -n1 "$iplist")"
fi
if [[ "$cur_ip" == "$saved_ip" ]]; then
exit
fi
if [[ -n $saved_ip ]]; then
if rulesavedip="$("$BIN"/v-list-firewall plain | sed -E 's/\s{1,}/ /g' | grep -E "\s$port\s$saved_ip\s")"; then
rule_number="$(cut -d ' ' -f1 <<<"$rulesavedip")"
"$BIN"/v-delete-firewall-rule "$rule_number"
fi
fi
if ! "$BIN"/v-list-firewall plain | sed -E 's/\s{1,}/ /g' | grep -E "\s$port\s$cur_ip\s"; then
"$BIN"/v-add-firewall-rule ACCEPT "$cur_ip" "$port" TCP DYN_IP
fi
echo "$cur_ip" >"$iplist"