home · contact · privacy
First scripts for Bullseye.
[config] / bullseye / setup_scripts / init_user_and_keybased_login.sh
1 #!/bin/sh
2 # This script turns a fresh server with password-based root access into
3 # one of only key-based access and only to new non-root account plom.
4 #
5 # CAUTION: This is optimized for a *fresh* setup. It will overwrite any
6 # pre-existing ~/.ssh/authorized_keys of user plom with one that solely
7 # contains the local ~/.ssh/id_rsa.pub, and also any old
8 # /etc/ssh/sshd_config.
9 #
10 # Dependencies: ssh, scp, sshpass, ~/.ssh/id_rsa.pub, properly
11 # configured sshd_config file in reach.
12 set -e
13 set -x
14
15 # Location of an sshd_config with "PermitRootLogin no" and
16 # "PasswordAuthentication no".
17 config_tree_prefix="${HOME}/public_repos/config/bullseye"
18 linkable_files_dir="${config_tree_prefix}/etc_files/server"
19 system_path_sshd_config='/etc/ssh/sshd_config'
20 local_path_sshd_config="${linkable_files_dir}${system_path_sshd_config}"
21
22 # Ensure we have a server name as argument.
23 if [ $# -eq 0 ]; then
24     echo "Need server as argument."
25     false
26 fi
27 server="$1"
28
29 # This will be used to log-in as root from plom account.
30 echo 'First, enter the old root password; then enter new password twice.'
31 ssh root@"${server}" "passwd"
32
33 # Save root password for sshpass
34 stty -echo
35 printf "Re-enter new server root password: "
36 read PW_ROOT
37 stty echo
38 printf "\n"
39 export SSHPASS="${PW_ROOT}"
40
41 # Create user plom, and his ~/.ssh/authorized_keys based on the local
42 # ~/.ssh/id_rsa.pub; ensure the result has proper permissions and
43 # ownerships. Then disable root and pw login by copying over the
44 # sshd_config and restart ssh daemon.
45 #
46 # This could be a line or two shorter by using ssh-copy-id, but that
47 # would require setting a password for user plom otherwise not needed.
48 sshpass -e scp ~/.ssh/id_rsa.pub root@"${server}":/tmp/authorized_keys
49 sshpass -e ssh root@"${server}" \
50         'useradd -m plom && '\
51         'mkdir /home/plom/.ssh && '\
52         'chown plom:plom /home/plom/.ssh && '\
53         'chown plom:plom /tmp/authorized_keys && '\
54         'chmod u=rw,go= /tmp/authorized_keys && '\
55         'mv /tmp/authorized_keys /home/plom/.ssh/'
56 sshpass -e scp "${local_path_sshd_config}" root@"${server}":"${system_path_sshd_config}"
57 sshpass -e ssh root@"${server}" 'service ssh restart'