How To change the default SSH port on a digital ocean droplet
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
- We need to alter the
sshd
config to add our new desired port.
vim /etc/ssh/sshd_config
- 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 (pressi
to enter insert mode):
Port 21833
- Save and quit (
ESC
to enterNORMAL
mode, then type:wq
hit enter/return)
sudo service ssh restart
-
Double check ssh is running on the desired port. Run
sudo netstat -tulpn | grep ssh
you should see something like:tcp 0 0 0.0.0.0:21833 0.0.0.0:* LISTEN 1515/sshd tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1515/sshd tcp6 0 0 :::21833 :::* LISTEN 1515/sshd tcp6 0 0 :::22 :::* LISTEN 1515/sshd
-
Your server should be listening on both ports you added.
-
Update the
ufw
firewall rules on the machine to allow connections insudo ufw allow 21833/tcp
-
Update the Firewall rules for the Droplet to allow TCP requests in on the port you added above.
-
By default Digital Ocean won’t add
https
access. Enable it. Unless you’re hosting an unsecure site you should only enablehttps
-
Exit by typing
exit
and hittingreturn/enter
. Now ssh back into your machine with the port you addedssh user@ip/domain -p 21833
. You should be able to connect. -
If you connected successfully go back to the
sshd_config
and remove the linePort 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.