How to limit SSH access by IP addresses using firewall

To make SSH on your server accessible only from specific IP networks, set up host-based firewall rules using iptables, nftables, ufw, or firewalld.

Using UFW (Ubuntu/Debian)

Allow SSH only from a specific IP or subnet:

sudo ufw allow from 203.0.113.0/24 to any port 22
sudo ufw deny 22
sudo ufw enable

Check the rules:

sudo ufw status

Using firewalld (CentOS/RHEL 7+)

Add a rich rule to allow SSH from a specific address:

sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="203.0.113.5/32" port protocol="tcp" port="22" accept'
sudo firewall-cmd --permanent --remove-service=ssh
sudo firewall-cmd --reload

Using iptables

Allow SSH from a trusted IP and drop all other SSH connections:

# Allow from trusted IP
sudo iptables -A INPUT -p tcp --dport 22 -s 203.0.113.5 -j ACCEPT

# Drop all other SSH
sudo iptables -A INPUT -p tcp --dport 22 -j DROP

Save the rules so they persist after reboot:

# Debian/Ubuntu
sudo netfilter-persistent save

# CentOS/RHEL
sudo service iptables save

Using nftables

sudo nft add rule inet filter input tcp dport 22 ip saddr 203.0.113.5 accept
sudo nft add rule inet filter input tcp dport 22 drop

Important notes

  • Always test in a new terminal session before closing your current one.
  • If you lose access, use the VNC Console in the Customer Portal to recover.
  • Replace 203.0.113.5 or 203.0.113.0/24 with your actual trusted IP(s).

On this page