packed_key.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. /* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
  2. * Use of this source code is governed by a BSD-style license that can be
  3. * found in the LICENSE file.
  4. *
  5. * Key unpacking functions
  6. */
  7. #include "2sysincludes.h"
  8. #include "2rsa.h"
  9. #include "vb2_common.h"
  10. const uint8_t *vb2_packed_key_data(const struct vb2_packed_key *key)
  11. {
  12. return (const uint8_t *)key + key->key_offset;
  13. }
  14. int vb2_verify_packed_key_inside(const void *parent,
  15. uint32_t parent_size,
  16. const struct vb2_packed_key *key)
  17. {
  18. return vb2_verify_member_inside(parent, parent_size,
  19. key, sizeof(*key),
  20. key->key_offset, key->key_size);
  21. }
  22. int vb2_unpack_key_buffer(struct vb2_public_key *key,
  23. const uint8_t *buf,
  24. uint32_t size)
  25. {
  26. const struct vb2_packed_key *packed_key =
  27. (const struct vb2_packed_key *)buf;
  28. const uint32_t *buf32;
  29. uint32_t expected_key_size;
  30. int rv;
  31. /* Make sure passed buffer is big enough for the packed key */
  32. rv = vb2_verify_packed_key_inside(buf, size, packed_key);
  33. if (rv)
  34. return rv;
  35. /* Unpack key algorithm */
  36. key->sig_alg = vb2_crypto_to_signature(packed_key->algorithm);
  37. if (key->sig_alg == VB2_SIG_INVALID) {
  38. VB2_DEBUG("Unsupported signature algorithm.\n");
  39. return VB2_ERROR_UNPACK_KEY_SIG_ALGORITHM;
  40. }
  41. key->hash_alg = vb2_crypto_to_hash(packed_key->algorithm);
  42. if (key->hash_alg == VB2_HASH_INVALID) {
  43. VB2_DEBUG("Unsupported hash algorithm.\n");
  44. return VB2_ERROR_UNPACK_KEY_HASH_ALGORITHM;
  45. }
  46. expected_key_size = vb2_packed_key_size(key->sig_alg);
  47. if (!expected_key_size || expected_key_size != packed_key->key_size) {
  48. VB2_DEBUG("Wrong key size for algorithm\n");
  49. return VB2_ERROR_UNPACK_KEY_SIZE;
  50. }
  51. /* Make sure source buffer is 32-bit aligned */
  52. buf32 = (const uint32_t *)vb2_packed_key_data(packed_key);
  53. if (!vb2_aligned(buf32, sizeof(uint32_t)))
  54. return VB2_ERROR_UNPACK_KEY_ALIGN;
  55. /* Sanity check key array size */
  56. key->arrsize = buf32[0];
  57. if (key->arrsize * sizeof(uint32_t) != vb2_rsa_sig_size(key->sig_alg))
  58. return VB2_ERROR_UNPACK_KEY_ARRAY_SIZE;
  59. key->n0inv = buf32[1];
  60. /* Arrays point inside the key data */
  61. key->n = buf32 + 2;
  62. key->rr = buf32 + 2 + key->arrsize;
  63. return VB2_SUCCESS;
  64. }
  65. int vb2_unpack_key(struct vb2_public_key *key,
  66. const struct vb2_packed_key *packed_key)
  67. {
  68. if (!packed_key)
  69. return VB2_ERROR_UNPACK_KEY_BUFFER;
  70. return vb2_unpack_key_buffer(key,
  71. (const uint8_t *)packed_key,
  72. packed_key->key_offset +
  73. packed_key->key_size);
  74. }