How to Change Your SSH Port with SELinux (RHEL 6)

In a previous post, we explained how to change the SSH port on your Linux server from the standard port 22.  In most cases, this works just fine, but if you are using Red Hat Enterprise Linux 6, there is a good chance you received an error such as the following:

sshd[82123]: error: Bind to port 2222 on failed: Permission denied

If you do, you most likely have SELinux (Security Enhanced Linux) enabled, as it is a standard feature of RHEL.  In this version, SELinux blocks all other ports for access to SSH, except for the standard port 22.  Fortunately, it is quite simple to change the settings to allow the port you want (2222, for example).

First of all, use semanage to display the current port settings.  As root, type:

semanage port -l | grep ssh

It should produce output that looks like this:

ssh_port_t    tcp    22

You can add port 2222 to the list of acceptable ports with the following command:

semanage port -a -t ssh_port_t -p tcp 2222

After you have entered the command, you should check to make sure the changes were saved.

semanage port -l | grep ssh

The output should now look like this:

ssh_port_t                     tcp      2222,22

Once you have verified the settings are correct, you must restart OpenSSH in order for the changes to take effect.

/sbin/service sshd restart

From now on, you should be able to connect to SSH from port 2222 or whichever port you chose.  Keep in mind that you will still need to configure SSH and your firewall in order to use that port, just as you normally would.