Setting Up SFTP on Amazon Linux 2 (Bash Script)

  1. Launch an instance using Amazon Linux 2 AMI, Open port 22 in Security Group to allow external connection for SFTP user and to SSH for setup.
  2. Create group for sftp users using command: groupadd <group-name> eg: groupadd sftpusers
  3. Create an user in this group using command: useradd -g <group-name> -d /incoming -s /sbin/nologin <username> eg: useradd -g sftpusers -d /incoming -s /sbin/nologin sftp_user
  4. Once user is created we need to create password for the above created user. command:passwd <username> eg: passwd sftp_user
  5. Check if user credentails are present in the passwd file using command:grep <username> /etc/passwd eg: grep sftp_user /etc/passwd. This will show the output with the username higlighted.
  6. Update /etc/ssh/sshd_config file and add following lines at the end

Match Group <group-name>
ChrootDirectory /sftp/%u
ForceCommand internal-sftp

eg: Match Group sftpusers
ChrootDirectory /sftp/%u
ForceCommand internal-sftp

7. Create folder for the file uploading with appropriate permissions

Folder 1 =/sftp, as we have mentioned /sftp as Chroot directory in above config, this will be the root folder for sftpusers group.

cmd: mkdir /sftp

Permission: chown root:root /sftp && chmod 755 /sftp

Folder 2 = /sftp/user-folder, this is the user folder, when the user logs into SFTP this will be the / folder for him

cmd: mkdir /sftp/sftp_user/

Permission: chown root:root /sftp/sftp_user/ && chmod 755 /sftp/sftp_user/

Folder 3 =/sftp/user-folder/data-folder, this is the path where a sftp user can upload files/create sub-folders.

cmd: mkdir/sftp/sftp_user/data_folder/

Permission: chown sftp_user:sftpusers /sftp/sftp_user/data_folder/ && chmod 755 /sftp/sftp_user/data_folder/

where sftp_user=SFTP user and sftpusers=Group-name

8. Restart sshd service

cmd: sudo service sshd restart

Common Issues:

Failed Permission Denied (Publickey,Gssapi-Keyex,Gssapi-With-Mic)

Solution: Check /etc/ssh/sshd_config find PasswordAuthentication yes and uncomment it, restart sshd service.

If issue still persist then in same sshd-config file find

AllowUsers ec2-user ssh_user, if your sftp user is not there in list append the name and restart sshd service.

Connection timed out

Check for SSH port 22 in Security Group, open the port to the required source address.

Example:

#!/bin/bash

groupadd sftpusers

useradd -g sftpusers -d /incoming -s /sbin/nologin sftp_user

passwd sftp_user

echo “Match Group sftpusers
ChrootDirectory /sftp/%u
ForceCommand internal-sftp” >> /etc/ssh/sshd_config

mkdir /sftp

chown root:root /sftp && chmod 755 /sftp

mkdir /sftp/sftp_user/

chown root:root /sftp/sftp_user/ && chmod 755 /sftp/sftp_user/

mkdir/sftp/sftp_user/data_folder/

chown sftp_user:sftpusers /sftp/sftp_user/data_folder/ && chmod 755 /sftp/sftp_user/data_folder/

sudo service sshd restart

AWS & DevOps Lead