tpm2_stirrandom.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. #include "tpm2_options.h"
  7. /* Spec enforce input data to be not longer than 128 bytes */
  8. #define MAX_SIZE_TO_READ 128
  9. typedef struct tpm_stirrandom_ctx tpm_stirrandom_ctx;
  10. struct tpm_stirrandom_ctx {
  11. TPM2B_SENSITIVE_DATA in_data;
  12. char *in_file;
  13. };
  14. static tpm_stirrandom_ctx ctx = {
  15. .in_data = { .size = MAX_SIZE_TO_READ }
  16. };
  17. static bool on_args(int argc, char **argv) {
  18. if (argc != 1) {
  19. LOG_ERR("Only supports one FILE_INPUT file, got %d arguments", argc);
  20. return false;
  21. }
  22. ctx.in_file = argv[0];
  23. return true;
  24. }
  25. static bool tpm2_tool_onstart(tpm2_options **opts) {
  26. *opts = tpm2_options_new(NULL, 0, NULL, NULL, on_args, 0);
  27. return *opts != NULL;
  28. }
  29. static bool load_sensitive(void) {
  30. bool res = files_load_bytes_from_buffer_or_file_or_stdin(NULL, ctx.in_file,
  31. &ctx.in_data.size, ctx.in_data.buffer);
  32. if (!res) {
  33. LOG_ERR("Error while reading data from file or stdin");
  34. return false;
  35. }
  36. if (ctx.in_data.size == 0) {
  37. LOG_ERR("Data size to send is zero");
  38. return false;
  39. }
  40. LOG_INFO("Submitting %d bytes to TPM", ctx.in_data.size);
  41. return true;
  42. }
  43. static tool_rc tpm2_tool_onrun(ESYS_CONTEXT *ectx, tpm2_option_flags flags) {
  44. UNUSED(flags);
  45. if (!load_sensitive()) {
  46. return tool_rc_general_error;
  47. }
  48. return tpm2_stirrandom(ectx, &ctx.in_data);
  49. }
  50. // Register this tool with tpm2_tool.c
  51. TPM2_TOOL_REGISTER("stirrandom", tpm2_tool_onstart, tpm2_tool_onrun, NULL, NULL)