tpm2_hierarchy.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* SPDX-License-Identifier: BSD-3-Clause */
  2. #include <stdbool.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include "log.h"
  6. #include "tool_rc.h"
  7. #include "tpm2.h"
  8. #include "tpm2_auth_util.h"
  9. #include "tpm2_alg_util.h"
  10. #include "tpm2_hierarchy.h"
  11. tool_rc tpm2_hierarchy_create_primary(ESYS_CONTEXT *ectx, tpm2_session *sess,
  12. tpm2_hierarchy_pdata *objdata, TPM2B_DIGEST *cp_hash) {
  13. ESYS_TR hierarchy;
  14. hierarchy = tpm2_tpmi_hierarchy_to_esys_tr(objdata->in.hierarchy);
  15. ESYS_TR shandle1 = ESYS_TR_NONE;
  16. tool_rc rc = tpm2_auth_util_get_shandle(ectx, hierarchy, sess, &shandle1);
  17. if (rc != tool_rc_success) {
  18. LOG_ERR("Couldn't get shandle for hierarchy");
  19. return rc;
  20. }
  21. if (cp_hash) {
  22. /*
  23. * Need sys_context to be able to calculate CpHash
  24. */
  25. TSS2_SYS_CONTEXT *sys_context = NULL;
  26. rc = tpm2_getsapicontext(ectx, &sys_context);
  27. if(rc != tool_rc_success) {
  28. LOG_ERR("Failed to acquire SAPI context.");
  29. return rc;
  30. }
  31. TSS2_RC rval = Tss2_Sys_CreatePrimary_Prepare(sys_context,
  32. objdata->in.hierarchy, &objdata->in.sensitive, &objdata->in.public,
  33. &objdata->in.outside_info, &objdata->in.creation_pcr);
  34. if (rval != TPM2_RC_SUCCESS) {
  35. LOG_PERR(Tss2_Sys_CreatePrimary_Prepare, rval);
  36. return tool_rc_general_error;
  37. }
  38. TPM2B_NAME *name1 = NULL;
  39. rc = tpm2_tr_get_name(ectx, hierarchy, &name1);
  40. if (rc != tool_rc_success) {
  41. goto tpm2_create_free_name1;
  42. }
  43. cp_hash->size = tpm2_alg_util_get_hash_size(
  44. tpm2_session_get_authhash(sess));
  45. rc = tpm2_sapi_getcphash(sys_context, name1, NULL, NULL,
  46. tpm2_session_get_authhash(sess), cp_hash);
  47. /*
  48. * Exit here without making the ESYS call since we just need the cpHash
  49. */
  50. tpm2_create_free_name1:
  51. Esys_Free(name1);
  52. return rc;
  53. }
  54. return tpm2_create_primary(ectx, hierarchy, shandle1, ESYS_TR_NONE,
  55. ESYS_TR_NONE, &objdata->in.sensitive, &objdata->in.public,
  56. &objdata->in.outside_info, &objdata->in.creation_pcr,
  57. &objdata->out.handle, &objdata->out.public,
  58. &objdata->out.creation.data, &objdata->out.hash,
  59. &objdata->out.creation.ticket);
  60. }
  61. void tpm2_hierarchy_pdata_free(tpm2_hierarchy_pdata *objdata) {
  62. free(objdata->out.creation.data);
  63. objdata->out.creation.data = NULL;
  64. free(objdata->out.creation.ticket);
  65. objdata->out.creation.ticket = NULL;
  66. free(objdata->out.hash);
  67. objdata->out.hash = NULL;
  68. free(objdata->out.public);
  69. objdata->out.public = NULL;
  70. }