diff --git a/build_library/qemu_template.sh b/build_library/qemu_template.sh index 86697ff887..2cd73e6e5d 100755 --- a/build_library/qemu_template.sh +++ b/build_library/qemu_template.sh @@ -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)