tpm2_clear.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /* SPDX-License-Identifier: BSD-3-Clause */
  2. #include "files.h"
  3. #include "log.h"
  4. #include "tpm2.h"
  5. #include "tpm2_tool.h"
  6. typedef struct clear_ctx clear_ctx;
  7. struct clear_ctx {
  8. struct {
  9. const char *ctx_path;
  10. const char *auth_str;
  11. tpm2_loaded_object object;
  12. } auth_hierarchy;
  13. char *cp_hash_path;
  14. };
  15. static clear_ctx ctx = {
  16. .auth_hierarchy.ctx_path = "l",
  17. };
  18. static bool on_option(char key, char *value) {
  19. switch (key) {
  20. case 'c':
  21. ctx.auth_hierarchy.ctx_path = value;
  22. break;
  23. case 0:
  24. ctx.cp_hash_path = value;
  25. break;
  26. }
  27. return true;
  28. }
  29. static bool on_arg(int argc, char **argv) {
  30. if (argc > 1) {
  31. LOG_ERR("Specify a single auth value");
  32. return false;
  33. }
  34. if (!argc) {
  35. //empty auth
  36. return true;
  37. }
  38. ctx.auth_hierarchy.auth_str = argv[0];
  39. return true;
  40. }
  41. static bool tpm2_tool_onstart(tpm2_options **opts) {
  42. const struct option topts[] = {
  43. { "auth-hierarchy", no_argument, NULL, 'c' },
  44. { "cphash", required_argument, NULL, 0 },
  45. };
  46. *opts = tpm2_options_new("c:", ARRAY_LEN(topts), topts, on_option, on_arg,
  47. 0);
  48. return *opts != NULL;
  49. }
  50. static tool_rc tpm2_tool_onrun(ESYS_CONTEXT *ectx, tpm2_option_flags flags) {
  51. UNUSED(flags);
  52. tool_rc rc = tpm2_util_object_load_auth(ectx, ctx.auth_hierarchy.ctx_path,
  53. ctx.auth_hierarchy.auth_str, &ctx.auth_hierarchy.object, false,
  54. TPM2_HANDLE_FLAGS_L | TPM2_HANDLE_FLAGS_P);
  55. if (rc != tool_rc_success) {
  56. LOG_ERR("Invalid lockout authorization");
  57. return rc;
  58. }
  59. if (ctx.cp_hash_path) {
  60. LOG_WARN("Generating cpHash. Exiting without executing clear.");
  61. TPM2B_DIGEST cp_hash = { .size = 0 };
  62. tool_rc rc = tpm2_clear(ectx, &ctx.auth_hierarchy.object, &cp_hash);
  63. if (rc != tool_rc_success) {
  64. return rc;
  65. }
  66. bool result = files_save_digest(&cp_hash, ctx.cp_hash_path);
  67. if (!result) {
  68. rc = tool_rc_general_error;
  69. }
  70. return rc;
  71. }
  72. return tpm2_clear(ectx, &ctx.auth_hierarchy.object, NULL);
  73. }
  74. static tool_rc tpm2_tool_onstop(ESYS_CONTEXT *ectx) {
  75. UNUSED(ectx);
  76. return tpm2_session_close(&ctx.auth_hierarchy.object.session);
  77. }
  78. // Register this tool with tpm2_tool.c
  79. TPM2_TOOL_REGISTER("clear", tpm2_tool_onstart, tpm2_tool_onrun, tpm2_tool_onstop, NULL)