Chroot'ing users with openssh

I recently learned about the new ChrootDirectory in OpenSSH 5.2, and wanted to play around with it to see what it was capable of. To begin my quest, I started off by creating a couple of users that would be chroot’ed to their home directories when they logged into the server with sftp. Once the users were created, I added the following configuration stanza to my sshd_config file to chroot these users when they logged in with their sftp client:

Subsystem sftp internal-sftp

Match user u1,u2,u3
ChrootDirectory /home/%u
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp

Once these directives where added, I started up the daemon in debug mode:

$ /usr/local/sbin/sshd -ddd -f /usr/local/etc/sshd_config

Debug mode will cause the daemon to log verbosely to stdout, which is extremely useful for locating problems with new configuration directives. Now that the daemon was running, I tried to login with the user u1:

$ sftp -oPort=222 u1@

Connecting to
u1@'s password:
Read from remote host Connection reset by peer
Connection closed

The first attempt was a no go, but luckily verbose logging made debugging this issue a snap:

debug3: mm_get_keystate: Getting compression state
debug3: mm_get_keystate: Getting Network I/O buffers
debug3: mm_share_sync: Share sync
debug3: mm_share_sync: Share sync end
debug3: safely_chroot: checking '/'
debug3: safely_chroot: checking '/home/'
debug3: safely_chroot: checking '/home/u1'
bad ownership or modes for chroot directory "/home/u1"

After changing /home/u1 to be owned by root, I was able to login and poke around:

$ sftp -oPort=222 u1@

Connecting to
u1@'s password:
sftp> **pwd**
Remote working directory: /
sftp> **ls -l**
drwxr-xr-x 2 1001 1001 4096 Mar 15 15:03 uploads
sftp> **cd uploads**
sftp> **ls -l**
-rw-r--r-- 1 1001 1001 39655552 Mar 15 15:04 techtalk1.mp3
sftp> put techtalk2*
Uploading techtalk2.mp3 to /uploads/techtalk2.mp3
techtalk2.mp3 3% 3776KB 2.3MB/s 00:39 ETA^
sftp> ls -l
-rw-r--r-- 1 1001 1001 5046272 Mar 15 15:11 techtalk2.mp3
-rw-r--r-- 1 1001 1001 39655552 Mar 15 15:04 techtalk1.mp3

This is super useful, though building chroot jails for normal SSH sessions will require a bit more work (i.e., you need to populate the chroot directory with all the config files and binaries needed to run a typical shell session). Makejail can make this a WHOLE lot easier, and I am about to submit a patch to the makejail developers to allow it to work on Solaris hosts. OpenSSH rocks!

This article was posted by Matty on 2009-03-15 11:31:00 -0400 EDT