In case you want to change the default SSH port 22 on your system and you are running into the following error:

Error: Bind to port failed: Permission denied


You will probably using a Linux distribution on which SELinux (Security-Enhanced Linux) is enabled.

Common Linux distributions that by default had enabled SELinux are Red Hat Enterprise Linux (RHEL) as used below for this post, CentOS, AlmaLinux, Rocky Linux, Fedora, Oracle Linux and Amazon Linux 2.

Available but not enabled by default are Debian, Ubuntu, openSUSE, SUSE Linux Enterprise Server, Gentoo and Arch Linux.

Ubuntu, openSUSE and Debian by default using SELinux’s counterpart AppAmor.


To see if SELinux is enabled on your system you can use the sestatus command.


As mentioned for this post I will use Red Hat Enterprise Linux 9 (RHEL). Here you will already see a notification within the /etc/ssh/sshd_config file that if we want to change the SSH port, we first need to tell SELinux about this change.


Otherwise we will run into the error below when trying to restart the sshd daemon.


By checking the logs using the journalctl -xeu sshd.service command we will get more details about the problem. In our case because SELinux is enabled here we first need to adjust the so called targeted policy to allow a different SSH port than 22.


We can first check the actual targeted policy for our SSH port by executing:

semanage port -l | grep ssh

When running a service on a custom port, you must change the configuration file for the service and also add an SELinux port definition. Without the port definition, the service will fail to start and log an error similar to “cannot bind to port”.

Source: https://www.redhat.com/sysadmin/semanage-keep-selinux-enforcing


Adjust the port definition to also allow tcp port 2222 will be used by the sshd daemon with:

# semanage port -a -t ssh_port_t -p tcp 2222

 -a, --add -> Add a record of the specified object type
 -t TYPE, --type TYPE -> SELinux type for the object


In case you want to remove the default SSH port by using the -d flag for this policy you will run into the following error:

ValueError: Port tcp/22 is defined in policy, cannot be deleted

Already default defined policies can’t be deleted, therefore you have to create your own policy.





Link

What is SELinux (Security-Enhanced Linux)?
https://www.redhat.com/en/topics/linux/what-is-selinux

Four semanage commands to keep SELinux in enforcing mode
https://www.redhat.com/sysadmin/semanage-keep-selinux-enforcing

Configuring SELinux
https://documentation.suse.com/sles/15-SP5/html/SLES-all/cha-selinux.html