Sunday, March 24, 2013

Setup chroot jail for ssh / sftp in Ubuntu

Using Ubuntu 10.04.2 LTS.

Step by step:

Read here for more complete and original information (thanks for the script).

Or follow instruction below:

You must be root.

Get the script from the above link:
# cd /usr/local/sbin
# wget http://www.fuschlberger.net/programs/ssh-scp-sftp-chroot-jail/make_chroot_jail.sh
# chmod 700 /usr/local/sbin/make_chroot_jail.sh


Edit the script (make_chroot_jail.sh):
# vi /usr/local/sbin/make_chroot_jail.sh
change first line, from:
#!/bin/sh
into:
#!/bin/bash
because it will be error if we use sh on Ubuntu 10.04.2 LTS.
Then add line after these below:
[...]
else
  APPS="/bin/bash /bin/cp /usr/bin/dircolors /bin/ls /bin/mkdir /bin/mv /bin/rm /bin/rmdir /bin/sh /bin/su /usr/bin/groups /usr/bin/id /usr/bin/rsync /usr/bin/ssh /usr/bin/scp /usr/sbin/unix_chkpwd"
fi


Add this line below, some program that we might want to add to the APPS variable:
APPS+=" /bin/cat /usr/bin/vi"
The /bin/cat is mandatory since .bashrc using it.

Create jail directory:
# mkdir /path/to/jail

Create will be jailed user account:
# adduser jailed_username

Run the script:
# make_chroot_jail.sh jailed_username /bin/bash /path/to/jail
Edit sshd_config:
# vi /etc/ssh/sshd_config
Change from:
Subsystem sftp /usr/lib/openssh/sftp-server
into:

Subsystem sftp internal-sftp 
And add these to the end of the file:
Match User jailed_username
   ChrootDirectory /path/to/jail
   AllowTCPForwarding no
   X11Forwarding no

Restart sshd:
# /etc/init.d/ssh restart

We need to edit /etc/passwd and change from:
jailed_username:x:1001:1001:,,,:/path/to/jail/home/jailed_username:/bin/bash
into:
jailed_username:x:1001:1001:,,,:/home/jailed_username:/bin/bash
because it will not see /path/to/jail anymore, but /

Finish.