#!/bin/bash

## Copyright (C) 2026 - 2026 ENCRYPTED SUPPORT LLC <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

## This script is disabled by default and requires an explicit opt-in.
## It allows kernel parameter injections via SMBIOS, which could be exploited
## for malicious purposes.
##
## TODO: Once live-build is removed, we may be able to get rid of the
## dm-smbios-reader border comments.

set -o errexit
set -o nounset
set -o pipefail
set -o errtrace
shopt -s inherit_errexit
shopt -s shift_verbose

[ -v GRUB_ENABLE_DM_SMBIOS_READER ] || GRUB_ENABLE_DM_SMBIOS_READER=""

if [ "${GRUB_ENABLE_DM_SMBIOS_READER}" != "true" ]; then
   exit 0
fi

## We only allow kernel parameter injection if SMBIOS reports that the
## manufacturer is QEMU. When that is the case, we read the SMBIOS serial
## number and see if it starts with "dm-cmdline='. If so, we take everything
## after the '=' and store it in dm_smbios_extra, which will eventually be
## interpolated into the kernel command line when this feature is enabled. We
## also enable a serial console and make boot instant.
##
## NOTE: Don't embed comments in the GRUB script code, those would end up in
## grub.cfg.

cat <<'EOF'
## dm-smbios-reader: begin
insmod regexp
insmod smbios
insmod serial
set dm_smbios_vendor=
set dm_smbios_serial_index=0
set dm_smbios_oem=
set dm_smbios_extra=
smbios --type 1 --get-string 4 --set dm_smbios_vendor
if [ "${dm_smbios_vendor}" = "QEMU" ]; then
    smbios --type 1 --get-byte 7 --set dm_smbios_serial_index
    if [ "${dm_smbios_serial_index}" != "0" ]; then
        smbios --type 1 --get-string 7 --set dm_smbios_oem
        regexp --set 1:dm_smbios_extra "^dm-cmdline=(.*)" "${dm_smbios_oem}"
    fi
fi
if [ -n "${dm_smbios_extra}" ]; then
    serial --unit=0 --speed=115200 --word=8 --parity=no --stop=1
    terminal_output serial console
    set timeout=0
fi
## dm-smbios-reader: end
EOF
