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