tpm_parser.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. // SPDX-License-Identifier: GPL-2.0
  2. #define pr_fmt(fmt) "TPM-PARSER: "fmt
  3. #include <linux/module.h>
  4. #include <linux/kernel.h>
  5. #include <linux/export.h>
  6. #include <linux/slab.h>
  7. #include <linux/err.h>
  8. #include <keys/asymmetric-subtype.h>
  9. #include <keys/asymmetric-parser.h>
  10. #include <crypto/asym_tpm_subtype.h>
  11. #include "tpm.asn1.h"
  12. struct tpm_parse_context {
  13. const void *blob;
  14. u32 blob_len;
  15. };
  16. /*
  17. * Note the key data of the ASN.1 blob.
  18. */
  19. int tpm_note_key(void *context, size_t hdrlen,
  20. unsigned char tag,
  21. const void *value, size_t vlen)
  22. {
  23. struct tpm_parse_context *ctx = context;
  24. ctx->blob = value;
  25. ctx->blob_len = vlen;
  26. return 0;
  27. }
  28. /*
  29. * Parse a TPM-encrypted private key blob.
  30. */
  31. static struct tpm_key *tpm_parse(const void *data, size_t datalen)
  32. {
  33. struct tpm_parse_context ctx;
  34. long ret;
  35. memset(&ctx, 0, sizeof(ctx));
  36. /* Attempt to decode the private key */
  37. ret = asn1_ber_decoder(&tpm_decoder, &ctx, data, datalen);
  38. if (ret < 0)
  39. goto error;
  40. return tpm_key_create(ctx.blob, ctx.blob_len);
  41. error:
  42. return ERR_PTR(ret);
  43. }
  44. /*
  45. * Attempt to parse a data blob for a key as a TPM private key blob.
  46. */
  47. static int tpm_key_preparse(struct key_preparsed_payload *prep)
  48. {
  49. struct tpm_key *tk;
  50. /*
  51. * TPM 1.2 keys are max 2048 bits long, so assume the blob is no
  52. * more than 4x that
  53. */
  54. if (prep->datalen > 256 * 4)
  55. return -EMSGSIZE;
  56. tk = tpm_parse(prep->data, prep->datalen);
  57. if (IS_ERR(tk))
  58. return PTR_ERR(tk);
  59. /* We're pinning the module by being linked against it */
  60. __module_get(asym_tpm_subtype.owner);
  61. prep->payload.data[asym_subtype] = &asym_tpm_subtype;
  62. prep->payload.data[asym_key_ids] = NULL;
  63. prep->payload.data[asym_crypto] = tk;
  64. prep->payload.data[asym_auth] = NULL;
  65. prep->quotalen = 100;
  66. return 0;
  67. }
  68. static struct asymmetric_key_parser tpm_key_parser = {
  69. .owner = THIS_MODULE,
  70. .name = "tpm_parser",
  71. .parse = tpm_key_preparse,
  72. };
  73. static int __init tpm_key_init(void)
  74. {
  75. return register_asymmetric_key_parser(&tpm_key_parser);
  76. }
  77. static void __exit tpm_key_exit(void)
  78. {
  79. unregister_asymmetric_key_parser(&tpm_key_parser);
  80. }
  81. module_init(tpm_key_init);
  82. module_exit(tpm_key_exit);
  83. MODULE_DESCRIPTION("TPM private key-blob parser");
  84. MODULE_LICENSE("GPL v2");