dss/create-user.bash

76 lines
2.5 KiB
Bash
Raw Normal View History

2019-01-12 03:50:24 +00:00
#!/bin/bash
# Determined Create User Script v2.0.3
# Written by AJ Oneal -- edited by Joshua Mudge
# Exit on any error
set -e
if [ -z "$(which openssl)" ]; then
echo "ERROR: 'openssl' is not found.";
echo "Please install openssl. It is used to generate a random password."
exit 1
fi
if [ -z "$(grep '^PermitRootLogin prohibit-password$' /etc/ssh/sshd_config)" ] && [ -z "$(grep '^PermitRootLogin no$' /etc/ssh/sshd_config)" ] && [ -z "$(grep '^PermitRootLogin without-password$' /etc/ssh/sshd_config)" ]; then
echo "SECURITY ERROR: 'PermitRootLogin prohibit-password' is not set in /etc/ssh/sshd_config";
exit 1
fi
if [ -z "$(grep '^PasswordAuthentication no$' /etc/ssh/sshd_config)" ]; then
echo "SECURITY ERROR: 'PasswordAuthentication no' is not set in /etc/ssh/sshd_config";
exit 1
fi
# http://stackoverflow.com/questions/43481923/security-audit-how-to-check-if-ssh-server-asks-for-a-password/43482975#43482975
if [ -n "$(ssh -v -o Batchmode=yes DOES_NOT_EXIST@localhost 2>/dev/null | grep password)" ]; then
echo "SECURITY ERROR: 'PasswordAuthentication no' has not taken affect. Try 'sudo service ssh restart'";
exit 1
fi
# exit if there are any unbound variables
set -u
USER=$1
USER=$(basename $USER .pub)
# If they try to create root, exit.
if test $USER = "root"
then
echo "You cannot create the root user, it already exists."
exit
fi
# TODO allow optional gecos i.e. create-user.bash bobs.pub 'Bob Smith'
# password will be set later in the script
#adduser --disabled-password --gecos '' $USER
sudo adduser --disabled-login --gecos '' $USER
sudo adduser $USER sudo # if sudo is needed
# FAIL before getting here via set -e
sudo mkdir -p /home/$USER/.ssh
sudo chmod 700 /home/$USER/.ssh
sudo touch /home/$USER/.ssh/authorized_keys
sudo chmod 600 /home/$USER/.ssh/authorized_keys
# PRE-REQ: get the user's ssh public key and store it in whoever.pub
sudo bash -c "cat $USER.pub >> /home/$USER/.ssh/authorized_keys"
sudo chown $USER:$USER /home/$USER
sudo chown $USER:$USER -R /home/$USER/.ssh/
PASSWD=$(openssl rand -hex 20)
#echo "$PASSWD" | passwd "$USER" --stdin
echo "$USER:$PASSWD" | sudo chpasswd
#echo "The temporary password for '"$USER"' is '"$PASSWD"'"
sudo passwd -d $USER
echo "'$USER'" has been added with key-only authentication and a password must be set on first login
sudo chage -d 0 $USER
# Other Methods as per https://www.howtogeek.com/howto/30184/10-ways-to-generate-a-random-password-from-the-command-line/
#
# Linux
# date "+%s.%N" | md5sum
#
# macOS
# date "+%s.%N" | md5