Limit SSH Access to Specific IPs on Ubuntu Linux

Securing your Ubuntu SSH server is crucial for preventing unauthorized access and brute-force attacks. This guide provides a straightforward, step-by-step walkthrough on how to configure the Uncomplicated Firewall (UFW) in Ubuntu Linux to restrict SSH connections to only trusted, specific IP addresses, thereby significantly enhancing your server’s security.

Step 1: Check Your Current UFW Status

Before making changes, check if the Uncomplicated Firewall (UFW) is active on your system.

sudo ufw status

If it says Status: inactive, do not enable it yet. You must first configure your allow rules so you do not lock yourself out of your server.

Step 2: Delete Existing Generic SSH Rules

If you previously set up your server, you might have a generic rule that allows SSH access from any IP address. You need to remove this rule.

  1. View your current rules with numbered indices:

    sudo ufw status numbered
  2. Locate the rule that allows SSH or port 22 (usually looks like 22/tcp or SSH with ALLOW IN Anywhere).

  3. Delete that rule using its number (replace 3 with the actual rule number from your list):

    sudo ufw delete 3

Step 3: Allow Specific IP Addresses

Now, create a rule that explicitly allows SSH connections only from your specific, trusted IP address. Replace your_trusted_ip with your actual public IP address.

sudo ufw allow from your_trusted_ip to any port 22 proto tcp

If you have a subnet or a range of IP addresses (for example, an office network), you can allow the entire subnet using CIDR notation:

sudo ufw allow from 192.168.1.0/24 to any port 22 proto tcp

Step 4: Enable the Firewall

By default, UFW blocks all incoming connections and allows all outgoing connections. Once you have allowed your specific IP, you can safely enable the firewall.

sudo ufw enable

Type y and press Enter when prompted to proceed.

Step 5: Verify the Configuration

To ensure your rules are applied correctly, check the status of UFW again:

sudo ufw status verbose

The output should show that port 22 traffic is only allowed from your specified IP address or subnet, while all other incoming traffic is denied by default.

Keep your current SSH session open and open a new terminal window to test the connection. This ensures you can revert the changes if you made a mistake.