tpm2_policycphash.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /* SPDX-License-Identifier: BSD-3-Clause */
  2. #include "files.h"
  3. #include "log.h"
  4. #include "tpm2.h"
  5. #include "tpm2_policy.h"
  6. #include "tpm2_tool.h"
  7. typedef struct tpm2_policycphash_ctx tpm2_policycphash_ctx;
  8. struct tpm2_policycphash_ctx {
  9. //Input
  10. TPM2B_DIGEST cphash;
  11. //Input/Output
  12. const char *session_file_path;
  13. tpm2_session *session;
  14. //Output
  15. const char *policy_digest_file_path;
  16. };
  17. static tpm2_policycphash_ctx ctx;
  18. static bool process_input_cphash(char *value) {
  19. bool result = files_load_digest(value, &ctx.cphash);
  20. if (!result) {
  21. LOG_ERR("Failed loading creation hash.");
  22. }
  23. return result;
  24. }
  25. static bool on_option(char key, char *value) {
  26. bool result = true;
  27. switch (key) {
  28. case 'L':
  29. ctx.policy_digest_file_path = value;
  30. break;
  31. case 'S':
  32. ctx.session_file_path = value;
  33. break;
  34. case 0:
  35. result = process_input_cphash(value);
  36. break;
  37. }
  38. return result;
  39. }
  40. static bool tpm2_tool_onstart(tpm2_options **opts) {
  41. static struct option topts[] = {
  42. { "policy", required_argument, NULL, 'L' },
  43. { "session", required_argument, NULL, 'S' },
  44. { "cphash-input", required_argument, NULL, 0 },
  45. { "cphash", required_argument, NULL, 0 },
  46. };
  47. *opts = tpm2_options_new("L:S:", ARRAY_LEN(topts), topts, on_option, NULL,
  48. 0);
  49. return *opts != NULL;
  50. }
  51. static bool is_input_option_args_valid(void) {
  52. if (!ctx.session_file_path) {
  53. LOG_ERR("Must specify -S session file.");
  54. return false;
  55. }
  56. if (!ctx.cphash.size) {
  57. LOG_ERR("CpHash file is of size zero.");
  58. }
  59. return true;
  60. }
  61. static tool_rc tpm2_tool_onrun(ESYS_CONTEXT *ectx, tpm2_option_flags flags) {
  62. UNUSED(flags);
  63. bool retval = is_input_option_args_valid();
  64. if (!retval) {
  65. return tool_rc_option_error;
  66. }
  67. tool_rc rc = tpm2_session_restore(ectx, ctx.session_file_path, false,
  68. &ctx.session);
  69. if (rc != tool_rc_success) {
  70. return rc;
  71. }
  72. rc = tpm2_policy_build_policycphash(ectx, ctx.session, &ctx.cphash);
  73. if (rc != tool_rc_success) {
  74. LOG_ERR("Could not build policycphash TPM");
  75. return rc;
  76. }
  77. return tpm2_policy_tool_finish(ectx, ctx.session, ctx.policy_digest_file_path);
  78. }
  79. static tool_rc tpm2_tool_onstop(ESYS_CONTEXT *ectx) {
  80. UNUSED(ectx);
  81. return tpm2_session_close(&ctx.session);
  82. }
  83. // Register this tool with tpm2_tool.c
  84. TPM2_TOOL_REGISTER("policycphash", tpm2_tool_onstart, tpm2_tool_onrun, tpm2_tool_onstop, NULL)