Jun 19, 2016

chrooted sftp with pubkey authentication

Method adopted from OpenSSH Cookbook.
I've automated user creation and added ability to use public key authentication.

Create a group for users that will be using chrooted sftp:
groupadd sftpusers

Append at the bottom of /etc/ssh/sshd_config
Match Group sftpusers
         ChrootDirectory /sftp/%u
         ForceCommand internal-sftp
         AuthorizedKeysFile     /home/%u/.ssh/authorized_keys

Save the following script and run as root/sudo, for example:
./addsftpusers.sh bob "ssh-rsa AAAA...."

Code:

#!/bin/sh

set -e

G="sftpusers"
U=$1
P=$2

if [ -z "$1" ]
  then
    echo "no username given"
    exit 1
fi

if [ -z "$2" ]
  then
    echo "no pubkey given"
    exit 1
fi

echo "Adding $U to $G"
useradd -g $G -d /incoming -s /sbin/nologin $U

echo "Creating sftp dir"
mkdir -p /sftp/$U/incoming
chown $U:$G /sftp/$U/incoming

echo "setting pubkey access"
mkdir -p /home/$U/.ssh
echo "$P" > /home/$U/.ssh/authorized_keys
chmod 600 /home/$U/.ssh/authorized_keys
chmod 700 /home/$U/.ssh/
chown -R $U:$G /home/$U
echo "Done"

No comments: