swtpm.sh 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/bin/sh
  2. # Script for provisioning and running the swtpm emulator. This script can only be run by a user with
  3. # sudo privileges.
  4. set -e
  5. # The name of the virtual TPM device. This will determine the name of the device under /dev.
  6. TPM_NAME=vtpm0
  7. # The path to the directory where the TPM's state will be stored.
  8. export TPM_PATH=/tmp/$TPM_NAME
  9. # The name of the user to run swtpm as.
  10. TPM_USER=tss
  11. # The file where swtpm's pid will be stored.
  12. TPM_PID=$TPM_PATH/swtpm.pid
  13. setup() {
  14. mkdir -p $TPM_PATH
  15. swtpm_setup --config swtpm_setup.conf --tpm-state dir://$TPM_PATH \
  16. --tpm2 --ecc --createek --display
  17. }
  18. start() {
  19. if [ ! -d $TPM_PATH ]; then
  20. setup
  21. fi
  22. if [ -f $TPM_PID ]; then
  23. echo "swtpm is already running with PID $(cat $TPM_PID)."
  24. exit 1
  25. fi
  26. sudo swtpm cuse --name $TPM_NAME --tpm2 --log file=$TPM_PATH/log.txt,level=5 \
  27. --flags not-need-init,startup-clear --pid file=$TPM_PID \
  28. --runas $TPM_USER --tpmstate dir=$TPM_PATH
  29. sudo chown :$TPM_USER /dev/$TPM_NAME
  30. sudo chmod 0660 /dev/$TPM_NAME
  31. }
  32. stop() {
  33. if [ ! -f $TPM_PID ]; then
  34. echo "swtpm is not running."
  35. exit 1
  36. fi
  37. pid=$(cat $TPM_PID)
  38. sudo rm $TPM_PID
  39. sudo kill -SIGTERM $pid
  40. }
  41. usage() {
  42. echo "${0} <start|stop>"
  43. }
  44. if [ "${1}" = start ]; then
  45. start
  46. elif [ "${1}" = stop ]; then
  47. stop
  48. else
  49. usage
  50. fi