UFW Makes it Easy to Manage a Linux Firewall

sudo apt install -y ufw
sudo ufw allow from 192.168.1.0/24
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh

sudo ufw allow http

sudo ufw allow [port]/[protocal]
sudo ufw allow 5900/tcp

sudo ufw enable ; sudo systemctl enable ufw ; sudo systemctl start ufw ; sudo ufw status


sudo ufw status numbered
sudo ufw delete [number]

sudo ufw allow from 1.1.1.1 to any port 3389

Allowing Traffic From a Domain With Dynamic IP Address
https://www.baeldung.com/linux/allowing-traffic-from-dynamic-ip-address

Table of Contents

#

sudo nano /home/rd/apps/ufw_ddns_update.sh

#
!/bin/bash
# Bash script to query DDNS service for hostname current IP address and create or update UFW firewall rules
# to allow access to all ports and protocols from the dynamic IP address.
# This script is intended to be run from a cron job with root privileges.
# The script will only update the firewall rules if the IP address has changed.

# Set the DDNS service URL
# Configure free DDNS at: https://www.dynu.com/en-US/
DDNS_HOSTNAME="your-custom-hostname.freeddns.org"
# Get the DDNS hostname IP address
DDNS_IP=$(dig +short ${DDNS_HOSTNAME})
# Get the current IP allowed in UFW for this hostname
OLD_IP=$(/usr/sbin/ufw status | grep $DDNS_HOSTNAME | head -n1 | tr -s ' ' | cut -f3 -d ' ')

# Check if the DDNS hostname IP address is valid
if [[ "${DDNS_IP}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
  # Check if the old IP is valid
  if [[ "${OLD_IP}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
    # Check if the DDNS service IP address is different from the old IP address
    if [[ "${DDNS_IP}" != "${OLD_IP}" ]]; then
        # Delete the old rule
        /usr/sbin/ufw delete allow from $OLD_IP to any
        # Create a new rule for the new IP address
        /usr/sbin/ufw allow from "${DDNS_IP}" to any comment $DDNS_HOSTNAME
    else
      echo "$0: The IP address is the same, no need to update the firewall rules."
    fi
  else
    # Create a new rule for the new IP address
    /usr/sbin/ufw allow from "${DDNS_IP}" to any comment $DDNS_HOSTNAME
  fi
else
  echo "$0: DDNS IP address is not valid for ${DDNS_HOSTNAME}: ${DDNS_IP}"
fi
#

sudo apt install dnsutils
sudo chmod +x /home/rd/apps/ufw_ddns_update.sh
sudo crontab -e
*/15 * * * * /home/rd/apps/ufw_ddns_update.sh

#

Leave a Reply

Your email address will not be published. Required fields are marked *