In this post I am going to outline the steps I took to create an SFTP server with OpenSSH. My SFTP server had the following characteristics:
- Each SFTP user is chroot’ed into their own private directory.
- Each chroot has 2 levels: a private, read-only directory and the user’s home directory where the user can upload files.
- Users do not have shell access.
- Users can authenticate via password or public rsa key.
The resulting structure looks like:
user1/ <- User with public key auth
user2/ <- User with password auth
Note: I put all of my SFTP chroots into a single directory, I chose “/var/sftp” but you are free to use something else. Also this post assumes that SELinux is disabled, this was fine for my use case but it is really not ideal. Perhaps in a future post I will add instructions for making this work with SELinux.
Create a Group for SFTP Users
Create a group called “sftpusers”, all SFTP users that will be chrooted will use this group. You are free to choose a name other than sftpusers.
# groupadd sftpusers
Update SSHD Config
Next, make the following changes to /etc/ssh/sshd_config.
Replace the line:
Subsystem sftp /usr/libexec/openssh/sftp-server
Subsystem sftp internal-sftp
Match Group sftpusers
This configuration will force all users with the sftpusers group to be chrooted /var/sftp/<username>
You will need to reload the sshd configuration for this change to take effect:
# service sshd reload
Create a user
Create the user:
# useradd -M -g sftpusers -d /upload -s /sbin/nologin myuser
Create the user’s writable home directory:
# mkdir -p /var/sftp/myuser/upload
Make them the owner and give them write permissions:
# chown myuser:sftpusers /var/sftp/myuser/upload/
# chmod o+w /var/sftp/myuser/upload/
If you are adding a lot of SFTP accounts, you will probably want to script these steps.
If you want password authentication for this user, create their password now:
# passwd myuser
Now you can test out the SFTP account, if you want to use public key authentication, continue to the next section:
Public Key Authentication
Create a ssh directory for the user:
# mkdir -p /var/sftp/myuser/.ssh
# chmod 700 /var/sftp/myuser/.ssh
Add the public key to “”/var/sftp/myuser/.ssh/authorized_keys” and set the correct permissions
# chown -R myuser /var/sftp/myuser/.ssh
# chmod 600 /var/sftp/myuser/.ssh/authorized_keys
We will need to update the sshd_config file again so that the daemon looks in the correct location for .ssh keys
In “/etc/ssh/sshd_config” change this line:
Reload the service again and you should be all set:
# service sshd reload