1 /* 2 * Copyright (c) 2015, ARM Limited and Contributors. All rights reserved. 3 * 4 * Redistribution and use in source and binary forms, with or without 5 * modification, are permitted provided that the following conditions are met: 6 * 7 * Redistributions of source code must retain the above copyright notice, this 8 * list of conditions and the following disclaimer. 9 * 10 * Redistributions in binary form must reproduce the above copyright notice, 11 * this list of conditions and the following disclaimer in the documentation 12 * and/or other materials provided with the distribution. 13 * 14 * Neither the name of ARM nor the names of its contributors may be used 15 * to endorse or promote products derived from this software without specific 16 * prior written permission. 17 * 18 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 19 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 20 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 21 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE 22 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 23 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 24 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 25 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 26 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 28 * POSSIBILITY OF SUCH DAMAGE. 29 */ 30 31 #include <assert.h> 32 #include <ctype.h> 33 #include <getopt.h> 34 #include <stdio.h> 35 #include <stdlib.h> 36 #include <string.h> 37 38 #include <openssl/conf.h> 39 #include <openssl/engine.h> 40 #include <openssl/err.h> 41 #include <openssl/pem.h> 42 #include <openssl/sha.h> 43 #include <openssl/x509v3.h> 44 45 #include "cert.h" 46 #include "cmd_opt.h" 47 #include "debug.h" 48 #include "ext.h" 49 #include "key.h" 50 #include "platform_oid.h" 51 #include "sha.h" 52 #include "tbbr/tbb_ext.h" 53 #include "tbbr/tbb_cert.h" 54 #include "tbbr/tbb_key.h" 55 56 /* 57 * Helper macros to simplify the code. This macro assigns the return value of 58 * the 'fn' function to 'v' and exits if the value is NULL. 59 */ 60 #define CHECK_NULL(v, fn) \ 61 do { \ 62 v = fn; \ 63 if (v == NULL) { \ 64 ERROR("NULL object at %s:%d\n", __FILE__, __LINE__); \ 65 exit(1); \ 66 } \ 67 } while (0) 68 69 /* 70 * This macro assigns the NID corresponding to 'oid' to 'v' and exits if the 71 * NID is undefined. 72 */ 73 #define CHECK_OID(v, oid) \ 74 do { \ 75 v = OBJ_txt2nid(oid); \ 76 if (v == NID_undef) { \ 77 ERROR("Cannot find TBB extension %s\n", oid); \ 78 exit(1); \ 79 } \ 80 } while (0) 81 82 #define MAX_FILENAME_LEN 1024 83 #define VAL_DAYS 7300 84 #define ID_TO_BIT_MASK(id) (1 << id) 85 #define NUM_ELEM(x) ((sizeof(x)) / (sizeof(x[0]))) 86 #define HELP_OPT_MAX_LEN 128 87 88 /* Global options */ 89 static int key_alg; 90 static int new_keys; 91 static int save_keys; 92 static int print_cert; 93 94 /* Info messages created in the Makefile */ 95 extern const char build_msg[]; 96 extern const char platform_msg[]; 97 98 99 static char *strdup(const char *str) 100 { 101 int n = strlen(str) + 1; 102 char *dup = malloc(n); 103 if (dup) { 104 strcpy(dup, str); 105 } 106 return dup; 107 } 108 109 static const char *key_algs_str[] = { 110 [KEY_ALG_RSA] = "rsa", 111 #ifndef OPENSSL_NO_EC 112 [KEY_ALG_ECDSA] = "ecdsa" 113 #endif /* OPENSSL_NO_EC */ 114 }; 115 116 static void print_help(const char *cmd, const struct option *long_opt) 117 { 118 int rem, i = 0; 119 const struct option *opt; 120 char line[HELP_OPT_MAX_LEN]; 121 char *p; 122 123 assert(cmd != NULL); 124 assert(long_opt != NULL); 125 126 printf("\n\n"); 127 printf("The certificate generation tool loads the binary images and\n" 128 "optionally the RSA keys, and outputs the key and content\n" 129 "certificates properly signed to implement the chain of trust.\n" 130 "If keys are provided, they must be in PEM format.\n" 131 "Certificates are generated in DER format.\n"); 132 printf("\n"); 133 printf("Usage:\n"); 134 printf("\t%s [OPTIONS]\n\n", cmd); 135 136 printf("Available options:\n"); 137 i = 0; 138 opt = long_opt; 139 while (opt->name) { 140 p = line; 141 rem = HELP_OPT_MAX_LEN; 142 if (isalpha(opt->val)) { 143 /* Short format */ 144 sprintf(p, "-%c,", (char)opt->val); 145 p += 3; 146 rem -= 3; 147 } 148 snprintf(p, rem, "--%s %s", opt->name, 149 (opt->has_arg == required_argument) ? "<arg>" : ""); 150 printf("\t%-32s %s\n", line, cmd_opt_get_help_msg(i)); 151 opt++; 152 i++; 153 } 154 printf("\n"); 155 156 exit(0); 157 } 158 159 static int get_key_alg(const char *key_alg_str) 160 { 161 int i; 162 163 for (i = 0 ; i < NUM_ELEM(key_algs_str) ; i++) { 164 if (0 == strcmp(key_alg_str, key_algs_str[i])) { 165 return i; 166 } 167 } 168 169 return -1; 170 } 171 172 static void check_cmd_params(void) 173 { 174 cert_t *cert; 175 ext_t *ext; 176 key_t *key; 177 int i, j; 178 179 /* Only save new keys */ 180 if (save_keys && !new_keys) { 181 ERROR("Only new keys can be saved to disk\n"); 182 exit(1); 183 } 184 185 /* Check that all required options have been specified in the 186 * command line */ 187 for (i = 0; i < num_certs; i++) { 188 cert = &certs[i]; 189 if (cert->fn == NULL) { 190 /* Certificate not requested. Skip to the next one */ 191 continue; 192 } 193 194 /* Check that all parameters required to create this certificate 195 * have been specified in the command line */ 196 for (j = 0; j < cert->num_ext; j++) { 197 ext = &extensions[cert->ext[j]]; 198 switch (ext->type) { 199 case EXT_TYPE_PKEY: 200 /* Key filename must be specified */ 201 key = &keys[ext->data.key]; 202 if (!new_keys && key->fn == NULL) { 203 ERROR("Key '%s' required by '%s' not " 204 "specified\n", key->desc, 205 cert->cn); 206 exit(1); 207 } 208 break; 209 case EXT_TYPE_HASH: 210 /* 211 * Binary image must be specified 212 * unless it is explicitly made optional. 213 */ 214 if ((!ext->optional) && (ext->data.fn == NULL)) { 215 ERROR("Image for '%s' not specified\n", 216 ext->ln); 217 exit(1); 218 } 219 break; 220 default: 221 ERROR("Unknown extension type in '%s'\n", 222 ext->ln); 223 exit(1); 224 break; 225 } 226 } 227 } 228 } 229 230 /* Common command line options */ 231 static const cmd_opt_t common_cmd_opt[] = { 232 { 233 { "help", no_argument, NULL, 'h' }, 234 "Print this message and exit" 235 }, 236 { 237 { "key-alg", required_argument, NULL, 'a' }, 238 "Key algorithm: 'rsa' (default), 'ecdsa'" 239 }, 240 { 241 { "save-keys", no_argument, NULL, 'k' }, 242 "Save key pairs into files. Filenames must be provided" 243 }, 244 { 245 { "new-keys", no_argument, NULL, 'n' }, 246 "Generate new key pairs if no key files are provided" 247 }, 248 { 249 { "print-cert", no_argument, NULL, 'p' }, 250 "Print the certificates in the standard output" 251 } 252 }; 253 254 int main(int argc, char *argv[]) 255 { 256 STACK_OF(X509_EXTENSION) * sk = NULL; 257 X509_EXTENSION *cert_ext = NULL; 258 ext_t *ext = NULL; 259 key_t *key = NULL; 260 cert_t *cert = NULL; 261 FILE *file = NULL; 262 int i, j, ext_nid; 263 int c, opt_idx = 0; 264 const struct option *cmd_opt; 265 const char *cur_opt; 266 unsigned int err_code; 267 unsigned char md[SHA256_DIGEST_LENGTH]; 268 const EVP_MD *md_info; 269 270 NOTICE("CoT Generation Tool: %s\n", build_msg); 271 NOTICE("Target platform: %s\n", platform_msg); 272 273 /* Set default options */ 274 key_alg = KEY_ALG_RSA; 275 276 /* Add common command line options */ 277 for (i = 0; i < NUM_ELEM(common_cmd_opt); i++) { 278 cmd_opt_add(&common_cmd_opt[i]); 279 } 280 281 /* Initialize the certificates */ 282 if (cert_init() != 0) { 283 ERROR("Cannot initialize certificates\n"); 284 exit(1); 285 } 286 287 /* Initialize the keys */ 288 if (key_init() != 0) { 289 ERROR("Cannot initialize keys\n"); 290 exit(1); 291 } 292 293 /* Initialize the new types and register OIDs for the extensions */ 294 if (ext_init() != 0) { 295 ERROR("Cannot initialize TBB extensions\n"); 296 exit(1); 297 } 298 299 /* Get the command line options populated during the initialization */ 300 cmd_opt = cmd_opt_get_array(); 301 302 while (1) { 303 /* getopt_long stores the option index here. */ 304 c = getopt_long(argc, argv, "a:hknp", cmd_opt, &opt_idx); 305 306 /* Detect the end of the options. */ 307 if (c == -1) { 308 break; 309 } 310 311 switch (c) { 312 case 'a': 313 key_alg = get_key_alg(optarg); 314 if (key_alg < 0) { 315 ERROR("Invalid key algorithm '%s'\n", optarg); 316 exit(1); 317 } 318 break; 319 case 'h': 320 print_help(argv[0], cmd_opt); 321 break; 322 case 'k': 323 save_keys = 1; 324 break; 325 case 'n': 326 new_keys = 1; 327 break; 328 case 'p': 329 print_cert = 1; 330 break; 331 case CMD_OPT_EXT: 332 cur_opt = cmd_opt_get_name(opt_idx); 333 ext = ext_get_by_opt(cur_opt); 334 ext->data.fn = strdup(optarg); 335 break; 336 case CMD_OPT_KEY: 337 cur_opt = cmd_opt_get_name(opt_idx); 338 key = key_get_by_opt(cur_opt); 339 key->fn = strdup(optarg); 340 break; 341 case CMD_OPT_CERT: 342 cur_opt = cmd_opt_get_name(opt_idx); 343 cert = cert_get_by_opt(cur_opt); 344 cert->fn = strdup(optarg); 345 break; 346 case '?': 347 default: 348 print_help(argv[0], cmd_opt); 349 exit(1); 350 } 351 } 352 353 /* Check command line arguments */ 354 check_cmd_params(); 355 356 /* Indicate SHA256 as image hash algorithm in the certificate 357 * extension */ 358 md_info = EVP_sha256(); 359 360 /* Load private keys from files (or generate new ones) */ 361 for (i = 0 ; i < num_keys ; i++) { 362 /* First try to load the key from disk */ 363 if (key_load(&keys[i], &err_code)) { 364 /* Key loaded successfully */ 365 continue; 366 } 367 368 /* Key not loaded. Check the error code */ 369 if (err_code == KEY_ERR_MALLOC) { 370 /* Cannot allocate memory. Abort. */ 371 ERROR("Malloc error while loading '%s'\n", keys[i].fn); 372 exit(1); 373 } else if (err_code == KEY_ERR_LOAD) { 374 /* File exists, but it does not contain a valid private 375 * key. Abort. */ 376 ERROR("Error loading '%s'\n", keys[i].fn); 377 exit(1); 378 } 379 380 /* File does not exist, could not be opened or no filename was 381 * given */ 382 if (new_keys) { 383 /* Try to create a new key */ 384 NOTICE("Creating new key for '%s'\n", keys[i].desc); 385 if (!key_create(&keys[i], key_alg)) { 386 ERROR("Error creating key '%s'\n", keys[i].desc); 387 exit(1); 388 } 389 } else { 390 if (err_code == KEY_ERR_OPEN) { 391 ERROR("Error opening '%s'\n", keys[i].fn); 392 } else { 393 ERROR("Key '%s' not specified\n", keys[i].desc); 394 } 395 exit(1); 396 } 397 } 398 399 /* Create the certificates */ 400 for (i = 0 ; i < num_certs ; i++) { 401 402 cert = &certs[i]; 403 404 /* Create a new stack of extensions. This stack will be used 405 * to create the certificate */ 406 CHECK_NULL(sk, sk_X509_EXTENSION_new_null()); 407 408 for (j = 0 ; j < cert->num_ext ; j++) { 409 410 ext = &extensions[cert->ext[j]]; 411 412 /* Get OpenSSL internal ID for this extension */ 413 CHECK_OID(ext_nid, ext->oid); 414 415 /* 416 * Three types of extensions are currently supported: 417 * - EXT_TYPE_NVCOUNTER 418 * - EXT_TYPE_HASH 419 * - EXT_TYPE_PKEY 420 */ 421 switch (ext->type) { 422 case EXT_TYPE_NVCOUNTER: 423 CHECK_NULL(cert_ext, ext_new_nvcounter(ext_nid, 424 EXT_CRIT, ext->data.nvcounter)); 425 break; 426 case EXT_TYPE_HASH: 427 if (ext->data.fn == NULL) { 428 if (ext->optional) { 429 /* Include a hash filled with zeros */ 430 memset(md, 0x0, SHA256_DIGEST_LENGTH); 431 } else { 432 /* Do not include this hash in the certificate */ 433 break; 434 } 435 } else { 436 /* Calculate the hash of the file */ 437 if (!sha_file(ext->data.fn, md)) { 438 ERROR("Cannot calculate hash of %s\n", 439 ext->data.fn); 440 exit(1); 441 } 442 } 443 CHECK_NULL(cert_ext, ext_new_hash(ext_nid, 444 EXT_CRIT, md_info, md, 445 SHA256_DIGEST_LENGTH)); 446 break; 447 case EXT_TYPE_PKEY: 448 CHECK_NULL(cert_ext, ext_new_key(ext_nid, 449 EXT_CRIT, keys[ext->data.key].key)); 450 break; 451 default: 452 ERROR("Unknown extension type in %s\n", 453 cert->cn); 454 exit(1); 455 } 456 457 /* Push the extension into the stack */ 458 sk_X509_EXTENSION_push(sk, cert_ext); 459 } 460 461 /* Create certificate. Signed with ROT key */ 462 if (cert->fn && !cert_new(cert, VAL_DAYS, 0, sk)) { 463 ERROR("Cannot create %s\n", cert->cn); 464 exit(1); 465 } 466 467 sk_X509_EXTENSION_free(sk); 468 } 469 470 471 /* Print the certificates */ 472 if (print_cert) { 473 for (i = 0 ; i < num_certs ; i++) { 474 if (!certs[i].x) { 475 continue; 476 } 477 printf("\n\n=====================================\n\n"); 478 X509_print_fp(stdout, certs[i].x); 479 } 480 } 481 482 /* Save created certificates to files */ 483 for (i = 0 ; i < num_certs ; i++) { 484 if (certs[i].x && certs[i].fn) { 485 file = fopen(certs[i].fn, "w"); 486 if (file != NULL) { 487 i2d_X509_fp(file, certs[i].x); 488 fclose(file); 489 } else { 490 ERROR("Cannot create file %s\n", certs[i].fn); 491 } 492 } 493 } 494 495 /* Save keys */ 496 if (save_keys) { 497 for (i = 0 ; i < num_keys ; i++) { 498 if (!key_store(&keys[i])) { 499 ERROR("Cannot save %s\n", keys[i].desc); 500 } 501 } 502 } 503 504 #ifndef OPENSSL_NO_ENGINE 505 ENGINE_cleanup(); 506 #endif 507 CRYPTO_cleanup_all_ex_data(); 508 509 return 0; 510 } 511