The general rule of a firewall is to block everything and allow only the required traffic. By default, ufw firewall blocks all incoming connections and allows all outgoing connections.
Generally, allowing ssh on port 22 permits everyone to access the server through ssh. A more granular approach (more restriction) would be to allow ssh access from a specific IP address or subnets.
Prerequisites
- A running Ubuntu / Debian System.
- A user with sudo access.
Allowing SSH connections with ufw
To allow ssh access from any incoming traffic - ie from any IP addresses, type:
sudo ufw allow 22
sudo ufw allow 22/tcp comment 'Allow SSH'
This will open the server to the outside world for any bad actors to perform brute force or bot attacks. You should allow access by a specific IP address, set limits, or implement other measures such as fail2ban.
Allowing SSH from IP address
For ufw to allow ssh connections only from a specific IP on port 22, use the syntax:
ufw allow from <ip-address> to any port 22
For example to allow ssh from IP address 10.20.30.2, type:
sudo ufw allow from 10.20.30.2 to any port 22
The syntax for using subnets:
ufw allow from ip-subnet/mask to any port 22
Example to allow all ssh connections from subnet 10.20.40.2/24, type:
sudo ufw allow from 10.20.40.2/24 to any port 22
orsudo ufw allow from 10.20.40.2/24 to any port 22 proto tcp
For more granularity, you define the IP address of the destination ssh server. Example
sudo ufw allow from 10.20.40.3/24 to 10.20.40.7 port 22 proto tcp
Additional points to Note:
UFW can be configured to limit the rate of incoming traffic on specific port or services. For example ufw limit 22/tcp
will deny connections from IP address that initiated 6 and more connections in the last 30 seconds.
Generally, the order of firewall rules is important. The same applies to ufw rules. Keep the most restrictive rules at the top such as all deny rules and general rules at the bottom. You can use sudo ufw status numbered
command to show ufw status and firewall rules with a number assigned to each of them.
Conclusion
Allowing ssh from specific IP address give more restricted control of connections.
Still, many systems use passwords instead of ssh keys. So you should further harden your setup with tools such as Fail2ban to drop requests from the sshd level to the network (iptables).
Thanks for reading, please leave your feedback and suggestions in the below comment section.
Comments