1 // SPDX-License-Identifier: BSD-2-Clause 2 /* 3 * Copyright (c) 2015-2017, Linaro Limited 4 */ 5 6 #include <crypto/crypto.h> 7 #include <signed_hdr.h> 8 #include <stdlib.h> 9 #include <string.h> 10 #include <ta_pub_key.h> 11 #include <tee_api_types.h> 12 #include <tee/tee_cryp_utl.h> 13 #include <utee_defines.h> 14 15 struct shdr *shdr_alloc_and_copy(const struct shdr *img, size_t img_size) 16 { 17 size_t shdr_size; 18 struct shdr *shdr; 19 20 if (img_size < sizeof(struct shdr)) 21 NULL; 22 shdr_size = SHDR_GET_SIZE(img); 23 if (img_size < shdr_size) 24 NULL; 25 26 shdr = malloc(shdr_size); 27 if (!shdr) 28 return NULL; 29 memcpy(shdr, img, shdr_size); 30 31 /* Check that the data wasn't modified before the copy was completed */ 32 if (shdr_size != SHDR_GET_SIZE(shdr)) { 33 free(shdr); 34 return NULL; 35 } 36 37 return shdr; 38 } 39 40 TEE_Result shdr_verify_signature(const struct shdr *shdr) 41 { 42 struct rsa_public_key key; 43 TEE_Result res; 44 uint32_t e = TEE_U32_TO_BIG_ENDIAN(ta_pub_key_exponent); 45 size_t hash_size; 46 47 if (shdr->magic != SHDR_MAGIC) 48 return TEE_ERROR_SECURITY; 49 50 if (TEE_ALG_GET_MAIN_ALG(shdr->algo) != TEE_MAIN_ALGO_RSA) 51 return TEE_ERROR_SECURITY; 52 53 res = tee_hash_get_digest_size(TEE_DIGEST_HASH_TO_ALGO(shdr->algo), 54 &hash_size); 55 if (res) 56 return TEE_ERROR_SECURITY; 57 if (hash_size != shdr->hash_size) 58 return TEE_ERROR_SECURITY; 59 60 res = crypto_acipher_alloc_rsa_public_key(&key, shdr->sig_size); 61 if (res) 62 return TEE_ERROR_SECURITY; 63 64 res = crypto_bignum_bin2bn((uint8_t *)&e, sizeof(e), key.e); 65 if (res) 66 goto out; 67 res = crypto_bignum_bin2bn(ta_pub_key_modulus, ta_pub_key_modulus_size, 68 key.n); 69 if (res) 70 goto out; 71 72 res = crypto_acipher_rsassa_verify(shdr->algo, &key, -1, 73 SHDR_GET_HASH(shdr), shdr->hash_size, 74 SHDR_GET_SIG(shdr), shdr->sig_size); 75 out: 76 crypto_acipher_free_rsa_public_key(&key); 77 if (res) 78 return TEE_ERROR_SECURITY; 79 return TEE_SUCCESS; 80 } 81