Skip to content

Commit 48780dc

Browse files
committed
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.
1 parent 7379db3 commit 48780dc

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

build_library/qemu_template.sh

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ SSH_KEYS=""
1717
CLOUD_CONFIG_FILE=""
1818
IGNITION_CONFIG_FILE=""
1919
CONFIG_IMAGE=""
20+
SWTPM_DIR=
2021
SAFE_ARGS=0
2122
USAGE="Usage: $0 [-a authorized_keys] [--] [qemu options...]
2223
Options:
@@ -28,6 +29,8 @@ Options:
2829
-p PORT The port on localhost to map to the VM's sshd. [2222]
2930
-I FILE Set a custom image file.
3031
-M MB Set VM memory in MBs.
32+
-T DIR Add a software TPM2 device through swtpm which stores secrets
33+
and the control socket to the given directory.
3134
-s Safe settings: single simple cpu and no KVM.
3235
-h this ;-)
3336
@@ -84,6 +87,9 @@ while [ $# -ge 1 ]; do
8487
-M|-memory)
8588
VM_MEMORY="$2"
8689
shift 2 ;;
90+
-T|-tpm)
91+
SWTPM_DIR="$2"
92+
shift 2 ;;
8793
-v|-verbose)
8894
set -x
8995
shift ;;
@@ -117,6 +123,29 @@ write_ssh_keys() {
117123
sed -e 's/^/ - /'
118124
}
119125

126+
if [ -n "${SWTPM_DIR}" ]; then
127+
mkdir -p "${SWTPM_DIR}"
128+
if ! command -v swtpm >/dev/null; then
129+
echo "$0: swtpm command not found!" >&2
130+
exit 1
131+
fi
132+
case "${VM_BOARD}" in
133+
amd64-usr)
134+
TPM_DEV=tpm-tis ;;
135+
arm64-usr)
136+
TPM_DEV=tpm-tis-device ;;
137+
*) die "Unsupported arch" ;;
138+
esac
139+
SWTPM_SOCK="${SWTPM_DIR}/socket"
140+
swtpm socket --tpmstate "dir=${SWTPM_DIR}" --ctrl "type=unixio,path=${SWTPM_SOCK},terminate" --tpm2 &
141+
SWTPM_PROC=$!
142+
PARENT=$$
143+
# The swtpm process exits if qemu disconnects but if we never started qemu because
144+
# this script fails or qemu failed to start, we need to kill the process.
145+
# The EXIT trap is already in use by the config drive cleanup and anyway doesn't work with kill -9.
146+
(while [ -e "/proc/${PARENT}" ]; do sleep 1; done; kill "${SWTPM_PROC}" 2>/dev/null; exit 0) &
147+
set -- -chardev "socket,id=chrtpm,path=${SWTPM_SOCK}" -tpmdev emulator,id=tpm0,chardev=chrtpm -device "${TPM_DEV}",tpmdev=tpm0 "$@"
148+
fi
120149

121150
if [ -z "${CONFIG_IMAGE}" ]; then
122151
CONFIG_DRIVE=$(mktemp -d)

0 commit comments

Comments
 (0)