UFW SSH Allow: Setup and Configuration

UFW SSH Allow: Setup and Configuration – A Comprehensive Guide

SSH (Secure Shell) is a vital protocol for remotely managing servers and devices. It provides a secure, encrypted connection, allowing administrators to execute commands, transfer files, and manage systems from a different location. UFW (Uncomplicated Firewall) is a user-friendly interface to iptables on Linux systems, providing a simplified way to manage firewall rules. This article provides a detailed walkthrough on setting up and configuring ufw to allow SSH connections, focusing on security best practices.

1. Understanding the Basics

Before diving into configuration, let’s clarify the core concepts:

  • SSH Default Port: SSH typically listens on port 22. This is a well-known port, making it a common target for attackers.
  • UFW’s Default Policy: By default, UFW usually has a “deny all incoming” and “allow all outgoing” policy. This means that without explicit rules, all incoming connection attempts, including SSH, will be blocked.
  • ufw allow vs. ufw deny: UFW’s primary commands are ufw allow (to permit traffic) and ufw deny (to block traffic). We’ll primarily use ufw allow to configure SSH access.
  • Best Practice – Least Privilege: Only allow the necessary access. Don’t open SSH to the entire world if you don’t need to.

2. Installing UFW (if not already installed)

On most modern Debian/Ubuntu-based systems, UFW is pre-installed. You can check its status with:

bash
sudo ufw status

If it’s not installed, you can install it with:

  • Debian/Ubuntu:

    bash
    sudo apt update
    sudo apt install ufw

  • CentOS/RHEL/Fedora: (UFW is less commonly used here, firewalld is the default. If you must use UFW, installation is more complex and involves enabling the EPEL repository). For simplicity, this guide focuses on Debian/Ubuntu-based systems. If you’re using a Red Hat-based system, refer to the firewalld documentation instead.

3. Enabling UFW (and setting defaults)

Before adding any rules, enable UFW and set the default policies. This is crucial for ensuring that your firewall is active and blocking unwanted traffic:

bash
sudo ufw enable

You will receive a warning that this might disrupt existing SSH connections. This is expected, and we’ll fix it immediately. If you’re connected via SSH when you run this command, you might get disconnected if the rule to allow SSH (below) isn’t added quickly enough. Ideally, have console access (e.g., through your hosting provider’s control panel) as a backup.

Now, set the default policies. These policies apply to traffic that doesn’t match any specific rules:

bash
sudo ufw default deny incoming
sudo ufw default allow outgoing

These commands set the default behaviour to deny any new incoming connection and to allow outgoing connections from your system.

4. Allowing SSH Connections (The Core Configuration)

Now for the most important part: allowing SSH connections. There are several ways to do this, with varying levels of security:

4.1 Allowing SSH on the Default Port (22) – Simplest, but less secure:

This is the easiest method but also the least secure, as it exposes the default SSH port:

bash
sudo ufw allow ssh

Or, explicitly specifying the port:

bash
sudo ufw allow 22/tcp

UFW understands “ssh” as a service name, which maps to port 22/tcp.

4.2 Allowing SSH on a Custom Port – More Secure:

Changing the default SSH port is a good security practice. It reduces the likelihood of automated attacks targeting port 22.

Step 1: Modify the SSH Configuration File:

Open the SSH configuration file (/etc/ssh/sshd_config) with your preferred text editor (e.g., nano, vim):

bash
sudo nano /etc/ssh/sshd_config

Find the line that says #Port 22 (it might be commented out with a #). Uncomment it (remove the #) and change the port number to a non-standard port, for example, 2222 (or any port number between 1024 and 65535 that isn’t already in use).

Port 2222
Also, find the line:
#ListenAddress 0.0.0.0
#ListenAddress ::

You can uncomment this line and specify a specific IP address if you need to, otherwise, leave them commented out.

Save the file and exit the editor.

Step 2: Restart the SSH Service:

Apply the changes by restarting the SSH service:

bash
sudo systemctl restart ssh

Step 3: Allow the Custom Port in UFW:

Now, allow the new port in UFW:

bash
sudo ufw allow 2222/tcp

If you previously allowed port 22, you should now deny it to enhance security:
bash
sudo ufw deny 22/tcp

4.3 Allowing SSH from Specific IP Addresses/Networks – Most Secure:

This is the most secure approach. It restricts SSH access to only authorized IP addresses or networks.

Allow a Single IP Address:

bash
sudo ufw allow from 192.168.1.100 to any port 22 # If using default port
sudo ufw allow from 192.168.1.100 to any port 2222 # If using a custom port (e.g., 2222)

Replace 192.168.1.100 with the actual IP address you want to allow.

Allow an Entire Network:

bash
sudo ufw allow from 192.168.1.0/24 to any port 22 # If using default port
sudo ufw allow from 192.168.1.0/24 to any port 2222 # If using custom port (e.g., 2222)

Replace 192.168.1.0/24 with the correct network and subnet mask (CIDR notation). /24 represents a network with 256 addresses (from .0 to .255).

Combining Custom Port and IP Restrictions (Recommended):

For optimal security, combine a custom port with IP address restrictions:

bash
sudo ufw allow from 192.168.1.100 to any port 2222

5. Verifying UFW Rules

Always verify your firewall rules after making changes:

bash
sudo ufw status verbose

This command will show you the current status of UFW, including all active rules, default policies, and whether it’s enabled. Look for your SSH rule in the output. It should show as “ALLOW” and list the source IP/network (if you specified one), the destination port, and the protocol (TCP).

6. Testing the SSH Connection

After configuring UFW, test your SSH connection from the allowed IP address(es). If you changed the port, make sure to use the new port number in your SSH client:

bash
ssh username@your_server_ip -p 2222 # If using a custom port (replace 2222 with your port)
ssh username@your_server_ip # If using the default port (22)

Replace username with your actual username and your_server_ip with your server’s IP address. If the connection succeeds, your UFW configuration is working correctly. If it fails, double-check your rules, the SSH configuration file, and ensure your SSH client is using the correct port and IP address. Also check sudo ufw status verbose to make sure the rules are actually loaded.

7. Deleting Rules

If you need to remove a rule, you can use ufw delete:

bash
sudo ufw delete allow 22/tcp # Delete the rule allowing port 22
sudo ufw delete allow from 192.168.1.100 to any port 2222 # Delete a specific IP/port rule

You can also delete rules by their rule number. First, run sudo ufw status numbered to show the rule list with numbers, then:
bash
sudo ufw delete 3 # Deletes the rule at number 3.

8. Advanced UFW Considerations

  • Rate Limiting: UFW can help protect against brute-force SSH attacks by limiting connection attempts. The ufw limit command is useful for this:
    bash
    sudo ufw limit ssh/tcp # Or your custom port, e.g., sudo ufw limit 2222/tcp

    This allows a new connection to the specified port every 30 seconds. If more than 6 attempts are made in 30 seconds from the same IP, subsequent connections are denied.
  • Logging: UFW can log blocked connection attempts. This can be useful for troubleshooting and monitoring. Enable logging with:
    bash
    sudo ufw logging on

    Logs are usually stored in /var/log/ufw.log (location may vary depending on the distribution).
  • IPv6: If you’re using IPv6, make sure to add rules for IPv6 addresses as well. UFW handles IPv6 separately. Use the same commands, but ensure your IP addresses are in the correct IPv6 format. Example:
    bash
    sudo ufw allow from 2001:db8::1 to any port 2222
  • Application Profiles: UFW can manage rules based on application profiles. You can list available profiles with sudo ufw app list. However, manually specifying ports and IP addresses generally offers more control and is recommended for SSH.

9. Security Best Practices

  • Use Strong Passwords: Even with a firewall, weak passwords are a significant vulnerability. Use long, complex passwords or, even better, SSH keys.
  • Use SSH Keys: SSH keys provide a much more secure authentication method than passwords. Disable password authentication in /etc/ssh/sshd_config after setting up key-based authentication:
    PasswordAuthentication no
    And restart the SSH service after making this change: sudo systemctl restart ssh.
  • Disable Root Login: Prevent direct root login via SSH. Create a standard user account and use sudo for administrative tasks. Set PermitRootLogin no in /etc/ssh/sshd_config.
  • Keep your System Updated: Regularly update your system (including UFW and OpenSSH) to patch any security vulnerabilities.
  • Monitor Logs: Regularly review your firewall and SSH logs for suspicious activity.
  • Consider a Fail2ban-like solution: Tools like Fail2ban can automatically block IP addresses that exhibit malicious behavior, such as repeated failed login attempts. This is an excellent addition to UFW, not a replacement.

Conclusion

Properly configuring UFW to allow SSH connections is crucial for secure server administration. This guide provides a comprehensive overview of the process, from basic setup to advanced security considerations. By following these steps and implementing the recommended best practices, you can significantly enhance the security of your server and protect it from unauthorized access. Remember to always prioritize security and adapt the configuration to your specific needs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top