Knowledge Base

How to limit access to SSH to one (or more) IPs

Learn how to restrict SSH access to specific IP addresses using IPTables, Firewalld, and UFW across various Linux distributions.

Yaro
ssh iptables firewalld ufw security linux

IMPORTANT NOTE: This may work for you well, but keep in mind that these methods are not universal. These are examples of basic use; we highly recommend you to check the documentation for a better understanding of how to set up these utilities for your needs.

IPTables (Universal)

Firstly, let’s allow access to your IP:

iptables -A INPUT --source Y -p tcp --dport 22 -j ACCEPT

NOTE: 22 is a standard port; if you are using another port, you need to change the —dport parameter to your port.

Then we need to block access for other IPs:

iptables -A INPUT -p tcp --dport 22 -j DROP

For more information, visit - https://linux.die.net/man/8/iptables

Firewalld (CentOS/Alma Linux)

Keep in mind that Firewalld is usually a built-in utility, so in some cases, installation is not needed.

Upgrade your package and install Firewalld using the next command:

yum upgrade --refresh -y && yum -y install firewalld

Enable and start Firewalld:

systemctl enable firewalld && systemctl start firewalld && systemctl status firewalld

Add a new zone and set it up:

firewall-cmd --permanent --new-zone=ssh-limited
firewall-cmd --permanent --zone=ssh-limited --add-source=my_IPAddress

Add SSH service to the new zone:

firewall-cmd --permanent --zone=ssh-limited --add-service=ssh

Remove SSH from the public zone:

firewall-cmd --permanent --remove-service=ssh

Apply changes:

firewall-cmd --reload

To see the list of active zones, type:

firewall-cmd --get-active-zones

For more information, visit - https://firewalld.org/documentation

UFW (Ubuntu/Debian)

UFW is an easy-to-use utility, usually built-in, but not always.

Upgrade your package and install UFW using the next command:

apt update -y && apt install -y ufw

Allow access for your address:

ufw limit from My_IPAddress to any app OpenSSH

Remove less-restrictive SSH-related rules:

ufw delete allow 22/tcp
ufw delete allow OpenSSH
ufw delete limit OpenSSH

Enable UFW:

ufw --force enable

To see status:

ufw status

For more information about UFW, visit - https://ubuntu.com/server/docs/security-firewall

Need Help?

Our support team is available 24/7 to assist you.

Contact Support

Related Articles

Browse more articles in these categories.