1 /* 2 * Copyright (c) 2013, Google Inc. 3 * 4 * SPDX-License-Identifier: GPL-2.0+ 5 */ 6 7 #include "mkimage.h" 8 #include <stdio.h> 9 #include <string.h> 10 #include <image.h> 11 #include <time.h> 12 #include <openssl/rsa.h> 13 #include <openssl/pem.h> 14 #include <openssl/err.h> 15 #include <openssl/ssl.h> 16 #include <openssl/evp.h> 17 18 #if OPENSSL_VERSION_NUMBER >= 0x10000000L 19 #define HAVE_ERR_REMOVE_THREAD_STATE 20 #endif 21 22 static int rsa_err(const char *msg) 23 { 24 unsigned long sslErr = ERR_get_error(); 25 26 fprintf(stderr, "%s", msg); 27 fprintf(stderr, ": %s\n", 28 ERR_error_string(sslErr, 0)); 29 30 return -1; 31 } 32 33 /** 34 * rsa_get_pub_key() - read a public key from a .crt file 35 * 36 * @keydir: Directory containins the key 37 * @name Name of key file (will have a .crt extension) 38 * @rsap Returns RSA object, or NULL on failure 39 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL) 40 */ 41 static int rsa_get_pub_key(const char *keydir, const char *name, RSA **rsap) 42 { 43 char path[1024]; 44 EVP_PKEY *key; 45 X509 *cert; 46 RSA *rsa; 47 FILE *f; 48 int ret; 49 50 *rsap = NULL; 51 snprintf(path, sizeof(path), "%s/%s.crt", keydir, name); 52 f = fopen(path, "r"); 53 if (!f) { 54 fprintf(stderr, "Couldn't open RSA certificate: '%s': %s\n", 55 path, strerror(errno)); 56 return -EACCES; 57 } 58 59 /* Read the certificate */ 60 cert = NULL; 61 if (!PEM_read_X509(f, &cert, NULL, NULL)) { 62 rsa_err("Couldn't read certificate"); 63 ret = -EINVAL; 64 goto err_cert; 65 } 66 67 /* Get the public key from the certificate. */ 68 key = X509_get_pubkey(cert); 69 if (!key) { 70 rsa_err("Couldn't read public key\n"); 71 ret = -EINVAL; 72 goto err_pubkey; 73 } 74 75 /* Convert to a RSA_style key. */ 76 rsa = EVP_PKEY_get1_RSA(key); 77 if (!rsa) { 78 rsa_err("Couldn't convert to a RSA style key"); 79 goto err_rsa; 80 } 81 fclose(f); 82 EVP_PKEY_free(key); 83 X509_free(cert); 84 *rsap = rsa; 85 86 return 0; 87 88 err_rsa: 89 EVP_PKEY_free(key); 90 err_pubkey: 91 X509_free(cert); 92 err_cert: 93 fclose(f); 94 return ret; 95 } 96 97 /** 98 * rsa_get_priv_key() - read a private key from a .key file 99 * 100 * @keydir: Directory containins the key 101 * @name Name of key file (will have a .key extension) 102 * @rsap Returns RSA object, or NULL on failure 103 * @return 0 if ok, -ve on error (in which case *rsap will be set to NULL) 104 */ 105 static int rsa_get_priv_key(const char *keydir, const char *name, RSA **rsap) 106 { 107 char path[1024]; 108 RSA *rsa; 109 FILE *f; 110 111 *rsap = NULL; 112 snprintf(path, sizeof(path), "%s/%s.key", keydir, name); 113 f = fopen(path, "r"); 114 if (!f) { 115 fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n", 116 path, strerror(errno)); 117 return -ENOENT; 118 } 119 120 rsa = PEM_read_RSAPrivateKey(f, 0, NULL, path); 121 if (!rsa) { 122 rsa_err("Failure reading private key"); 123 fclose(f); 124 return -EPROTO; 125 } 126 fclose(f); 127 *rsap = rsa; 128 129 return 0; 130 } 131 132 static int rsa_init(void) 133 { 134 int ret; 135 136 ret = SSL_library_init(); 137 if (!ret) { 138 fprintf(stderr, "Failure to init SSL library\n"); 139 return -1; 140 } 141 SSL_load_error_strings(); 142 143 OpenSSL_add_all_algorithms(); 144 OpenSSL_add_all_digests(); 145 OpenSSL_add_all_ciphers(); 146 147 return 0; 148 } 149 150 static void rsa_remove(void) 151 { 152 CRYPTO_cleanup_all_ex_data(); 153 ERR_free_strings(); 154 #ifdef HAVE_ERR_REMOVE_THREAD_STATE 155 ERR_remove_thread_state(NULL); 156 #else 157 ERR_remove_state(0); 158 #endif 159 EVP_cleanup(); 160 } 161 162 static int rsa_sign_with_key(RSA *rsa, struct checksum_algo *checksum_algo, 163 const struct image_region region[], int region_count, 164 uint8_t **sigp, uint *sig_size) 165 { 166 EVP_PKEY *key; 167 EVP_MD_CTX *context; 168 int size, ret = 0; 169 uint8_t *sig; 170 int i; 171 172 key = EVP_PKEY_new(); 173 if (!key) 174 return rsa_err("EVP_PKEY object creation failed"); 175 176 if (!EVP_PKEY_set1_RSA(key, rsa)) { 177 ret = rsa_err("EVP key setup failed"); 178 goto err_set; 179 } 180 181 size = EVP_PKEY_size(key); 182 sig = malloc(size); 183 if (!sig) { 184 fprintf(stderr, "Out of memory for signature (%d bytes)\n", 185 size); 186 ret = -ENOMEM; 187 goto err_alloc; 188 } 189 190 context = EVP_MD_CTX_create(); 191 if (!context) { 192 ret = rsa_err("EVP context creation failed"); 193 goto err_create; 194 } 195 EVP_MD_CTX_init(context); 196 if (!EVP_SignInit(context, checksum_algo->calculate_sign())) { 197 ret = rsa_err("Signer setup failed"); 198 goto err_sign; 199 } 200 201 for (i = 0; i < region_count; i++) { 202 if (!EVP_SignUpdate(context, region[i].data, region[i].size)) { 203 ret = rsa_err("Signing data failed"); 204 goto err_sign; 205 } 206 } 207 208 if (!EVP_SignFinal(context, sig, sig_size, key)) { 209 ret = rsa_err("Could not obtain signature"); 210 goto err_sign; 211 } 212 EVP_MD_CTX_cleanup(context); 213 EVP_MD_CTX_destroy(context); 214 EVP_PKEY_free(key); 215 216 debug("Got signature: %d bytes, expected %d\n", *sig_size, size); 217 *sigp = sig; 218 *sig_size = size; 219 220 return 0; 221 222 err_sign: 223 EVP_MD_CTX_destroy(context); 224 err_create: 225 free(sig); 226 err_alloc: 227 err_set: 228 EVP_PKEY_free(key); 229 return ret; 230 } 231 232 int rsa_sign(struct image_sign_info *info, 233 const struct image_region region[], int region_count, 234 uint8_t **sigp, uint *sig_len) 235 { 236 RSA *rsa; 237 int ret; 238 239 ret = rsa_init(); 240 if (ret) 241 return ret; 242 243 ret = rsa_get_priv_key(info->keydir, info->keyname, &rsa); 244 if (ret) 245 goto err_priv; 246 ret = rsa_sign_with_key(rsa, info->algo->checksum, region, 247 region_count, sigp, sig_len); 248 if (ret) 249 goto err_sign; 250 251 RSA_free(rsa); 252 rsa_remove(); 253 254 return ret; 255 256 err_sign: 257 RSA_free(rsa); 258 err_priv: 259 rsa_remove(); 260 return ret; 261 } 262 263 /* 264 * rsa_get_exponent(): - Get the public exponent from an RSA key 265 */ 266 static int rsa_get_exponent(RSA *key, uint64_t *e) 267 { 268 int ret; 269 BIGNUM *bn_te; 270 uint64_t te; 271 272 ret = -EINVAL; 273 bn_te = NULL; 274 275 if (!e) 276 goto cleanup; 277 278 if (BN_num_bits(key->e) > 64) 279 goto cleanup; 280 281 *e = BN_get_word(key->e); 282 283 if (BN_num_bits(key->e) < 33) { 284 ret = 0; 285 goto cleanup; 286 } 287 288 bn_te = BN_dup(key->e); 289 if (!bn_te) 290 goto cleanup; 291 292 if (!BN_rshift(bn_te, bn_te, 32)) 293 goto cleanup; 294 295 if (!BN_mask_bits(bn_te, 32)) 296 goto cleanup; 297 298 te = BN_get_word(bn_te); 299 te <<= 32; 300 *e |= te; 301 ret = 0; 302 303 cleanup: 304 if (bn_te) 305 BN_free(bn_te); 306 307 return ret; 308 } 309 310 /* 311 * rsa_get_params(): - Get the important parameters of an RSA public key 312 */ 313 int rsa_get_params(RSA *key, uint64_t *exponent, uint32_t *n0_invp, 314 BIGNUM **modulusp, BIGNUM **r_squaredp) 315 { 316 BIGNUM *big1, *big2, *big32, *big2_32; 317 BIGNUM *n, *r, *r_squared, *tmp; 318 BN_CTX *bn_ctx = BN_CTX_new(); 319 int ret = 0; 320 321 /* Initialize BIGNUMs */ 322 big1 = BN_new(); 323 big2 = BN_new(); 324 big32 = BN_new(); 325 r = BN_new(); 326 r_squared = BN_new(); 327 tmp = BN_new(); 328 big2_32 = BN_new(); 329 n = BN_new(); 330 if (!big1 || !big2 || !big32 || !r || !r_squared || !tmp || !big2_32 || 331 !n) { 332 fprintf(stderr, "Out of memory (bignum)\n"); 333 return -ENOMEM; 334 } 335 336 if (0 != rsa_get_exponent(key, exponent)) 337 ret = -1; 338 339 if (!BN_copy(n, key->n) || !BN_set_word(big1, 1L) || 340 !BN_set_word(big2, 2L) || !BN_set_word(big32, 32L)) 341 ret = -1; 342 343 /* big2_32 = 2^32 */ 344 if (!BN_exp(big2_32, big2, big32, bn_ctx)) 345 ret = -1; 346 347 /* Calculate n0_inv = -1 / n[0] mod 2^32 */ 348 if (!BN_mod_inverse(tmp, n, big2_32, bn_ctx) || 349 !BN_sub(tmp, big2_32, tmp)) 350 ret = -1; 351 *n0_invp = BN_get_word(tmp); 352 353 /* Calculate R = 2^(# of key bits) */ 354 if (!BN_set_word(tmp, BN_num_bits(n)) || 355 !BN_exp(r, big2, tmp, bn_ctx)) 356 ret = -1; 357 358 /* Calculate r_squared = R^2 mod n */ 359 if (!BN_copy(r_squared, r) || 360 !BN_mul(tmp, r_squared, r, bn_ctx) || 361 !BN_mod(r_squared, tmp, n, bn_ctx)) 362 ret = -1; 363 364 *modulusp = n; 365 *r_squaredp = r_squared; 366 367 BN_free(big1); 368 BN_free(big2); 369 BN_free(big32); 370 BN_free(r); 371 BN_free(tmp); 372 BN_free(big2_32); 373 if (ret) { 374 fprintf(stderr, "Bignum operations failed\n"); 375 return -ENOMEM; 376 } 377 378 return ret; 379 } 380 381 static int fdt_add_bignum(void *blob, int noffset, const char *prop_name, 382 BIGNUM *num, int num_bits) 383 { 384 int nwords = num_bits / 32; 385 int size; 386 uint32_t *buf, *ptr; 387 BIGNUM *tmp, *big2, *big32, *big2_32; 388 BN_CTX *ctx; 389 int ret; 390 391 tmp = BN_new(); 392 big2 = BN_new(); 393 big32 = BN_new(); 394 big2_32 = BN_new(); 395 if (!tmp || !big2 || !big32 || !big2_32) { 396 fprintf(stderr, "Out of memory (bignum)\n"); 397 return -ENOMEM; 398 } 399 ctx = BN_CTX_new(); 400 if (!tmp) { 401 fprintf(stderr, "Out of memory (bignum context)\n"); 402 return -ENOMEM; 403 } 404 BN_set_word(big2, 2L); 405 BN_set_word(big32, 32L); 406 BN_exp(big2_32, big2, big32, ctx); /* B = 2^32 */ 407 408 size = nwords * sizeof(uint32_t); 409 buf = malloc(size); 410 if (!buf) { 411 fprintf(stderr, "Out of memory (%d bytes)\n", size); 412 return -ENOMEM; 413 } 414 415 /* Write out modulus as big endian array of integers */ 416 for (ptr = buf + nwords - 1; ptr >= buf; ptr--) { 417 BN_mod(tmp, num, big2_32, ctx); /* n = N mod B */ 418 *ptr = cpu_to_fdt32(BN_get_word(tmp)); 419 BN_rshift(num, num, 32); /* N = N/B */ 420 } 421 422 ret = fdt_setprop(blob, noffset, prop_name, buf, size); 423 if (ret) { 424 fprintf(stderr, "Failed to write public key to FIT\n"); 425 return -ENOSPC; 426 } 427 free(buf); 428 BN_free(tmp); 429 BN_free(big2); 430 BN_free(big32); 431 BN_free(big2_32); 432 433 return ret; 434 } 435 436 int rsa_add_verify_data(struct image_sign_info *info, void *keydest) 437 { 438 BIGNUM *modulus, *r_squared; 439 uint64_t exponent; 440 uint32_t n0_inv; 441 int parent, node; 442 char name[100]; 443 int ret; 444 int bits; 445 RSA *rsa; 446 447 debug("%s: Getting verification data\n", __func__); 448 ret = rsa_get_pub_key(info->keydir, info->keyname, &rsa); 449 if (ret) 450 return ret; 451 ret = rsa_get_params(rsa, &exponent, &n0_inv, &modulus, &r_squared); 452 if (ret) 453 return ret; 454 bits = BN_num_bits(modulus); 455 parent = fdt_subnode_offset(keydest, 0, FIT_SIG_NODENAME); 456 if (parent == -FDT_ERR_NOTFOUND) { 457 parent = fdt_add_subnode(keydest, 0, FIT_SIG_NODENAME); 458 if (parent < 0) { 459 ret = parent; 460 if (ret != -FDT_ERR_NOSPACE) { 461 fprintf(stderr, "Couldn't create signature node: %s\n", 462 fdt_strerror(parent)); 463 } 464 } 465 } 466 if (ret) 467 goto done; 468 469 /* Either create or overwrite the named key node */ 470 snprintf(name, sizeof(name), "key-%s", info->keyname); 471 node = fdt_subnode_offset(keydest, parent, name); 472 if (node == -FDT_ERR_NOTFOUND) { 473 node = fdt_add_subnode(keydest, parent, name); 474 if (node < 0) { 475 ret = node; 476 if (ret != -FDT_ERR_NOSPACE) { 477 fprintf(stderr, "Could not create key subnode: %s\n", 478 fdt_strerror(node)); 479 } 480 } 481 } else if (node < 0) { 482 fprintf(stderr, "Cannot select keys parent: %s\n", 483 fdt_strerror(node)); 484 ret = node; 485 } 486 487 if (!ret) { 488 ret = fdt_setprop_string(keydest, node, "key-name-hint", 489 info->keyname); 490 } 491 if (!ret) 492 ret = fdt_setprop_u32(keydest, node, "rsa,num-bits", bits); 493 if (!ret) 494 ret = fdt_setprop_u32(keydest, node, "rsa,n0-inverse", n0_inv); 495 if (!ret) { 496 ret = fdt_setprop_u64(keydest, node, "rsa,exponent", exponent); 497 } 498 if (!ret) { 499 ret = fdt_add_bignum(keydest, node, "rsa,modulus", modulus, 500 bits); 501 } 502 if (!ret) { 503 ret = fdt_add_bignum(keydest, node, "rsa,r-squared", r_squared, 504 bits); 505 } 506 if (!ret) { 507 ret = fdt_setprop_string(keydest, node, FIT_ALGO_PROP, 508 info->algo->name); 509 } 510 if (info->require_keys) { 511 ret = fdt_setprop_string(keydest, node, "required", 512 info->require_keys); 513 } 514 done: 515 BN_free(modulus); 516 BN_free(r_squared); 517 if (ret) 518 return ret == -FDT_ERR_NOSPACE ? -ENOSPC : -EIO; 519 520 return 0; 521 } 522