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.
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.
10 # Dependencies: ssh, scp, sshpass, ~/.ssh/id_rsa.pub, properly
11 # configured sshd_config file in reach.
14 # Location of an sshd_config with "PermitRootLogin no" and
15 # "PasswordAuthentication no".
16 config_tree_prefix="${HOME}/public_repos/config/bullseye"
17 linkable_files_dir="${config_tree_prefix}/etc_files/server"
18 system_path_sshd_config='/etc/ssh/sshd_config'
19 local_path_sshd_config="${linkable_files_dir}${system_path_sshd_config}"
21 # Ensure we have a server name as argument.
23 echo "Need server as argument."
28 # This will be used to log-in as root from plom account.
29 echo 'First, enter the old root password; then enter new password twice.'
30 ssh root@"${server}" "passwd"
32 # Save root password for sshpass
34 printf "Re-enter new server root password: "
38 export SSHPASS="${PW_ROOT}"
40 # Create user plom, and his ~/.ssh/authorized_keys based on the local
41 # ~/.ssh/id_rsa.pub; ensure the result has proper permissions and
42 # ownerships. Then disable root and pw login by copying over the
43 # sshd_config and restart ssh daemon.
45 # This could be a line or two shorter by using ssh-copy-id, but that
46 # would require setting a password for user plom otherwise not needed.
47 sshpass -e scp ~/.ssh/id_rsa.pub root@"${server}":/tmp/authorized_keys
48 sshpass -e ssh root@"${server}" \
49 'useradd -m plom && '\
50 'mkdir /home/plom/.ssh && '\
51 'chown plom:plom /home/plom/.ssh && '\
52 'chown plom:plom /tmp/authorized_keys && '\
53 'chmod u=rw,go= /tmp/authorized_keys && '\
54 'mv /tmp/authorized_keys /home/plom/.ssh/'
55 sshpass -e scp "${local_path_sshd_config}" root@"${server}":"${system_path_sshd_config}"
56 sshpass -e ssh root@"${server}" 'service ssh restart'