Changing SSH port is a good idea if you want to reduce the possibility of being hacked by bots that scan every network node every day to try to log in your servers using popular weak passwords.
You don’t really need to change SSH port if:
- your servers are running in a private network, not publicly exposed to the internet;
- your servers are publicly exposed but you’ve disabled password authentication and you keep your SSH keys private.
Following is three basic steps:
- Add a firewall rule to open the new port
- If SELinux is enabled, modify its policy to allow the new port
- Configure SSH daemon
The above order ensures that you won’t accidentally block yourself out.
Implementation on CentOS 7 (let’s say you want to change SSH port to 12345 and your default zone is public)
Disclaimer: I’m not responsible for any troubles you get after applying the following commands.
firewall-cmd --permanent --add-port 12345/tcp
firewall-cmd is the command line utility to interact with firewalld rules. firewalld is a service that talks to Linux kernel’s netfilter. It has a front-end that is easier to understand compared to the iptables command. firewalld is installed by default on CentOS.
semanage port -a -t ssh_port_t -p tcp 12345
semanage is the command to manage SELinux policies. While netfilter only works with network packets, SELinux (security enhanced) goes further by enforcing rules like which user can access which files, which service can talk to an external port, which role can listen on a port, etc…
If you get a ‘command not found’ error with semanage, run
yum install -y policycoreutils-python
SSH daemon configuration
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak
sed -i "s/#Port 22/Port 22\nPort 12345/g" /etc/ssh/sshd_config
systemctl restart sshd
That will make SSH listen on both 22 and 12345. Now open another terminal, try SSH-ing with the new port. After everything is ok, edit /etc/ssh/sshd_config to remove Port 22 and restart sshd.
That’s it. Let’s discuss further in comments.
Thanks for reading.