swtpm.sh 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. TPM_PATH=/tmp/$TPM_NAME
  9. # The file where swtpm's pid will be stored.
  10. TPM_PID=$TPM_PATH/swtpm.pid
  11. # The file where tpm2-abrmd's pid will be stored.
  12. TPM_ABRMD_PID=$TPM_PATH/tpm2-abrmd.pid
  13. TPM_ADDR=127.0.0.1
  14. TPM_PORT=2321
  15. setup() {
  16. mkdir -p $TPM_PATH
  17. swtpm_setup --config swtpm_setup.conf --tpm-state dir://$TPM_PATH \
  18. --tpm2 --ecc --createek --display
  19. }
  20. start() {
  21. if [ ! -d $TPM_PATH ]; then
  22. setup
  23. fi
  24. if [ -f $TPM_PID ]; then
  25. echo "swtpm is already running with PID $(cat $TPM_PID)."
  26. exit 1
  27. fi
  28. swtpm socket --server type=tcp,port=$TPM_PORT,bindaddr=$TPM_ADDR \
  29. --ctrl type=tcp,port=$(($TPM_PORT + 1)),bindaddr=$TPM_ADDR \
  30. --tpm2 --log file=$TPM_PATH/log.txt,level=5 \
  31. --flags not-need-init,startup-clear --pid file=$TPM_PID \
  32. --tpmstate dir=$TPM_PATH --daemon
  33. if [ "$UID" = 0 ]; then
  34. # If this script was run as root, then connect to the system bus.
  35. tpm2-abrmd --tcti="swtpm:host=$TPM_ADDR" --allow-root &
  36. else
  37. tpm2-abrmd --tcti="swtpm:host=$TPM_ADDR" --session &
  38. fi
  39. echo -n $! > $TPM_ABRMD_PID
  40. }
  41. kill_from_file() {
  42. pid=$(cat $1)
  43. kill -s TERM $pid
  44. }
  45. stop() {
  46. if [ ! -f $TPM_PID ]; then
  47. echo "swtpm is not running."
  48. exit 1
  49. fi
  50. kill_from_file $TPM_ABRMD_PID
  51. rm $TPM_ABRMD_PID
  52. kill_from_file $TPM_PID
  53. }
  54. restart() {
  55. stop
  56. sleep 0.2
  57. start
  58. }
  59. purge() {
  60. if [ -f $TPM_PID ]; then
  61. stop
  62. fi
  63. rm -rf $TPM_PATH
  64. }
  65. usage() {
  66. echo "${0} <start|stop|restart>"
  67. }
  68. case "${1}" in
  69. start)
  70. start
  71. ;;
  72. stop)
  73. stop
  74. ;;
  75. restart)
  76. restart
  77. ;;
  78. purge)
  79. purge
  80. ;;
  81. *)
  82. usage
  83. ;;
  84. esac