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 enableCheck the rules:
sudo ufw statusUsing 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 --reloadUsing 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 DROPSave the rules so they persist after reboot:
# Debian/Ubuntu
sudo netfilter-persistent save
# CentOS/RHEL
sudo service iptables saveUsing 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 dropImportant 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.5or203.0.113.0/24with your actual trusted IP(s).