Under ideal circumstances, you should restrict ingress on TCP port 22 to a whitelist of IP addresses. But if this IP whitelist grows to an unmanageable size, you may have to open port 22 to the world.
This is not a best practice, for security reasons. To mitigate the security risk, you can separate the OpenSSH protocols by port number:
- SFTP: Port
- SSH: Port
This allows you to open port 22 (SFTP) to the world, while properly restricting port 2222 (SSH) to a whitelist of IP addresses used by administrators.
Before you do anything, first make a backup of your
sudo su cd /etc/ssh/ cp -a sshd_config sshd_config.orig
Now you can edit the
sshd_config file, located here:
On line 17, you will see the following line:
Replace it with the following:
Port 22 Port 2222
OpenSSH listens on port 22 by default. This overrides the default with ports 22 and 2222.
Toward the bottom, around line 157, you'll see this stanza:
Match group sftponly ChrootDirectory /home/%u/home/%u X11Forwarding no AllowTcpForwarding no ForceCommand internal-sftp -l INFO MaxSessions 10000
Directly above it, insert the following lines:
Match LocalPort 22 ForceCommand internal-sftp
This forces all traffic on port 22 to use the SFTP protocol.
Save your changes.
Restart the SSH service to apply your changes.
service sshd restart
Note: As a precaution, keep this current SSH session open until the end of the article, after you have confirmed that you can reconnect on port 2222.
Manage Network Security Group rules
Edit the NSG rules for your VM:
- Create a rule that allows all TCP port 22 traffic from
- Create a rule that allows TCP port 2222 traffic from your current IP address.
Connect via SSH
Confirm that you are still able to connect to your VM over port 2222:
ssh -i <private.key> <admin-user>@<ip-address> -p 2222
If for some reason you are unable to connect, switch back to your
open SSH session. You can double-check the syntax of your
file, or revert all of your changes if necessary.