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 statusIf 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.
View your current rules with numbered indices:
sudo ufw status numberedLocate the rule that allows SSH or port 22 (usually looks like
22/tcporSSHwithALLOW IN Anywhere).Delete that rule using its number (replace
3with 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 tcpIf 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 tcpStep 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 enableType 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 verboseThe 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.