#!/bin/bash
# nd-ssh-auth: SSH access settings for NDOS (used by rc.initial and nd-firstboot)
#
#   nd-ssh-auth status          -> prints "on" or "off" (SSH password login)
#   nd-ssh-auth password on|off -> allow / forbid SSH password login
#   nd-ssh-auth add-key         -> read a public key from stdin/prompt, add for ndadmin
#   nd-ssh-auth is-ec2          -> exit 0 on AWS EC2
#
# Key login is always allowed. The base sshd_config says PasswordAuthentication no;
# "password on" only adds the drop-in below (sshd_config includes it at the top).
set -u

ADMIN=ndadmin
PW_DROPIN=/etc/ssh/sshd_config.d/40-nd-password.conf

is_ec2() {
    grep -qi 'amazon' /sys/class/dmi/id/sys_vendor 2>/dev/null && return 0
    grep -q '^i-' /sys/class/dmi/id/board_asset_tag 2>/dev/null && return 0
    grep -qi 'amazon' /sys/class/dmi/id/bios_version 2>/dev/null && return 0
    grep -qi '^ec2' /sys/hypervisor/uuid 2>/dev/null && return 0
    return 1
}

reload_sshd() {
    if ! sshd -t; then
        echo "sshd configuration test failed; sshd not reloaded."
        return 1
    fi
    if systemctl is-active --quiet sshd; then
        systemctl reload-or-restart sshd
    fi
}

# Check one pasted public key line and print it normalised, or fail with a
# reason on stderr. Accepted: "<type> <base64> [comment]" only - no
# authorized_keys options (command=, from=, ...), one key, a modern key type,
# RSA at least 2048 bits.
check_pubkey() {
    local key="$1" type b64 comment bits

    key=${key//$'\r'/}
    key="${key#"${key%%[![:space:]]*}"}"
    key="${key%"${key##*[![:space:]]}"}"

    if [ -z "$key" ]; then
        echo "No key given." >&2; return 1
    fi
    if [ "${#key}" -gt 16384 ]; then
        echo "Key is too long." >&2; return 1
    fi
    if [[ $key == *[[:cntrl:]]* ]]; then
        echo "Key contains control characters." >&2; return 1
    fi

    read -r type b64 comment <<< "$key"
    case "$type" in
        ssh-ed25519|ecdsa-sha2-nistp256|ecdsa-sha2-nistp384|ecdsa-sha2-nistp521|\
        sk-ssh-ed25519@openssh.com|sk-ecdsa-sha2-nistp256@openssh.com|ssh-rsa) ;;
        ssh-dss)
            echo "DSA keys are not accepted. Use an ed25519 key (ssh-keygen -t ed25519)." >&2; return 1 ;;
        *)
            echo "Not a public key line: it must start with the key type (e.g. ssh-ed25519)." >&2
            echo "authorized_keys options such as command= or from= are not accepted." >&2
            return 1 ;;
    esac
    if ! [[ $b64 =~ ^[A-Za-z0-9+/]+={0,2}$ ]]; then
        echo "The key data is not valid base64." >&2; return 1
    fi
    # The comment is free text but must not look like a second key
    if [[ $comment =~ (^|[[:space:]])(ssh-|ecdsa-|sk-)[A-Za-z0-9@.-]+[[:space:]]+AAAA ]]; then
        echo "Paste one key at a time." >&2; return 1
    fi

    key="$type $b64${comment:+ $comment}"
    bits=$(printf '%s\n' "$key" | ssh-keygen -l -f /dev/stdin 2>/dev/null | awk '{print $1}')
    if ! [[ $bits =~ ^[0-9]+$ ]]; then
        echo "That is not a valid SSH public key." >&2; return 1
    fi
    if [ "$type" = ssh-rsa ] && [ "$bits" -lt 2048 ]; then
        echo "RSA key is only $bits bits; at least 2048 is required (ed25519 is recommended)." >&2
        return 1
    fi

    printf '%s\n' "$key"
}

has_password() {
    local p
    p=$(getent shadow "$ADMIN" | cut -d: -f2)
    [[ $p == \$* ]]
}

case "${1:-}" in
status)
    if [ -f "$PW_DROPIN" ] && grep -qi '^PasswordAuthentication[[:space:]]\+yes' "$PW_DROPIN"; then
        echo on
    else
        echo off
    fi
    ;;
password)
    case "${2:-}" in
    on)
        if ! has_password; then
            echo "ndadmin has no password yet. Set one first (menu option 3)."
            exit 1
        fi
        if is_ec2; then
            echo "WARNING: this is an AWS instance. Password login over SSH is"
            echo "less secure than the EC2 key pair it was launched with."
            read -r -p "Type 'yes' to enable password login anyway: " a
            [ "$a" = yes ] || { echo "Cancelled."; exit 1; }
        fi
        install -d -m 0755 /etc/ssh/sshd_config.d
        printf 'PasswordAuthentication yes\n' > "$PW_DROPIN"
        chmod 0644 "$PW_DROPIN"
        reload_sshd && echo "SSH password login enabled."
        ;;
    off)
        rm -f "$PW_DROPIN"
        reload_sshd && echo "SSH password login disabled (key login only)."
        ;;
    *)
        echo "usage: nd-ssh-auth password on|off"; exit 2 ;;
    esac
    ;;
add-key)
    key=""
    if [ -t 0 ]; then
	read -r -p "Paste the SSH public key for $ADMIN: " key || true
    else
	read -r key || true
    fi
    key=$(check_pubkey "$key") || exit 1
    h=$(getent passwd "$ADMIN" | cut -d: -f6)
    case "$h" in
        /?*) ;;
        *) echo "Cannot find the home directory of $ADMIN."; exit 1 ;;
    esac
    if [ -L "$h/.ssh" ] || [ -L "$h/.ssh/authorized_keys" ]; then
        echo "$h/.ssh or its authorized_keys is a symbolic link; refusing to write."
        exit 1
    fi
    install -d -m 700 -o "$ADMIN" -g "$ADMIN" "$h/.ssh"
    touch "$h/.ssh/authorized_keys"
    if grep -qxF "$key" "$h/.ssh/authorized_keys"; then
        echo "Key already present."
    else
        printf '%s\n' "$key" >> "$h/.ssh/authorized_keys"
        echo "Key added: $(printf '%s\n' "$key" | ssh-keygen -l -f /dev/stdin)"
    fi
    chown "$ADMIN:$ADMIN" "$h/.ssh/authorized_keys"
    chmod 600 "$h/.ssh/authorized_keys"
    ;;
is-ec2)
    is_ec2
    ;;
*)
    echo "usage: nd-ssh-auth status | password on|off | add-key | is-ec2"
    exit 2
    ;;
esac
