Setting up a secure SFTP server using OpenSSH is a common need for IT admins. One key aspect of hardening your SFTP setup is using ChrootDirectory
to restrict users to their own file spaces. However, this introduces an often-overlooked detail: where to place the authorized_keys
file for SSH key authentication.
Why Use SFTP with Chroot?
SFTP (SSH File Transfer Protocol) offers encrypted file transfers over SSH. Using ChrootDirectory
in your SSH config restricts users to a specific directory, preventing them from accessing the rest of the server’s file system — a critical security measure.
Example config in /etc/ssh/sshd_config
:
Subsystem sftp internal-sftp
Match Group sftpusers
ChrootDirectory /sftp/%u
ForceCommand internal-sftp
AllowTcpForwarding no
X11Forwarding no
Ensure the chroot path (e.g., /sftp/username
) is owned by root and not writable by the user.
The authorized_keys Catch
SSH needs access to the user’s ~/.ssh/authorized_keys
file before the chroot takes effect. If .ssh
is inside the chroot, SSH can’t read the key — and authentication fails.
Solution: Keep .ssh Outside the Chroot
To use SSH key auth with chroot:
- Set the user’s home directory outside the chroot (e.g.,
/home/username
) - Place
.ssh/authorized_keys
there - Set
ChrootDirectory
to something like/sftp/username
- Ensure proper ownership and permissions
Example:
useradd -m -d /home/username -s /sbin/nologin -G sftpusers username
mkdir -p /sftp/username/uploads
chown root:root /sftp/username && chmod 755 /sftp/username
chown username:sftpusers /sftp/username/uploads
# SSH Key Setup
mkdir -p /home/username/.ssh
cp id_rsa.pub /home/username/.ssh/authorized_keys
chown -R username:username /home/username/.ssh
chmod 700 /home/username/.ssh
chmod 600 /home/username/.ssh/authorized_keys