Setup SFTP server with public key authentication and chroot on Ubuntu

Reason why i setup SFTP server with public key authentication is for lab testing purpose.


Using username "test1".
Authenticating with public key "rsa-key-20171018"
Welcome to Ubuntu 16.04.3 LTS (GNU/Linux 4.10.0-37-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

71 packages can be updated.
0 updates are security updates.

Last login: Wed Oct 18 22:00:19 2017 from 192.168.1.68
test1@ubuntu:~$


0. install sshd and vsftpd

sudo apt-get update
sudo apt-get install vsftpd
sudo apt-get install openssh-server

1. create sftp user group

sudo groupadd sftponly

2. create testing user

sudo useradd -g sftponly -d /incoming -s /sbin/nologin test2
passwd test2

3. check user and group just created

grep test2 /etc/passwd
cat /etc/group

4. config sshd

nano /etc/ssh/sshd_config

change/add:
RSAAuthentication yes
PubkeyAuthentication yes
AuthorizedKeysFile      %h/.ssh/authorized_keys /var/ftpdir/.ssh/authorized_keys



Match group sftponly
ChrootDirectory /var/ftpdir/%u
X11Forwarding no
AllowTcpForwarding no
ForceCommand internal-sftp

you also can change to : UsePAM no 

5. create required folders

sudo mkdir /var/ftpdir
sudo mkdir /var/ftpdir/.ssh
sudo mkdir /var/ftpdir/test1/psdir

6 set folder permission and restart ssh server

sudo chown test1:sftponly /var/ftpdir/test1/psdir
sudo service sshd restart

7 create private/public key with putty key-gen and upload public to to the server folder

sudo nano /var/ftpdir/.ssh/authorized_keys
public key key-gen with putty

---- BEGIN SSH2 PUBLIC KEY ----
Comment: "rsa-key-20171018"
AAAAB3NzaC1yc2EAAAABJQAAAQEAj3Hx0olZ1a7CD1vcFCHz4jhc80fbr7Buq2+I
07Lox0rYuBJS3uZJj8b7Qo1BxlrWI44zWyZcOCssOtkNIEBD6B5prKGqd4osuh+b
G+Pz2PRhIT1FkJU3SWnbnuASmr06lUSxbBQYMg+lum1AV5Y+5k3bN6nv3kgvfHz3
Y0wZNOuM/a6B9mDX9+miiGeDopzAklPaObSVbdVurfpUSa3/GDVco7ZYiY75B42y
w9cvVLVVDQbHrBJNlihLw6h79VtAsydn93RQFkDhr7piIdWrouOUM/O+vSOIPpaa
AO8mZeEpC40ut0SDRpXIALS8Kt3S31bHRGjFbyblN+7zAofEQw==
---- END SSH2 PUBLIC KEY ----

you have to modify it to be like
ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAQ......... all in one line

8 connect with putty +key and use psftp to connect to server

PS C:\Users\user\Desktop> .\psftp.exe -load test1@homelab
Using username "test1".
Remote working directory is /
psftp> dir
Listing directory /
drwxr-xr-x    3 0        0            4096 Oct 19 05:30 .
drwxr-xr-x    3 0        0            4096 Oct 19 05:30 ..
drwxr-xr-x    2 1002     1001         4096 Oct 19 05:30 psdir
psftp>
psftp> cd /etc
Directory /etc: no such file or directory

Leave a Reply

Your email address will not be published. Required fields are marked *