Skip to content

UFW Update Home IP Rule

I like to play with a VPS that I have hosted with someone, but I don't want just anyone to be able to connect to them. The issue I run into, is I might wipe these so I don't want to have to set up something like wireguard to tailscale every time I do so.
This simply bash script will grab the IP Address of a DDNS domain that I have set up to update from my house, and update the UFW rule to allow traffic from it.
I have this set up to run on a cron so if my IP changes I can still get to the server.
Outside of this, I have the default deny incoming set up.

#!/bin/bash

DOMAIN="ddns_domain.com"
RULE_DESCRIPTION="Allow traffic from $DOMAIN"

# Get the current IP address of the domain
NEW_IP=$(dig +short "$DOMAIN")

if [ -z "$NEW_IP" ]; then
  echo "Error: Could not resolve IP address for $DOMAIN"
  exit 1
fi

# Check if a rule with the description already exists
RULE_EXISTS=$(ufw status numbered | grep "$RULE_DESCRIPTION")

if [ -n "$RULE_EXISTS" ]; then
  # Extract the rule number and old IP address
  RULE_NUMBER=$(echo "$RULE_EXISTS" | awk '{print $1}')
  OLD_IP=$(echo "$RULE_EXISTS" | awk '{print $3}')

  if [ "$NEW_IP" != "$OLD_IP" ]; then
    # Delete the old rule and add the new rule
    ufw delete "$RULE_NUMBER"
    ufw allow from "$NEW_IP" comment "$RULE_DESCRIPTION"
    echo "Firewall rule updated for $DOMAIN: Old IP: $OLD_IP, New IP: $NEW_IP"
  else
    echo "IP address for $DOMAIN has not changed: $NEW_IP"
  fi
else
  # Add the rule if it doesn't exist
  ufw allow from "$NEW_IP" comment "$RULE_DESCRIPTION"
  echo "Firewall rule added for $DOMAIN: IP: $NEW_IP"
fi