In this guide, we will see how to change the SSH service port on CentOS 7/8, RHEL 7/8, and Fedora 31/30/29 using SELinux running in Enforcing mode. When SELinux running Enforce Mode it Enforce of SELinux Policy and deny access based on SELinux Policy rules. The standard SSH port on most Linux / Unix systems is TCP port 22. It can be easily changed to a custom port that is not used by other applications in the system.
When SELinux is running in Enforcing mode, you need to reset the port to be set so that the policy rules that control access can accept ssh services for binding. Follow the steps discussed below to change the SSH port of SELinux running Enforcing mode on a CentOS / RHEL / Fedora server or desktop.
Step 1: Back up your current SSH configuration
Log in to your CentOS / RHEL / Fedora system and back up your current ssh daemon configuration file.
date_format=`date +%Y_%m_%d:%H:%M:%S` sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config_$date_format
$ ls /etc/ssh/sshd_config* /etc/ssh/sshd_config /etc/ssh/sshd_config_2019_09_05:21:40:10
Step 2: Change the SSH service port
Use your favorite text editor-vi, vim, nano e.t.c to open the SSH service configuration file.
sudo vi /etc/ssh/sshd_config
Find the line with:
Uncomment the port line and set a new service port to use. I will use port 33000.
Save your changes and close the file.
Step 3: Allow new SSH ports on SELinux
The default port marked as SSH is 22.
$ semanage port -l | grep ssh ssh_port_t tcp 22
If you want to allow sshd Bind to the configured network port, you need to change the port type to ssh_port_t.
sudo semanage port -a -t ssh_port_t -p tcp 33000
Confirm that the new port has been added to the list of ports allowed by ssh.
$ semanage port -l | grep ssh ssh_port_t tcp 33000, 22
Step 4: Open the SSH port on Firewalld
It is always recommended to keep the firewall service running and allow only trusted services.
sudo firewall-cmd --add-port=33000/tcp --permananet sudo firewall-cmd --reload
If Firewalld is not installed, use yum to install and start the service.
sudo yum -y install firewalld sudo systemctl enable --now firewalld sudo firewall-cmd --add-port=33000/tcp --permanent sudo firewall-cmd --reload
You can now delete the ssh service.
sudo firewall-cmd --remove-service=ssh --permanent sudo firewall-cmd --reload
Step 5: Restart the sshd service
Restart the ssh service for the changes to take effect.
sudo systemctl restart sshd
Verify the ssh listening address.
$ netstat -tunl | grep 33000 tcp 0 0 0.0.0.0:33000 0.0.0.0:* LISTEN tcp6 0 0 :::33000 :::* LISTEN
How to disable SSH reverse DNS lookup in Linux / Unix systems
How to set up two factor (2FA) authentication for SSH on CentOS / RHEL
Easy way to create SSH tunnel on Linux CLI
How to change or update SSH key password on Linux / Unix
Ssh cheat sheet for Linux SysAdmins