Setting Up SFTP Users on Linux

Published August 15, 2024

This article shows how to create and set up a new SFTP user in Linux. You'll learn to add a user account, create a dedicated SFTP directory, and set up SSH for secure SFTP access. The article also covers important security steps, like setting up a chroot jail and limiting user actions to SFTP only.

Creating a New SFTP User

Adding a User Account

To create a new SFTP user in Linux:

  1. Open a terminal or connect to your Linux server via SSH.

  2. Use the adduser command to create a new user account:

    sudo adduser sftpuser

    Replace "sftpuser" with your preferred username.

  3. Set a strong password for the new user when prompted.

  4. The system will ask for additional user information. You can press Enter to skip these fields or fill them out as needed.

Tip: Choose a Strong Username

When creating an SFTP user, choose a username that's not easily guessable. Avoid common names like "admin," "user," or "sftp." Instead, use a combination of letters, numbers, and underscores to create a unique username that's harder for potential attackers to guess.

Command Syntax and Options

Command Description
sudo Run the command with administrative privileges
adduser The command to add a new user
sftpuser The username for the new account (replace with your chosen name)

Additional Options for adduser

Option Description
--disabled-password Create the user without a password (useful for key-based authentication)
--gecos "" Skip the user information prompts
--home /path/to/home Specify a custom home directory

Example with options:

sudo adduser --disabled-password --gecos "" --home /sftp/sftpuser sftpuser

Setting Up User Directory

After creating the user account, set up a dedicated SFTP directory:

  1. Create the SFTP root directory:

    sudo mkdir -p /home/sftpuser/sftp
  2. Create a directory for file transfers within the SFTP root:

    sudo mkdir /home/sftpuser/sftp/uploads
  3. Set the correct ownership for the directories:

    sudo chown root:root /home/sftpuser/sftp
    sudo chown sftpuser:sftpuser /home/sftpuser/sftp/uploads
  4. Set the appropriate permissions:

    sudo chmod 755 /home/sftpuser/sftp
    sudo chmod 775 /home/sftpuser/sftp/uploads

These settings allow the SFTP user to access and modify files in the uploads directory while restricting access to the parent directory.

Configuring SSH for SFTP

To restrict the user to SFTP access only:

  1. Edit the SSH configuration file:

    sudo nano /etc/ssh/sshd_config
  2. Add the following lines at the end of the file:

    Match User sftpuser
       ForceCommand internal-sftp
       PasswordAuthentication yes
       ChrootDirectory /home/sftpuser/sftp
       PermitTunnel no
       AllowAgentForwarding no
       AllowTcpForwarding no
       X11Forwarding no
  3. Save the file and exit the editor.

  4. Restart the SSH service to apply the changes:

    sudo systemctl restart sshd

This configuration restricts the user to SFTP access only and sets up a chroot environment for added security.

Configuring SSH for SFTP

Modifying SSH Configuration

To set up SSH for SFTP access, you need to change the SSH server configuration file. This file is usually at /etc/ssh/sshd_config. Follow these steps to edit the configuration:

  1. Open the SSH configuration file with a text editor using root privileges:

    sudo nano /etc/ssh/sshd_config
  2. Go to the end of the file and add these lines:

    Match User sftpuser
       ForceCommand internal-sftp
       PasswordAuthentication yes
       ChrootDirectory /home/sftpuser/sftp
       PermitTunnel no
       AllowAgentForwarding no
       AllowTcpForwarding no
       X11Forwarding no

    Replace "sftpuser" with the username you made earlier.

  3. Save the changes and exit the text editor.

This table explains the main settings for SFTP access:

Setting Value Description
ForceCommand internal-sftp Uses the internal SFTP server, stopping SSH shell access
PasswordAuthentication yes Allows password-based login for the SFTP user
ChrootDirectory /home/sftpuser/sftp Sets the root folder for the SFTP user, limiting their access
PermitTunnel no Turns off SSH tunneling for the user
AllowAgentForwarding no Stops SSH agent forwarding
AllowTcpForwarding no Turns off TCP forwarding
X11Forwarding no Turns off X11 forwarding

Tip: Backup Your Configuration

Before making changes to the SSH configuration file, it's a good practice to create a backup. You can do this by running:

sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup

This allows you to easily revert changes if needed.

Restricting User Access

Setting up a chroot jail and limiting user actions to SFTP only are key steps in securing your SFTP setup. Here's how to do this:

  1. Setting up chroot jail:

    The ChrootDirectory option in the SSH configuration creates a chroot jail for the SFTP user. This keeps the user in a specific folder, stopping access to other parts of the file system.

    Set the right ownership and permissions for the chroot folder and its parent:

    sudo chown root:root /home/sftpuser
    sudo chmod 755 /home/sftpuser
    sudo chown root:root /home/sftpuser/sftp
    sudo chmod 755 /home/sftpuser/sftp
  2. Limiting user actions to SFTP only:

    The ForceCommand internal-sftp option uses the internal SFTP server, stopping the user from using a normal SSH shell.

    These settings turn off various SSH features, further limiting the user's actions to SFTP operations only.

  3. Apply the new configuration:

    After making these changes, restart the SSH service:

    sudo systemctl restart sshd

Creating a Writable Directory

To let the SFTP user upload files, you need to make a writable folder within the chroot jail:

  1. Make a new folder:

    sudo mkdir /home/sftpuser/sftp/uploads
  2. Set the ownership and permissions:

    sudo chown sftpuser:sftpuser /home/sftpuser/sftp/uploads
    sudo chmod 755 /home/sftpuser/sftp/uploads

This setup creates a secure environment where the SFTP user can only transfer files within their assigned folder, without access to other parts of the system or extra SSH features.

Example: Setting Up Multiple SFTP Users

If you need to set up multiple SFTP users with different access permissions, you can create a group for SFTP users and modify the SSH configuration accordingly:

  1. Create an SFTP group:

    sudo groupadd sftpusers
  2. Add users to the group:

    sudo usermod -aG sftpusers user1
    sudo usermod -aG sftpusers user2
  3. Modify the SSH configuration to apply settings to all users in the group:

    Match Group sftpusers
       ForceCommand internal-sftp
       PasswordAuthentication yes
       ChrootDirectory /home/%u/sftp
       PermitTunnel no
       AllowAgentForwarding no
       AllowTcpForwarding no
       X11Forwarding no

This setup allows you to manage multiple SFTP users more efficiently.

Testing the SFTP Connection

Using Command Line

To test the SFTP connection from the command line:

  1. Open a terminal on your local machine.

  2. Use this command to connect to the SFTP server:

    sftp sftpuser@your_server_ip

    Replace "sftpuser" with your SFTP username and "your_server_ip" with your server's IP address or domain name.

  3. Enter your password when prompted.

  4. If the connection works, you'll see an sftp prompt.

Basic SFTP commands for file transfer:

Command Description Example
ls List files and directories ls /home/user
cd directory Change to a different directory cd uploads
put localfile Upload a file from your local machine put document.pdf
get remotefile Download a file from the server get report.xlsx
mkdir directory Create a new directory mkdir new_folder
rm file Remove a file rm oldfile.txt
exit Close the SFTP connection exit

Example usage:

sftp> ls
sftp> cd uploads
sftp> put myfile.txt
sftp> get serverfile.pdf
sftp> exit

Tip: Use Tab Completion

Many SFTP command-line clients support tab completion. Press the Tab key after typing part of a filename or command to auto-complete or see available options. This can save time and reduce typing errors.

Using SFTP Clients

Steps to connect using a graphical SFTP client (using FileZilla as an example):

  1. Download and install FileZilla from the official website.

  2. Open FileZilla and click on "File" > "Site Manager".

  3. Click "New Site" and give it a name.

  4. Enter these details:

    • Host: Your server's IP address or domain name
    • Protocol: SFTP - SSH File Transfer Protocol
    • Logon Type: Normal
    • User: Your SFTP username
    • Password: Your SFTP password
  5. Click "Connect" to start the SFTP connection.

  6. Once connected, you'll see your local files on the left and server files on the right.

  7. To transfer files, drag and drop between the local and remote panes.

Feature Command Line Graphical Client
Learning Curve Steeper Easier for beginners
Speed Faster for experienced users May be slower due to GUI
Automation Easily scriptable Limited automation options
Visual Feedback Text-based Visual file browsing
Remote Editing Requires additional tools Often built-in

Example: Automating SFTP Transfers

For regular file transfers, you can use scripts to automate the process. Here's a simple bash script example:

#!/bin/bash

HOST="your_server_ip"
USER="sftpuser"
PASS="your_password"
REMOTEPATH="/uploads/"
LOCALPATH="/path/to/local/files/"

lftp sftp://$USER:$PASS@$HOST << EOF
cd $REMOTEPATH
mput $LOCALPATH*
bye
EOF

Save this as a .sh file and make it executable with chmod +x scriptname.sh. You can then run it manually or set up a cron job for scheduled transfers.

Troubleshooting SFTP Connections

If you have issues while connecting to the SFTP server, try these steps:

  1. Check your network connection.
  2. Verify the server's IP address or hostname.
  3. Confirm your username and password are correct.
  4. Make sure the SFTP service is running on the server.
  5. Check if any firewalls are blocking the SFTP port (usually 22).

For more detailed diagnostics, use the verbose mode in command-line SFTP:

sftp -v sftpuser@your_server_ip

This setup allows for both command-line and graphical SFTP access, providing options for different user preferences and automation needs. The choice between command-line and graphical clients depends on your comfort level, the frequency of transfers, and the need for automation.

Tip: Use SSH Key Authentication

For enhanced security, consider using SSH key authentication instead of password-based login. Generate an SSH key pair, add the public key to the server's authorized_keys file, and configure your SFTP client to use the private key. This method is more secure and can simplify the login process, especially for automated scripts.

Troubleshooting Common Issues

When setting up and using SFTP, you may face various issues. This guide covers common problems and their solutions.

Permission Problems

Permission issues often cause SFTP connection problems. Follow these steps to address them:

  1. Check directory permissions:

    ls -l /home/sftpuser/sftp
    ls -l /home/sftpuser/sftp/uploads

    The sftp directory should be owned by root, and the uploads directory should be owned by the SFTP user.

  2. Fix incorrect permissions:

    sudo chown root:root /home/sftpuser/sftp
    sudo chmod 755 /home/sftpuser/sftp
    sudo chown sftpuser:sftpuser /home/sftpuser/sftp/uploads
    sudo chmod 755 /home/sftpuser/sftp/uploads
  3. Check SELinux settings (if applicable):

    sudo sestatus

    If SELinux is enabled, set the correct context:

    sudo chcon -Rt ssh_home_t /home/sftpuser/sftp

Tip: Verify File Ownership

Use the ls -la command to check file ownership and permissions in detail. This command shows hidden files and provides a comprehensive view of the directory structure:

ls -la /home/sftpuser/sftp

Expected Directory Permissions

Directory Owner Group Permissions
/home/sftpuser/sftp root root 755
/home/sftpuser/sftp/uploads sftpuser sftpuser 755

Connection Errors

If you're having connection issues:

  1. Verify the SSH service status:

    sudo systemctl status sshd
  2. Check if the correct port is open (usually 22):

    sudo ss -tlnp | grep ssh
  3. Test the connection using verbose mode:

    sftp -v sftpuser@your_server_ip
  4. Check for firewall issues:

    sudo ufw status

    If the firewall is active, allow port 22:

    sudo ufw allow 22/tcp

Common Connection Error Causes

Error Possible Cause Solution
Connection refused SSH service not running Start SSH service
Connection timed out Firewall blocking port Allow port 22 in firewall
Permission denied Incorrect credentials or permissions Verify username/password and file permissions
Host key verification failed Server's host key changed Update known_hosts file

Enabling Detailed SSH Logging

  1. Edit /etc/ssh/sshd_config:

    LogLevel VERBOSE
    SyslogFacility AUTH
  2. Restart the SSH service:

    sudo systemctl restart sshd

More Troubleshooting Tips

  1. Check SFTP server configuration:

    sudo grep "Subsystem sftp" /etc/ssh/sshd_config
  2. Verify user account status:

    sudo passwd -S sftpuser
  3. Test SFTP connection with a different client to isolate client-specific issues.

  4. Use packet capture tools like tcpdump to analyze network traffic if the problem persists:

    sudo tcpdump -i any port 22 -vv

Example: Analyzing SSH Connection Attempts

To monitor SSH connection attempts in real-time, use the following command:

sudo tail -f /var/log/auth.log | grep sshd

This will display live SSH connection attempts, helping you identify potential issues or unauthorized access attempts.