How To change the default SSH port on a digital ocean droplet

· [Daniel Baker]

Figure 1: Photo by regularguy.eth on Unsplash

Figure 1: Photo by regularguy.eth on Unsplash

Good security practices can save your ass. If you have a server in the cloud and SSH enabled then you probably have it running on Port 22. Anyone can guess this port and start running a brute force attack. To help mitigate this you can change the SSH port to some random port. This will add an extra barrier to help deter unauthorised access to your server.

However, I had issues changing the ports on my remote server in Digital Ocean. Every time I changed the ports I lost access to the server even though I verified ssh was listening on the correct port. Low and behold it was because the firewall settings were wrong. Here are the steps I took to change the default SSH port on Digital Ocean.

The instructions below are based on a droplet running ubuntu.

Change the Default port on Digital Ocean

  1. We need to alter the sshd config to add our new desired port.
vim /etc/ssh/sshd_config
  1. Find the line Port 22. For now we’re adding an additional Port so we can still access on Port 22 while we check everythings working. Above the port 22 line add a new port (press i to enter insert mode):

Port 21833
  1. Save and quit (ESC to enter NORMAL mode, then type :wq hit enter/return)
sudo service ssh restart
  1. Double check ssh is running on the desired port. Run sudo netstat -tulpn | grep ssh you should see something like:

       tcp        0      0 *               LISTEN      1515/sshd
       tcp        0      0    *               LISTEN      1515/sshd
       tcp6       0      0 :::21833                :::*                    LISTEN      1515/sshd
       tcp6       0      0 :::22                   :::*                    LISTEN      1515/sshd
  2. Your server should be listening on both ports you added.

  3. Update the ufw firewall rules on the machine to allow connections in

       sudo ufw allow 21833/tcp
  4. Update the Firewall rules for the Droplet to allow TCP requests in on the port you added above.

  5. By default Digital Ocean won’t add https access. Enable it. Unless you’re hosting an unsecure site you should only enable https

  6. Exit by typing exit and hitting return/enter. Now ssh back into your machine with the port you added ssh user@ip/domain -p 21833. You should be able to connect.

  7. If you connected successfully go back to the sshd_config and remove the line Port 22. This will disable access via port 22. And you’re done.

    P.S. you might want to pick a different port number to the one listed here ;)

A note on security

Although changing the default port for SSH adds an extra layer of security it’s not bullet proof. It’s actually pretty easy to write a script using telnet that loops over a range of ports checking which one’s are open. You should still disable password authentication and access only via ssh keys.