Setup an SFTP Server on CentOS

 
 

Set up an SFTP server on CentOS is our next tutorial where we will guide you as always, step by step, how to build from scratch such a server. We all agree that an SFTP server can be quite handy or sometimes a must if for example one or more applications within our stack requires file transfer between different processing steps or maybe for backups. In this tutorial we will learn how to build an SFTP server on CentOS 7 and OpenSSH 7.4 and also providing you two authentication solutions, first one being based on using basic password authentication and the second one by using SSH keys in order to get access to your files. You can easily manage these files using any (S)FTP clients, directly via your application or maybe via cron jobs, is up to you. We must say that this SFTP solution for sharing and managing files can be also applied even for lower or higher versions as long the principle stays the same in terms of linux user management and also SSH configuration. Before we start let’s make clear one thing, STPF doesn’t mean Secure FTP, it means FTP over SSH and nothing more, we have highlighted that just to avoid any confusion about this term.

Table of contents

Scenario
Create folders for SFTP storage
Create linux users
Set up credentials for SFTP users
Get SSH Private Keys
Remove SSH Private Keys
Change folders permission
Create symlinks to storage folders
SSH daemon configuration
Testing SFTP solution
Troubleshooting

Scenario

Assuming that we have some external / internal applications that needs to get some CSV files exported by another internal / external application or maybe by a SQL server and we need to provide a simple way to facilitate this file exchange process then a simple, easy and fast solution will be to build an SFTP server. We have a CentOS 7 server already up and running and now we’ll have to configure it in order to accept external connections by using a basic password authentication or by using SSH keys.

Create folders for SFTP storage

Our first step is to make sure that we have properly anticipated and resized the overall space that will be used by these files and also we have a proper folder structure in place for multiple users. In this example we will create three different folders for three different applications, you can create only one or how many do you need, we will resume to only three and we will create these folder using just one command line:


$ mkdir -p /mnt/{first,second,third}_sftp_folder

A successful ls -l output should look similar to this one:


$ ls -l
...
drwxr-xr-x   2 dummyuser   dummyuser          6 Nov 23 06:36 first_sftp_folder
drwxr-xr-x   2 dummyuser   dummyuser          6 Nov 23 06:36 second_sftp_folder
drwxr-xr-x   2 dummyuser   dummyuser          6 Nov 23 06:36 third_sftp_folder

As you can see currently only dummyuser has permissions to these three folders but we will cover this later on change folders permission step.

Create linux users

On this particular step we have to create three different linux users, each one being later assigned to use one of our folder that we have previously created. So lets start this step by creating three users like shown in the example below assuming that you are logged in as root user or you are using sudo command in front of useradd to impersonate root account:


# useradd first_sftp_user
# useradd second_sftp_user
# useradd third_sftp_user

If everything went fine and no errors were shown then we can perform a quick check to see if our SFTP users were created by running once again a simple ls -l command on our terminal window:


$ ls -l
...
drwx------   2 first_sftp_user    first_sftp_user      59 Nov 23 06:50 first_sftp_user
drwx------   2 second_sftp_user   second_sftp_user     59 Nov 23 06:50 second_sftp_user
drwx------   2 third_sftp_user    third_sftp_user      59 Nov 23 06:50 third_sftp_user

If you get a similar console output assuming that same users were used then we can move to our next step where we have to create some credentials for these SFTP users.

Set up credentials for SFTP users

As we said in the beginning of our short tutorial we will be providing two authentication methods for SFTP clients / SFTP users. First authentication method will be based on password, this is also called basic authentication. So lets start by setting up the password for each users that we have previously created, assuming that you are using root user please follow the next lines:


# passwd first_sftp_user

Once passwd command has been invoked you should get a similar output like the one shown below. Please note that the password won’t be displayed, both fields New password: and Retype new password: will remain empty but the password will be saved and you will get a confirmation message if the password has been correctly typed or not, please bear in mind that you need need to use a password containing minimum eight characters.


Changing password for user first_sftp_user.
New password:
Retype new password:
passwd: all authentication tokens updated successfully.

If the password for the first user has been successfully set then please repeat this step for the other two SFTP users using the same passwd command followed by the username.

The second authentication option is based on SSH Keys as we said previously but this time we will start by impersonating each user using su command before running ssh-keygen command. So lets start now to create SSH Keys for SFTP users, assuming once again that we are root user as show here:


# su first_sftp_user
$ ssh-keygen

On the next screen you will be prompted to set a location where the keys to be stored and also to use a passphrase for these keys. We will go with the defaults by simply pressing Enter key until ssh-keygen generates both SSH Keys for us, private (id_rsa) and public (id_rsa.pub) keys and finally we get back control over the terminal window:


Generating public/private rsa key pair.
Enter file in which to save the key (/home/first_sftp_user/.ssh/id_rsa):
Created directory '/home/first_sftp_user/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/first_sftp_user/.ssh/id_rsa.
Your public key has been saved in /home/first_sftp_user/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:eboy8rBhu0D1z8abQcyLtnLXLEyo1COM1Xj25SAAyfU first_sftp_user@dummyhost
The key's randomart image is:
+---[RSA 2048]----+
| ..+.            |
|  o ..           |
|    .+E          |
|   .o.=o...      |
|  .+ +.+S+.      |
| .. + +*o+.      |
|  ..+oo+Oo       |
|   o+*+o+=o      |
|    +*o++.       |
+----[SHA256]-----+

As we have said in this tutorial we are using CentOS 7 and sshd by default is configured to use authorized_keys for public keys instead of id_rsa.pub so we need to make sure that we have such a file first, the easiest way to get this done is to simply run a copy command like shown below:


$ cp id_rsa.pub authorized_keys

Now we are done with our first user, we have managed to set up the SSH Keys for our first SFTP user and we have to close the session or to stop impersonating first_sftp_user, lets type to our terminal window the next command:


$ exit

Repeat the steps above from second authentication option for each of the two remaining users in order to set up their SSH Keys as well.

Get SSH Private Keys

On the above steps we have managed to generate SSH Keys for each SFTP Users, private SSH keys and also public SSH keys. From a security prospective private keys should not be stored on the servers and we need to make sure that these remains private so we will have to copy these private keys and to remove them from the server. Only public SSH keys should reside on the server, so lets make sure that we’re doing the right thing by removing all these private keys:


$ cat /home/fisrt_sftp_user/.ssh/id_rsa

Copy the output to your machine using a text editor and save it for example like private_key_first_sftp_user:


-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEA7C06Whm7CE++ihgMXL5ufCNw9MwuqRZCLnXg8hJK2ktgYw+1
GGGsKxNMjJjmKCawzRQhwDVa+R9e4hf1d0ZQDRK6hns6jN4nHPPVsgiHHXSSdGyj
BI0u3l0ZARy8oNMpiOyu4unH+nG+lsbidASoshW2dWtZ/69dOjnAa8tECm61VXoY
y5w1ZQJzXeVc9wfSYrrpaze1aKia8XuzPUlj1t5dUEIZ4Yvp6vEqZe6uoC4DlXun
n/KE8npwUJubsJGogsf0HQcI1ZxpeP5HdQMqaOzoq3FJWIQWPdaaZHqXMZtmhEQs
qMaZXLHhpw+NZY5LM3YZtdCcrReiqldwaeMd2wIDAQABAoIBACkGUjSEc7Cl6Xsj
YkJZ8ec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MGlbPbpRO76Z4A7h1TkeasXs+OoeNO1/Ah/l7w88BRn7k7v7gcuRhfwg+
V/IpzrRt73LU1mMDQceS+zrVh+FA6J1oZMm6SDsTawbxcyVkE9FIZA==
-----END RSA PRIVATE KEY-----

Please repeat this step for each of the user and make sure that all SSH private keys were stored locally on your machine or in a safe place as we will need these keys later.

Remove SSH Private Keys

As you may already know by having SSH Private Keys stored on remote servers poses a high security risk, we would like to avoid that and we should immediately remove these, a good example is listed below:


$ rm -f /home/{first,second,third}_sftp_user/.ssh/id_rsa

Change folders permission

Having now pretty much everything in place is time to set up folders permission, basically a folder for each configured users, each one having full access to place or remove any files within its own folder, so lets set up the permissions like shown in the example below:


$ chown -R first_sftp_user:first_sftp_user first_sftp_folder/
$ chown -R second_sftp_user:second_sftp_user second_sftp_folder/
$ chown -R third_sftp_user:third_sftp_user third_sftp_folder/

Please not that -R argument is used for recursive ownership, so any existing subfolder or files within first_sftp_folder for example will get the same permissions as the parent which in this case is first_sftp_folder. Once all permissions are in place we can move to the next step where we have to configure SSH Daemon.

For simplicity we can also create some symlinks for each user within their home folders, this is purely to ease the pain of changing the folders using cd command every time a user gets to our SFTP server via SSH.


$ ln -s /mnt/first_sftp_folder/ /home/first_sftp_user/sftp-files
$ ln -s /mnt/second_sftp_folder/ /home/second_sftp_user/sftp-files
$ ln -s /mnt/third_sftp_folder/ /home/third_sftp_user/sftp-files

SSH daemon configuration

Finally we have managed to get to the last step of our Set up an SFTP Server on CentOS tutorial, this is really the last configuration step that we have to perform in order to get a fully functional SFTP Server. Here, on this step we need purely to instruct SSH Daemon to allow and redirect each individual user to it’s own storage folder, so please let type in our terminal window next command:


$ vi /etc/ssh/sshd_config

Go to the end of the file (Shift + G for vi users) and add the next lines right after the last line:


....

Match User first_sftp_user
ForceCommand internal-sftp
PasswordAuthentication yes
ChrootDirectory /mnt/first_sftp_folder
PermitTunnel no
AllowAgentForwarding no
AllowTcpForwarding no
X11Forwarding no

Match User second_sftp_user
ForceCommand internal-sftp
PasswordAuthentication yes
ChrootDirectory /mnt/second_sftp_folder
PermitTunnel no
AllowAgentForwarding no
AllowTcpForwarding no
X11Forwarding no

Match User third_sftp_user
ForceCommand internal-sftp
PasswordAuthentication yes
ChrootDirectory /mnt/third_sftp_folder
PermitTunnel no
AllowAgentForwarding no
AllowTcpForwarding no
X11Forwarding no

Testing SFTP solution

We’ve managed so far to configure our CentOS 7 server for SFTP by creating storage folders, users and their credentials, setting up permissions and amending SSH configuration file, quite a few steps though, but now it’s time to test our solution.

For testing our SFTP server we will be using two different methods, for the first method we will be using password authentication and for the second method we will be using authentication based on private keys.

So on our first SSH test we will be using password authentication, lets have a look:


$ ssh first_sftp_user@dummyhost
first_sftp_user@dummyhost's password:
Last login: Fri Nov 23 15:08:44 2018 from 10.0.0.10
[first_sftp_user@dummyhost ~]$

As you can see we were able to log in successfully to our SFTP server, now the second authentication method using once again a SSH connection but this time we will use private_key_first_sftp_user file where our private key resides, key that’s been generate previously on set up credentials for sftp users step:


$ ssh -i "private_key_first_sftp_user" first_sftp_user@dummyhost
Last login: Fri Nov 23 16:57:42 2018 from 10.0.0.10
[first_sftp_user@dummyhost ~]$

We have just proved that both SSH authentication methods are valid, we were able to log in onto our SFTP server.

Troubleshooting

If you can’t connect to SFTP server please make sure that the firewall accepts incoming connections on port 22, as we have said SFTP uses FTP over SSH. A quick test can be performed using telnet command as show below being using you local machine or even using the remote server that you are trying to connect from:


$ telnet sftphost 22

If nothing comes back please check firewalld service that comes by default with CentOS 7 or iptables that comes with older CentOS versions.

Video

No video posted for this page.

Screenshots

No screenshots posted for this page.

Source code

No code posted for this page.

About this page

Article
Setup an SFTP Server on CentOS
Author
Category
Published
08/11/2018
Updated
14/12/2018
Tags

Share this page

If you found this page useful please share it with your friends or colleagues.