Install and setup your SSH

The key of this blog is to deal with the conflict between key-only SSH and password-enabled SFTP.

If you haven't had an available SSH access, set up one first. And we assume you like to disable password logon and use key access only. Otherwise, it would be pretty easy.

Create Unprivileged SFTP User Account

Create a group to assign SFTP user accounts to. Note that this is not necessary as the directories you will be assigning the user may already have specific group assigned to them.

1
  groupadd sftpgroup

Next, create a less privileged account for an SFTP user. Replace the username accordingly;

1
  useradd -M -g sftpgroup -s /usr/sbin/nologin sftpuser

And set up its password via

1
  passwd sftpuser

If your like to create more groups and add the user to them,

1
  usermod -aG NEWGROUP sftpuser

or, change the default group

1
  usermod -g NEWGROUP sftpuser

Restrict SFTP User Access to Directory with Chroot Jail

Open the SSH configuration file for editing;

1
  vim /etc/ssh/sshd_config

Enable SSH in-process SFTP server by commenting (add # at the beginning) the following line:

1
2
  # override default of no subsystems
  Subsystem      sftp    /usr/libexec/openssh/sftp-server

and replacing it as follows;

1
  Subsystem sftp  internal-sftp

Next, add the following configuration options after the line above;

1
2
3
4
5
  Match User sftpuser
    ChrootDirectory /var/sftp/
    ForceCommand internal-sftp
    AllowTcpForwarding no
    X11Forwarding no

⚠️ Warning: The folder /var/sftp/ must be owned by root and root group!

Allow SFTP user to connect via password

The key is to use Match directive in /etc/ssh/sshd_config, e.g.,

1
2
  Match Group sftpgroup
    PasswordAuthentication yes

⚠️ Warning: You must append these lines at the end (this is important!) of your sshd_config.

Then you'll also have to restart the ssh process for this to take effect:

1
  sudo systemctl restart ssh

Done! Enjoy your SFTP via any FTP clients.

A quick test could be:

1
  sftp -P port sftpuser@server_IP