How to Configure UFW to Allow Ports on IPv4 Only (Excluding IPv6)


11 views

UFW (Uncomplicated Firewall) defaults to creating rules for both IPv4 and IPv6 when you execute commands like ufw allow 22. This behavior occurs because:

  • Modern systems typically operate in dual-stack mode
  • UFW aims to maintain consistent firewall policies across protocols
  • The syntax doesn't explicitly specify protocol version

To restrict port access to IPv4 only, use these methods:

# Method 1: Explicit protocol specification
ufw allow proto tcp to any port 22

# Method 2: IP version restriction
ufw allow from any to any port 22 proto tcp

# Method 3: Rule modification
ufw delete allow 22
ufw allow proto tcp from any to any port 22

After applying changes, verify your rules:

ufw status numbered
ufw show added

For persistent configuration, edit /etc/default/ufw and set:

IPV6=no

When you execute standard UFW commands like:

sudo ufw allow 22

UFW automatically creates rules for both IPv4 and IPv6. This can be verified by checking the rules:

sudo ufw status numbered

To explicitly create rules only for IPv4, you need to specify the protocol family:

sudo ufw allow proto tcp to any port 22

Alternatively, you can be more precise with:

sudo ufw allow from any to any proto tcp port 22

After applying these rules, check your configuration:

sudo iptables -L -n -v
sudo ip6tables -L -n -v  # Should show no corresponding IPv6 rules

If you consistently want IPv4-only rules, modify the UFW configuration:

sudo nano /etc/default/ufw

Set these values:

IPV6=no

Then reload:

sudo ufw disable
sudo ufw enable

For common services:

# HTTP (IPv4 only)
sudo ufw allow proto tcp to any port 80

# Custom application port
sudo ufw allow from 192.168.1.0/24 to any port 9000 proto tcp

# Range of ports
sudo ufw allow proto tcp from any to any port 8000:8010

If you accidentally create dual-stack rules, remove them with:

sudo ufw delete allow 22/tcp
sudo ufw delete allow 22/udp

Then recreate with IPv4-specific syntax.