#!/bin/sh
# ExecStartPre for the ordinary cryptroot unit. Any failure leaves its PIN prompt intact.
# Only TPM-encrypted blobs and policy inputs are carried in the disk initramfs.
umask 077
bundle=${1:-/etc/starchaser/firmware-seal}
runtime=${2:-/run}
handoff=${3:-/dev/starchaser-firmware-handoff}
work=$(mktemp -d "$runtime/starchaser-firmware-unseal.XXXXXX") || exit 0
tpm() { timeout 15 "$@"; }
cleanup() {
    for context in session child primary; do
        tpm tpm2_flushcontext "$work/$context" >/dev/null 2>&1 || :
    done
    rm -rf "$work"
}
trap cleanup EXIT
trap 'exit 0' HUP INT TERM
# A failed policy must not be followed by unsealing or attaching the drive.
try_unlock() {
    # The read consumes kernel RAM even if subsequent policy/drive work fails.
    dd if="$handoff" of="$work/auth" bs=32 count=1 status=none || return 1
    [ "$(wc -c < "$work/auth")" -eq 32 ] || return 1
    uuid=$(cat "$bundle/uuid") || return 1
    case "$uuid" in *[!0-9a-fA-F-]*|'') return 1;; esac
    [ "${#uuid}" -eq 36 ] || return 1
    resets=$(cat "$bundle/resets") || return 1
    restarts=$(cat "$bundle/restarts") || return 1
    case "$resets:$restarts" in *[!0-9:]*|:*|*:) return 1;; esac
    tpm tpm2_createprimary -C o -g sha256 -G rsa2048 -c "$work/primary" || return 1
    tpm tpm2_load -C "$work/primary" -u "$bundle/public" -r "$bundle/sealed" -c "$work/child" || return 1
    tpm tpm2_startauthsession --policy-session -S "$work/session" || return 1
    tpm tpm2_policypcr -S "$work/session" -l sha256:7,15 || return 1
    tpm tpm2_policycountertimer -S "$work/session" --eq "resets=$resets" || return 1
    tpm tpm2_policycountertimer -S "$work/session" --eq "restarts=$restarts" || return 1
    tpm tpm2_policyauthvalue -S "$work/session" || return 1
    tpm tpm2_unseal -c "$work/child" -p "session:$work/session+file:$work/auth" > "$work/key" || return 1
    [ "$(wc -c < "$work/key")" -eq 64 ] || return 1
    # Invalidate replay in this same TPM startup (including a later kexec).
    # Do this before exposing the key to cryptsetup, and fail to the prompt if
    # consumption fails. The next hardware boot is also bound by both counters.
    tpm tpm2_pcrextend 15:sha256=143af1a805b35d361166adfdac647895201a1b01912566a6a1dd579147b86d71 || return 1
    # The following normal systemd-cryptsetup attach notices the active mapping.
    cryptsetup open --key-file "$work/key" "/dev/disk/by-uuid/$uuid" cryptroot || return 1
}
# No TPM stdout/stderr reaches the journal, including unsealed material.
try_unlock >/dev/null 2>&1 || :
exit 0
