swtpm.sh 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. tpm2-abrmd --tcti="swtpm:host=$TPM_ADDR" --session &
  34. echo -n $! > $TPM_ABRMD_PID
  35. }
  36. kill_from_file() {
  37. pid=$(cat $1)
  38. kill -s TERM $pid
  39. }
  40. stop() {
  41. if [ ! -f $TPM_PID ]; then
  42. echo "swtpm is not running."
  43. exit 1
  44. fi
  45. kill_from_file $TPM_ABRMD_PID
  46. rm $TPM_ABRMD_PID
  47. kill_from_file $TPM_PID
  48. }
  49. restart() {
  50. stop
  51. start
  52. }
  53. purge() {
  54. if [ -f $TPM_PID ]; then
  55. stop
  56. fi
  57. rm -rf $TPM_PATH
  58. }
  59. usage() {
  60. echo "${0} <start|stop|restart>"
  61. }
  62. case "${1}" in
  63. start)
  64. start
  65. ;;
  66. stop)
  67. stop
  68. ;;
  69. restart)
  70. restart
  71. ;;
  72. purge)
  73. purge
  74. ;;
  75. *)
  76. usage
  77. ;;
  78. esac