1 /* Copyright 2014 The ChromiumOS Authors
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
8 #include "2common.h"
9 #include "2packed_key.h"
10 #include "2rsa.h"
11 #include "2sysincludes.h"
12
13 test_mockable
vb2_unpack_key_buffer(struct vb2_public_key * key,const uint8_t * buf,uint32_t size)14 vb2_error_t vb2_unpack_key_buffer(struct vb2_public_key *key,
15 const uint8_t *buf, uint32_t size)
16 {
17 const struct vb2_packed_key *packed_key =
18 (const struct vb2_packed_key *)buf;
19 const uint32_t *buf32;
20 uint32_t expected_key_size;
21
22 /* Make sure passed buffer is big enough for the packed key */
23 VB2_TRY(vb2_verify_packed_key_inside(buf, size, packed_key));
24
25 /* Unpack key algorithm */
26 key->sig_alg = vb2_crypto_to_signature(packed_key->algorithm);
27 if (key->sig_alg == VB2_SIG_INVALID) {
28 VB2_DEBUG("Unsupported signature algorithm.\n");
29 return VB2_ERROR_UNPACK_KEY_SIG_ALGORITHM;
30 }
31
32 key->hash_alg = vb2_crypto_to_hash(packed_key->algorithm);
33 if (key->hash_alg == VB2_HASH_INVALID) {
34 VB2_DEBUG("Unsupported hash algorithm.\n");
35 return VB2_ERROR_UNPACK_KEY_HASH_ALGORITHM;
36 }
37
38 expected_key_size = vb2_packed_key_size(key->sig_alg);
39 if (!expected_key_size || expected_key_size != packed_key->key_size) {
40 VB2_DEBUG("Wrong key size for algorithm\n");
41 return VB2_ERROR_UNPACK_KEY_SIZE;
42 }
43
44 /* Make sure source buffer is 32-bit aligned */
45 buf32 = (const uint32_t *)vb2_packed_key_data(packed_key);
46 if (!vb2_aligned(buf32, sizeof(uint32_t)))
47 return VB2_ERROR_UNPACK_KEY_ALIGN;
48
49 /* Validity check key array size */
50 key->arrsize = buf32[0];
51 if ((uint64_t)key->arrsize * sizeof(uint32_t) != vb2_rsa_sig_size(key->sig_alg))
52 return VB2_ERROR_UNPACK_KEY_ARRAY_SIZE;
53
54 key->n0inv = buf32[1];
55
56 /* Arrays point inside the key data */
57 key->n = buf32 + 2;
58 key->rr = buf32 + 2 + key->arrsize;
59
60 /* disable hwcrypto for RSA by default */
61 key->allow_hwcrypto = 0;
62
63 #ifdef __COVERITY__
64 __coverity_tainted_data_sanitize__(key);
65 __coverity_tainted_data_sanitize__(buf);
66 #endif
67 return VB2_SUCCESS;
68 }
69
vb2_unpack_key(struct vb2_public_key * key,const struct vb2_packed_key * packed_key)70 vb2_error_t vb2_unpack_key(struct vb2_public_key *key,
71 const struct vb2_packed_key *packed_key)
72 {
73 if (!packed_key)
74 return VB2_ERROR_UNPACK_KEY_BUFFER;
75
76 return vb2_unpack_key_buffer(key,
77 (const uint8_t *)packed_key,
78 packed_key->key_offset +
79 packed_key->key_size);
80 }
81