qemu_template.sh: Add support for attaching a software TPM

For testing TPM2-backed rootfs encryption it is handy to have a software
TPM option for the qemu script.
Add a flag for a software TPM with swtpm like kola also does. The user
has to specify a folder for the secret state and this won't be removed
because the same store should be able to be passed when booting the VM
again after shutdown.
This commit is contained in:
Kai Lueke 2024-04-03 21:01:00 +09:00
parent 7379db37e8
commit 48780dc375

View File

@ -17,6 +17,7 @@ SSH_KEYS=""
CLOUD_CONFIG_FILE=""
IGNITION_CONFIG_FILE=""
CONFIG_IMAGE=""
SWTPM_DIR=
SAFE_ARGS=0
USAGE="Usage: $0 [-a authorized_keys] [--] [qemu options...]
Options:
@ -28,6 +29,8 @@ Options:
-p PORT The port on localhost to map to the VM's sshd. [2222]
-I FILE Set a custom image file.
-M MB Set VM memory in MBs.
-T DIR Add a software TPM2 device through swtpm which stores secrets
and the control socket to the given directory.
-s Safe settings: single simple cpu and no KVM.
-h this ;-)
@ -84,6 +87,9 @@ while [ $# -ge 1 ]; do
-M|-memory)
VM_MEMORY="$2"
shift 2 ;;
-T|-tpm)
SWTPM_DIR="$2"
shift 2 ;;
-v|-verbose)
set -x
shift ;;
@ -117,6 +123,29 @@ write_ssh_keys() {
sed -e 's/^/ - /'
}
if [ -n "${SWTPM_DIR}" ]; then
mkdir -p "${SWTPM_DIR}"
if ! command -v swtpm >/dev/null; then
echo "$0: swtpm command not found!" >&2
exit 1
fi
case "${VM_BOARD}" in
amd64-usr)
TPM_DEV=tpm-tis ;;
arm64-usr)
TPM_DEV=tpm-tis-device ;;
*) die "Unsupported arch" ;;
esac
SWTPM_SOCK="${SWTPM_DIR}/socket"
swtpm socket --tpmstate "dir=${SWTPM_DIR}" --ctrl "type=unixio,path=${SWTPM_SOCK},terminate" --tpm2 &
SWTPM_PROC=$!
PARENT=$$
# The swtpm process exits if qemu disconnects but if we never started qemu because
# this script fails or qemu failed to start, we need to kill the process.
# The EXIT trap is already in use by the config drive cleanup and anyway doesn't work with kill -9.
(while [ -e "/proc/${PARENT}" ]; do sleep 1; done; kill "${SWTPM_PROC}" 2>/dev/null; exit 0) &
set -- -chardev "socket,id=chrtpm,path=${SWTPM_SOCK}" -tpmdev emulator,id=tpm0,chardev=chrtpm -device "${TPM_DEV}",tpmdev=tpm0 "$@"
fi
if [ -z "${CONFIG_IMAGE}" ]; then
CONFIG_DRIVE=$(mktemp -d)