0
0
Fork 0
mirror of https://github.com/atmoz/sftp.git synced 2024-11-17 12:51:33 -05:00
atmoz-sftp/entrypoint
2016-03-28 18:06:53 +02:00

131 lines
3.2 KiB
Bash
Executable file

#!/bin/bash
set -e
export DEBIAN_FRONTEND=noninteractive
userConfPath="/etc/sftp-users.conf"
userConfFinalPath="/var/run/sftp-users.conf"
function printHelp() {
echo "Add users as command arguments, STDIN or mounted in $userConfPath"
echo "Syntax: user:pass[:e][:uid[:gid]]..."
echo "Use --readme for more information and examples."
}
function printReadme() {
cat /README.md
echo "TIP: Read this in HTML format here: https://github.com/atmoz/sftp"
}
function createUser() {
IFS=':' read -a param <<< $@
user="${param[0]}"
pass="${param[1]}"
if [ "${param[2]}" == "e" ]; then
chpasswdOptions="-e"
uid="${param[3]}"
gid="${param[4]}"
else
uid="${param[2]}"
gid="${param[3]}"
fi
if [ -z "$user" ]; then
echo "FATAL: You must at least provide a username."
exit 1
fi
if $(cat /etc/passwd | cut -d: -f1 | grep -q "$user"); then
echo "FATAL: User \"$user\" already exists."
exit 2
fi
useraddOptions="--no-user-group"
if [ -n "$uid" ]; then
useraddOptions="$useraddOptions --non-unique --uid $uid"
fi
if [ -n "$gid" ]; then
if ! $(cat /etc/group | cut -d: -f3 | grep -q "$gid"); then
groupadd --gid $gid $gid
fi
useraddOptions="$useraddOptions --gid $gid"
fi
useradd $useraddOptions $user
mkdir -p /home/$user
chown root:root /home/$user
chmod 755 /home/$user
if [ -z "$pass" ]; then
pass="$(tr -dc A-Za-z0-9 </dev/urandom | head -c256)"
chpasswdOptions=""
fi
echo "$user:$pass" | chpasswd $chpasswdOptions
# Add SSH keys to authorized_keys with valid permissions
if [ -d /home/$user/.ssh/keys ]; then
cat /home/$user/.ssh/keys/* >> /home/$user/.ssh/authorized_keys
chown $user /home/$user/.ssh/authorized_keys
chmod 600 /home/$user/.ssh/authorized_keys
fi
}
if [[ $1 =~ ^--help$|^-h$ ]]; then
printHelp
exit 0
fi
if [ "$1" == "--readme" ]; then
printReadme
exit 0
fi
# Create users only on first run
if [ ! -f "$userConfFinalPath" ]; then
# Append mounted config to final config
if [ -f "$userConfPath" ]; then
cat "$userConfPath" > "$userConfFinalPath"
fi
# Append users from arguments to final config
for user in "$@"; do
echo "$user" >> "$userConfFinalPath"
done
# Append users from STDIN to final config
if [ ! -t 0 ]; then
while IFS= read -r user || [[ -n "$user" ]]; do
echo "$user" >> "$userConfFinalPath"
done
fi
# Check that we have users in config
if [ "$(cat "$userConfFinalPath" | wc -l)" == 0 ]; then
echo "FATAL: No users provided!"
printHelp
exit 3
fi
# Import users from final conf file
while IFS= read -r user || [[ -n "$user" ]]; do
createUser "$user"
done < "$userConfFinalPath"
# Generate unique ssh keys for this container
dpkg-reconfigure openssh-server
# Source custom scripts, if any
if [ -d /etc/sftp.d ]; then
for f in /etc/sftp.d/*; do
[ -x "$f" ] && . "$f"
done
unset f
fi
fi
exec /usr/sbin/sshd -D