ssh-treasure-hunt/entrypoint.sh

80 lines
2.3 KiB
Bash
Raw Normal View History

2022-01-18 18:02:41 +00:00
#!/bin/sh
HOME_BASE="/home"
2022-01-18 19:03:06 +00:00
USERS_LIST="./config/users.txt"
PASSWD_LIST="./config/passwords.txt"
2022-01-18 18:02:41 +00:00
separator="=" # Must be ascii for cut
forbidden_chars=". / : # = \ "
# Check we got user list
if [ ! -f "$USERS_LIST" ] && [ ! -f "$PASSWD_LIST" ] ; then
echo "Les fichiers des utilisateurs ou des passwords nont pas étés trouvées."
exit 1
fi
for c in $forbidden_chars ; do
if [ -n "$(cat "$USERS_LIST" | grep -F $c)" ] ; then
echo "Le fichier « $USERS_LIST » ne doit pas contenir le caractère « $c » !"
exit 1
fi
done
echo "-------------------------------------------------------------"
echo " Create users (and passwords if needed) as in $USERS_LIST"
# Generate passwords if not done yet
genPassowrd () {
tr -dc A-Za-z0-9 </dev/urandom | head -c $1
}
2022-01-18 19:03:06 +00:00
sanitizeFile () {
tmp="$(mktemp)"
sed -e "s/\r//g" "$1" > "$tmp"
2022-01-18 21:16:45 +00:00
cat "$tmp" > "$1"
rm "$tmp"
2022-01-18 19:03:06 +00:00
}
2022-01-18 18:02:41 +00:00
if [ ! -e "$PASSWD_LIST" ] ; then
touch "$PASSWD_LIST"
fi
2022-01-18 19:03:06 +00:00
sanitizeFile "$PASSWD_LIST"
sanitizeFile "$USERS_LIST"
2022-01-18 18:02:41 +00:00
for user in $(cat "$USERS_LIST") ; do
if [ -z "$user" ] || [ -n "$(cat $PASSWD_LIST | grep "$user$separator")" ] ; then continue ; fi
echo "$user$separator$(genPassowrd 6)" >> $PASSWD_LIST
done
for line in $(cat $PASSWD_LIST) ; do
name="$(echo "$line" | cut -d "$separator" -f 1)"
pass="$(echo "$line" | cut -d "$separator" -f 2)"
if [ -z "$name" ] || [ -z "$pass" ] ; then echo "Malformed line skipped: '$line'" ; continue ; fi
home="$HOME_BASE/$name"
mkdir -p "$home"
chmod 700 "$home"
useradd --home-dir "$home" --no-user-group -G eleve --shell /bin/bash "$name"
ret="$?"
if [ "$ret" -ne 0 ] && [ "$ret" -ne 9 ] ; then
echo "Cant create user '$name'. Error '$ret'."
continue
fi
echo "$pass\n$pass" | passwd "$name" >/dev/null 2>/dev/null
chown "$name":eleve "$home"
done
echo "-------------------------------------------------------------"
echo " Allow SSH as root"
if [ -z "$(grep '^PermitRootLogin yes' /etc/ssh/sshd_config)" ] ; then
echo "PermitRootLogin yes" >> /etc/ssh/sshd_config
fi
echo "-------------------------------------------------------------"
echo " Setting root password"
echo "root\nroot" | passwd 2>/dev/null >/dev/null
echo "-------------------------------------------------------------"
echo " Running main process"
exec "$@"