How to limit SSH (TCP port 22) connections with ufw on Ubuntu Linux

Posted on in Categories , , , last updated August 18, 2017

How do I limit ssh connection attempts using UFW (Uncomplicated Firewall) on Ubuntu or Debian Linux server?

UFW means Uncomplicated Firewall. It defaults on Ubuntu and can be installed on other Linux distros such as Arch Linux, Debian and more. It is nothing but a front-end for managing a Netfilter firewall. It provides a command line interface and aims to be uncomplicated and easy to use.
Limiting SSH Connections with ufw

Rate limiting with ufw

You can add limit rule. Currently only IPv4 is supported. With this syntax you can deny connections from an IP address that has attempted to initiate 6 or more connections in the last 30 seconds. This option is very useful for services such as sshd.


The syntax is pretty simple:

## ufw limit ssh various usage ##
ufw limit ssh
ufw limit ssh/tcp
ufw limit ssh comment 'Rate limit for openssh serer'
### if sshd is running on tcp port 2022 ####
ufw limit 2022/tcp comment 'SSH port rate limit'

The above rules are useful for protecting against brute-force login attacks. When a limit rule is used, ufw will normally allow the connection but will deny connections if an IP address attempts to initiate six or more connections within thirty seconds. Once setup you can verify it with the following command:
$ sudo ufw limit ssh/tcp comment 'Rate limit for openssh serer'
$ sudo ufw status

Sample outputs:

Status: active

To                         Action      From
--                         ------      ----
22/tcp                     LIMIT       Anywhere                   # Rate limit for openssh serer
22/tcp (v6)                LIMIT       Anywhere (v6)              # Rate limit for openssh serer

The actual rules are as follows in iptables:

-A ufw-user-input -p tcp -m tcp --dport 22 -m conntrack --ctstate NEW -m recent --set --name DEFAULT --mask --rsource
-A ufw-user-input -p tcp -m tcp --dport 22 -m conntrack --ctstate NEW -m recent --update --seconds 30 --hitcount 6 --name DEFAULT --mask --rsource -j ufw-user-limit
-A ufw-user-input -p tcp -m tcp --dport 22 -j ufw-user-limit-accept

Please note that the new ssh rule will then replace the previous ssh rule.

Posted by: Vivek Gite

The author is the creator of nixCraft and a seasoned sysadmin and a trainer for the Linux operating system/Unix shell scripting. He has worked with global clients and in various industries, including IT, education, defense and space research, and the nonprofit sector. Follow him on Twitter, Facebook, Google+.

3 comment

Leave a Comment