Change the default SSH port on Linux

If you check the security logs in a public device, there are many failed login attempts from different IPs around the world whatever your system is (server, router Etc.), in short, brute force attacks. Mostly of them are trying on Shell (SSH ) protocol, using the default known port 22.

This is one of the reasons why the password should be complex, very complex. To avoid these automatic attempts is recommended to take one of the actions:

  • Allow only specific IP ranges to connect on your server using port SSH
  • Change the port 22 to a non standard port
By changing the default SSH port doesn't mean that you are safe now, you just avoid these annoying automatic attempts. For an intentional attacker it is not so hard to scan your server and to find the new SSH port. But at least you avoid tons of useless security logs and you may avoid an unexpected success login.

In this tutorial you will learn how to change the Linux SSH port 22 to a non standard port.

In our example we will use port 56789.

According to IANA (Internet Assigned Numbers Authority) ports 49152 to 65535 are free to use (if another service is not already using it). Better using this range to avoid any conflict with future services that commonly use standard ports.

You have to use root credentials in order to make these changes.

First modify the firewall to allow TCP connection on port 56789 (This is the new SSH port for this example).

For iptables

iptables -A INPUT -p tcp --dport 56789 -j ACCEPT
service iptables save
service iptables restart

For firewalld

firewall-cmd --add-port 56789/tcp
firewall-cmd --add-port 56789/tcp --permanent

For APF firewall

vi /etc/apf/conf.apf

Locate the line labeled: Common ingress (inbound) TCP ports.

#Common ingress (inbound) TCP ports

Add new SSH port (In our example 56789) to the list (comma separated) and restart the service

service apf restart
Update SELinux

semanage port -a -t ssh_port_t -p tcp 56789
Edit the SSH daemon (SSH service) configuration file
vi /etc/ssh/sshd_config

Change port 22 to your new port (In our example 56789).

Port 56789
#AddressFamily any
#ListenAddress ::

Restart sshd service

service sshd restart