How to setup an SFTP server with RSA public key authentication mechanism

Why SFTP over FTP? The reason is visualized in its name: “S”, that means Security. Using SSH will employ a client-server model to authenticate two parties and encrypt the data between them. This topic will guide you through how to setup an SFTP authentication mechanism using public key cryptography, the working OS is CentOS version 6.9. Let’s get started!

1. Make sure ssh and ssh-server are installed

user@localhost:$which ssh
/usr/bin/ssh

2. Create a new user and a new group in server

To be easier and clarified in permission managing, we should create a separated group for SFTP and add the corresponding user to the group. To acquire this, using the following groupadd and useradd command under root:

user@localhost:$sudo groupadd sftp_users 
user@localhost:$sudo useradd sftp_user1 
user@localhost:$sudo passwd sftp_user1
user@localhost:$sudo usermod -G sftp_users sftp_user1

3. Generate RSA public and private key

Let’s make a recall how public key cryptography works. This link for detail. In short, 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 *nix based OS, you can use ssh-keygen to generate keys as being described below. Otherwise, for Windows, you can use PuTTY, you can refer this article to know how to process the generating.

user@localhost:$ssh-keygen -t rsa -f sftp_rsa

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

user@localhost:$cd /home/sftp_user1/ 
user@localhost:$mkdir .ssh # In case of no .ssh folder inside
user@localhost:$ls -a
...
.ssh
...
user@localhost:$cd .ssh # <= Copy the public key to this folder

4. Correct permissions and owner

user@localhost:$cd /home/sftp_user1/
user@localhost:$chmod 700 .ssh 
user@localhost:$chown sftp_user1:sftp_user1 .ssh 
user@localhost:$cd .ssh mv sftp_rsa.pub authorized_keys
user@localhost:$chmod 600 authorized_keys
user@localhost:$chown sftp_user1:sftp_user1 authorized_keys

5. Change SSH configurations

user@localhost:$vi /etc/ssh/sshd_config

Check the following configurations (uncomment these settings by removing # if needed):

RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
PasswordAuthentication no

6. Restart the service

 user@localhost:$service sshd restart

Now you can check if it works by using any program that supports SFTP.

Advertisements