diff --git a/setup.sh b/setup.sh index edfb2dc..060f294 100644 --- a/setup.sh +++ b/setup.sh @@ -126,14 +126,35 @@ configure_ssh() { printf "%s\n" "$SSH_KEY" > "/home/$USERNAME/.ssh/authorized_keys" chmod 600 "/home/$USERNAME/.ssh/authorized_keys" chown -R "$USERNAME":"$USERNAME" "/home/$USERNAME/.ssh" - sed -i -E "s/^[[:space:]]*#?[[:space:]]*PasswordAuthentication.*/PasswordAuthentication no/" /etc/ssh/sshd_config - sed -i -E "s/^[[:space:]]*#?[[:space:]]*PermitRootLogin.*/PermitRootLogin no/" /etc/ssh/sshd_config - sed -i -E "s/^[[:space:]]*#?[[:space:]]*(KbdInteractiveAuthentication|ChallengeResponseAuthentication).*/KbdInteractiveAuthentication no/" /etc/ssh/sshd_config - if [ -d /etc/ssh/sshd_config.d ]; then - rm -f /etc/ssh/sshd_config.d/*-cloud-init.conf - find /etc/ssh/sshd_config.d -maxdepth 1 -type f -name "*.conf" \ - -exec sed -i "/^[[:space:]]*PasswordAuthentication[[:space:]]\\+yes[[:space:]]*$/d" {} + + if ! grep -qE "^[[:space:]]*Include[[:space:]]+/etc/ssh/sshd_config.d/\\*.conf" /etc/ssh/sshd_config; then + echo "Include /etc/ssh/sshd_config.d/*.conf" >> /etc/ssh/sshd_config fi + install -d -m 755 /etc/ssh/sshd_config.d + dir=/etc/ssh/sshd_config.d + shopt -s nullglob + for f in "$dir"/*.conf; do + base=$(basename "$f") + case "$base" in + [0-9][0-9]-*.conf) + [[ $base == 99-* ]] && mv "$f" "${f%.conf}.disabled" + ;; + *) + mv "$f" "${f%.conf}.disabled" + ;; + esac + done + shopt -u nullglob + max=$(find "$dir" -maxdepth 1 -type f -name "[0-9][0-9]-*.conf" | sed -n "s#.*/\\([0-9][0-9]\\)-.*#\\1#p" | sort -n | tail -1) + if [ -z "$max" ]; then + next=10 + else + next=$((10#$max + 10)) + [ "$next" -gt 99 ] && next=99 + fi + newfile=$(printf "%s/%02d-hardening.conf" "$dir" "$next") + printf "%s\n" "PasswordAuthentication no" "PermitRootLogin no" "KbdInteractiveAuthentication no" > "$newfile" + chown root:root "$newfile" + chmod 0644 "$newfile" sshd -t systemctl reload sshd 2>/dev/null || systemctl reload ssh 2>/dev/null || systemctl restart sshd 2>/dev/null || systemctl restart ssh '