tss2_createkey.c 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /* SPDX-License-Identifier: BSD-3-Clause */
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include "tools/fapi/tss2_template.h"
  6. /* needed to conditionally free variable authValue */
  7. static bool has_asked_for_password = false;
  8. /* Context struct used to store passed commandline parameters */
  9. static struct cxt {
  10. char const *keyPath;
  11. char const *keyType;
  12. char const *policyPath;
  13. char *authValue;
  14. } ctx;
  15. /* Parse commandline parameters */
  16. static bool on_option(char key, char *value) {
  17. switch (key) {
  18. case 'a':
  19. ctx.authValue = value;
  20. break;
  21. case 'p':
  22. ctx.keyPath = value;
  23. break;
  24. case 'P':
  25. ctx.policyPath = value;
  26. break;
  27. case 't':
  28. ctx.keyType = value;
  29. break;
  30. }
  31. return true;
  32. }
  33. /* Define possible commandline parameters */
  34. static bool tss2_tool_onstart(tpm2_options **opts) {
  35. struct option topts[] = {
  36. {"path", required_argument, NULL, 'p'},
  37. {"type", required_argument, NULL, 't'},
  38. {"policyPath", required_argument, NULL, 'P'},
  39. {"authValue", required_argument, NULL, 'a'},
  40. };
  41. return (*opts = tpm2_options_new ("a:p:P:t:", ARRAY_LEN(topts), topts,
  42. on_option, NULL, 0)) != NULL;
  43. }
  44. /* Execute specific tool */
  45. static int tss2_tool_onrun (FAPI_CONTEXT *fctx) {
  46. /* Check availability of required parameters */
  47. if (!ctx.keyPath) {
  48. fprintf (stderr, "key path missing, use --path\n");
  49. return -1;
  50. }
  51. /* If no authValue was given, prompt the user interactively */
  52. if (!ctx.authValue) {
  53. ctx.authValue = ask_for_password ();
  54. has_asked_for_password = true;
  55. if (!ctx.authValue){
  56. return 1; /* User entered two different passwords */
  57. }
  58. }
  59. /* Execute FAPI command with passed arguments */
  60. TSS2_RC r = Fapi_CreateKey (fctx, ctx.keyPath, ctx.keyType, ctx.policyPath,
  61. ctx.authValue);
  62. if (r != TSS2_RC_SUCCESS){
  63. if(has_asked_for_password){
  64. free (ctx.authValue);
  65. }
  66. LOG_PERR ("Fapi_CreateKey", r);
  67. return 1;
  68. }
  69. if(has_asked_for_password){
  70. free (ctx.authValue);
  71. }
  72. return 0;
  73. }
  74. TSS2_TOOL_REGISTER("createkey", tss2_tool_onstart, tss2_tool_onrun, NULL)