#!/bin/sh
# Blackbox: the booted system answers with the same SSH host key as this
# initramfs (bb-attest), so a client sees one key for the machine before and
# after unlock and "ssh root@<ip>" never trips over a changed key. On the first
# boot cloud-init installs it from the seed (bb-seed). On later boots, if the
# root's ed25519 host key is not this one (the key was re-made after a new
# release, an IP change or a move to another machine), it is replaced here.
# Opt out: create /etc/ssh/blackbox-hostkey.keep in the guest.
PREREQ="bb-seed"
prereqs() { echo "$PREREQ"; }
case "$1" in prereqs) prereqs; exit 0 ;; esac
. /scripts/functions

K=/run/bb/ssh_host_ed25519_key
D="${rootmnt}/etc/ssh"
sync_key() {
    [ -s "$K" ] && [ -s "$K.pub" ] && [ -d "$D" ] || return 0
    [ -e "$D/blackbox-hostkey.keep" ] && return 0
    # Never booted: cloud-init writes the key from the seed on this boot.
    [ -e "$D/ssh_host_ed25519_key.pub" ] || return 0
    want=$(cut -d' ' -f1,2 "$K.pub")
    have=$(cut -d' ' -f1,2 "$D/ssh_host_ed25519_key.pub" 2>/dev/null)
    [ "$want" = "$have" ] && return 0
    ro=0
    grep -q " ${rootmnt} [^ ]* ro[, ]" /proc/mounts && ro=1
    if [ $ro = 1 ]; then mount -o remount,rw "${rootmnt}" 2>/dev/null || return 0; fi
    cp "$K" "$D/ssh_host_ed25519_key.new" && chmod 600 "$D/ssh_host_ed25519_key.new" \
        && cp "$K.pub" "$D/ssh_host_ed25519_key.pub.new" && chmod 644 "$D/ssh_host_ed25519_key.pub.new" \
        && mv -f "$D/ssh_host_ed25519_key.new" "$D/ssh_host_ed25519_key" \
        && mv -f "$D/ssh_host_ed25519_key.pub.new" "$D/ssh_host_ed25519_key.pub"
    rm -f "$D/ssh_host_ed25519_key.new" "$D/ssh_host_ed25519_key.pub.new"
    sync
    if [ $ro = 1 ]; then mount -o remount,ro "${rootmnt}" 2>/dev/null || true; fi
}
sync_key
# The seed and the root have their copies now; /run moves into the booted
# system, so do not leave a spare private key there.
rm -f "$K"
