tpm2_policycommandcode.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. /* SPDX-License-Identifier: BSD-3-Clause */
  2. #include <stdlib.h>
  3. #include "files.h"
  4. #include "log.h"
  5. #include "tpm2_cc_util.h"
  6. #include "tpm2_policy.h"
  7. #include "tpm2_tool.h"
  8. typedef struct tpm2_policycommandcode_ctx tpm2_policycommandcode_ctx;
  9. struct tpm2_policycommandcode_ctx {
  10. const char *session_path;
  11. TPM2_CC command_code;
  12. const char *out_policy_dgst_path;
  13. tpm2_session *session;
  14. };
  15. static tpm2_policycommandcode_ctx ctx;
  16. static bool on_option(char key, char *value) {
  17. switch (key) {
  18. case 'S':
  19. ctx.session_path = value;
  20. break;
  21. case 'L':
  22. ctx.out_policy_dgst_path = value;
  23. break;
  24. }
  25. return true;
  26. }
  27. static bool is_input_option_args_valid(void) {
  28. if (!ctx.session_path) {
  29. LOG_ERR("Must specify -S session file.");
  30. return false;
  31. }
  32. return true;
  33. }
  34. static bool on_arg(int argc, char **argv) {
  35. if (argc > 1) {
  36. LOG_ERR("Specify only the TPM2 command code.");
  37. return false;
  38. }
  39. if (!argc) {
  40. LOG_ERR("TPM2 command code must be specified.");
  41. return false;
  42. }
  43. bool result = tpm2_cc_util_from_str(argv[0], &ctx.command_code);
  44. if (!result) {
  45. return false;
  46. }
  47. return true;
  48. }
  49. static bool tpm2_tool_onstart(tpm2_options **opts) {
  50. static struct option topts[] = {
  51. { "session", required_argument, NULL, 'S' },
  52. { "policy", required_argument, NULL, 'L' },
  53. };
  54. *opts = tpm2_options_new("S:L:", ARRAY_LEN(topts), topts, on_option, on_arg,
  55. 0);
  56. return *opts != NULL;
  57. }
  58. static tool_rc tpm2_tool_onrun(ESYS_CONTEXT *ectx, tpm2_option_flags flags) {
  59. UNUSED(flags);
  60. bool retval = is_input_option_args_valid();
  61. if (!retval) {
  62. return tool_rc_option_error;
  63. }
  64. tool_rc rc = tpm2_session_restore(ectx, ctx.session_path, false,
  65. &ctx.session);
  66. if (rc != tool_rc_success) {
  67. return rc;
  68. }
  69. rc = tpm2_policy_build_policycommandcode(ectx, ctx.session,
  70. ctx.command_code);
  71. if (rc != tool_rc_success) {
  72. LOG_ERR("Could not build TPM policy_command_code");
  73. return rc;
  74. }
  75. return tpm2_policy_tool_finish(ectx, ctx.session, ctx.out_policy_dgst_path);
  76. }
  77. static tool_rc tpm2_tool_onstop(ESYS_CONTEXT *ectx) {
  78. UNUSED(ectx);
  79. return tpm2_session_close(&ctx.session);
  80. }
  81. // Register this tool with tpm2_tool.c
  82. TPM2_TOOL_REGISTER("policycommandcode", tpm2_tool_onstart, tpm2_tool_onrun, tpm2_tool_onstop, NULL)