Moving SFTP to Port 2222 (AWS)
Note: This page applies to SFTP Gateway version 2.x. Visit Here for documentation on version 3.x.
Overview
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.
AWS advises against this practice, for security reasons. To mitigate the security risk, you can separate the OpenSSH protocols by port number:
- SFTP: Port
22
- SSH: Port
2222
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.
sshd_config
file
Edit the Before you do anything, first make a backup of your sshd_config
file.
sudo su
cd /etc/ssh/
cp -a sshd_config sshd_config.orig
Now you can edit the sshd_config
file, located here:
/etc/ssh/sshd_config
On line 17, you will see the following line:
#Port 22
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 EC2 Security Group rules
Edit the EC2 Security Group rules for your EC2 instance:
- Create a rule that allows all TCP port 22 traffic from
0.0.0.0/0
. - 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 EC2 instance over port 2222:
ssh -i <private.key> ec2-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 sshd_config
file, or revert all of your changes if necessary.