zkbro

Change default port on SSH server

2025-05-17 16:59

Background

I've heard it's a good idea to change the default SSH listening port 22 for machines running an SSH server for an added level of security. Given I'm SSHing into my Raspberry Pi regularly, which is serving up my Gemini capsule and notes website, I thought I'd (finally) make this change. I am running Debian 12 bookworm on a Raspberry Pi 4.

Steps

Allow port listening on firewall. Replace PORT with a number in the User Ports (1024-49151) range. Do a search on the Internet Assigned Numbers Authority (IANA) website prior to check it hasn't been registered already for another protocol. Supposedly the User Ports range is preferred over the Dynamic and/or Private Ports range (49152-65535) in case the port number is swiped up dynamically. There was some discussion on StackOverflow which gave me direction. Some guides out there say to use the Dynamic and/or Private Ports range however.

sudo ufw allow **PORT**/tcp

Delete listening on port 22 if it exists:

sudo ufw status numbered
sudo ufw delete [number]

Edit the sshd_config file:

sudo nano /etc/ssh/sshd_config

Note sshd_config is the server configuration file which relates to incoming connections, rather than ssh_config which relates to outbound connections.

Find the line with #Port 22, un-comment and change 22 to the port number chosen.

Reload ufw and restart sshd service:

sudo ufw reload
sudo systemctl restart sshd  ## or ssh - it doesn't matter

Now when I SSH into the RasPi from say my laptop it will default to the new port number:

ssh zkbro@192.168.1.4

~/.ssh/config

The command above is a bit of a pain to write out, so to make life easier on my laptop, or whatever client I am SSHing from I can define credentials by creating and editing the ~/.ssh/config file:

Host pi
	HostName 192.168.1.4
	User zkbro
	Port PORT

Replace PORT with port number. Not entirely sure why I need to define port given there's a default..

Now I can SSH into the RasPi with:

ssh pi

Summary

Overall a pretty quick and easy additional layer of security for SSH Servers. Apparently not a huge measure, but every bit counts.