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