Ssh – SFTP via port 22 or vsftp over port 20 / 21 – Best way to secure FTP access to a server

chrootsftpssh

I've read many articles and questions on SF about this, and still can't figure out if the way I'm doing it is (a) possible, and (b) secure.

The server is running on AWS EC2, and all access is via SSH keys. I also only open port 22 to my own IP, but it seems if I want to allow others to access via SFTP, I'll need to open port 22 to the world (or spend my days managing firewall rules for dynamic IP addresses). Is this really better than, say, vsftp on port 21?

Assuming for the moment SFTP on port 22 is best, this is what I've done:

  • Created an 'ftp' user with a public / private key
  • Set up /home/ftp/.ssh/authorized_keys and tested SSH access
  • Added a ChrootDirectory entry in /etc/ssh/sshd_config pointing to /var/www/html
  • Adjusted the permissions from /var/www downwards so the chroot 'works'

Now, I'm stuck in a seeming catch 22, which is, I suspect (hope), just misconfiguration. Without the chroot block in sshd_config, I can connect either via Putty or an SFTP client, and all is well – apart from having access to the whole file system. With the chroot block in place, I was hitting the Could not chdir to home directory /home/ftp error during authentication, as now the /home/ftp/.ssh folder is unreachable and so the keys don't work. This old question / answer suggests putting a .ssh folder inside the /var/www/html/ folder, but that seems very odd to me – is that really OK to do, given that it's accessible by the web server?

Is there a more 'correct' way to have a user connect via SSH key and then be restricted to only /var/www/html?

Best Answer

In your OpenSSH configuration you can put some configuration in match blocks. This lets you set different configuration for different users/groups/networks.

So you could put all your sftp users into a group sftpd and then add a block like this. This forced chroot and forced sftp would only apply to that group. Your main account would then be able to use a shell as normal.

Match Group sftp
    ChrootDirectory /var/www/
    AllowTCPForwarding no
    X11Forwarding no
    ForceCommand internal-sftp

.ssh folder inside the /var/www/html/ folder, but that seems very odd to me - is that really OK to do

It isn't the worst thing. One would hope that those users aren't making outbound connections, so there will be no keypairs, and no known_hosts in that folder, leaving only the authorized_keys file. Which only has public keys in it. Public keys are public, sharing them shouldn't be particularly dangerous. Though it wouldn't be a bad idea to set the chroot directory for the sftp accounts at least one directory from the web root so that the .ssh isn't served publicly and outside the web root. If your chroot was to /var/www and you set your root for the web server at /var/www/html that would seem to satisfy your concern.