Skip to content

Commit

Permalink
tests/setup_swtpm.sh: Add script to setup temporary TPM
Browse files Browse the repository at this point in the history
Add the tests/setup_swtpm.sh script which setup a Software TPM in a
temporary directory, starts the swtpm socket, and sets the environment
TCTI accordingly.

This allows the tests to be executed locally, even with the "testing"
feature.

Unfortunately, it is not possible to cleanup some of the transient
objects created during tests, being necessary to cleanup manually
between runs by running:

$ tpm2_flushcontext -t -l -s

Another caveat is that the tests need to run on a single thread to avoid
test cases that create objects to run in parallel, which can fill up the
TPM memory with transient object contexts. For this, please run the
tests on a single thread:

$ cargo test --features=testing -- --test-threads=1

The swtpm socket process is stopped when exiting from the started shell.

Fixes: #259

Signed-off-by: Anderson Toshiyuki Sasaki <[email protected]>
  • Loading branch information
ansasaki committed Nov 20, 2024
1 parent 7b19329 commit 11c8157
Showing 1 changed file with 57 additions and 0 deletions.
57 changes: 57 additions & 0 deletions tests/setup_swtpm.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#!/usr/bin/env bash
# SPDX-License-Identifier: Apache-2.0
# Copyright 2021 Keylime Authors

set -euf -o pipefail

if [[ $# -eq 0 ]] || [[ -z "$1" ]]; then
TEMPDIR=$(mktemp -d)
TPMDIR="${TEMPDIR}/tpmdir"
mkdir -p ${TPMDIR}
else
echo "Using TPM state from $1"
TPMDIR=$1
fi

# Manufacture a new Software TPM
swtpm_setup --tpm2 \
--tpmstate ${TPMDIR} \
--createek --decryption --create-ek-cert \
--create-platform-cert \
--lock-nvram \
--not-overwrite \
--pcr-banks sha256 \
--display

function start_swtpm {
# Initialize the swtpm socket
swtpm socket --tpm2 \
--tpmstate dir=${TPMDIR} \
--flags startup-clear \
--ctrl type=tcp,port=2322 \
--server type=tcp,port=2321 \
--log level=1 &
SWTPM_PID=$!
}

function stop_swtpm {
# Stop swtpm if running
if [[ -n "$SWTPM_PID" ]]; then
echo "Stopping swtpm"
kill $SWTPM_PID
fi
}

# Set cleanup function to run at exit
function cleanup {
echo "-------- Cleanup processes"
stop_swtpm
}
trap cleanup EXIT

# Set the TCTI to use the swtpm socket
export TCTI=swtpm
export TPM2TOOLS_TCTI=swtpm

start_swtpm
bash

0 comments on commit 11c8157

Please sign in to comment.