main.c 13.2 KB
Newer Older
1
/*
2
 * Copyright (c) 2015-2020, ARM Limited and Contributors. All rights reserved.
3
 *
dp-arm's avatar
dp-arm committed
4
 * SPDX-License-Identifier: BSD-3-Clause
5
6
 */

7
8
#include <assert.h>
#include <ctype.h>
9
10
11
12
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
13
#include <stdbool.h>
14
15
16
17
18
19
20
21
22

#include <openssl/conf.h>
#include <openssl/engine.h>
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/sha.h>
#include <openssl/x509v3.h>

#include "cert.h"
23
#include "cmd_opt.h"
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include "debug.h"
#include "ext.h"
#include "key.h"
#include "sha.h"

/*
 * Helper macros to simplify the code. This macro assigns the return value of
 * the 'fn' function to 'v' and exits if the value is NULL.
 */
#define CHECK_NULL(v, fn) \
	do { \
		v = fn; \
		if (v == NULL) { \
			ERROR("NULL object at %s:%d\n", __FILE__, __LINE__); \
			exit(1); \
		} \
	} while (0)

/*
 * This macro assigns the NID corresponding to 'oid' to 'v' and exits if the
 * NID is undefined.
 */
#define CHECK_OID(v, oid) \
	do { \
		v = OBJ_txt2nid(oid); \
		if (v == NID_undef) { \
50
			ERROR("Cannot find extension %s\n", oid); \
51
52
53
54
55
56
57
			exit(1); \
		} \
	} while (0)

#define MAX_FILENAME_LEN		1024
#define VAL_DAYS			7300
#define ID_TO_BIT_MASK(id)		(1 << id)
58
#define NUM_ELEM(x)			((sizeof(x)) / (sizeof(x[0])))
59
#define HELP_OPT_MAX_LEN		128
60
61

/* Global options */
62
static int key_alg;
63
static int hash_alg;
64
static int key_size;
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
static int new_keys;
static int save_keys;
static int print_cert;

/* Info messages created in the Makefile */
extern const char build_msg[];
extern const char platform_msg[];


static char *strdup(const char *str)
{
	int n = strlen(str) + 1;
	char *dup = malloc(n);
	if (dup) {
		strcpy(dup, str);
	}
	return dup;
}

84
85
static const char *key_algs_str[] = {
	[KEY_ALG_RSA] = "rsa",
86
#ifndef OPENSSL_NO_EC
87
	[KEY_ALG_ECDSA] = "ecdsa"
88
#endif /* OPENSSL_NO_EC */
89
90
};

91
92
93
94
95
96
static const char *hash_algs_str[] = {
	[HASH_ALG_SHA256] = "sha256",
	[HASH_ALG_SHA384] = "sha384",
	[HASH_ALG_SHA512] = "sha512",
};

97
static void print_help(const char *cmd, const struct option *long_opt)
98
{
99
100
101
102
103
104
105
106
	int rem, i = 0;
	const struct option *opt;
	char line[HELP_OPT_MAX_LEN];
	char *p;

	assert(cmd != NULL);
	assert(long_opt != NULL);

107
108
109
110
111
112
113
	printf("\n\n");
	printf("The certificate generation tool loads the binary images and\n"
	       "optionally the RSA keys, and outputs the key and content\n"
	       "certificates properly signed to implement the chain of trust.\n"
	       "If keys are provided, they must be in PEM format.\n"
	       "Certificates are generated in DER format.\n");
	printf("\n");
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
	printf("Usage:\n");
	printf("\t%s [OPTIONS]\n\n", cmd);

	printf("Available options:\n");
	opt = long_opt;
	while (opt->name) {
		p = line;
		rem = HELP_OPT_MAX_LEN;
		if (isalpha(opt->val)) {
			/* Short format */
			sprintf(p, "-%c,", (char)opt->val);
			p += 3;
			rem -= 3;
		}
		snprintf(p, rem, "--%s %s", opt->name,
			 (opt->has_arg == required_argument) ? "<arg>" : "");
		printf("\t%-32s %s\n", line, cmd_opt_get_help_msg(i));
		opt++;
		i++;
133
134
135
136
	}
	printf("\n");
}

137
138
139
140
141
142
143
144
145
146
147
148
149
static int get_key_alg(const char *key_alg_str)
{
	int i;

	for (i = 0 ; i < NUM_ELEM(key_algs_str) ; i++) {
		if (0 == strcmp(key_alg_str, key_algs_str[i])) {
			return i;
		}
	}

	return -1;
}

150
151
152
153
154
155
156
157
158
159
160
161
static int get_key_size(const char *key_size_str)
{
	char *end;
	long key_size;

	key_size = strtol(key_size_str, &end, 10);
	if (*end != '\0')
		return -1;

	return key_size;
}

162
163
164
165
166
167
168
169
170
171
172
173
174
static int get_hash_alg(const char *hash_alg_str)
{
	int i;

	for (i = 0 ; i < NUM_ELEM(hash_algs_str) ; i++) {
		if (0 == strcmp(hash_alg_str, hash_algs_str[i])) {
			return i;
		}
	}

	return -1;
}

175
176
static void check_cmd_params(void)
{
177
178
179
180
	cert_t *cert;
	ext_t *ext;
	key_t *key;
	int i, j;
181
	bool valid_size;
182

183
184
185
186
187
188
	/* Only save new keys */
	if (save_keys && !new_keys) {
		ERROR("Only new keys can be saved to disk\n");
		exit(1);
	}

189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
	/* Validate key-size */
	valid_size = false;
	for (i = 0; i < KEY_SIZE_MAX_NUM; i++) {
		if (key_size == KEY_SIZES[key_alg][i]) {
			valid_size = true;
			break;
		}
	}
	if (!valid_size) {
		ERROR("'%d' is not a valid key size for '%s'\n",
				key_size, key_algs_str[key_alg]);
		NOTICE("Valid sizes are: ");
		for (i = 0; i < KEY_SIZE_MAX_NUM &&
				KEY_SIZES[key_alg][i] != 0; i++) {
			printf("%d ", KEY_SIZES[key_alg][i]);
		}
		printf("\n");
		exit(1);
	}

209
210
211
212
213
214
215
	/* Check that all required options have been specified in the
	 * command line */
	for (i = 0; i < num_certs; i++) {
		cert = &certs[i];
		if (cert->fn == NULL) {
			/* Certificate not requested. Skip to the next one */
			continue;
216
217
		}

218
219
220
221
222
		/* Check that all parameters required to create this certificate
		 * have been specified in the command line */
		for (j = 0; j < cert->num_ext; j++) {
			ext = &extensions[cert->ext[j]];
			switch (ext->type) {
223
224
225
226
227
228
229
230
			case EXT_TYPE_NVCOUNTER:
				/* Counter value must be specified */
				if ((!ext->optional) && (ext->arg == NULL)) {
					ERROR("Value for '%s' not specified\n",
					      ext->ln);
					exit(1);
				}
				break;
231
232
			case EXT_TYPE_PKEY:
				/* Key filename must be specified */
233
				key = &keys[ext->attr.key];
234
235
236
237
238
239
240
241
				if (!new_keys && key->fn == NULL) {
					ERROR("Key '%s' required by '%s' not "
					      "specified\n", key->desc,
					      cert->cn);
					exit(1);
				}
				break;
			case EXT_TYPE_HASH:
242
243
244
245
				/*
				 * Binary image must be specified
				 * unless it is explicitly made optional.
				 */
246
				if ((!ext->optional) && (ext->arg == NULL)) {
247
248
249
250
251
252
					ERROR("Image for '%s' not specified\n",
					      ext->ln);
					exit(1);
				}
				break;
			default:
253
254
				ERROR("Unknown extension type '%d' in '%s'\n",
				      ext->type, ext->ln);
255
256
257
				exit(1);
				break;
			}
258
259
260
261
		}
	}
}

262
263
264
265
266
267
268
269
/* Common command line options */
static const cmd_opt_t common_cmd_opt[] = {
	{
		{ "help", no_argument, NULL, 'h' },
		"Print this message and exit"
	},
	{
		{ "key-alg", required_argument, NULL, 'a' },
270
		"Key algorithm: 'rsa' (default)- RSAPSS scheme as per PKCS#1 v2.1, 'ecdsa'"
271
	},
272
273
274
275
	{
		{ "key-size", required_argument, NULL, 'b' },
		"Key size (for supported algorithms)."
	},
276
277
278
279
	{
		{ "hash-alg", required_argument, NULL, 's' },
		"Hash algorithm : 'sha256' (default), 'sha384', 'sha512'"
	},
280
281
282
283
284
285
286
287
288
289
290
291
292
293
	{
		{ "save-keys", no_argument, NULL, 'k' },
		"Save key pairs into files. Filenames must be provided"
	},
	{
		{ "new-keys", no_argument, NULL, 'n' },
		"Generate new key pairs if no key files are provided"
	},
	{
		{ "print-cert", no_argument, NULL, 'p' },
		"Print the certificates in the standard output"
	}
};

294
295
int main(int argc, char *argv[])
{
296
	STACK_OF(X509_EXTENSION) * sk;
297
	X509_EXTENSION *cert_ext = NULL;
298
299
300
301
	ext_t *ext;
	key_t *key;
	cert_t *cert;
	FILE *file;
302
	int i, j, ext_nid, nvctr;
303
	int c, opt_idx = 0;
304
305
	const struct option *cmd_opt;
	const char *cur_opt;
306
	unsigned int err_code;
307
308
	unsigned char md[SHA512_DIGEST_LENGTH];
	unsigned int  md_len;
309
	const EVP_MD *md_info;
310
311
312
313

	NOTICE("CoT Generation Tool: %s\n", build_msg);
	NOTICE("Target platform: %s\n", platform_msg);

314
315
	/* Set default options */
	key_alg = KEY_ALG_RSA;
316
	hash_alg = HASH_ALG_SHA256;
317
	key_size = -1;
318

319
	/* Add common command line options */
320
321
322
	for (i = 0; i < NUM_ELEM(common_cmd_opt); i++) {
		cmd_opt_add(&common_cmd_opt[i]);
	}
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337

	/* Initialize the certificates */
	if (cert_init() != 0) {
		ERROR("Cannot initialize certificates\n");
		exit(1);
	}

	/* Initialize the keys */
	if (key_init() != 0) {
		ERROR("Cannot initialize keys\n");
		exit(1);
	}

	/* Initialize the new types and register OIDs for the extensions */
	if (ext_init() != 0) {
338
		ERROR("Cannot initialize extensions\n");
339
340
341
342
343
344
		exit(1);
	}

	/* Get the command line options populated during the initialization */
	cmd_opt = cmd_opt_get_array();

345
346
	while (1) {
		/* getopt_long stores the option index here. */
347
		c = getopt_long(argc, argv, "a:b:hknps:", cmd_opt, &opt_idx);
348
349
350
351
352
353
354

		/* Detect the end of the options. */
		if (c == -1) {
			break;
		}

		switch (c) {
355
356
357
358
359
360
361
		case 'a':
			key_alg = get_key_alg(optarg);
			if (key_alg < 0) {
				ERROR("Invalid key algorithm '%s'\n", optarg);
				exit(1);
			}
			break;
362
363
364
365
366
367
368
		case 'b':
			key_size = get_key_size(optarg);
			if (key_size <= 0) {
				ERROR("Invalid key size '%s'\n", optarg);
				exit(1);
			}
			break;
369
		case 'h':
370
			print_help(argv[0], cmd_opt);
371
			exit(0);
372
373
374
375
376
377
378
379
380
		case 'k':
			save_keys = 1;
			break;
		case 'n':
			new_keys = 1;
			break;
		case 'p':
			print_cert = 1;
			break;
381
382
383
384
385
386
387
		case 's':
			hash_alg = get_hash_alg(optarg);
			if (hash_alg < 0) {
				ERROR("Invalid hash algorithm '%s'\n", optarg);
				exit(1);
			}
			break;
388
389
390
		case CMD_OPT_EXT:
			cur_opt = cmd_opt_get_name(opt_idx);
			ext = ext_get_by_opt(cur_opt);
391
			ext->arg = strdup(optarg);
392
			break;
393
394
395
396
		case CMD_OPT_KEY:
			cur_opt = cmd_opt_get_name(opt_idx);
			key = key_get_by_opt(cur_opt);
			key->fn = strdup(optarg);
397
			break;
398
399
400
401
		case CMD_OPT_CERT:
			cur_opt = cmd_opt_get_name(opt_idx);
			cert = cert_get_by_opt(cur_opt);
			cert->fn = strdup(optarg);
402
403
404
			break;
		case '?':
		default:
405
			print_help(argv[0], cmd_opt);
406
407
408
409
			exit(1);
		}
	}

410
411
412
413
414
	/* Select a reasonable default key-size */
	if (key_size == -1) {
		key_size = KEY_SIZES[key_alg][0];
	}

415
416
417
	/* Check command line arguments */
	check_cmd_params();

418
	/* Indicate SHA as image hash algorithm in the certificate
419
	 * extension */
420
421
422
423
424
425
426
427
428
429
	if (hash_alg == HASH_ALG_SHA384) {
		md_info = EVP_sha384();
		md_len  = SHA384_DIGEST_LENGTH;
	} else if (hash_alg == HASH_ALG_SHA512) {
		md_info = EVP_sha512();
		md_len  = SHA512_DIGEST_LENGTH;
	} else {
		md_info = EVP_sha256();
		md_len  = SHA256_DIGEST_LENGTH;
	}
430

431
	/* Load private keys from files (or generate new ones) */
432
	for (i = 0 ; i < num_keys ; i++) {
433
434
435
436
437
		if (!key_new(&keys[i])) {
			ERROR("Failed to allocate key container\n");
			exit(1);
		}

438
439
440
441
442
443
444
		/* First try to load the key from disk */
		if (key_load(&keys[i], &err_code)) {
			/* Key loaded successfully */
			continue;
		}

		/* Key not loaded. Check the error code */
445
		if (err_code == KEY_ERR_LOAD) {
446
447
448
449
			/* File exists, but it does not contain a valid private
			 * key. Abort. */
			ERROR("Error loading '%s'\n", keys[i].fn);
			exit(1);
450
		}
451
452
453
454
455
456

		/* File does not exist, could not be opened or no filename was
		 * given */
		if (new_keys) {
			/* Try to create a new key */
			NOTICE("Creating new key for '%s'\n", keys[i].desc);
457
			if (!key_create(&keys[i], key_alg, key_size)) {
458
				ERROR("Error creating key '%s'\n", keys[i].desc);
459
460
				exit(1);
			}
461
462
463
464
465
466
467
		} else {
			if (err_code == KEY_ERR_OPEN) {
				ERROR("Error opening '%s'\n", keys[i].fn);
			} else {
				ERROR("Key '%s' not specified\n", keys[i].desc);
			}
			exit(1);
468
469
470
		}
	}

471
472
	/* Create the certificates */
	for (i = 0 ; i < num_certs ; i++) {
473

474
		cert = &certs[i];
475

476
477
		/* Create a new stack of extensions. This stack will be used
		 * to create the certificate */
478
479
		CHECK_NULL(sk, sk_X509_EXTENSION_new_null());

480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
		for (j = 0 ; j < cert->num_ext ; j++) {

			ext = &extensions[cert->ext[j]];

			/* Get OpenSSL internal ID for this extension */
			CHECK_OID(ext_nid, ext->oid);

			/*
			 * Three types of extensions are currently supported:
			 *     - EXT_TYPE_NVCOUNTER
			 *     - EXT_TYPE_HASH
			 *     - EXT_TYPE_PKEY
			 */
			switch (ext->type) {
			case EXT_TYPE_NVCOUNTER:
495
496
497
				if (ext->arg) {
					nvctr = atoi(ext->arg);
					CHECK_NULL(cert_ext, ext_new_nvcounter(ext_nid,
498
						EXT_CRIT, nvctr));
499
				}
500
501
				break;
			case EXT_TYPE_HASH:
502
				if (ext->arg == NULL) {
503
504
					if (ext->optional) {
						/* Include a hash filled with zeros */
505
						memset(md, 0x0, SHA512_DIGEST_LENGTH);
506
507
508
509
510
511
					} else {
						/* Do not include this hash in the certificate */
						break;
					}
				} else {
					/* Calculate the hash of the file */
512
					if (!sha_file(hash_alg, ext->arg, md)) {
513
						ERROR("Cannot calculate hash of %s\n",
514
							ext->arg);
515
516
						exit(1);
					}
517
518
519
				}
				CHECK_NULL(cert_ext, ext_new_hash(ext_nid,
						EXT_CRIT, md_info, md,
520
						md_len));
521
522
523
				break;
			case EXT_TYPE_PKEY:
				CHECK_NULL(cert_ext, ext_new_key(ext_nid,
524
					EXT_CRIT, keys[ext->attr.key].key));
525
526
				break;
			default:
527
528
				ERROR("Unknown extension type '%d' in %s\n",
						ext->type, cert->cn);
529
530
				exit(1);
			}
531

532
533
			/* Push the extension into the stack */
			sk_X509_EXTENSION_push(sk, cert_ext);
534
535
		}

536
		/* Create certificate. Signed with corresponding key */
537
		if (cert->fn && !cert_new(hash_alg, cert, VAL_DAYS, 0, sk)) {
538
			ERROR("Cannot create %s\n", cert->cn);
539
540
541
			exit(1);
		}

Jimmy Brisson's avatar
Jimmy Brisson committed
542
543
544
545
546
		for (cert_ext = sk_X509_EXTENSION_pop(sk); cert_ext != NULL;
				cert_ext = sk_X509_EXTENSION_pop(sk)) {
			X509_EXTENSION_free(cert_ext);
		}

547
548
549
550
551
552
		sk_X509_EXTENSION_free(sk);
	}


	/* Print the certificates */
	if (print_cert) {
553
		for (i = 0 ; i < num_certs ; i++) {
554
555
556
557
558
559
560
561
562
			if (!certs[i].x) {
				continue;
			}
			printf("\n\n=====================================\n\n");
			X509_print_fp(stdout, certs[i].x);
		}
	}

	/* Save created certificates to files */
563
	for (i = 0 ; i < num_certs ; i++) {
564
565
566
567
568
569
570
571
572
573
574
575
576
		if (certs[i].x && certs[i].fn) {
			file = fopen(certs[i].fn, "w");
			if (file != NULL) {
				i2d_X509_fp(file, certs[i].x);
				fclose(file);
			} else {
				ERROR("Cannot create file %s\n", certs[i].fn);
			}
		}
	}

	/* Save keys */
	if (save_keys) {
577
		for (i = 0 ; i < num_keys ; i++) {
578
579
580
581
582
583
			if (!key_store(&keys[i])) {
				ERROR("Cannot save %s\n", keys[i].desc);
			}
		}
	}

Jimmy Brisson's avatar
Jimmy Brisson committed
584
585
586
587
588
589
590
	/* If we got here, then we must have filled the key array completely.
	 * We can then safely call free on all of the keys in the array
	 */
	for (i = 0; i < num_keys; i++) {
		EVP_PKEY_free(keys[i].key);
	}

591
592
593
594
595
596
597
#ifndef OPENSSL_NO_ENGINE
	ENGINE_cleanup();
#endif
	CRYPTO_cleanup_all_ex_data();

	return 0;
}