#!/usr/bin/bash
# build-ovmf-vars.sh: build the OVMF variable store LamBoot ships for Secure Boot VMs.
#
# The output starts from a distribution's Microsoft-enrolled OVMF VARS template,
# keeps that template's PK, and holds:
#
#   KEK  Microsoft Corporation KEK CA 2011 and Microsoft Corporation KEK 2K CA 2023,
#        next to whatever the template's KEK already held (Debian's own key on
#        Debian's template)
#   db   Microsoft Windows Production PCA 2011 and Windows UEFI CA 2023,
#        Microsoft Corporation UEFI CA 2011 and Microsoft UEFI CA 2023,
#        Microsoft Option ROM UEFI CA 2023, and LamBoot's signing certificate
#   dbx  Microsoft's current x64 revocation list, replacing the template's dbx
#
# Both generations of Microsoft CA are needed: shims and Windows boot managers
# signed before mid-2026 chain only to the 2011 CAs, and everything Microsoft
# has signed since chains only to the 2023 CAs. The template's dbx is replaced
# because Debian's trixie template carries a stand-in dbx (the hash of an
# empty file) that revokes nothing.
#
# Run with --help for options. Prerequisites: virt-firmware 26.10 or later
# (earlier releases lack some of the 2023 certificates; pip install
# 'virt-firmware>=26.10' into a venv works), openssl, curl, and an OVMF VARS
# template with a PK enrolled (Debian/Ubuntu: /usr/share/OVMF/OVMF_VARS_4M.ms.fd).

set -euo pipefail

# The usage text names the script as it was called. lamboot-tools ships this
# file as lamboot-pve-ovmf-vars, and its help used to tell people to run
# tools/build-ovmf-vars.sh, a path that package doesn't have.
usage() {
    sed "s|tools/build-ovmf-vars.sh|$0|g" <<'EOF'
Usage: tools/build-ovmf-vars.sh [options] [CERT]

Build an OVMF VARS file whose db trusts LamBoot's signing certificate next to
Microsoft's 2011 and 2023 CAs, with Microsoft's current x64 dbx.

Options:
  --cert FILE          LamBoot db certificate, PEM or DER (default: keys/db.crt).
                       A bare CERT argument means the same, for older callers.
  --output FILE        Where to write the result (default: dist/OVMF_VARS_lamboot.fd).
                       The file is replaced only after the build is verified.
  --template FILE      OVMF VARS template with a PK enrolled. Its PK is kept.
                       Default: the first of /usr/share/OVMF/OVMF_VARS_4M.ms.fd,
                       /usr/share/qemu/OVMF_VARS_4M.ms.fd,
                       /usr/share/edk2/ovmf/OVMF_VARS.ms.fd.
  --dbx FILE           Authenticated dbx update (.efiauth2 or DBXUpdate.bin) from
                       github.com/microsoft/secureboot_objects. Repeatable: the
                       first replaces dbx, later ones are merged into it.
                       Default: PostSignedObjects/SignedByKEK2023/dbx_x64.efiauth2
                       at a pinned commit, downloaded into
                       ${XDG_CACHE_HOME:-~/.cache}/lamboot/secureboot_objects/
                       and refused unless its sha256 matches the pinned value.
                       Use this option when building offline.
  --ms-certs DIR       Directory holding the seven Microsoft certificates, PEM or
                       DER, under any names (for example a secureboot_objects
                       checkout's PreSignedObjects). Default: the certificates
                       bundled with virt-firmware. Either way each one is matched
                       by its pinned SHA-256 fingerprint.
  --virt-fw-vars PATH  virt-fw-vars to run. Default: $VIRT_FW_VARS, then
                       ~/.local/bin, /var/tmp/virt-fw-venv/bin and
                       /tmp/virt-fw-venv/bin, then PATH.
  -h, --help           Show this help.

Examples:
  tools/build-ovmf-vars.sh --cert keys/db.der
  tools/build-ovmf-vars.sh --cert keys/db.der --output /var/tmp/OVMF_VARS_lamboot.fd \
      --virt-fw-vars /var/tmp/virt-fw-venv/bin/virt-fw-vars
EOF
}

CERT="keys/db.crt"
OUTPUT="dist/OVMF_VARS_lamboot.fd"
VARS_TEMPLATE=""
VIRT_FW_VARS="${VIRT_FW_VARS:-}"
MS_CERT_DIR=""
DBX_FILES=()

die() { echo "ERROR: $*" >&2; exit 1; }

need_arg() { [[ $# -ge 2 && -n "$2" ]] || die "$1 needs a value (see --help)"; }

while [[ $# -gt 0 ]]; do
    case $1 in
        --cert) need_arg "$@"; CERT="$2"; shift 2 ;;
        --output) need_arg "$@"; OUTPUT="$2"; shift 2 ;;
        --template) need_arg "$@"; VARS_TEMPLATE="$2"; shift 2 ;;
        --dbx) need_arg "$@"; DBX_FILES+=("$2"); shift 2 ;;
        --ms-certs) need_arg "$@"; MS_CERT_DIR="$2"; shift 2 ;;
        --virt-fw-vars) need_arg "$@"; VIRT_FW_VARS="$2"; shift 2 ;;
        -h|--help) usage; exit 0 ;;
        -*) die "unknown option: $1 (see --help)" ;;
        *) CERT="$1"; shift ;;
    esac
done

# Owner GUIDs are informational to the firmware. Microsoft's entries carry
# Microsoft's vendor GUID, as they do in the distribution templates.
MS_OWNER="77fa9abd-0359-4d32-bd60-28f4e78f784b"
LAMBOOT_GUID="4c414d42-4f4f-5400-0000-000000000002"

# SHA-256 fingerprints of the DER certificates, checked against the copies in
# microsoft/secureboot_objects PreSignedObjects (commit daa32713651f, 2026-10-13).
declare -A MS_FP=(
    [kek-2011]=a1117f516a32cefcba3f2d1ace10a87972fd6bbe8fe0d0b996e09e65d802a503
    [kek-2023]=3cd3f0309edae228767a976dd40d9f4affc4fbd5218f2e8cc3c9dd97e8ac6f9d
    [windows-2011]=e8e95f0733a55e8bad7be0a1413ee23c51fcea64b3c8fa6a786935fddcc71961
    [windows-2023]=076f1fea90ac29155ebf77c17682f75f1fdd1be196da302dc8461e350a9ae330
    [uefi-2011]=48e99b991f57fc52f76149599bff0a58c47154229b9f8d603ac40d3500248507
    [uefi-2023]=f6124e34125bee3fe6d79a574eaa7b91c0e7bd9d929c1a321178efd611dad901
    [rom-2023]=e5be3e64c6e66a281457ecdece0d6d0787577aad2a3a0144262c10c14ba8d8f1
)
declare -A MS_NAME=(
    [kek-2011]="Microsoft Corporation KEK CA 2011"
    [kek-2023]="Microsoft Corporation KEK 2K CA 2023"
    [windows-2011]="Microsoft Windows Production PCA 2011"
    [windows-2023]="Windows UEFI CA 2023"
    [uefi-2011]="Microsoft Corporation UEFI CA 2011"
    [uefi-2023]="Microsoft UEFI CA 2023"
    [rom-2023]="Microsoft Option ROM UEFI CA 2023"
)
KEK_CERTS=(kek-2011 kek-2023)
DB_CERTS=(windows-2011 windows-2023 uefi-2011 uefi-2023 rom-2023)

# Pinned to the commit that last changed dbx_x64.efiauth2 (2026-09-01), so a
# rebuild gives the same bytes until someone chooses a newer list. The older
# PostSignedObjects/DBX/amd64/DBXUpdate.bin stopped at its 2026-06-30 contents
# and Microsoft marks it obsolete; docs/OVMF-VARS-PROXMOX.md §7 compares them.
DBX_COMMIT="92b433ecf7154c7bf1b8f45245233bdde6cd14e5"
DBX_REPO_PATH="PostSignedObjects/SignedByKEK2023/dbx_x64.efiauth2"
DBX_SHA256="524c796ade42db0048b656f6cf3863832174ae7f58cad6986d1ccae1e3d3ecd1"
DBX_URL="https://raw.githubusercontent.com/microsoft/secureboot_objects/${DBX_COMMIT}/${DBX_REPO_PATH}"

for tool in openssl sha256sum; do
    command -v "$tool" >/dev/null 2>&1 || die "$tool not found"
done

# A venv or user install comes before PATH because Debian 13's packaged
# virt-firmware (24.11) is too old, and whoever made the newer install meant it.
if [[ -z "$VIRT_FW_VARS" ]]; then
    for candidate in \
        "$HOME/.local/bin/virt-fw-vars" \
        /var/tmp/virt-fw-venv/bin/virt-fw-vars \
        /tmp/virt-fw-venv/bin/virt-fw-vars \
        "$(command -v virt-fw-vars 2>/dev/null || true)"; do
        if [[ -n "$candidate" && -x "$candidate" ]]; then
            VIRT_FW_VARS="$candidate"
            break
        fi
    done
fi
[[ -n "$VIRT_FW_VARS" && -x "$VIRT_FW_VARS" ]] \
    || die "virt-fw-vars not found. Install virt-firmware 26.10 or later (pip install 'virt-firmware>=26.10' in a venv) and pass --virt-fw-vars"

WORK=$(mktemp -d)
TMP_OUT=""
cleanup() {
    rm -rf "$WORK"
    [[ -z "$TMP_OUT" ]] || rm -f "$TMP_OUT"
}
trap cleanup EXIT

# virt-fw-vars prints names but not fingerprints, so the checks below read the
# stores through virt-firmware's own parser, run by the interpreter that
# virt-fw-vars itself uses so the same library version does the reading.
VFW_PY=()
read -r shebang < "$VIRT_FW_VARS" || true
if [[ "$shebang" == '#!'*python* ]]; then
    read -r -a VFW_PY <<< "${shebang#\#!}"
else
    VFW_PY=(python3)
fi
cat > "$WORK/lamboot_vars_probe.py" <<'PY'
import hashlib
import sys
from cryptography import x509
from cryptography.hazmat.primitives import serialization
from virt.firmware.efi import efivar, guids, ucs16
from virt.firmware.varstore import autodetect

def cn_of(cert):
    names = cert.subject.get_attributes_for_oid(x509.oid.NameOID.COMMON_NAME)
    return names[0].value if names else cert.subject.rfc4514_string()

def dump_sigdb(prefix, sigdb):
    for siglist in sigdb:
        if siglist.x509 is not None:
            der = siglist.x509.public_bytes(serialization.Encoding.DER)
            print(f'{prefix} x509 {hashlib.sha256(der).hexdigest()} {cn_of(siglist.x509)}')
        elif str(siglist.guid) == guids.EfiCertSha256:
            for sig in siglist:
                print(f'{prefix} sha256 {sig["data"].hex()}')
        else:
            print(f'{prefix} other {guids.name(siglist.guid)} {len(siglist)}')

cmd = sys.argv[1]
if cmd == 'version':
    from importlib.metadata import version
    print(version('virt-firmware'))
elif cmd == 'certs-dir':
    import importlib.resources
    print(importlib.resources.files('virt.firmware') / 'certs')
elif cmd == 'vars':
    store = autodetect.open_varstore(sys.argv[2])
    if store is None:
        sys.exit(f'{sys.argv[2]}: not an edk2 varstore')
    varlist = store.get_varlist()
    for name in ('PK', 'KEK', 'db', 'dbx'):
        var = varlist.get(name)
        if var is not None and var.sigdb is not None:
            dump_sigdb(name, var.sigdb)
elif cmd == 'dbx':
    with open(sys.argv[2], 'rb') as f:
        var = efivar.EfiVar(ucs16.from_string('dbx'), authdata=f.read())
    if var.sigdb is None:
        sys.exit(f'{sys.argv[2]}: no signature list in this update')
    dump_sigdb('dbx', var.sigdb)
PY
probe() { "${VFW_PY[@]}" "$WORK/lamboot_vars_probe.py" "$@"; }
VFW_VERSION=$(probe version 2>/dev/null) \
    || die "cannot import virt-firmware with ${VFW_PY[*]} (the interpreter of $VIRT_FW_VARS)"

# Template: its PK is what makes the result enforce Secure Boot, so refuse one
# in setup mode instead of producing a store that silently trusts everything.
if [[ -z "$VARS_TEMPLATE" ]]; then
    for template in \
        /usr/share/OVMF/OVMF_VARS_4M.ms.fd \
        /usr/share/qemu/OVMF_VARS_4M.ms.fd \
        /usr/share/edk2/ovmf/OVMF_VARS.ms.fd; do
        if [[ -f "$template" ]]; then
            VARS_TEMPLATE="$template"
            break
        fi
    done
fi
[[ -n "$VARS_TEMPLATE" ]] || die "no OVMF VARS template found. Install ovmf, or pass --template"
[[ -f "$VARS_TEMPLATE" ]] || die "template not found: $VARS_TEMPLATE"
probe vars "$VARS_TEMPLATE" > "$WORK/template.lst" 2>/dev/null \
    || die "cannot read $VARS_TEMPLATE as an edk2 varstore"
PK_LINE=$(grep '^PK x509 ' "$WORK/template.lst" || true)
[[ -n "$PK_LINE" ]] || die "$VARS_TEMPLATE has no PK enrolled; the result would not enforce Secure Boot"
[[ $(grep -c '^PK x509 ' "$WORK/template.lst") -eq 1 ]] || die "$VARS_TEMPLATE has more than one PK certificate"
PK_FP=$(cut -d' ' -f3 <<< "$PK_LINE")

[[ -f "$CERT" ]] || die "certificate not found: $CERT (generate keys with ./tools/sign-lamboot.sh)"
cert_fp() {
    { openssl x509 -in "$1" -noout -fingerprint -sha256 2>/dev/null \
        || openssl x509 -inform der -in "$1" -noout -fingerprint -sha256 2>/dev/null; } \
        | cut -d= -f2 | tr -d ':' | tr 'A-F' 'a-f'
}
cert_subject() {
    openssl x509 -in "$1" -noout -subject 2>/dev/null \
        || openssl x509 -inform der -in "$1" -noout -subject
}
LAMBOOT_FP=$(cert_fp "$CERT" || true)
[[ -n "$LAMBOOT_FP" ]] || die "$CERT is not an X.509 certificate in PEM or DER form"
for key in "${!MS_FP[@]}"; do
    [[ "$LAMBOOT_FP" != "${MS_FP[$key]}" ]] || die "$CERT is ${MS_NAME[$key]}, not LamBoot's certificate"
done

if [[ -z "$MS_CERT_DIR" ]]; then
    MS_CERT_DIR=$(probe certs-dir) || die "cannot locate virt-firmware's bundled certificates"
fi
[[ -d "$MS_CERT_DIR" ]] || die "certificate directory not found: $MS_CERT_DIR"
declare -A MS_FILE=()
while IFS= read -r -d '' file; do
    fp=$(cert_fp "$file") || continue
    for key in "${!MS_FP[@]}"; do
        if [[ "$fp" == "${MS_FP[$key]}" && -z "${MS_FILE[$key]:-}" ]]; then
            MS_FILE[$key]="$file"
        fi
    done
done < <(find "$MS_CERT_DIR" -type f \( -name '*.pem' -o -name '*.der' -o -name '*.crt' -o -name '*.cer' \) -print0)
missing=()
for key in "${KEK_CERTS[@]}" "${DB_CERTS[@]}"; do
    [[ -n "${MS_FILE[$key]:-}" ]] || missing+=("${MS_NAME[$key]}")
done
if [[ ${#missing[@]} -gt 0 ]]; then
    printf 'ERROR: %s lacks:\n' "$MS_CERT_DIR" >&2
    printf '  %s\n' "${missing[@]}" >&2
    die "use virt-firmware 26.10 or later (--virt-fw-vars), or point --ms-certs at Microsoft's certificates"
fi

if [[ ${#DBX_FILES[@]} -eq 0 ]]; then
    command -v curl >/dev/null 2>&1 || die "curl not found; download $DBX_URL yourself and pass --dbx"
    cache_dir="${XDG_CACHE_HOME:-$HOME/.cache}/lamboot/secureboot_objects/${DBX_COMMIT:0:12}"
    cached="$cache_dir/dbx_x64.efiauth2"
    if [[ ! -f "$cached" ]] || [[ $(sha256sum < "$cached" | cut -d' ' -f1) != "$DBX_SHA256" ]]; then
        mkdir -p "$cache_dir"
        echo "Downloading Microsoft's x64 dbx update..."
        curl -fsSL --proto '=https' --retry 2 -o "$cached.part" "$DBX_URL" \
            || die "download failed: $DBX_URL (download it yourself and pass --dbx)"
        got=$(sha256sum < "$cached.part" | cut -d' ' -f1)
        if [[ "$got" != "$DBX_SHA256" ]]; then
            rm -f "$cached.part"
            die "$DBX_URL has sha256 $got, expected $DBX_SHA256"
        fi
        mv "$cached.part" "$cached"
    fi
    DBX_FILES=("$cached")
fi
if [[ ${#DBX_FILES[@]} -gt 1 ]] && ! "$VIRT_FW_VARS" --help 2>/dev/null | grep -q -- '--add-dbx'; then
    die "$VIRT_FW_VARS has no --add-dbx, so it cannot merge several --dbx files"
fi
: > "$WORK/dbx-in.lst"
DBX_SUMMARY=()
for f in "${DBX_FILES[@]}"; do
    [[ -s "$f" ]] || die "dbx update not found or empty: $f"
    probe dbx "$f" > "$WORK/dbx-one.lst" 2>/dev/null \
        || die "$f is not an authenticated dbx update"
    count=$(grep -c '^dbx sha256 ' "$WORK/dbx-one.lst" || true)
    [[ "$count" -gt 0 ]] || die "$f holds no revoked hashes"
    DBX_SUMMARY+=("sha256 $(sha256sum < "$f" | cut -d' ' -f1), $count revoked hashes")
    cat "$WORK/dbx-one.lst" >> "$WORK/dbx-in.lst"
done

echo "Building OVMF VARS with LamBoot's key and Microsoft's 2011 and 2023 CAs"
echo "  virt-fw-vars: $VIRT_FW_VARS (virt-firmware $VFW_VERSION)"
echo "  Template:     $VARS_TEMPLATE"
echo "                sha256 $(sha256sum < "$VARS_TEMPLATE" | cut -d' ' -f1)"
echo "                PK kept: $(cut -d' ' -f4- <<< "$PK_LINE")"
echo "  Certificate:  $CERT"
echo "                $(cert_subject "$CERT")"
echo "                sha256 fingerprint $LAMBOOT_FP"
echo "  MS certs:     $MS_CERT_DIR"
for i in "${!DBX_FILES[@]}"; do
    echo "  dbx update:   ${DBX_FILES[$i]}"
    echo "                ${DBX_SUMMARY[$i]}"
done
echo "  Output:       $OUTPUT"
echo ""

args=()
for key in "${KEK_CERTS[@]}"; do
    args+=(--add-kek "$MS_OWNER" "${MS_FILE[$key]}")
done
for key in "${DB_CERTS[@]}"; do
    args+=(--add-db "$MS_OWNER" "${MS_FILE[$key]}")
done
args+=(--add-db "$LAMBOOT_GUID" "$CERT")
args+=(--set-dbx "${DBX_FILES[0]}")
for f in "${DBX_FILES[@]:1}"; do
    args+=(--add-dbx "$f")
done

mkdir -p "$(dirname "$OUTPUT")"
TMP_OUT=$(mktemp -p "$(dirname "$OUTPUT")")
cp "$VARS_TEMPLATE" "$TMP_OUT"
"$VIRT_FW_VARS" --inplace "$TMP_OUT" "${args[@]}" 2> "$WORK/virt-fw-vars.log" \
    || { cat "$WORK/virt-fw-vars.log" >&2; die "virt-fw-vars failed"; }

probe vars "$TMP_OUT" > "$WORK/out.lst" || die "cannot read back $TMP_OUT"
has() { grep -q "^$1 x509 $2 " "$WORK/out.lst"; }
if [[ $(grep -c '^PK x509 ' "$WORK/out.lst") -ne 1 ]] || ! has PK "$PK_FP"; then
    die "PK in the result differs from the template's"
fi
for key in "${KEK_CERTS[@]}"; do
    has KEK "${MS_FP[$key]}" || die "KEK lacks ${MS_NAME[$key]}"
done
for key in "${DB_CERTS[@]}"; do
    has db "${MS_FP[$key]}" || die "db lacks ${MS_NAME[$key]}"
done
has db "$LAMBOOT_FP" || die "db lacks LamBoot's certificate"
grep '^dbx sha256 ' "$WORK/dbx-in.lst" | sort -u > "$WORK/dbx-want"
grep '^dbx sha256 ' "$WORK/out.lst" | sort -u > "$WORK/dbx-have"
lost=$(comm -23 "$WORK/dbx-want" "$WORK/dbx-have" | wc -l)
extra=$(comm -13 "$WORK/dbx-want" "$WORK/dbx-have" | wc -l)
[[ "$lost" -eq 0 ]] || die "$lost revoked hashes from the dbx update are missing from the result"
[[ "$extra" -eq 0 ]] || die "dbx in the result holds $extra hashes that are not in the dbx update"

# mktemp made the file private; the store holds only public certificates and is
# shipped in release tarballs.
chmod 0644 "$TMP_OUT"
mv "$TMP_OUT" "$OUTPUT"
TMP_OUT=""

echo "=== OVMF VARS built and verified ==="
echo "Output: $OUTPUT ($(stat -c %s "$OUTPUT") bytes)"
echo "sha256: $(sha256sum < "$OUTPUT" | cut -d' ' -f1)"
echo ""
"$VIRT_FW_VARS" -i "$OUTPUT" -p -v 2>/dev/null \
    | awk '/^name=/ { show = ($1 ~ /^name=(PK|KEK|db|dbx)$/) } show'
for var in PK KEK db; do
    echo "$var certificates (sha256 fingerprint, CN):"
    grep "^$var x509 " "$WORK/out.lst" | cut -d' ' -f3- | awk '{ printf "  %s\n", $0 }'
done
echo "dbx: $(wc -l < "$WORK/dbx-have") revoked SHA-256 hashes"
echo ""
echo "Deploying to Proxmox VMs, including the warning Proxmox prints for a"
echo "copied-in efidisk: docs/OVMF-VARS-PROXMOX.md"
echo ""
echo "To use with QEMU:"
echo "  qemu-system-x86_64 -machine q35,smm=on \\"
echo "    -global driver=cfi.pflash01,property=secure,value=on \\"
echo "    -drive if=pflash,format=raw,readonly=on,file=/usr/share/OVMF/OVMF_CODE_4M.secboot.fd \\"
echo "    -drive if=pflash,format=raw,file=<a writable copy of $OUTPUT>"
