Correct Way to Change SSH Port on Ubuntu (Oracle Cloud Guide)

I recently changed the SSH port on my Ubuntu VM hosted on Oracle Cloud and found myself locked out. After searching online, I came across this article:

🔗 AskUbuntu - Can't log in after changing default port 22 on Oracle Cloud VM

However, the article didn't provide a clear solution, so I kept testing different approaches until I found the correct fix.

Understanding the Issue

By default, Ubuntu on Oracle Cloud uses iptables instead of ufw, which means manually changing the SSH port in /etc/ssh/sshd_config is not enough. You must also update firewall rules accordingly.

The Correct Way to Change the SSH Port

1️⃣ Edit the SSH Configuration File

sudo nano /etc/ssh/sshd_config

Find the line that specifies the port and change it:

Port 2222  # Replace with your desired port

2️⃣ Allow the New SSH Port in iptables

sudo iptables -I INPUT 6 -p tcp --dport 2222 -m state --state NEW -j ACCEPT

🔹 The number 6 represents the position where this rule should be inserted. It must be placed above the reject-all rule.

To check existing rules and determine the correct line number, use:

sudo iptables -L INPUT --line-numbers

3️⃣ Save the iptables Configuration

sudo netfilter-persistent save

4️⃣ Restart the SSH Service

sudo systemctl restart ssh

Updating Oracle Cloud Firewall Rules

After configuring iptables, you must also update the security rules in the Oracle Cloud web portal:

  1. Navigate to:
    Networking > Virtual Cloud Networks > [Your VCN] > Security Lists > [Default Security List]
  2. Click Add Ingress Rules and enter the following:
    • Source Type: CIDR
    • Source CIDR: 0.0.0.0/0
    • IP Protocol: TCP
    • Source Port Range: All
    • Destination Port Range: 2222 (or the port you set in SSH and iptables)
  3. Save the changes.

Connecting via SSH

Now, you can connect using the new port:

ssh -i ssh-xxx.key -p 2222 ubuntu@your-public-ip

Cleaning Up Old Rules

Once you've successfully connected using the new port, you can remove the old rule for port 22:

sudo iptables -D INPUT 8

🔹 Replace 8 with the correct line number for the old port 22 rule (check using iptables -L INPUT --line-numbers).

You may also remove the old Ingress Rule for port 22 in Oracle Cloud's security settings.

Conclusion

This method ensures a proper SSH port change without getting locked out of your Oracle Cloud Ubuntu VM. Hope this helps! 🚀