swtpm.sh 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. sleep 0.2
  52. start
  53. }
  54. purge() {
  55. if [ -f $TPM_PID ]; then
  56. stop
  57. fi
  58. rm -rf $TPM_PATH
  59. }
  60. usage() {
  61. echo "${0} <start|stop|restart>"
  62. }
  63. case "${1}" in
  64. start)
  65. start
  66. ;;
  67. stop)
  68. stop
  69. ;;
  70. restart)
  71. restart
  72. ;;
  73. purge)
  74. purge
  75. ;;
  76. *)
  77. usage
  78. ;;
  79. esac