Saturday, December 24, 2016

Changing the SSH port on Fedora 25


Recently I've setup a new Fedora machine and I found changing the SSH port to be a bit more difficult than expected. This is because modern versions of Fedora use both SELinux and Firewalld by default which both complicate this process. As far as I'm aware no one currently explains everything you need to do in one place, so I figured I would.

Why bother changing the SSH port?

If you have an SSH server exposed to the internet on port 22 (the default), you'll quickly get login attempts from bots online. In theory a good password (or even better, public-key authentication) should protect you from these threats. However, I still feel it's worth a couple of minutes to switch ports and stay below the radar of all of these automated attacks.

How to change your SSH port

Change sshd_config

On my Fedora 25 installation this is located at /etc/ssh/sshd_config. Find the line which reads "Port 22" and change it to your desired port. Uncomment it if necessary.

Do not restart sshd yet! If you restart it before completing the other steps you'll lose SSH access to the machine. If this is a Fedora Server machine you may still be able to access it through the Cockpit at <YOUR IP ADDRESS>:9090.

Tell SELinux about the change

SELinux will prevent SSH from starting on the new port until you run this.
semanage port -a -t ssh_port_t -p tcp <YOUR NEW PORT>
(you'll need policycoreutils-python-utils for this)

Tell firewalld about the change

Fedora 25 comes with firewalld enabled by default. It's configured to allow port 22 in, but not other ports. There are a few different ways you can open your new port, but the most elegant is to update the firewalld's ssh service.

The default services are all located in /usr/lib/firewalld/services/, however any changes made to these will be overwritten by updates. In order to modify ssh.xml first copy it to /etc/firewalld/services:
cp /usr/lib/firewalld/services/ssh.xml /etc/firewalld/services/

Then open it in your favorite editor. There will be a line that reads:
<port protocol="tcp" port="22"/>

Simply change this to your desired port.

Restart the necessary services

Now, to get these configuration changes to take effect we need to restart firewalld, then sshd.
This order is important.
service firewalld restart
service sshd restart

Confirm you can login

If you're doing this through SSH it can be a good idea to confirm you can start a new SSH session on your new port before you log out of your existing session.

No comments:

Post a Comment