#!/bin/bash
# plinius-ssh-hostkeys: the SSH server's host keys, neither RSA nor ECDSA:
#
#   ssh_host_ed25519_key           Ed25519
#   ssh_host_mldsa44_ed25519_key   ML-DSA-44 with Ed25519 (post-quantum hybrid)
#
# Runs in place of "ssh-keygen -A" of sshdgenkeys.service (drop-in of this package), at every
# start before sshd: it makes a key that is missing or incomplete, and removes RSA, ECDSA and DSA
# keys. Keys that are right stay untouched, so the phone keeps its identity. The keys are made on
# the phone, never in the image (tools/image-check.sh); 30-plinius-hostkeys.conf gives sshd
# exactly these two.
#
# SPDX-License-Identifier: MIT
set -euo pipefail

dir=/etc/ssh

# make TYPE NAME: ssh_host_NAME_key of TYPE
make() {
	local type=$1 key=$dir/ssh_host_$2_key tmp
	[[ -s $key && -s $key.pub ]] && return 0
	# Made under another name and moved into place: an interrupted run leaves no half key
	tmp=$(mktemp -u "$key.new.XXXXXX")
	ssh-keygen -q -t "$type" -N '' -f "$tmp"
	chmod 600 "$tmp"
	chmod 644 "$tmp.pub"
	mv -f "$tmp" "$key"
	mv -f "$tmp.pub" "$key.pub"
	echo "plinius-ssh-hostkeys: made $key"
}

make ed25519 ed25519
make mldsa44-ed25519 mldsa44_ed25519

for kind in rsa ecdsa dsa; do
	key=$dir/ssh_host_${kind}_key
	if [[ -e $key || -e $key.pub ]]; then
		rm -f "$key" "$key.pub"
		echo "plinius-ssh-hostkeys: removed the ${kind^^} host key"
	fi
done
