1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright 2018 Linaro Limited
4  *		Author: AKASHI Takahiro
5  */
6 
7 #include <getopt.h>
8 #include <inttypes.h>
9 #include <pe.h>
10 #include <stdbool.h>
11 #include <stdint.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <linux/types.h>
16 
17 #include <sys/stat.h>
18 #include <sys/types.h>
19 
20 #include <gnutls/gnutls.h>
21 #include <gnutls/pkcs7.h>
22 #include <gnutls/abstract.h>
23 
24 #include <version.h>
25 #include <libfdt.h>
26 #include <u-boot/uuid.h>
27 
28 #include "eficapsule.h"
29 
30 // Matches CONFIG_EFI_CAPSULE_NAMESPACE_GUID
31 #define DEFAULT_NAMESPACE_GUID "8c9f137e-91dc-427b-b2d6-b420faebaf2a"
32 
33 static const char *tool_name = "mkeficapsule";
34 
35 efi_guid_t efi_guid_fm_capsule = EFI_FIRMWARE_MANAGEMENT_CAPSULE_ID_GUID;
36 efi_guid_t efi_guid_cert_type_pkcs7 = EFI_CERT_TYPE_PKCS7_GUID;
37 
38 static const char *opts_short = "g:i:I:v:p:c:m:o:dhARDV";
39 
40 enum {
41 	CAPSULE_NORMAL_BLOB = 0,
42 	CAPSULE_ACCEPT,
43 	CAPSULE_REVERT,
44 } capsule_type;
45 
46 static struct option options[] = {
47 	{"guid", required_argument, NULL, 'g'},
48 	{"index", required_argument, NULL, 'i'},
49 	{"instance", required_argument, NULL, 'I'},
50 	{"fw-version", required_argument, NULL, 'v'},
51 	{"private-key", required_argument, NULL, 'p'},
52 	{"certificate", required_argument, NULL, 'c'},
53 	{"monotonic-count", required_argument, NULL, 'm'},
54 	{"dump-sig", no_argument, NULL, 'd'},
55 	{"fw-accept", no_argument, NULL, 'A'},
56 	{"fw-revert", no_argument, NULL, 'R'},
57 	{"capoemflag", required_argument, NULL, 'o'},
58 	{"dump-capsule", no_argument, NULL, 'D'},
59 	{"help", no_argument, NULL, 'h'},
60 	{NULL, 0, NULL, 0},
61 };
62 
print_usage_guidgen(void)63 static void print_usage_guidgen(void)
64 {
65 	fprintf(stderr, "%s guidgen [GUID] DTB IMAGE_NAME...\n"
66 		"Options:\n"
67 
68 		"\tGUID                        Namespace GUID (default: %s)\n"
69 		"\tDTB                         Device Tree Blob\n"
70 		"\tIMAGE_NAME...               One or more names of fw_images to generate GUIDs for\n",
71 		tool_name, DEFAULT_NAMESPACE_GUID);
72 }
73 
print_usage_mkeficapsule(void)74 static void print_usage_mkeficapsule(void)
75 {
76 	fprintf(stderr, "Usage:\n\n%s [options] <image blob> <output file>\n"
77 		"Options:\n"
78 
79 		"\t-g, --guid <guid string>    guid for image blob type\n"
80 		"\t-i, --index <index>         update image index\n"
81 		"\t-I, --instance <instance>   update hardware instance\n"
82 		"\t-v, --fw-version <version>  firmware version\n"
83 		"\t-p, --private-key <privkey file>  private key file\n"
84 		"\t-c, --certificate <cert file>     signer's certificate file\n"
85 		"\t-m, --monotonic-count <count>     monotonic count\n"
86 		"\t-d, --dump_sig              dump signature (*.p7)\n"
87 		"\t-A, --fw-accept  firmware accept capsule, requires GUID, no image blob\n"
88 		"\t-R, --fw-revert  firmware revert capsule, takes no GUID, no image blob\n"
89 		"\t-o, --capoemflag Capsule OEM Flag, an integer between 0x0000 and 0xffff\n"
90 		"\t-D, --dump-capsule          dump the contents of the capsule headers\n"
91 		"\t-V, --version               show version number\n"
92 		"\t-h, --help                  print a help message\n\n",
93 		tool_name);
94 	print_usage_guidgen();
95 }
96 
97 /**
98  * auth_context - authentication context
99  * @key_file:	Path to a private key file
100  * @cert_file:	Path to a certificate file
101  * @image_data:	Pointer to firmware data
102  * @image_size:	Size of firmware data
103  * @auth:	Authentication header
104  * @sig_data:	Signature data
105  * @sig_size:	Size of signature data
106  *
107  * Data structure used in create_auth_data(). @key_file through
108  * @image_size are input parameters. @auth, @sig_data and @sig_size
109  * are filled in by create_auth_data().
110  */
111 struct auth_context {
112 	char *key_file;
113 	char *cert_file;
114 	uint8_t *image_data;
115 	size_t image_size;
116 	struct efi_firmware_image_authentication auth;
117 	uint8_t *sig_data;
118 	size_t sig_size;
119 };
120 
121 static int dump_sig;
122 
123 /**
124  * read_bin_file - read a firmware binary file
125  * @bin:	Path to a firmware binary file
126  * @data:	Pointer to pointer of allocated buffer
127  * @bin_size:	Size of allocated buffer
128  *
129  * Read out a content of binary, @bin, into @data.
130  * A caller should free @data.
131  *
132  * Return:
133  * * 0  - on success
134  * * -1 - on failure
135  */
read_bin_file(char * bin,uint8_t ** data,off_t * bin_size)136 static int read_bin_file(char *bin, uint8_t **data, off_t *bin_size)
137 {
138 	FILE *g;
139 	struct stat bin_stat;
140 	void *buf;
141 	size_t size;
142 	int ret = 0;
143 
144 	g = fopen(bin, "r");
145 	if (!g) {
146 		fprintf(stderr, "cannot open %s\n", bin);
147 		return -1;
148 	}
149 	if (stat(bin, &bin_stat) < 0) {
150 		fprintf(stderr, "cannot determine the size of %s\n", bin);
151 		ret = -1;
152 		goto err;
153 	}
154 	if (bin_stat.st_size > SIZE_MAX) {
155 		fprintf(stderr, "file size is too large for malloc: %s\n", bin);
156 		ret = -1;
157 		goto err;
158 	}
159 	buf = malloc(bin_stat.st_size);
160 	if (!buf) {
161 		fprintf(stderr, "cannot allocate memory: %zx\n",
162 			(size_t)bin_stat.st_size);
163 		ret = -1;
164 		goto err;
165 	}
166 
167 	size = fread(buf, 1, bin_stat.st_size, g);
168 	if (size < bin_stat.st_size) {
169 		fprintf(stderr, "read failed (%zx)\n", size);
170 		ret = -1;
171 		free(buf);
172 		goto err;
173 	}
174 
175 	*data = buf;
176 	*bin_size = bin_stat.st_size;
177 err:
178 	fclose(g);
179 
180 	return ret;
181 }
182 
183 /**
184  * write_capsule_file - write a capsule file
185  * @bin:	FILE stream
186  * @data:	Pointer to data
187  * @bin_size:	Size of data
188  *
189  * Write out data, @data, with the size @bin_size.
190  *
191  * Return:
192  * * 0  - on success
193  * * -1 - on failure
194  */
write_capsule_file(FILE * f,void * data,size_t size,const char * msg)195 static int write_capsule_file(FILE *f, void *data, size_t size, const char *msg)
196 {
197 	size_t size_written;
198 
199 	size_written = fwrite(data, 1, size, f);
200 	if (size_written < size) {
201 		fprintf(stderr, "%s: write failed (%zx != %zx)\n", msg,
202 			size_written, size);
203 		return -1;
204 	}
205 
206 	return 0;
207 }
208 
209 /**
210  * create_auth_data - compose authentication data in capsule
211  * @auth_context:	Pointer to authentication context
212  *
213  * Fill up an authentication header (.auth) and signature data (.sig_data)
214  * in @auth_context, using library functions from openssl.
215  * All the parameters in @auth_context must be filled in by a caller.
216  *
217  * Return:
218  * * 0  - on success
219  * * -1 - on failure
220  */
create_auth_data(struct auth_context * ctx)221 static int create_auth_data(struct auth_context *ctx)
222 {
223 	gnutls_datum_t cert;
224 	gnutls_datum_t key;
225 	off_t file_size;
226 	gnutls_privkey_t pkey;
227 	gnutls_x509_crt_t x509;
228 	gnutls_pkcs7_t pkcs7;
229 	gnutls_datum_t data;
230 	gnutls_datum_t signature;
231 	int ret;
232 
233 	ret = read_bin_file(ctx->cert_file, &cert.data, &file_size);
234 	if (ret < 0)
235 		return -1;
236 	if (file_size > UINT_MAX)
237 		return -1;
238 	cert.size = file_size;
239 
240 	ret = read_bin_file(ctx->key_file, &key.data, &file_size);
241 	if (ret < 0)
242 		return -1;
243 	if (file_size > UINT_MAX)
244 		return -1;
245 	key.size = file_size;
246 
247 	/*
248 	 * For debugging,
249 	 * gnutls_global_set_time_function(mytime);
250 	 * gnutls_global_set_log_function(tls_log_func);
251 	 * gnutls_global_set_log_level(6);
252 	 */
253 
254 	ret = gnutls_privkey_init(&pkey);
255 	if (ret < 0) {
256 		fprintf(stderr, "error in gnutls_privkey_init(): %s\n",
257 			gnutls_strerror(ret));
258 		return -1;
259 	}
260 
261 	ret = gnutls_x509_crt_init(&x509);
262 	if (ret < 0) {
263 		fprintf(stderr, "error in gnutls_x509_crt_init(): %s\n",
264 			gnutls_strerror(ret));
265 		return -1;
266 	}
267 
268 	/* load a private key */
269 	ret = gnutls_privkey_import_x509_raw(pkey, &key, GNUTLS_X509_FMT_PEM,
270 					     0, 0);
271 	if (ret < 0) {
272 		fprintf(stderr,
273 			"error in gnutls_privkey_import_x509_raw(): %s\n",
274 			gnutls_strerror(ret));
275 		return -1;
276 	}
277 
278 	/* load x509 certificate */
279 	ret = gnutls_x509_crt_import(x509, &cert, GNUTLS_X509_FMT_PEM);
280 	if (ret < 0) {
281 		fprintf(stderr, "error in gnutls_x509_crt_import(): %s\n",
282 			gnutls_strerror(ret));
283 		return -1;
284 	}
285 
286 	/* generate a PKCS #7 structure */
287 	ret = gnutls_pkcs7_init(&pkcs7);
288 	if (ret < 0) {
289 		fprintf(stderr, "error in gnutls_pkcs7_init(): %s\n",
290 			gnutls_strerror(ret));
291 		return -1;
292 	}
293 
294 	/* sign */
295 	/*
296 	 * Data should have
297 	 *  * firmware image
298 	 *  * monotonic count
299 	 * in this order!
300 	 * See EDK2's FmpAuthenticatedHandlerRsa2048Sha256()
301 	 */
302 	data.size = ctx->image_size + sizeof(ctx->auth.monotonic_count);
303 	data.data = malloc(data.size);
304 	if (!data.data) {
305 		fprintf(stderr, "allocating memory (0x%x) failed\n", data.size);
306 		return -1;
307 	}
308 	memcpy(data.data, ctx->image_data, ctx->image_size);
309 	memcpy(data.data + ctx->image_size, &ctx->auth.monotonic_count,
310 	       sizeof(ctx->auth.monotonic_count));
311 
312 	ret = gnutls_pkcs7_sign(pkcs7, x509, pkey, &data, NULL, NULL,
313 				GNUTLS_DIG_SHA256,
314 				/* GNUTLS_PKCS7_EMBED_DATA? */
315 				GNUTLS_PKCS7_INCLUDE_CERT |
316 				GNUTLS_PKCS7_INCLUDE_TIME);
317 	if (ret < 0) {
318 		fprintf(stderr, "error in gnutls_pkcs7)sign(): %s\n",
319 			gnutls_strerror(ret));
320 		return -1;
321 	}
322 
323 	/* export */
324 	ret = gnutls_pkcs7_export2(pkcs7, GNUTLS_X509_FMT_DER, &signature);
325 	if (ret < 0) {
326 		fprintf(stderr, "error in gnutls_pkcs7_export2: %s\n",
327 			gnutls_strerror(ret));
328 		return -1;
329 	}
330 	ctx->sig_data = signature.data;
331 	ctx->sig_size = signature.size;
332 
333 	/* fill auth_info */
334 	ctx->auth.auth_info.hdr.dwLength = sizeof(ctx->auth.auth_info)
335 						+ ctx->sig_size;
336 	ctx->auth.auth_info.hdr.wRevision = WIN_CERT_REVISION_2_0;
337 	ctx->auth.auth_info.hdr.wCertificateType = WIN_CERT_TYPE_EFI_GUID;
338 	memcpy(&ctx->auth.auth_info.cert_type, &efi_guid_cert_type_pkcs7,
339 	       sizeof(efi_guid_cert_type_pkcs7));
340 
341 	/*
342 	 * For better clean-ups,
343 	 * gnutls_pkcs7_deinit(pkcs7);
344 	 * gnutls_privkey_deinit(pkey);
345 	 * gnutls_x509_crt_deinit(x509);
346 	 * free(cert.data);
347 	 * free(key.data);
348 	 * if error
349 	 *   gnutls_free(signature.data);
350 	 */
351 
352 	return 0;
353 }
354 
355 /**
356  * dump_signature - dump out a signature
357  * @path:	Path to a capsule file
358  * @signature:	Signature data
359  * @sig_size:	Size of signature data
360  *
361  * Signature data pointed to by @signature will be saved into
362  * a file whose file name is @path with ".p7" suffix.
363  *
364  * Return:
365  * * 0  - on success
366  * * -1 - on failure
367  */
dump_signature(const char * path,uint8_t * signature,size_t sig_size)368 static int dump_signature(const char *path, uint8_t *signature, size_t sig_size)
369 {
370 	char *sig_path;
371 	FILE *f;
372 	size_t size;
373 	int ret = -1;
374 
375 	sig_path = malloc(strlen(path) + 3 + 1);
376 	if (!sig_path)
377 		return ret;
378 
379 	sprintf(sig_path, "%s.p7", path);
380 	f = fopen(sig_path, "w");
381 	if (!f)
382 		goto err;
383 
384 	size = fwrite(signature, 1, sig_size, f);
385 	if (size == sig_size)
386 		ret = 0;
387 
388 	fclose(f);
389 err:
390 	free(sig_path);
391 	return ret;
392 }
393 
394 /**
395  * free_sig_data - free out signature data
396  * @ctx:	Pointer to authentication context
397  *
398  * Free signature data allocated in create_auth_data().
399  */
free_sig_data(struct auth_context * ctx)400 static void free_sig_data(struct auth_context *ctx)
401 {
402 	if (ctx->sig_size)
403 		gnutls_free(ctx->sig_data);
404 }
405 
406 /**
407  * create_fwbin - create an uefi capsule file
408  * @path:	Path to a created capsule file
409  * @bin:	Path to a firmware binary to encapsulate
410  * @guid:	GUID of related FMP driver
411  * @index:	Index number in capsule
412  * @instance:	Instance number in capsule
413  * @mcount:	Monotonic count in authentication information
414  * @private_file:	Path to a private key file
415  * @cert_file:	Path to a certificate file
416  * @oemflags:  Capsule OEM Flags, bits 0-15
417  *
418  * This function actually does the job of creating an uefi capsule file.
419  * All the arguments must be supplied.
420  * If either @private_file ror @cert_file is NULL, the capsule file
421  * won't be signed.
422  *
423  * Return:
424  * * 0  - on success
425  * * -1 - on failure
426  */
create_fwbin(char * path,char * bin,efi_guid_t * guid,unsigned long index,unsigned long instance,struct fmp_payload_header_params * fmp_ph_params,uint64_t mcount,char * privkey_file,char * cert_file,uint16_t oemflags)427 static int create_fwbin(char *path, char *bin, efi_guid_t *guid,
428 			unsigned long index, unsigned long instance,
429 			struct fmp_payload_header_params *fmp_ph_params,
430 			uint64_t mcount, char *privkey_file, char *cert_file,
431 			uint16_t oemflags)
432 {
433 	struct efi_capsule_header header;
434 	struct efi_firmware_management_capsule_header capsule;
435 	struct efi_firmware_management_capsule_image_header image;
436 	struct auth_context auth_context;
437 	FILE *f;
438 	uint8_t *data, *new_data, *buf;
439 	off_t bin_size;
440 	uint64_t offset;
441 	int ret;
442 	struct fmp_payload_header payload_header;
443 
444 #ifdef DEBUG
445 	fprintf(stderr, "For output: %s\n", path);
446 	fprintf(stderr, "\tbin: %s\n\ttype: %pUl\n", bin, guid);
447 	fprintf(stderr, "\tindex: %lu\n\tinstance: %lu\n", index, instance);
448 #endif
449 	auth_context.sig_size = 0;
450 	f = NULL;
451 	data = NULL;
452 	new_data = NULL;
453 	ret = -1;
454 
455 	/*
456 	 * read a firmware binary
457 	 */
458 	if (read_bin_file(bin, &data, &bin_size))
459 		goto err;
460 
461 	buf = data;
462 
463 	/* insert fmp payload header right before the payload */
464 	if (fmp_ph_params->have_header) {
465 		new_data = malloc(bin_size + sizeof(payload_header));
466 		if (!new_data)
467 			goto err;
468 
469 		payload_header.signature = FMP_PAYLOAD_HDR_SIGNATURE;
470 		payload_header.header_size = sizeof(payload_header);
471 		payload_header.fw_version = fmp_ph_params->fw_version;
472 		payload_header.lowest_supported_version = 0; /* not used */
473 		memcpy(new_data, &payload_header, sizeof(payload_header));
474 		memcpy(new_data + sizeof(payload_header), data, bin_size);
475 		buf = new_data;
476 		bin_size += sizeof(payload_header);
477 	}
478 
479 	/* first, calculate signature to determine its size */
480 	if (privkey_file && cert_file) {
481 		auth_context.key_file = privkey_file;
482 		auth_context.cert_file = cert_file;
483 		auth_context.auth.monotonic_count = mcount;
484 		auth_context.image_data = buf;
485 		auth_context.image_size = bin_size;
486 
487 		if (create_auth_data(&auth_context)) {
488 			fprintf(stderr, "Signing firmware image failed\n");
489 			goto err;
490 		}
491 
492 		if (dump_sig &&
493 		    dump_signature(path, auth_context.sig_data,
494 				   auth_context.sig_size)) {
495 			fprintf(stderr, "Creating signature file failed\n");
496 			goto err;
497 		}
498 	}
499 
500 	/*
501 	 * write a capsule file
502 	 */
503 	f = fopen(path, "w");
504 	if (!f) {
505 		fprintf(stderr, "cannot open %s\n", path);
506 		goto err;
507 	}
508 
509 	/*
510 	 * capsule file header
511 	 */
512 	header.capsule_guid = efi_guid_fm_capsule;
513 	header.header_size = sizeof(header);
514 	/* TODO: The current implementation ignores flags */
515 	header.flags = CAPSULE_FLAGS_PERSIST_ACROSS_RESET;
516 	if (oemflags)
517 		header.flags |= oemflags;
518 	header.capsule_image_size = sizeof(header)
519 					+ sizeof(capsule) + sizeof(uint64_t)
520 					+ sizeof(image)
521 					+ bin_size;
522 	if (auth_context.sig_size)
523 		header.capsule_image_size += sizeof(auth_context.auth)
524 				+ auth_context.sig_size;
525 	if (write_capsule_file(f, &header, sizeof(header),
526 			       "Capsule header"))
527 		goto err;
528 
529 	/*
530 	 * firmware capsule header
531 	 * This capsule has only one firmware capsule image.
532 	 */
533 	capsule.version = 0x00000001;
534 	capsule.embedded_driver_count = 0;
535 	capsule.payload_item_count = 1;
536 	if (write_capsule_file(f, &capsule, sizeof(capsule),
537 			       "Firmware capsule header"))
538 		goto err;
539 
540 	offset = sizeof(capsule) + sizeof(uint64_t);
541 	if (write_capsule_file(f, &offset, sizeof(offset),
542 			       "Offset to capsule image"))
543 		goto err;
544 
545 	/*
546 	 * firmware capsule image header
547 	 */
548 	image.version = 0x00000003;
549 	memcpy(&image.update_image_type_id, guid, sizeof(*guid));
550 	image.update_image_index = index;
551 	image.reserved[0] = 0;
552 	image.reserved[1] = 0;
553 	image.reserved[2] = 0;
554 	image.update_image_size = bin_size;
555 	if (auth_context.sig_size)
556 		image.update_image_size += sizeof(auth_context.auth)
557 				+ auth_context.sig_size;
558 	image.update_vendor_code_size = 0; /* none */
559 	image.update_hardware_instance = instance;
560 	image.image_capsule_support = 0;
561 	if (auth_context.sig_size)
562 		image.image_capsule_support |= CAPSULE_SUPPORT_AUTHENTICATION;
563 	if (write_capsule_file(f, &image, sizeof(image),
564 			       "Firmware capsule image header"))
565 		goto err;
566 
567 	/*
568 	 * signature
569 	 */
570 	if (auth_context.sig_size) {
571 		if (write_capsule_file(f, &auth_context.auth,
572 				       sizeof(auth_context.auth),
573 				       "Authentication header"))
574 			goto err;
575 
576 		if (write_capsule_file(f, auth_context.sig_data,
577 				       auth_context.sig_size, "Signature"))
578 			goto err;
579 	}
580 
581 	/*
582 	 * firmware binary
583 	 */
584 	if (write_capsule_file(f, buf, bin_size, "Firmware binary"))
585 		goto err;
586 
587 	ret = 0;
588 err:
589 	if (f)
590 		fclose(f);
591 	free_sig_data(&auth_context);
592 	free(data);
593 	free(new_data);
594 
595 	return ret;
596 }
597 
create_empty_capsule(char * path,efi_guid_t * guid,bool fw_accept)598 static int create_empty_capsule(char *path, efi_guid_t *guid, bool fw_accept)
599 {
600 	struct efi_capsule_header header = { 0 };
601 	FILE *f = NULL;
602 	int ret = -1;
603 	efi_guid_t fw_accept_guid = FW_ACCEPT_OS_GUID;
604 	efi_guid_t fw_revert_guid = FW_REVERT_OS_GUID;
605 	efi_guid_t capsule_guid;
606 
607 	f = fopen(path, "w");
608 	if (!f) {
609 		fprintf(stderr, "cannot open %s\n", path);
610 		goto err;
611 	}
612 
613 	capsule_guid = fw_accept ? fw_accept_guid : fw_revert_guid;
614 
615 	memcpy(&header.capsule_guid, &capsule_guid, sizeof(efi_guid_t));
616 	header.header_size = sizeof(header);
617 	header.flags = 0;
618 
619 	header.capsule_image_size = fw_accept ?
620 		sizeof(header) + sizeof(efi_guid_t) : sizeof(header);
621 
622 	if (write_capsule_file(f, &header, sizeof(header),
623 			       "Capsule header"))
624 		goto err;
625 
626 	if (fw_accept) {
627 		if (write_capsule_file(f, guid, sizeof(*guid),
628 				       "FW Accept Capsule Payload"))
629 			goto err;
630 	}
631 
632 	ret = 0;
633 
634 err:
635 	if (f)
636 		fclose(f);
637 
638 	return ret;
639 }
640 
print_guid(void * ptr)641 static void print_guid(void *ptr)
642 {
643 	static char buf[37] = { 0 };
644 
645 	uuid_bin_to_str(ptr, buf, UUID_STR_FORMAT_GUID | UUID_STR_UPPER_CASE);
646 	printf("%s\n", buf);
647 }
648 
dump_fmp_payload_header(struct fmp_payload_header * fmp_payload_hdr)649 static uint32_t dump_fmp_payload_header(
650 	struct fmp_payload_header *fmp_payload_hdr)
651 {
652 	if (fmp_payload_hdr->signature == FMP_PAYLOAD_HDR_SIGNATURE) {
653 		printf("--------\n");
654 		printf("FMP_PAYLOAD_HDR.SIGNATURE\t\t\t: %08X\n",
655 		       FMP_PAYLOAD_HDR_SIGNATURE);
656 		printf("FMP_PAYLOAD_HDR.HEADER_SIZE\t\t\t: %08X\n",
657 		       fmp_payload_hdr->header_size);
658 		printf("FMP_PAYLOAD_HDR.FW_VERSION\t\t\t: %08X\n",
659 		       fmp_payload_hdr->fw_version);
660 		printf("FMP_PAYLOAD_HDR.LOWEST_SUPPORTED_VERSION\t: %08X\n",
661 		       fmp_payload_hdr->lowest_supported_version);
662 		return fmp_payload_hdr->header_size;
663 	}
664 
665 	return 0;
666 }
667 
dump_capsule_auth_header(struct efi_firmware_image_authentication * capsule_auth_hdr)668 static void dump_capsule_auth_header(
669 	struct efi_firmware_image_authentication *capsule_auth_hdr)
670 {
671 	printf("EFI_FIRMWARE_IMAGE_AUTH.MONOTONIC_COUNT\t\t: %08" PRIX64 "\n",
672 	       capsule_auth_hdr->monotonic_count);
673 	printf("EFI_FIRMWARE_IMAGE_AUTH.AUTH_INFO.HDR.dwLENGTH\t: %08X\n",
674 	       capsule_auth_hdr->auth_info.hdr.dwLength);
675 	printf("EFI_FIRMWARE_IMAGE_AUTH.AUTH_INFO.HDR.wREVISION\t: %08X\n",
676 	       capsule_auth_hdr->auth_info.hdr.wRevision);
677 	printf("EFI_FIRMWARE_IMAGE_AUTH.AUTH_INFO.HDR.wCERTTYPE\t: %08X\n",
678 	       capsule_auth_hdr->auth_info.hdr.wCertificateType);
679 	printf("EFI_FIRMWARE_IMAGE_AUTH.AUTH_INFO.CERT_TYPE\t: ");
680 	print_guid(&capsule_auth_hdr->auth_info.cert_type);
681 }
682 
dump_fmp_capsule_image_header(struct efi_firmware_management_capsule_image_header * image_hdr)683 static void dump_fmp_capsule_image_header(
684 	struct efi_firmware_management_capsule_image_header *image_hdr)
685 {
686 	void *capsule_auth_hdr;
687 	void *fmp_payload_hdr;
688 	uint64_t signature_size = 0;
689 	uint32_t payload_size = 0;
690 	uint32_t fmp_payload_hdr_size = 0;
691 	struct efi_firmware_image_authentication *auth_hdr;
692 
693 	printf("--------\n");
694 	printf("FMP_CAPSULE_IMAGE_HDR.VERSION\t\t\t: %08X\n",
695 	       image_hdr->version);
696 	printf("FMP_CAPSULE_IMAGE_HDR.UPDATE_IMAGE_TYPE_ID\t: ");
697 	print_guid(&image_hdr->update_image_type_id);
698 	printf("FMP_CAPSULE_IMAGE_HDR.UPDATE_IMAGE_INDEX\t: %08X\n",
699 	       image_hdr->update_image_index);
700 	printf("FMP_CAPSULE_IMAGE_HDR.UPDATE_IMAGE_SIZE\t\t: %08X\n",
701 	       image_hdr->update_image_size);
702 	printf("FMP_CAPSULE_IMAGE_HDR.UPDATE_VENDOR_CODE_SIZE\t: %08X\n",
703 	       image_hdr->update_vendor_code_size);
704 	printf("FMP_CAPSULE_IMAGE_HDR.UPDATE_HARDWARE_INSTANCE\t: %08" PRIX64 "\n",
705 	       image_hdr->update_hardware_instance);
706 	printf("FMP_CAPSULE_IMAGE_HDR.IMAGE_CAPSULE_SUPPORT\t: %08" PRIX64 "\n",
707 	       image_hdr->image_capsule_support);
708 
709 	printf("--------\n");
710 	if (image_hdr->image_capsule_support & CAPSULE_SUPPORT_AUTHENTICATION) {
711 		capsule_auth_hdr = (char *)image_hdr + sizeof(*image_hdr);
712 		dump_capsule_auth_header(capsule_auth_hdr);
713 
714 		auth_hdr = capsule_auth_hdr;
715 		signature_size = sizeof(auth_hdr->monotonic_count) +
716 			auth_hdr->auth_info.hdr.dwLength;
717 		fmp_payload_hdr = (char *)capsule_auth_hdr + signature_size;
718 	} else {
719 		printf("Capsule Authentication Not Enabled\n");
720 		fmp_payload_hdr = (char *)image_hdr + sizeof(*image_hdr);
721 	}
722 
723 	fmp_payload_hdr_size = dump_fmp_payload_header(fmp_payload_hdr);
724 
725 	payload_size = image_hdr->update_image_size - signature_size -
726 		fmp_payload_hdr_size;
727 	printf("--------\n");
728 	printf("Payload Image Size\t\t\t\t: %08X\n", payload_size);
729 }
730 
dump_fmp_header(struct efi_firmware_management_capsule_header * fmp_hdr)731 static void dump_fmp_header(
732 	struct efi_firmware_management_capsule_header *fmp_hdr)
733 {
734 	int i;
735 	void *capsule_image_hdr;
736 
737 	printf("EFI_FMP_HDR.VERSION\t\t\t\t: %08X\n", fmp_hdr->version);
738 	printf("EFI_FMP_HDR.EMBEDDED_DRIVER_COUNT\t\t: %08X\n",
739 	       fmp_hdr->embedded_driver_count);
740 	printf("EFI_FMP_HDR.PAYLOAD_ITEM_COUNT\t\t\t: %08X\n",
741 	       fmp_hdr->payload_item_count);
742 
743 	/*
744 	 * We currently don't support Embedded Drivers.
745 	 * Only worry about the payload items.
746 	 */
747 	for (i = 0; i < fmp_hdr->payload_item_count; i++) {
748 		capsule_image_hdr = (char *)fmp_hdr +
749 			fmp_hdr->item_offset_list[i];
750 		dump_fmp_capsule_image_header(capsule_image_hdr);
751 	}
752 }
753 
dump_capsule_header(struct efi_capsule_header * capsule_hdr)754 static void dump_capsule_header(struct efi_capsule_header *capsule_hdr)
755 {
756 	printf("EFI_CAPSULE_HDR.CAPSULE_GUID\t\t\t: ");
757 	print_guid((void *)&capsule_hdr->capsule_guid);
758 	printf("EFI_CAPSULE_HDR.HEADER_SIZE\t\t\t: %08X\n",
759 	       capsule_hdr->header_size);
760 	printf("EFI_CAPSULE_HDR.FLAGS\t\t\t\t: %08X\n", capsule_hdr->flags);
761 	printf("EFI_CAPSULE_HDR.CAPSULE_IMAGE_SIZE\t\t: %08X\n",
762 	       capsule_hdr->capsule_image_size);
763 }
764 
normal_capsule_dump(void * capsule_buf)765 static void normal_capsule_dump(void *capsule_buf)
766 {
767 	void *fmp_hdr;
768 	struct efi_capsule_header *hdr = capsule_buf;
769 
770 	dump_capsule_header(hdr);
771 	printf("--------\n");
772 
773 	fmp_hdr = (char *)capsule_buf + sizeof(*hdr);
774 	dump_fmp_header(fmp_hdr);
775 }
776 
empty_capsule_dump(void * capsule_buf)777 static void empty_capsule_dump(void *capsule_buf)
778 {
779 	efi_guid_t *accept_image_guid;
780 	struct efi_capsule_header *hdr = capsule_buf;
781 	efi_guid_t efi_empty_accept_capsule = FW_ACCEPT_OS_GUID;
782 
783 	dump_capsule_header(hdr);
784 
785 	if (!memcmp(&efi_empty_accept_capsule, &hdr->capsule_guid,
786 		    sizeof(efi_guid_t))) {
787 		accept_image_guid = (void *)(char *)capsule_buf +
788 			sizeof(struct efi_capsule_header);
789 		printf("--------\n");
790 		printf("ACCEPT_IMAGE_GUID\t\t\t\t: ");
791 		print_guid(accept_image_guid);
792 	}
793 }
794 
dump_capsule_contents(char * capsule_file)795 static void dump_capsule_contents(char *capsule_file)
796 {
797 	int fd;
798 	char *ptr;
799 	efi_guid_t efi_fmp_guid = EFI_FIRMWARE_MANAGEMENT_CAPSULE_ID_GUID;
800 	efi_guid_t efi_empty_accept_capsule = FW_ACCEPT_OS_GUID;
801 	efi_guid_t efi_empty_revert_capsule = FW_REVERT_OS_GUID;
802 	struct stat sbuf;
803 
804 	if (!capsule_file) {
805 		fprintf(stderr, "No capsule file provided\n");
806 		exit(EXIT_FAILURE);
807 	}
808 
809 	if ((fd = open(capsule_file, O_RDONLY)) < 0) {
810 		fprintf(stderr, "Error opening capsule file: %s\n",
811 			capsule_file);
812 		exit(EXIT_FAILURE);
813 	}
814 
815 	if (fstat(fd, &sbuf) < 0) {
816 		fprintf(stderr, "Can't stat capsule file: %s\n", capsule_file);
817 		exit(EXIT_FAILURE);
818 	}
819 
820 	if ((ptr = mmap(0, sbuf.st_size, PROT_READ, MAP_SHARED, fd, 0))
821 	    == MAP_FAILED) {
822 		fprintf(stderr, "Can't mmap capsule file: %s\n", capsule_file);
823 		exit(EXIT_FAILURE);
824 	}
825 
826 	if (!memcmp(&efi_fmp_guid, ptr, sizeof(efi_guid_t))) {
827 		normal_capsule_dump(ptr);
828 	} else if (!memcmp(&efi_empty_accept_capsule, ptr,
829 		   sizeof(efi_guid_t)) ||
830 		   !memcmp(&efi_empty_revert_capsule, ptr,
831 			   sizeof(efi_guid_t))) {
832 		empty_capsule_dump(ptr);
833 	} else {
834 		fprintf(stderr, "Unable to decode the capsule file: %s\n",
835 			capsule_file);
836 		exit(EXIT_FAILURE);
837 	}
838 }
839 
load_dtb(const char * path)840 static struct fdt_header *load_dtb(const char *path)
841 {
842 	struct fdt_header *dtb;
843 	ssize_t dtb_size;
844 	FILE *f;
845 
846 	/* Open and parse DTB */
847 	f = fopen(path, "r");
848 	if (!f) {
849 		fprintf(stderr, "Cannot open %s\n", path);
850 		return NULL;
851 	}
852 
853 	if (fseek(f, 0, SEEK_END)) {
854 		fprintf(stderr, "Cannot seek to the end of %s: %s\n",
855 			path, strerror(errno));
856 		return NULL;
857 	}
858 
859 	dtb_size = ftell(f);
860 	if (dtb_size < 0) {
861 		fprintf(stderr, "Cannot ftell %s: %s\n",
862 			path, strerror(errno));
863 		return NULL;
864 	}
865 
866 	fseek(f, 0, SEEK_SET);
867 
868 	dtb = malloc(dtb_size);
869 	if (!dtb) {
870 		fprintf(stderr, "Can't allocated %zd\n", dtb_size);
871 		return NULL;
872 	}
873 
874 	if (fread(dtb, dtb_size, 1, f) != 1) {
875 		fprintf(stderr, "Can't read %zd bytes from %s\n",
876 			dtb_size, path);
877 		free(dtb);
878 		return NULL;
879 	}
880 
881 	fclose(f);
882 
883 	return dtb;
884 }
885 
886 #define MAX_IMAGE_NAME_LEN 128
genguid(int argc,char ** argv)887 static int genguid(int argc, char **argv)
888 {
889 	int idx = 2, ret;
890 	unsigned char namespace[16];
891 	struct efi_guid image_type_id;
892 	const char *dtb_path;
893 	struct fdt_header *dtb;
894 	const char *compatible;
895 	int compatlen, namelen;
896 	uint16_t fw_image[MAX_IMAGE_NAME_LEN];
897 
898 	if (argc < 2) {
899 		fprintf(stderr, "Usage: ");
900 		print_usage_guidgen();
901 		return -1;
902 	}
903 
904 	if (uuid_str_to_bin(argv[1], namespace, UUID_STR_FORMAT_GUID)) {
905 		uuid_str_to_bin(DEFAULT_NAMESPACE_GUID, namespace, UUID_STR_FORMAT_GUID);
906 		dtb_path = argv[1];
907 	} else {
908 		dtb_path = argv[2];
909 		idx = 3;
910 	}
911 
912 	if (idx == argc) {
913 		fprintf(stderr, "Usage: ");
914 		print_usage_guidgen();
915 		return -1;
916 	}
917 
918 	dtb = load_dtb(dtb_path);
919 	if (!dtb)
920 		return -1;
921 
922 	ret = fdt_check_header(dtb);
923 	if (ret) {
924 		fprintf(stderr, "Invalid DTB header: %d\n", ret);
925 		return -1;
926 	}
927 
928 	compatible = fdt_getprop(dtb, 0, "compatible", &compatlen);
929 	if (!compatible) {
930 		fprintf(stderr, "No compatible string found in DTB\n");
931 		return -1;
932 	}
933 	if (strnlen(compatible, compatlen) >= compatlen) {
934 		fprintf(stderr, "Compatible string not null-terminated\n");
935 		return -1;
936 	}
937 
938 	printf("Generating GUIDs for %s with namespace %s:\n",
939 	       compatible, DEFAULT_NAMESPACE_GUID);
940 	for (; idx < argc; idx++) {
941 		memset(fw_image, 0, sizeof(fw_image));
942 		namelen = strlen(argv[idx]);
943 		if (namelen > MAX_IMAGE_NAME_LEN) {
944 			fprintf(stderr, "Image name too long: %s\n", argv[idx]);
945 			return -1;
946 		}
947 
948 		for (int i = 0; i < namelen; i++)
949 			fw_image[i] = (uint16_t)argv[idx][i];
950 
951 		gen_v5_guid((struct uuid *)&namespace, &image_type_id,
952 			    compatible, strlen(compatible),
953 			    fw_image, namelen * sizeof(uint16_t),
954 			    NULL);
955 
956 		printf("%s: ", argv[idx]);
957 		print_guid(&image_type_id);
958 	}
959 
960 	return 0;
961 }
962 
963 /**
964  * main - main entry function of mkeficapsule
965  * @argc:	Number of arguments
966  * @argv:	Array of pointers to arguments
967  *
968  * Create an uefi capsule file, optionally signing it.
969  * Parse all the arguments and pass them on to create_fwbin().
970  *
971  * Return:
972  * * 0  - on success
973  * * -1 - on failure
974  */
main(int argc,char ** argv)975 int main(int argc, char **argv)
976 {
977 	efi_guid_t *guid;
978 	unsigned char uuid_buf[16];
979 	unsigned long index, instance;
980 	uint64_t mcount;
981 	unsigned long oemflags;
982 	bool capsule_dump;
983 	char *privkey_file, *cert_file;
984 	int c, idx;
985 	struct fmp_payload_header_params fmp_ph_params = { 0 };
986 
987 	/* Generate dynamic GUIDs */
988 	if (argc > 1 && !strcmp(argv[1], "guidgen")) {
989 		if (genguid(argc - 1, argv + 1))
990 			exit(EXIT_FAILURE);
991 		exit(EXIT_SUCCESS);
992 	}
993 
994 	guid = NULL;
995 	index = 0;
996 	instance = 0;
997 	mcount = 0;
998 	privkey_file = NULL;
999 	cert_file = NULL;
1000 	capsule_dump = false;
1001 	dump_sig = 0;
1002 	capsule_type = CAPSULE_NORMAL_BLOB;
1003 	oemflags = 0;
1004 	for (;;) {
1005 		c = getopt_long(argc, argv, opts_short, options, &idx);
1006 		if (c == -1)
1007 			break;
1008 
1009 		switch (c) {
1010 		case 'g':
1011 			if (guid) {
1012 				fprintf(stderr,
1013 					"Image type already specified\n");
1014 				exit(EXIT_FAILURE);
1015 			}
1016 			if (uuid_str_to_bin(optarg, uuid_buf, UUID_STR_FORMAT_GUID)) {
1017 				fprintf(stderr, "Wrong guid format\n");
1018 				exit(EXIT_FAILURE);
1019 			}
1020 			guid = (efi_guid_t *)uuid_buf;
1021 			break;
1022 		case 'i':
1023 			index = strtoul(optarg, NULL, 0);
1024 			break;
1025 		case 'I':
1026 			instance = strtoul(optarg, NULL, 0);
1027 			break;
1028 		case 'v':
1029 			fmp_ph_params.fw_version = strtoul(optarg, NULL, 0);
1030 			fmp_ph_params.have_header = true;
1031 			break;
1032 		case 'p':
1033 			if (privkey_file) {
1034 				fprintf(stderr,
1035 					"Private Key already specified\n");
1036 				exit(EXIT_FAILURE);
1037 			}
1038 			privkey_file = optarg;
1039 			break;
1040 		case 'c':
1041 			if (cert_file) {
1042 				fprintf(stderr,
1043 					"Certificate file already specified\n");
1044 				exit(EXIT_FAILURE);
1045 			}
1046 			cert_file = optarg;
1047 			break;
1048 		case 'm':
1049 			mcount = strtoul(optarg, NULL, 0);
1050 			break;
1051 		case 'd':
1052 			dump_sig = 1;
1053 			break;
1054 		case 'A':
1055 			if (capsule_type) {
1056 				fprintf(stderr,
1057 					"Select either of Accept or Revert capsule generation\n");
1058 				exit(1);
1059 			}
1060 			capsule_type = CAPSULE_ACCEPT;
1061 			break;
1062 		case 'R':
1063 			if (capsule_type) {
1064 				fprintf(stderr,
1065 					"Select either of Accept or Revert capsule generation\n");
1066 				exit(1);
1067 			}
1068 			capsule_type = CAPSULE_REVERT;
1069 			break;
1070 		case 'o':
1071 			oemflags = strtoul(optarg, NULL, 0);
1072 			if (oemflags > 0xffff) {
1073 				fprintf(stderr,
1074 					"oemflags must be between 0x0 and 0xffff\n");
1075 				exit(1);
1076 			}
1077 			break;
1078 		case 'D':
1079 			capsule_dump = true;
1080 			break;
1081 		case 'V':
1082 			printf("mkeficapsule version %s\n", PLAIN_VERSION);
1083 			exit(EXIT_SUCCESS);
1084 		default:
1085 			print_usage_mkeficapsule();
1086 			exit(EXIT_FAILURE);
1087 		}
1088 	}
1089 
1090 	if (capsule_dump) {
1091 		if (argc != optind + 1) {
1092 			fprintf(stderr, "Must provide the capsule file to parse\n");
1093 			exit(EXIT_FAILURE);
1094 		}
1095 		dump_capsule_contents(argv[argc - 1]);
1096 		exit(EXIT_SUCCESS);
1097 	}
1098 
1099 	/* check necessary parameters */
1100 	if ((capsule_type == CAPSULE_NORMAL_BLOB &&
1101 	    ((argc != optind + 2) || !guid ||
1102 	     ((privkey_file && !cert_file) ||
1103 	      (!privkey_file && cert_file)))) ||
1104 	    (capsule_type != CAPSULE_NORMAL_BLOB &&
1105 	    ((argc != optind + 1) ||
1106 	     ((capsule_type == CAPSULE_ACCEPT) && !guid) ||
1107 	     ((capsule_type == CAPSULE_REVERT) && guid)))) {
1108 		print_usage_mkeficapsule();
1109 		exit(EXIT_FAILURE);
1110 	}
1111 
1112 	if (capsule_type != CAPSULE_NORMAL_BLOB) {
1113 		if (create_empty_capsule(argv[argc - 1], guid,
1114 					 capsule_type == CAPSULE_ACCEPT) < 0) {
1115 			fprintf(stderr, "Creating empty capsule failed\n");
1116 			exit(EXIT_FAILURE);
1117 		}
1118 	} else 	if (create_fwbin(argv[argc - 1], argv[argc - 2], guid,
1119 				 index, instance, &fmp_ph_params, mcount, privkey_file,
1120 				 cert_file, (uint16_t)oemflags) < 0) {
1121 		fprintf(stderr, "Creating firmware capsule failed\n");
1122 		exit(EXIT_FAILURE);
1123 	}
1124 
1125 	exit(EXIT_SUCCESS);
1126 }
1127