#!/bin/sh UNAME=$(uname) [ $(id -u) -ne 0 ] && { echo "error: this script must be run as root">&2; exit 1; } echo "warning: this script will disable ssh password authentication" echo -n "continue? [y/N] " read answer [ "${answer}" != "y" ] && exit 0 ssh_moduli="/etc/ssh/moduli" moduli="/etc/moduli" if [ -f ${ssh_moduli} ]; then echo "filtering safe primes" awk '$5 > 2000' ${ssh_moduli} > /tmp/moduli mv /tmp/moduli ${ssh_moduli} elif [ -f ${moduli} ]; then echo "filtering safe primes" awk '$5 > 2000' ${moduli} > /tmp/moduli mv /tmp/moduli ${moduli} else echo "generating safe primes" echo "warning: this can take a long time (2h+)" echo -n "continue? [n/Y] " read answer if [ "${answer}" == "n" ]; then exit 0 fi ssh-keygen -G ${ssh_moduli}.all -b 4096 > /dev/null ssh-keygen -T ${ssh_moduli}.safe -f ${ssh_moduli}.all > /dev/null mv ${ssh_moduli}.safe ${ssh_moduli} rm ${ssh_moduli}.all fi echo "cleaning ssh host keys" rm /etc/ssh/ssh_host_{ecdsa,dsa,dss}_key* 2>/dev/null [ ! -f /etc/ssh/ssh_host_ed25519_key ] && ssh-keygen -t ed25519 -f /etc/ssh/ssh_host_ed25519_key -N "" > /dev/null [ ! -f /etc/ssh/ssh_host_rsa_key ] && ssh-keygen -t rsa -b 4096 -f /etc/ssh/ssh_host_rsa_key -N "" > /dev/null ssh_config="/etc/ssh/sshd_config" echo "writing ssh config" [ -f ${ssh_config} ] && mv ${ssh_config} ${ssh_config}.bak cat < ${ssh_config} HostKey /etc/ssh/ssh_host_ed25519_key HostKey /etc/ssh/ssh_host_rsa_key KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256 Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com MACs umac-128-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com PermitRootLogin no ChallengeResponseAuthentication no PasswordAuthentication no HostbasedAuthentication no KerberosAuthentication no PrintMotd no Subsystem sftp internal-sftp EOF [ "${UNAME}" = "Linux" ] && cat <> ${ssh_config} UsePrivilegeSeparation sandbox UsePAM yes EOF echo -n "enter your username " read user if [ -z "${user}" ]; then echo "error: no user submitted">&2 mv ${ssh_config}.bak ${ssh_config} exit 1 fi user_ssh="/home/${user}/.ssh" user_auth_keys="${user_ssh}/authorized_keys" [ ! -d ${user_ssh} ] && mkdir ${user_ssh} chmod 700 ${user_ssh} chown ${user}: ${user_ssh} echo "paste your full ssh public key " read sshkey if [ -z "${sshkey}" ]; then echo "error: no ssh key submitted">&2 mv ${ssh_config}.bak ${ssh_config} exit 1 fi echo "${sshkey}" > ${user_auth_keys} chmod 600 ${user_auth_keys} chown ${user}: ${user_auth_keys} case ${UNAME} in Linux) service ssh restart ;; OpenBSD) rcctl restart sshd ;; FreeBSD) /etc/rc.d/sshd restart ;; esac if [ -z "$(ps aux -w | awk '/\/usr\/s?bin\/sshd/')" ]; then echo "error: ssh service failed to restart">&2 echo "please check for sshd config errors manually">&2 exit 1 fi