Sftp

From Christoph's Personal Wiki
Revision as of 11:40, 20 September 2014 by Christoph (Talk | contribs)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

SSH File Transfer Protocol (also Secure File Transfer Protocol or SFTP) is a network protocol that provides file access, file transfer, and file management functionalities over any reliable data stream. It is an extension of the Secure Shell protocol (SSH) version 2.0 to provide secure file transfer capability, but is also intended to be usable with other protocols.

SFTP chroot jail

A "chroot" in Linux is an operation that changes the apparent root directory for the current running process and its children. A program that is run in such a modified environment cannot name (and therefore normally not access) files outside the designated directory tree. The term "chroot" may refer to the chroot(2) system call or the chroot(8) wrapper program. The following is how one would setup a modified environment (a "chroot jail") for a given directory that only allows a given user to access a specified directory (and only that directory, no other on the system).

NOTE: In the following example, there will be a user "bob" who only has access to upload/download files from the /var/www/jail/bob directory.

  • Step#1: Add the following to the bottom of your /etc/ssh/sshd_config file
Match user bob
    ChrootDirectory /var/www/jail/%u

Then,

$ sudo service ssh restart
  • Step #2: Run the following commands (as root/sudo):
$ mkdir -p /var/www/jail/bob
$ addgroup --system sftp-users
$ useradd -m -s /bin/nologin -c "bob" -G sftp-users bob
$ passwd bob  # set password for user "bob"
$ chown root:root /home/
$ chown root:root /home/bob/
$ chmod 755 /home/bob
$ mkdir -p /home/bob/data
$ chown -Rv bob:sftp-users data
$ chown -Rv bob:sftp-users /var/www/jail/bob/
$ mount --bind /var/www/jail/bob/ /home/bob/data/
$ cat /etc/mtab  # check that the following line exists
/var/www/jail/bob /home/bob/data none rw,bind 0 0
$ cp /etc/fstab{,.bak}  # backup your old fstab
$ tail -1 /etc/mtab >>/etc/fstab
$ echo "Testing bob's SFTP chroot jail" >/home/bob/data/README
$ chown root /var/www/jail/bob
  • Step #3: Testing your setup (where "x.x.x.x" is the IP address of the remote server):
$ sftp bob@x.x.x.x
sftp> ls
README

If all goes as planned, user "bob" should be able to read/download the "README" file and upload files to that /var/www/jail/bob/ directory (and that directory only).

See also