Set up SFTP server on Ubuntu using Public Key Auth(AWS-EC2)

This topic will guide you through how to setup an SFTP authentication mechanism using **public key cryptography**.

I recently set up SFTP by using the Id and Password.
↓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;↓&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;↓
[How to set up SFTP server on Ubuntu(AWS-EC2)]
(https://qiita.com/alokrawat050/items/709d3c777407ab658aa9)
But SFTP provides an alternative method for client authentication. It's called **SFTP public key authentication**. This method allows users to login to your SFTP service without entering a password.

Let’s get started!
Make sure that SSH and SSH-Server are installed. I assumed that you have already install the **OpenSSH-server & SSH**. If not then please check below link.
[Install OpenSSH-Server & SSH(Step-1)]
(https://qiita.com/alokrawat050/items/709d3c777407ab658aa9)

**Step 1：Create SFTP user account**
First, we need to create a new user who will be granted only file transfer access to the server.

```
$ sudo adduser sftp_user
```
You’ll be prompted to create a password for the account, followed by some information about the user. The user information is optional, so you can press ENTER to leave those fields blank.

```
Enter new UNIX password: 
Retype new UNIX password: 
.....
passwd: password updated successfully
```

You have now created a new user that we will be granted access to the restricted directory. 
In the next step we will create the directory for file transfers and set up the necessary permissions.

**Step 2：Creating a Directory for File Transfers**
In order to restrict SFTP access to one directory, first, we have to make sure the directory complies with the SSH server’s permissions requirements, which are very particular.

Specifically, the directory itself and all directories above it in the filesystem tree must be owned by root and not writable by anyone else. Consequently, it’s not possible to simply give restricted access to a user’s home directory because home directories are owned by the user, not root.

Here, we’ll create and use **/var/sftp/myfolder/data/** as the target upload directory. **/var/sftp/myfolder** will be owned by root and will not be writable by other users. 
The subdirectory **/var/sftp/myfolder/data/** will be owned by **sftp_user**(which we created earlier), so that the user will be able to upload files to it.

First, create the directories.

```
$ sudo mkdir -p /var/sftp/myfolder/data/
```
Set the owner of /var/sftp/myfolder to root.

```
$ sudo chown root:root /var/sftp/myfolder
```
Give root write permissions to the same directory, and give other users only read and execute rights.

```
$ sudo chmod 755 /var/sftp/myfolder
```
Change the ownership on the uploads directory to sftp_user.

```
$ sudo chown sftp_user:sftp_user /var/sftp/myfolder/data/
```
Here we have done the directory restriction.
So, our sftp_user will use only **/data/** from the below path. sftp_user never change the directory.
**/var/sftp/myfolder/data/** 

**Step 3：Genrate RSA public and Private Key**
SSH key pairs can be used to authenticate a client to a server. The client creates a key pair and then uploads the public key to any remote server it wishes to access. This is placed in a file called **authorized_keys** within the ~/.ssh directory in the user account’s home directory on the remote server.

If you’re under linuz based OS, you can use ssh-keygen to generate keys. Otherwise, for Windows, you can use PuTTY, you can refer this article to know how to process the generating.
[PuTTYgen - Key Generator for PuTTY on Windows]
(https://www.ssh.com/ssh/putty/windows/puttygen)

```
$ ssh-keygen -t rsa
```

Immediately after running the ssh-keygen command, you'll be asked to enter a couple of values, including:
**The file** in which to save the private key (normally id_rsa). Just press Enter to accept the default value.
**The passphrase** - this is a phrase that functions just like a password (except that it's supposed to be much longer) and is used to protect your private key file. You'll need it later, so make sure it's a phrase you can easily recall.
As soon as you've entered the passphrase twice, ssh-keygen will generate your private (id_rsa) and public (id_rsa.pub) key files.

Then, copy the public key to the server within the ~/.ssh folder (corresponding to which user will be authenticated).

```
$ cd /home/sftp_user/ 
$ mkdir .ssh # In case of no .ssh folder inside
$ ls -a
...
.ssh
...
$ cd .ssh
$ touch authorized_keys
$ echo <your_public_key> >> authorized_keys
```

**Step 4：Change the permissions and owner**

```
$ cd /home/sftp_user/
$ chmod 700 .ssh 
$ chown sftp_user:sftp_user .ssh 
$ cd .ssh
$ chmod 600 authorized_keys
$ chown sftp_user:sftp_user authorized_keys
```

**Step 5：sshd_config Settings**
In this step, we’ll modify the SSH server configuration to disallow terminal access for sftp_user but allow file transfer access.

Open the SSH server configuration file by using the below command.

```
$ sudo nano /etc/ssh/sshd_config
```
or you can do by↓.

```
$ sudo vi /etc/ssh/sshd_config
```

Scroll to the very bottom of the file and append the following configuration snippet:

**/etc/ssh/sshd_config**
. . .

```
Port <your_port_number>

Match User sftp_user
ForceCommand internal-sftp
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no
ChrootDirectory /var/sftp/myfolder
PermitTunnel no
AllowAgentForwarding no
AllowTcpForwarding no
X11Forwarding no
```
Then save and close the file.[Press **:wq + enter**]

In the **Match User [user_name]**, you can also use the group by using the below command.
**Match Group [sftp_group]**
NOTE: You need to create a new group called, sftp_group.

**Step 6：Restart the service**
To apply the configuration changes, restart the service.

```
$ sudo systemctl restart sshd
```
or

```
$ sudo /etc/init.d/ssh restart
```
You have now configured the SSH server to restrict access to file transfer only for sftp_user. 

Below step may be not required, but if you not able to connect successfully, then please whitelist your IP for the particular port.
**Step 7：Open your sftp port in AWS-EC2 security group**
If you are using AWS-EC2 instance, then you need to open the port here.
**Login into your AWS account.**
↓
**Go to the services and then click on EC2 menu -> Running Instances.**
↓
**Go to the your instance.**
↓
**Open the Security groups.**
↓
**In the Inbound rules, Edit inbound rules**
↓
**Please do the following settings**
**1.Type** = Custom TCP
**2.Protocol** = TCP
**3.Port range** = your_port(same as set in sshd_config file)
**4.Source** = You need to whitelist the IP here, if you do not want then set anywhere.
**5.Description - optional** = You can mention here some useful info.

The last step is testing the configuration to make sure it works as intended.

**Step 8：Verifying the Configuration**
You can verify it within your terminal and as well as third-party software, such as WinSCP.
Please don't forgot to use your private key and passphrase(if you set).

**Conclusion**
You’ve restricted a user to SFTP-only access by public key and also to a single directory on a server without full shell access.

I hope this article helped you in setting up SFTP server on your server.
If you encountered any error then please share it with me.

If this guide has been helpful to you and your team please share it with others!

**Thanks & Best Regards,
Alok Rawat**