blob: 3d2b4ba252a01f73530f12b04c9c8f6b269caf7b [file] [log] [blame]
Juan Castillo6f971622014-10-21 11:30:42 +01001/*
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
Juan Castillo159807e2015-12-15 16:37:57 +000031#include <assert.h>
32#include <ctype.h>
Juan Castillo6f971622014-10-21 11:30:42 +010033#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"
Juan Castilload2c1a92015-07-03 16:23:16 +010046#include "cmd_opt.h"
Juan Castillo6f971622014-10-21 11:30:42 +010047#include "debug.h"
48#include "ext.h"
49#include "key.h"
50#include "platform_oid.h"
51#include "sha.h"
Juan Castillo55e291a2015-06-12 11:27:59 +010052#include "tbbr/tbb_ext.h"
53#include "tbbr/tbb_cert.h"
54#include "tbbr/tbb_key.h"
Juan Castillo6f971622014-10-21 11:30:42 +010055
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)
Juan Castilloccbf8902015-06-01 16:34:23 +010085#define NUM_ELEM(x) ((sizeof(x)) / (sizeof(x[0])))
Juan Castillo159807e2015-12-15 16:37:57 +000086#define HELP_OPT_MAX_LEN 128
Juan Castillo6f971622014-10-21 11:30:42 +010087
88/* Global options */
Juan Castilloccbf8902015-06-01 16:34:23 +010089static int key_alg;
Juan Castillo6f971622014-10-21 11:30:42 +010090static int new_keys;
91static int save_keys;
92static int print_cert;
Juan Castillo6f971622014-10-21 11:30:42 +010093
Juan Castillo6f971622014-10-21 11:30:42 +010094/* Info messages created in the Makefile */
95extern const char build_msg[];
96extern const char platform_msg[];
97
98
99static 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
Juan Castilloccbf8902015-06-01 16:34:23 +0100109static const char *key_algs_str[] = {
110 [KEY_ALG_RSA] = "rsa",
Juan Castilloed2a76e2015-06-30 13:36:57 +0100111#ifndef OPENSSL_NO_EC
Juan Castilloccbf8902015-06-01 16:34:23 +0100112 [KEY_ALG_ECDSA] = "ecdsa"
Juan Castilloed2a76e2015-06-30 13:36:57 +0100113#endif /* OPENSSL_NO_EC */
Juan Castilloccbf8902015-06-01 16:34:23 +0100114};
115
Juan Castilload2c1a92015-07-03 16:23:16 +0100116static void print_help(const char *cmd, const struct option *long_opt)
Juan Castillo6f971622014-10-21 11:30:42 +0100117{
Juan Castillo159807e2015-12-15 16:37:57 +0000118 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
Juan Castillo6f971622014-10-21 11:30:42 +0100126 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");
Juan Castillo159807e2015-12-15 16:37:57 +0000133 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++;
Juan Castillo6f971622014-10-21 11:30:42 +0100153 }
154 printf("\n");
Juan Castillo6f971622014-10-21 11:30:42 +0100155
156 exit(0);
157}
158
Juan Castilloccbf8902015-06-01 16:34:23 +0100159static 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
Juan Castillo6f971622014-10-21 11:30:42 +0100172static void check_cmd_params(void)
173{
Juan Castillodfc90e22015-07-08 12:11:38 +0100174 cert_t *cert;
175 ext_t *ext;
176 key_t *key;
177 int i, j;
178
Juan Castilloccbf8902015-06-01 16:34:23 +0100179 /* 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
Juan Castillodfc90e22015-07-08 12:11:38 +0100185 /* 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;
Juan Castillo6f971622014-10-21 11:30:42 +0100192 }
193
Juan Castillodfc90e22015-07-08 12:11:38 +0100194 /* 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:
Yatharth Kocharcebe1f22015-08-21 15:30:55 +0100210 /*
211 * Binary image must be specified
212 * unless it is explicitly made optional.
213 */
214 if ((!ext->optional) && (ext->data.fn == NULL)) {
Juan Castillodfc90e22015-07-08 12:11:38 +0100215 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 }
Juan Castillo6f971622014-10-21 11:30:42 +0100226 }
227 }
228}
229
Juan Castillo159807e2015-12-15 16:37:57 +0000230/* Common command line options */
231static 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
Juan Castillo6f971622014-10-21 11:30:42 +0100254int main(int argc, char *argv[])
255{
256 STACK_OF(X509_EXTENSION) * sk = NULL;
Juan Castillo55e291a2015-06-12 11:27:59 +0100257 X509_EXTENSION *cert_ext = NULL;
258 ext_t *ext = NULL;
Juan Castilload2c1a92015-07-03 16:23:16 +0100259 key_t *key = NULL;
260 cert_t *cert = NULL;
Juan Castillo6f971622014-10-21 11:30:42 +0100261 FILE *file = NULL;
Juan Castillo55e291a2015-06-12 11:27:59 +0100262 int i, j, ext_nid;
Juan Castillo6f971622014-10-21 11:30:42 +0100263 int c, opt_idx = 0;
Juan Castilload2c1a92015-07-03 16:23:16 +0100264 const struct option *cmd_opt;
265 const char *cur_opt;
Juan Castilloccbf8902015-06-01 16:34:23 +0100266 unsigned int err_code;
Juan Castillo6f971622014-10-21 11:30:42 +0100267 unsigned char md[SHA256_DIGEST_LENGTH];
Juan Castilloc3da66b2015-03-05 14:30:00 +0000268 const EVP_MD *md_info;
Juan Castillo6f971622014-10-21 11:30:42 +0100269
270 NOTICE("CoT Generation Tool: %s\n", build_msg);
271 NOTICE("Target platform: %s\n", platform_msg);
272
Juan Castilloccbf8902015-06-01 16:34:23 +0100273 /* Set default options */
274 key_alg = KEY_ALG_RSA;
275
Juan Castilload2c1a92015-07-03 16:23:16 +0100276 /* Add common command line options */
Juan Castillo159807e2015-12-15 16:37:57 +0000277 for (i = 0; i < NUM_ELEM(common_cmd_opt); i++) {
278 cmd_opt_add(&common_cmd_opt[i]);
279 }
Juan Castilload2c1a92015-07-03 16:23:16 +0100280
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
Juan Castillo6f971622014-10-21 11:30:42 +0100302 while (1) {
303 /* getopt_long stores the option index here. */
Juan Castillo159807e2015-12-15 16:37:57 +0000304 c = getopt_long(argc, argv, "a:hknp", cmd_opt, &opt_idx);
Juan Castillo6f971622014-10-21 11:30:42 +0100305
306 /* Detect the end of the options. */
307 if (c == -1) {
308 break;
309 }
310
311 switch (c) {
Juan Castilloccbf8902015-06-01 16:34:23 +0100312 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;
Juan Castillo6f971622014-10-21 11:30:42 +0100319 case 'h':
Juan Castilload2c1a92015-07-03 16:23:16 +0100320 print_help(argv[0], cmd_opt);
Juan Castillo6f971622014-10-21 11:30:42 +0100321 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;
Juan Castilload2c1a92015-07-03 16:23:16 +0100331 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);
Juan Castillo6f971622014-10-21 11:30:42 +0100335 break;
Juan Castilload2c1a92015-07-03 16:23:16 +0100336 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);
Juan Castillo6f971622014-10-21 11:30:42 +0100340 break;
Juan Castilload2c1a92015-07-03 16:23:16 +0100341 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);
Juan Castillo6f971622014-10-21 11:30:42 +0100345 break;
346 case '?':
347 default:
Juan Castillo159807e2015-12-15 16:37:57 +0000348 print_help(argv[0], cmd_opt);
Juan Castillo6f971622014-10-21 11:30:42 +0100349 exit(1);
350 }
351 }
352
Juan Castillo6f971622014-10-21 11:30:42 +0100353 /* Check command line arguments */
354 check_cmd_params();
355
Juan Castilloc3da66b2015-03-05 14:30:00 +0000356 /* Indicate SHA256 as image hash algorithm in the certificate
357 * extension */
358 md_info = EVP_sha256();
359
Juan Castillo6f971622014-10-21 11:30:42 +0100360 /* Load private keys from files (or generate new ones) */
Juan Castillo55e291a2015-06-12 11:27:59 +0100361 for (i = 0 ; i < num_keys ; i++) {
Juan Castilloccbf8902015-06-01 16:34:23 +0100362 /* First try to load the key from disk */
363 if (key_load(&keys[i], &err_code)) {
364 /* Key loaded successfully */
365 continue;
Juan Castillo6f971622014-10-21 11:30:42 +0100366 }
Juan Castilloccbf8902015-06-01 16:34:23 +0100367
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);
Juan Castillo6f971622014-10-21 11:30:42 +0100387 exit(1);
388 }
Juan Castilloccbf8902015-06-01 16:34:23 +0100389 } 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);
Juan Castillo6f971622014-10-21 11:30:42 +0100396 }
397 }
398
Juan Castillo55e291a2015-06-12 11:27:59 +0100399 /* Create the certificates */
400 for (i = 0 ; i < num_certs ; i++) {
Juan Castillo6f971622014-10-21 11:30:42 +0100401
Juan Castillo55e291a2015-06-12 11:27:59 +0100402 cert = &certs[i];
Juan Castillo6f971622014-10-21 11:30:42 +0100403
Juan Castillo55e291a2015-06-12 11:27:59 +0100404 /* Create a new stack of extensions. This stack will be used
405 * to create the certificate */
Juan Castillo6f971622014-10-21 11:30:42 +0100406 CHECK_NULL(sk, sk_X509_EXTENSION_new_null());
Juan Castillo55e291a2015-06-12 11:27:59 +0100407
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) {
Yatharth Kocharcebe1f22015-08-21 15:30:55 +0100428 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 }
Juan Castillo55e291a2015-06-12 11:27:59 +0100442 }
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);
Juan Castillo6f971622014-10-21 11:30:42 +0100459 }
Juan Castillo6f971622014-10-21 11:30:42 +0100460
Juan Castillo55e291a2015-06-12 11:27:59 +0100461 /* Create certificate. Signed with ROT key */
Juan Castillodfc90e22015-07-08 12:11:38 +0100462 if (cert->fn && !cert_new(cert, VAL_DAYS, 0, sk)) {
Juan Castillo55e291a2015-06-12 11:27:59 +0100463 ERROR("Cannot create %s\n", cert->cn);
Juan Castillo6f971622014-10-21 11:30:42 +0100464 exit(1);
465 }
466
467 sk_X509_EXTENSION_free(sk);
468 }
469
Juan Castillo6f971622014-10-21 11:30:42 +0100470
471 /* Print the certificates */
472 if (print_cert) {
Juan Castillo55e291a2015-06-12 11:27:59 +0100473 for (i = 0 ; i < num_certs ; i++) {
Juan Castillo6f971622014-10-21 11:30:42 +0100474 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 */
Juan Castillo55e291a2015-06-12 11:27:59 +0100483 for (i = 0 ; i < num_certs ; i++) {
Juan Castillo6f971622014-10-21 11:30:42 +0100484 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) {
Juan Castillo55e291a2015-06-12 11:27:59 +0100497 for (i = 0 ; i < num_keys ; i++) {
Juan Castillo6f971622014-10-21 11:30:42 +0100498 if (!key_store(&keys[i])) {
499 ERROR("Cannot save %s\n", keys[i].desc);
500 }
501 }
502 }
503
Juan Castillo6f971622014-10-21 11:30:42 +0100504#ifndef OPENSSL_NO_ENGINE
505 ENGINE_cleanup();
506#endif
507 CRYPTO_cleanup_all_ex_data();
508
509 return 0;
510}