Anasayfa / Cyber Security / Securely Transfer Files Over SFTP on Linux: A Beginner’s Guide

Securely Transfer Files Over SFTP on Linux: A Beginner’s Guide

SFTP Linux

Transferring files between computers is a daily task for developers, system administrators, and anyone who works with data. While FTP used to be the go‑to protocol, its lack of encryption makes it unsuitable for modern security standards. SFTP (SSH File Transfer Protocol) solves that problem by tunneling file operations through an encrypted SSH connection. In this guide we’ll walk you through setting up a secure SFTP server on a Linux machine, configuring client access, and troubleshooting common issues—all in a conversational, beginner‑friendly tone.

What You’ll Need

  • A Linux distribution (Ubuntu, Debian, CentOS, Fedora, etc.) with sudo privileges.
  • Access to the command line (terminal or SSH session).
  • A non‑root user account that will act as the SFTP client.
  • Basic familiarity with Linux file permissions and the ssh command.
  • Optional: A graphical SFTP client like FileZilla or WinSCP for those who prefer a UI.

Step 1: Install the OpenSSH Server

The backbone of SFTP is the OpenSSH server package. Most Linux distributions ship it by default, but it’s worth confirming it’s installed and up to date. Open a terminal and run:

sudo apt update && sudo apt install -y openssh-server   # Debian/Ubuntu
sudo yum install -y openssh-server # CentOS/RHEL 7
sudo dnf install -y openssh-server # Fedora/CentOS 8+

After installation, start and enable the service so it launches on boot:

sudo systemctl enable sshd
sudo systemctl start sshd

Verify the daemon is listening on port 22 (the default SFTP port) with:

sudo ss -tlnp | grep sshd

You should see a line similar to LISTEN 0 128 *:22 *:* users:("root",pid=1234,fd=3).

Step 2: Create a Dedicated SFTP User Group

For security, it’s best to isolate SFTP users from regular shell users. Create a group that will own the SFTP chroot directory:

sudo groupadd sftpusers

Now create the actual user account that will log in via SFTP. Replace john with your preferred username:

sudo useradd -m -G sftpusers -s /usr/sbin/nologin john
sudo passwd john

The -s /usr/sbin/nologin flag prevents the user from obtaining an interactive shell, limiting them to SFTP only.

Step 3: Configure the SSH Daemon for Chrooted SFTP

Open the SSH configuration file for editing:

sudo nano /etc/ssh/sshd_config

Scroll to the end of the file and add the following block. It tells SSH to force members of sftpusers into a restricted directory (chroot) and to use the internal‑sftp subsystem.

Match Group sftpusers
ChrootDirectory /sftp/%u
ForceCommand internal-sftp
X11Forwarding no
AllowTcpForwarding no

Explanation of each directive:

  • Match Group sftpusers: Apply the following rules only to users in the sftpusers group.
  • ChrootDirectory /sftp/%u: After login, the user is jailed to /sftp/username. The %u token expands to the actual username.
  • ForceCommand internal-sftp: Prevents any SSH shell access; only SFTP commands are allowed.
  • X11Forwarding no and AllowTcpForwarding no: Additional hardening to close unnecessary tunnels.

Save the file (Ctrl+O, Enter, Ctrl+X in nano) and restart the SSH service:

sudo systemctl restart sshd

Step 4: Set Up the Chroot Directory Structure

The chroot directory must be owned by root and not writable by any other user. Create the base directory and set proper permissions:

sudo mkdir -p /sftp/john/uploads
sudo chown root:root /sftp
sudo chmod 755 /sftp

Now give the user ownership of the uploads subdirectory where they will actually place files:

sudo chown john:sftpusers /sftp/john/uploads
sudo chmod 750 /sftp/john/uploads

If you plan to host multiple users, you can automate the directory creation with a small script:

for u in alice bob carol; do
sudo mkdir -p /sftp/$u/uploads
sudo chown root:root /sftp/$u
sudo chmod 755 /sftp/$u
sudo chown $u:sftpusers /sftp/$u/uploads
sudo chmod 750 /sftp/$u/uploads
done

Step 5: Test the SFTP Connection Locally

From the same machine, use the sftp client to verify everything works:

sftp john@localhost

You’ll be prompted for the password you set earlier. After a successful login you should see a prompt that looks like:

john@localhost:/upload>

Notice the leading slash reflects the chrooted path (/upload is relative to /sftp/john). Try uploading a test file:

put /etc/hosts
ls

You should see hosts listed. Exit with bye or exit.

Step 6: Connect from a Remote Machine

From any other computer with SSH/SFTP capability, run:

sftp [email protected]

If you’re behind a firewall, ensure port 22 (or whichever custom port you chose) is open. For added security you can change the default port by editing /etc/ssh/sshd_config (add Port 2222) and updating your firewall rules accordingly.

Step 7: Harden the Server (Optional but Recommended)

Even though SFTP is encrypted, hardening your SSH daemon reduces the attack surface:

  • Disable password authentication and rely on SSH keys. Add PubkeyAuthentication yes and PasswordAuthentication no to sshd_config. Then generate a key pair on the client (ssh-keygen -t ed25519) and copy the public key to /home/john/.ssh/authorized_keys.
  • Limit login attempts using fail2ban or the built‑in MaxAuthTries 3 directive.
  • Use a firewall (ufw, firewalld, iptables) to allow only trusted IP ranges.
  • Enable logging for audit trails. Set LogLevel VERBOSE in sshd_config and monitor /var/log/auth.log (or /var/log/secure on RHEL).

After making changes, always restart the daemon:

sudo systemctl restart sshd

Common Mistakes to Avoid

Even a seasoned admin can slip up when configuring SFTP. Here are the most frequent pitfalls and how to fix them:

  • Incorrect ownership of the chroot directory. The top‑level /sftp/username must be owned by root:root and have permissions no more permissive than 755. If it’s owned by the user, SSH will refuse the login with “Bad owner or permissions on chroot directory”.
  • Leaving /usr/sbin/nologin out of the user definition. Without this, the user could obtain a shell, defeating the purpose of a restricted SFTP account.
  • Forgetting to restart the SSH service. Changes in sshd_config don’t take effect until you run systemctl restart sshd.
  • Using the same port for both SSH and SFTP without adjusting firewalls. If you change the SSH port, remember to update any client configurations and firewall rules.
  • Not creating a writable subdirectory. Users need a directory inside the chroot that they own; otherwise they’ll be able to log in but won’t be able to upload files.

Tips and Tricks

These extra tips will make your SFTP workflow smoother:

  • Batch uploads. Use sftp -b batch.txt user@host where batch.txt contains a list of put and get commands.
  • Recursive directory sync. The rsync -e ssh command works over SFTP‑compatible SSH, allowing efficient incremental transfers.
  • Graphical client shortcuts. In FileZilla, set the protocol to “SFTP – SSH File Transfer Protocol” and store the private key under “Edit → Settings → Connection → SFTP”.
  • Logging per user. Add Subsystem sftp internal-sftp -l INFO to increase verbosity for troubleshooting.
  • Automated backups. Schedule a cron job that runs tar -czf /backup/sftp_$(date +%F).tar.gz /sftp to keep snapshots of uploaded data.

Frequently Asked Questions

Is SFTP the same as FTPS?

No. SFTP runs over SSH and encrypts both commands and data in a single channel. FTPS is FTP over TLS/SSL, which uses separate control and data connections and requires additional firewall configuration.

Can I use SFTP with a non‑standard SSH port?

Absolutely. Change the Port line in /etc/ssh/sshd_config, restart the daemon, and then connect with sftp -P 2222 user@host (or configure the port in your GUI client).

What if I need to give a user read‑only access?

Set the upload directory permissions to chmod 550 for the group and avoid giving write rights. You can also use ForceCommand internal-sftp -d /readonly and point the user’s chroot to a directory that only contains files they may download.

Conclusion

Secure file transfer is a cornerstone of modern IT operations, and SFTP provides a robust, encrypted alternative to legacy FTP. By following this step‑by‑step guide you’ve installed and hardened an OpenSSH server, created a chrooted SFTP user, and learned how to troubleshoot the most common issues. Remember to keep your SSH daemon updated, enforce key‑based authentication, and regularly audit logs. With these practices in place, you can confidently move sensitive files across the network without exposing them to eavesdroppers. Happy transferring!

Photo by Gabriel Heinzer on Unsplash

Etiketlendi: