Back

How to limit SSH access by IP addresses using firewall

You may want to make SSH on your server or a set of servers to be accessible only from certain IP networks. To do that, you can set up host-based firewall rules using iptables, nftables, ufw, and firewalld. You can also use the network-based firewall service provided by Servers.com.

Using UFW on Debian/Ubuntu

UFW is a frontend for iptables and it is the default firewall configuration tool for Ubuntu. UFW is much simpler to use than iptables, and it's particularly well-suited for host-based firewalls.

UFW is not enabled by default. Here is how you can install UFW and configure it to limit SSH access to the 10.20.10.0/24 subnet.

# update the package list and install ufw
apt update -y && apt install -y ufw
 
# allow access to OpenSSH only from 10.20.10.0/24
# limit directive is used instead of allow to set rate limiting
ufw limit from 10.20.10.0/24 to any app OpenSSH
 
# remove less-restrictive SSH-related rules (if any)
ufw delete allow 22/tcp
ufw delete allow OpenSSH
ufw delete limit OpenSSH
 
# enable ufw
ufw --force enable
 
# see the status
ufw status

Using firewalld on RHEL/AlmaLinux

Firewalld is a frontend for nftables and it is the default firewall configuration tool for AlmaLinux and RHEL-based distros. Firewalld is much simpler to use than nftables, and it's particularly well-suited for host-based firewalls.

Firewalld is not enabled by default. Here is how you can install firewalld and configure it to limit SSH access to the 10.20.10.0/24 subnet.

# update the package list and install firewalld
dnf upgrade --refresh -y && dnf -y install firewalld
 
# enable and start firewalld
systemctl enable firewalld && systemctl start firewalld && systemctl status firewalld
 
# add a new zone with a set of allowed source networks
firewall-cmd --permanent --new-zone=ssh-limited
firewall-cmd --permanent --zone=ssh-limited --add-source=10.20.10.0/24
 
# add the SSH service to the created zone
firewall-cmd --permanent --zone=ssh-limited --add-service=ssh
 
# remove SSH from the default zone (public)
firewall-cmd --permanent --remove-service=ssh
 
# apply changes by reloading the firewall
firewall-cmd --reload
 
# list active zones and their configurations
firewall-cmd --get-active-zones
firewall-cmd --list-all && firewall-cmd --zone=ssh-limited --list-all

Using the network⁠-⁠based firewall service provided by servers.com

You can use the network⁠-⁠based firewall service provided by Servers.com to apply a set of rules for multiple hosts at once. Please note that the service only works with dedicated servers and not cloud servers. Please refer to the "Firewall" section in our Knowledge Base for details.

Customer portal screenshot

Suggested Articles

  • Linux administration

    Connecting to a remote server via SSH

  • Linux administration

    How to create a new SSH key pair