Chrooting SFTP

(redirected from Openbsd.Sftp)

This guide explains how to chroot users that login to the sftp server.

Creating user and sftp group

First, we create the group sftp that all sftp users must belong to.

# groupadd sftp

If the user account does not already exist, we must create it with adduser or useradd.

# useradd -m -G sftp $USER
# passwd $USER
# chsh -s /sbin/nologin $USER

Replace $USER with the actual user. As an added precaution, we disable any possible shell login.

If the user accouunt already exists, make sure the user is a member of the sftp group:

# usermod -G sftp $USER

We then append this block to sshd_config:

Match Group sftp
	Subsystem sftp internal-sftp
	PasswordAuthentication yes
	ForceCommand internal-sftp
	ChrootDirectory %h
	DisableForwarding yes
	PermitTunnel no
	PermitTTY no

We then reload the configuration:

# pkill -HUP sshd

In sshd_config(5), it states:

     ChrootDirectory
             Specifies the pathname of a directory to chroot(2) to after
             authentication.  At session startup sshd(8) checks that all
             components of the pathname are root-owned directories which are
             not writable by group or others.  After the chroot, sshd(8)
             changes the working directory to the user's home directory.

sshd(8) requires that the chroot directory be owned by root, and not writeable by group or others. Since the chroot directory is the user's home folder, we run:

# chown root:wheel /home/$USER
# ls -ld /home/$USER       
drwxr-xr-x  4 root  wheel   512B Jun 17 12:56 /home/$USER

Inside the home directory, we create a folder uploads for holding user files:

# mkdir -p /home/$USER/uploads
# chown $USER:$USER /home/$USER/uploads

Troubleshooting

The default syslog.conf will record any authentication information messages in /var/log/authlog:

Jun 17 12:49:01 $USER sshd[60020]: fatal: bad ownership or modes for chroot directory component "/home/$USER/"

This error message indicates an error in file permissions.