Custom Port on Socket-based SSH


I recently set up a new VM running Ubuntu 23.10. This version of Ubuntu comes with a change to the way that the ssh daemon is configured.

I’ve always preferred to run SSH on a non-standard port on most of my machines. While the usefulness of this as a security measure is debatable, it’s also become muscle memory for me so now I have a preference to just use my other chosen port.

With the new versions of Ubuntu, and surely others as well going forward, the mechanism by which SSH listens for connections has changed to a socket-based model. While the change is more or less transparent for anyone with default configurations, or who upgraded from a previous version of Ubuntu, fresh installs with a “special” requirement like a custom port have a few steps to take.

Specifically a file needs to be created within the systemd configuration directory that will enable the socket-based SSH listener to use a custom port. This change can be made to listen to multiple ports, or specific ports on different addresses, but I’m going to keep this simple since my use case is simple.

We are going to add a listener configuration file which has two lines. One to blank out the existing listener port (port 22) and one to add our custom port (port 30303).

kdmurray@mimas:~$ sudo -s

root@mimas:# mkdir -p /etc/systemd/system/ssh.socket.d

root@mimas:# cat >/etc/systemd/system/ssh.socket.d/listen.conf <<EOF
[Socket]
ListenStream=
ListenStream=30303
EOF

By using the cat command to insert the text and delimiting with an EOF (end of file) marker this can be done without needing to open a text editor like vi or nano.

Old School

For reference, and completeness, the “old” way to do this was to change the port in the regular sshd config file. This is still valid on any OS not using the new socket-based method, or on a system which has had it disabled.

This simply un-comments the Port line and swaps the default port (22) for something else.

# /etc/ssh/sshd_config

#       $OpenBSD: sshd_config,v 1.103 2018/04/09 20:41:22 tj Exp $

# ...

Include /etc/ssh/sshd_config.d/*.conf

Port 30303
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

# ...

By default much of that config file is commented out in favour of sensible defaults. If you are going to make changes though, there are a few other lines to consider:

PermitRootLogin no         # Disable SSH for root user
PasswordAuthentication no  # Require keyed logins rather than passwords

There are also a number of options for forwarding ports and services through the SSH tunnel. One I’ve used somewhat frequently is X11 forwarding

X11Forwarding yes