How to set up SFTP server in Linux
How to Set Up SFTP Server in Linux
Secure File Transfer Protocol (SFTP) is an essential tool for secure file transfers over networks. Unlike traditional FTP, SFTP encrypts both authentication credentials and data transfers, making it the preferred choice for organizations prioritizing security. This comprehensive guide will walk you through setting up an SFTP server on Linux, configuring user access, and implementing security best practices.
What is SFTP and Why Use It?
SFTP (SSH File Transfer Protocol) is a secure file transfer protocol that runs over SSH (Secure Shell). It provides several advantages over traditional file transfer methods:
- Encryption: All data transfers are encrypted end-to-end
- Authentication: Supports multiple authentication methods including key-based authentication
- Firewall-friendly: Uses a single port (typically 22)
- Cross-platform compatibility: Works across different operating systems
- Integrated with SSH: Leverages existing SSH infrastructure
Common use cases for SFTP servers include:
- Secure file sharing between remote teams
- Automated backup transfers
- Website file management
- Data exchange with partners or clients
- Secure log file collection
Prerequisites
Before setting up your SFTP server, ensure you have:
- A Linux system (Ubuntu, CentOS, RHEL, or similar)
- Root or sudo access
- Basic command-line knowledge
- Network connectivity
- Firewall configuration access (if applicable)
Installing SSH Server
Most Linux distributions include OpenSSH server, which provides SFTP functionality. Here's how to install and enable it on different systems:
Ubuntu/Debian
```bash
Update package list
sudo apt update
Install OpenSSH server
sudo apt install openssh-server
Enable and start SSH service
sudo systemctl enable ssh
sudo systemctl start ssh
Check service status
sudo systemctl status ssh
```
CentOS/RHEL/Rocky Linux
```bash
Install OpenSSH server
sudo yum install openssh-server
For newer versions, use: sudo dnf install openssh-server
Enable and start SSH service
sudo systemctl enable sshd
sudo systemctl start sshd
Check service status
sudo systemctl status sshd
```
Basic SFTP Server Configuration
The main SSH configuration file is located at `/etc/ssh/sshd_config`. Let's examine the essential settings for SFTP:
```bash
Backup the original configuration
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup
Edit the configuration file
sudo nano /etc/ssh/sshd_config
```
Essential Configuration Parameters
```bash
Basic SSH/SFTP settings
Port 22
Protocol 2
PermitRootLogin no
PasswordAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
SFTP subsystem (usually already present)
Subsystem sftp /usr/lib/openssh/sftp-server
Enable SFTP logging
SyslogFacility AUTH
LogLevel INFO
```
After making changes, restart the SSH service:
```bash
Test configuration syntax
sudo sshd -t
Restart SSH service
sudo systemctl restart sshd
or
sudo systemctl restart ssh
```
Creating SFTP Users and Groups
Creating a Dedicated SFTP Group
It's a best practice to create a dedicated group for SFTP users:
```bash
Create SFTP group
sudo groupadd sftpusers
Verify group creation
grep sftpusers /etc/group
```
Creating SFTP Users
Method 1: Regular User with Shell Access
```bash
Create user with home directory
sudo useradd -m -g sftpusers -s /bin/bash sftpuser1
Set password
sudo passwd sftpuser1
Create SSH directory and set permissions
sudo mkdir -p /home/sftpuser1/.ssh
sudo chmod 700 /home/sftpuser1/.ssh
sudo chown sftpuser1:sftpusers /home/sftpuser1/.ssh
```
Method 2: SFTP-Only User (Recommended)
```bash
Create user without shell access
sudo useradd -m -g sftpusers -s /sbin/nologin sftpuser2
Set password
sudo passwd sftpuser2
Create SSH directory
sudo mkdir -p /home/sftpuser2/.ssh
sudo chmod 700 /home/sftpuser2/.ssh
sudo chown sftpuser2:sftpusers /home/sftpuser2/.ssh
```
Advanced SFTP Configuration
Chroot Configuration
Chrooting restricts users to their home directories, enhancing security:
Add the following to `/etc/ssh/sshd_config`:
```bash
Add at the end of sshd_config
Match Group sftpusers
ChrootDirectory /home/%u
ForceCommand internal-sftp
AllowTcpForwarding no
X11Forwarding no
```
Setting Up Proper Directory Structure
For chroot to work correctly, the home directory must be owned by root:
```bash
Change ownership of user home directory
sudo chown root:root /home/sftpuser1
sudo chmod 755 /home/sftpuser1
Create writable subdirectory
sudo mkdir /home/sftpuser1/uploads
sudo chown sftpuser1:sftpusers /home/sftpuser1/uploads
sudo chmod 755 /home/sftpuser1/uploads
```
Custom SFTP Root Directory
You can create a custom directory structure:
```bash
Create SFTP root directory
sudo mkdir -p /sftp/users
Create user-specific directories
sudo mkdir -p /sftp/users/sftpuser1/uploads
sudo mkdir -p /sftp/users/sftpuser1/downloads
Set ownership and permissions
sudo chown root:root /sftp/users/sftpuser1
sudo chmod 755 /sftp/users/sftpuser1
sudo chown sftpuser1:sftpusers /sftp/users/sftpuser1/uploads
sudo chown sftpuser1:sftpusers /sftp/users/sftpuser1/downloads
```
Update the SSH configuration:
```bash
Match Group sftpusers
ChrootDirectory /sftp/users/%u
ForceCommand internal-sftp
AllowTcpForwarding no
X11Forwarding no
```
Setting Up Key-Based Authentication
Key-based authentication provides enhanced security over password authentication:
Generating SSH Key Pair (Client-side)
```bash
Generate RSA key pair
ssh-keygen -t rsa -b 4096 -f ~/.ssh/sftp_key
Or generate ED25519 key (recommended for better security)
ssh-keygen -t ed25519 -f ~/.ssh/sftp_key_ed25519
```
Installing Public Key on Server
```bash
Copy public key to server (replace with actual key content)
echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDExample..." | sudo tee -a /home/sftpuser1/.ssh/authorized_keys
Set proper permissions
sudo chmod 600 /home/sftpuser1/.ssh/authorized_keys
sudo chown sftpuser1:sftpusers /home/sftpuser1/.ssh/authorized_keys
```
Disabling Password Authentication (Optional)
For maximum security, disable password authentication:
```bash
Edit SSH configuration
sudo nano /etc/ssh/sshd_config
Modify or add these lines
PasswordAuthentication no
PubkeyAuthentication yes
AuthenticationMethods publickey
```
Firewall Configuration
UFW (Ubuntu Firewall)
```bash
Allow SSH/SFTP port
sudo ufw allow 22/tcp
Enable firewall
sudo ufw enable
Check status
sudo ufw status
```
Firewalld (CentOS/RHEL)
```bash
Allow SSH service
sudo firewall-cmd --permanent --add-service=ssh
Reload firewall
sudo firewall-cmd --reload
Check active services
sudo firewall-cmd --list-services
```
Iptables
```bash
Allow SSH/SFTP connections
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT
Save rules (method varies by distribution)
sudo iptables-save > /etc/iptables/rules.v4
```
Testing SFTP Connection
Command-Line Testing
```bash
Test SFTP connection
sftp sftpuser1@your-server-ip
Using specific key file
sftp -i ~/.ssh/sftp_key sftpuser1@your-server-ip
Test with verbose output for troubleshooting
sftp -v sftpuser1@your-server-ip
```
Basic SFTP Commands
Once connected, you can use these commands:
```bash
List remote directory contents
ls
Change remote directory
cd uploads
Upload file
put localfile.txt
Download file
get remotefile.txt
Create remote directory
mkdir newdir
Check current directory
pwd
Exit SFTP session
quit
```
Security Best Practices
1. Change Default SSH Port
```bash
Edit SSH configuration
sudo nano /etc/ssh/sshd_config
Change port (example: 2222)
Port 2222
Restart SSH service
sudo systemctl restart sshd
Update firewall rules
sudo ufw allow 2222/tcp
sudo ufw delete allow 22/tcp
```
2. Implement Connection Limits
```bash
Add to sshd_config
MaxAuthTries 3
MaxSessions 2
ClientAliveInterval 300
ClientAliveCountMax 0
```
3. Use Fail2Ban for Intrusion Prevention
```bash
Install Fail2Ban
sudo apt install fail2ban # Ubuntu/Debian
sudo yum install fail2ban # CentOS/RHEL
Configure SSH jail
sudo nano /etc/fail2ban/jail.local
```
Add the following configuration:
```ini
[sshd]
enabled = true
port = 22
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
findtime = 600
```
4. Regular Security Auditing
```bash
Check active SSH connections
sudo netstat -tnpa | grep ':22'
Review authentication logs
sudo tail -f /var/log/auth.log
Check failed login attempts
sudo grep "Failed password" /var/log/auth.log
```
Monitoring and Logging
Enable Detailed Logging
```bash
Edit SSH configuration
sudo nano /etc/ssh/sshd_config
Add or modify logging settings
SyslogFacility AUTH
LogLevel VERBOSE
```
Log Analysis Commands
```bash
View recent SFTP connections
sudo grep "sftp-server" /var/log/auth.log
Check user login history
sudo last -10
Monitor real-time authentication attempts
sudo tail -f /var/log/auth.log | grep sshd
```
Troubleshooting Common Issues
Issue 1: Permission Denied Errors
Symptoms: Users cannot connect or access files
Solutions:
```bash
Check SSH service status
sudo systemctl status sshd
Verify user exists and has correct shell
grep username /etc/passwd
Check home directory permissions
ls -la /home/username
Verify SSH directory permissions
ls -la /home/username/.ssh
```
Issue 2: Chroot Directory Issues
Symptoms: "subsystem request failed" errors
Solutions:
```bash
Ensure chroot directory is owned by root
sudo chown root:root /home/username
Check directory permissions
sudo chmod 755 /home/username
Verify internal-sftp is specified in config
grep "ForceCommand internal-sftp" /etc/ssh/sshd_config
```
Issue 3: Key Authentication Failures
Symptoms: Key authentication not working
Solutions:
```bash
Check authorized_keys file permissions
sudo chmod 600 /home/username/.ssh/authorized_keys
sudo chown username:username /home/username/.ssh/authorized_keys
Verify SSH directory permissions
sudo chmod 700 /home/username/.ssh
Check for SELinux issues (CentOS/RHEL)
sudo restorecon -R /home/username/.ssh
```
Issue 4: Connection Timeouts
Symptoms: Connections timing out or dropping
Solutions:
```bash
Add keep-alive settings to sshd_config
ClientAliveInterval 30
ClientAliveCountMax 3
Check firewall rules
sudo ufw status
sudo firewall-cmd --list-all
Verify network connectivity
ping your-server-ip
telnet your-server-ip 22
```
Performance Optimization
Tuning SSH Performance
```bash
Edit SSH configuration for performance
sudo nano /etc/ssh/sshd_config
Add performance optimizations
Compression yes
MaxStartups 20:30:100
TCPKeepAlive yes
```
File System Considerations
```bash
For high-volume SFTP servers, consider:
- Using SSD storage for better I/O performance
- Implementing disk quotas
- Regular disk space monitoring
Set up user quotas (if needed)
sudo quotacheck -cum /
sudo quotaon /
sudo setquota -u sftpuser1 100000 110000 0 0 /
```
Backup and Maintenance
Configuration Backup
```bash
Create backup script
sudo nano /usr/local/bin/backup-ssh-config.sh
#!/bin/bash
DATE=$(date +%Y%m%d)
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup.$DATE
cp /etc/ssh/ssh_config /etc/ssh/ssh_config.backup.$DATE
echo "SSH configuration backed up with date: $DATE"
Make executable
sudo chmod +x /usr/local/bin/backup-ssh-config.sh
```
Regular Maintenance Tasks
```bash
Check disk space usage
df -h
Monitor user activity
sudo lastlog
Review and rotate logs
sudo logrotate -f /etc/logrotate.d/rsyslog
Update system packages
sudo apt update && sudo apt upgrade # Ubuntu/Debian
sudo yum update # CentOS/RHEL
```
Conclusion
Setting up an SFTP server in Linux provides a secure, reliable method for file transfers. By following this guide, you've learned how to:
- Install and configure OpenSSH server for SFTP
- Create and manage SFTP users with appropriate permissions
- Implement security best practices including chroot jails and key-based authentication
- Configure firewalls and monitoring systems
- Troubleshoot common issues
Remember to regularly update your system, monitor logs for security issues, and maintain proper backups of your configuration files. With proper setup and maintenance, your SFTP server will provide years of secure file transfer capabilities.
For production environments, consider implementing additional security measures such as VPN access, two-factor authentication, and regular security audits to ensure your SFTP server remains secure and performant.