xref: /aosp_15_r20/external/vboot_reference/futility/vb1_helper.c (revision 8617a60d3594060b7ecbd21bc622a7c14f3cf2bc)
1 /* Copyright 2014 The ChromiumOS Authors
2  * Use of this source code is governed by a BSD-style license that can be
3  * found in the LICENSE file.
4  */
5 
6 #include <errno.h>
7 #include <inttypes.h>		/* For PRIu64 */
8 #include <stdio.h>
9 #include <string.h>
10 #include <unistd.h>
11 #include <openssl/rsa.h>
12 
13 #include "2api.h"
14 #include "2common.h"
15 #include "2rsa.h"
16 #include "2sha.h"
17 #include "2sysincludes.h"
18 #include "file_type.h"
19 #include "futility.h"
20 #include "host_common.h"
21 #include "kernel_blob.h"
22 #include "util_misc.h"
23 #include "vb1_helper.h"
24 
25 /****************************************************************************/
26 /* Here are globals containing all the bits & pieces I'm working on.
27  *
28  * kernel vblock    = keyblock + kernel preamble + padding to 64K (or whatever)
29  * kernel blob      = 32-bit kernel + config file + params + bootloader stub +
30  *                    vmlinuz_header
31  * kernel partition = kernel vblock + kernel blob
32  *
33  * The vb2_kernel_preamble.preamble_size includes the padding.
34  */
35 
36 /* The keyblock, preamble, and kernel blob are kept in separate places. */
37 static struct vb2_keyblock *g_keyblock;
38 static struct vb2_kernel_preamble *g_preamble;
39 static uint8_t *g_kernel_blob_data;
40 static uint32_t g_kernel_blob_size;
41 
42 /* These refer to individual parts within the kernel blob. */
43 static uint8_t *g_kernel_data;
44 static uint32_t g_kernel_size;
45 static uint8_t *g_config_data;
46 static uint32_t g_config_size;
47 static uint8_t *g_param_data;
48 static uint32_t g_param_size;
49 static uint8_t *g_bootloader_data;
50 static uint32_t g_bootloader_size;
51 static uint8_t *g_vmlinuz_header_data;
52 static uint32_t g_vmlinuz_header_size;
53 
54 static uint64_t g_ondisk_bootloader_addr;
55 static uint64_t g_ondisk_vmlinuz_header_addr;
56 
57 
58 /*
59  * Read the kernel command line from a file. Get rid of \n characters along
60  * the way and verify that the line fits into a 4K buffer.
61  *
62  * Return the buffer contaning the line on success (and set the line length
63  * using the passed in parameter), or NULL in case something goes wrong.
64  */
ReadConfigFile(const char * config_file,uint32_t * config_size)65 uint8_t *ReadConfigFile(const char *config_file, uint32_t *config_size)
66 {
67 	uint8_t *config_buf;
68 	int i;
69 
70 	if (VB2_SUCCESS != vb2_read_file(config_file, &config_buf, config_size))
71 		return NULL;
72 	VB2_DEBUG(" config file size=%#x\n", *config_size);
73 	if (CROS_CONFIG_SIZE <= *config_size) {	/* room for trailing '\0' */
74 		fprintf(stderr, "Config file %s is too large (>= %d bytes)\n",
75 			config_file, CROS_CONFIG_SIZE);
76 		free(config_buf);
77 		return NULL;
78 	}
79 
80 	/* Replace newlines with spaces */
81 	for (i = 0; i < *config_size; i++)
82 		if ('\n' == config_buf[i])
83 			config_buf[i] = ' ';
84 
85 	/* Trim trailing spaces */
86 	while (*config_size > 0 && config_buf[*config_size - 1] == ' ')
87 		(*config_size)--;
88 
89 	return config_buf;
90 }
91 
92 /****************************************************************************/
93 
94 /* Return the smallest integral multiple of [alignment] that is equal
95  * to or greater than [val]. Used to determine the number of
96  * pages/sectors/blocks/whatever needed to contain [val]
97  * items/bytes/etc. */
roundup(uint32_t val,uint32_t alignment)98 static uint32_t roundup(uint32_t val, uint32_t alignment)
99 {
100 	uint32_t rem = val % alignment;
101 	if (rem)
102 		return val + (alignment - rem);
103 	return val;
104 }
105 
106 /* Match regexp /\b--\b/ to delimit the start of the kernel commandline. If we
107  * don't find one, we'll use the whole thing. */
find_cmdline_start(uint8_t * buf_ptr,unsigned int max_len)108 static unsigned int find_cmdline_start(uint8_t *buf_ptr, unsigned int max_len)
109 {
110 	char *input = (char *)buf_ptr;
111 	int start = 0;
112 	int i;
113 	for (i = 0; i < max_len - 1 && input[i]; i++) {
114 		if ('-' == input[i] && '-' == input[i + 1]) {
115 			if ((i == 0 || ' ' == input[i - 1]) &&
116 			    (i + 2 >= max_len || ' ' == input[i + 2])) {
117 				/* found "--" with nothing before or after it */
118 				start = i + 2;	/* hope for a trailing '\0' */
119 				break;
120 			}
121 		}
122 	}
123 	while (' ' == input[start])	/* skip leading spaces */
124 		start++;
125 
126 	return start;
127 }
128 
129 /* Offset of kernel command line string from the start of the kernel blob */
kernel_cmd_line_offset(const struct vb2_kernel_preamble * preamble)130 uint64_t kernel_cmd_line_offset(const struct vb2_kernel_preamble *preamble)
131 {
132 	return preamble->bootloader_address - preamble->body_load_address -
133 	    CROS_CONFIG_SIZE - CROS_PARAMS_SIZE;
134 }
135 
136 /* Returns whether the kernel CONFIG_EFI_STUB enabled. */
KernelHasEfiBootStub(const uint8_t * kernel_buf,uint32_t kernel_size)137 static int KernelHasEfiBootStub(const uint8_t *kernel_buf,
138 				uint32_t kernel_size)
139 {
140 	if (kernel_size < 2)
141 		return 0;
142 
143 	/* If the stub is enabled then the kernel data will start with
144 	 * the COFF header, which begins with the magic bytes "MZ". */
145 	return kernel_buf[0] == 'M' && kernel_buf[1] == 'Z';
146 }
147 
148 /* Returns the size of the 32-bit kernel, or negative on error. */
KernelSize(uint8_t * kernel_buf,uint32_t kernel_size,enum arch_t arch)149 static int KernelSize(uint8_t *kernel_buf,
150 		      uint32_t kernel_size,
151 		      enum arch_t arch)
152 {
153 	uint32_t kernel32_start = 0;
154 	struct linux_kernel_params *lh;
155 
156 	/* Except for x86, the kernel is the kernel. */
157 	if (arch != ARCH_X86)
158 		return kernel_size;
159 
160 	/* The first part of the x86 vmlinuz is a header, followed by
161 	 * a real-mode boot stub. We only want the 32-bit part. */
162 	lh = (struct linux_kernel_params *)kernel_buf;
163 	if (lh->header != VMLINUZ_HEADER_SIG) {
164 		VB2_DEBUG("Not a linux kernel image\n");
165 		return kernel_size;
166 	}
167 	kernel32_start = (lh->setup_sects + 1) << 9;
168 	if (kernel32_start >= kernel_size) {
169 		fprintf(stderr, "Malformed kernel\n");
170 		return -1;
171 	}
172 	return kernel_size - kernel32_start;
173 }
174 
175 /* This extracts g_kernel_* and g_param_* from a standard vmlinuz file. */
PickApartVmlinuz(uint8_t * kernel_buf,uint32_t kernel_size,enum arch_t arch,uint64_t kernel_body_load_address)176 static void PickApartVmlinuz(uint8_t *kernel_buf,
177 			     uint32_t kernel_size,
178 			     enum arch_t arch,
179 			     uint64_t kernel_body_load_address)
180 {
181 	uint32_t kernel32_start = 0;
182 	uint32_t kernel32_size = kernel_size;
183 	struct linux_kernel_params *lh, *params;
184 
185 	/* Except for x86, the kernel is the kernel. */
186 	switch (arch) {
187 	case ARCH_X86:
188 		/* The first part of the x86 vmlinuz is a header, followed by
189 		 * a real-mode boot stub. We only want the 32-bit part. We
190 		 * already calculated this in KernelSize() earlier. */
191 		kernel32_size = g_kernel_size;
192 		kernel32_start = kernel_size - kernel32_size;
193 
194 		VB2_DEBUG(" kernel16_start=%#x\n", 0);
195 		VB2_DEBUG(" kernel16_size=%#x\n", kernel32_start);
196 
197 		/* Copy the original zeropage data from kernel_buf into
198 		 * g_param_data, then tweak a few fields for our purposes */
199 		lh = (struct linux_kernel_params *)kernel_buf;
200 		params = (struct linux_kernel_params *)(g_param_data);
201 		memcpy(&(params->setup_sects), &(lh->setup_sects),
202 		       offsetof(struct linux_kernel_params, e820_entries)
203 		       - offsetof(struct linux_kernel_params, setup_sects));
204 		params->boot_flag = 0;
205 		params->ramdisk_image = 0;	/* we don't support initrd */
206 		params->ramdisk_size = 0;
207 		params->type_of_loader = 0xff;
208 		/* We need to point to the kernel commandline arg. On disk, it
209 		 * will come right after the 32-bit part of the kernel. */
210 		params->cmd_line_ptr = kernel_body_load_address +
211 			roundup(kernel32_size, CROS_ALIGN) +
212 			find_cmdline_start(g_config_data, g_config_size);
213 		VB2_DEBUG(" cmdline_addr=%#x\n", params->cmd_line_ptr);
214 		VB2_DEBUG(" version=%#x\n", params->version);
215 		VB2_DEBUG(" kernel_alignment=%#x\n", params->kernel_alignment);
216 		VB2_DEBUG(" relocatable_kernel=%#x\n",
217 			  params->relocatable_kernel);
218 		/* Add a fake e820 memory map with 2 entries. */
219 		params->n_e820_entry = 2;
220 		params->e820_entries[0].start_addr = 0x00000000;
221 		params->e820_entries[0].segment_size = 0x00001000;
222 		params->e820_entries[0].segment_type = E820_TYPE_RAM;
223 		params->e820_entries[1].start_addr = 0xfffff000;
224 		params->e820_entries[1].segment_size = 0x00001000;
225 		params->e820_entries[1].segment_type = E820_TYPE_RESERVED;
226 		break;
227 	default:
228 		break;
229 	}
230 
231 	VB2_DEBUG(" kernel32_start=%#x\n", kernel32_start);
232 	VB2_DEBUG(" kernel32_size=%#x\n", kernel32_size);
233 
234 	/* Keep just the 32-bit kernel. */
235 	if (kernel32_size) {
236 		g_kernel_size = kernel32_size;
237 		memcpy(g_kernel_data, kernel_buf + kernel32_start,
238 		       g_kernel_size);
239 	}
240 }
241 
242 /* Split a kernel blob into separate g_kernel, g_param, g_config,
243  * g_bootloader, and g_vmlinuz_header parts. */
UnpackKernelBlob(uint8_t * kernel_blob_data)244 static void UnpackKernelBlob(uint8_t *kernel_blob_data)
245 {
246 	uint32_t now;
247 	uint32_t vmlinuz_header_size = 0;
248 	uint64_t vmlinuz_header_address = 0;
249 
250 	/* We have to work backwards from the end, because the preamble
251 	   only describes the bootloader and vmlinuz stubs. */
252 
253 	/* Vmlinuz Header is at the end */
254 	vb2_kernel_get_vmlinuz_header(g_preamble,
255 				      &vmlinuz_header_address,
256 				      &vmlinuz_header_size);
257 	if (vmlinuz_header_size) {
258 		now = vmlinuz_header_address - g_preamble->body_load_address;
259 		g_vmlinuz_header_size = vmlinuz_header_size;
260 		g_vmlinuz_header_data = kernel_blob_data + now;
261 
262 		VB2_DEBUG("vmlinuz_header_size     = %#x\n",
263 			  g_vmlinuz_header_size);
264 		VB2_DEBUG("vmlinuz_header_ofs      = %#x\n", now);
265 	}
266 
267 	/* Where does the bootloader stub begin? */
268 	now = g_preamble->bootloader_address - g_preamble->body_load_address;
269 
270 	/* Bootloader is at the end */
271 	g_bootloader_size = g_preamble->bootloader_size;
272 	g_bootloader_data = kernel_blob_data + now;
273 	/* TODO: What to do if this is beyond the end of the blob? */
274 
275 	VB2_DEBUG("bootloader_size     = %#x\n", g_bootloader_size);
276 	VB2_DEBUG("bootloader_ofs      = %#x\n", now);
277 
278 	/* Before that is the params */
279 	now -= CROS_PARAMS_SIZE;
280 	g_param_size = CROS_PARAMS_SIZE;
281 	g_param_data = kernel_blob_data + now;
282 	VB2_DEBUG("param_ofs           = %#x\n", now);
283 
284 	/* Before that is the config */
285 	now -= CROS_CONFIG_SIZE;
286 	g_config_size = CROS_CONFIG_SIZE;
287 	g_config_data = kernel_blob_data + now;
288 	VB2_DEBUG("config_ofs          = %#x\n", now);
289 
290 	/* The kernel starts at offset 0 and extends up to the config */
291 	g_kernel_data = kernel_blob_data;
292 	g_kernel_size = now;
293 	VB2_DEBUG("kernel_size         = %#x\n", g_kernel_size);
294 }
295 
296 
297 /* Replaces the config section of the specified kernel blob.
298  * Return nonzero on error. */
UpdateKernelBlobConfig(uint8_t * kblob_data,uint32_t kblob_size,uint8_t * config_data,uint32_t config_size)299 int UpdateKernelBlobConfig(uint8_t *kblob_data, uint32_t kblob_size,
300 			   uint8_t *config_data, uint32_t config_size)
301 {
302 	/* We should have already examined this blob. If not, we could do it
303 	 * again, but it's more likely due to an error. */
304 	if (kblob_data != g_kernel_blob_data ||
305 	    kblob_size != g_kernel_blob_size) {
306 		fprintf(stderr, "Trying to update some other blob\n");
307 		return -1;
308 	}
309 
310 	memset(g_config_data, 0, g_config_size);
311 	memcpy(g_config_data, config_data, config_size);
312 
313 	return 0;
314 }
315 
316 /* Split a kernel partition into separate vblock and blob parts. */
unpack_kernel_partition(uint8_t * kpart_data,uint32_t kpart_size,struct vb2_keyblock ** keyblock_ptr,struct vb2_kernel_preamble ** preamble_ptr,uint32_t * blob_size_ptr)317 uint8_t *unpack_kernel_partition(uint8_t *kpart_data,
318 				 uint32_t kpart_size,
319 				 struct vb2_keyblock **keyblock_ptr,
320 				 struct vb2_kernel_preamble **preamble_ptr,
321 				 uint32_t *blob_size_ptr)
322 {
323 	struct vb2_kernel_preamble *preamble;
324 	uint32_t vmlinuz_header_size = 0;
325 	uint64_t vmlinuz_header_address = 0;
326 	uint32_t now = 0;
327 
328 	/* Validity-check the keyblock */
329 	struct vb2_keyblock *keyblock = (struct vb2_keyblock *)kpart_data;
330 	VB2_DEBUG("Keyblock is %#x bytes\n", keyblock->keyblock_size);
331 	now += keyblock->keyblock_size;
332 	if (now > kpart_size) {
333 		fprintf(stderr,
334 			"keyblock_size advances past the end of the blob\n");
335 		return NULL;
336 	}
337 
338 	/* LGTM */
339 	g_keyblock = keyblock;
340 
341 	/* And the preamble */
342 	preamble = (struct vb2_kernel_preamble *)(kpart_data + now);
343 	VB2_DEBUG("Preamble is %#x bytes\n", preamble->preamble_size);
344 	now += preamble->preamble_size;
345 	if (now > kpart_size) {
346 		fprintf(stderr,
347 			"preamble_size advances past the end of the blob\n");
348 		return NULL;
349 	}
350 	/* LGTM */
351 	VB2_DEBUG(" kernel_version = %d\n", preamble->kernel_version);
352 	VB2_DEBUG(" bootloader_address = 0x%" PRIx64 "\n",
353 		  preamble->bootloader_address);
354 	VB2_DEBUG(" bootloader_size = %#x\n", preamble->bootloader_size);
355 	VB2_DEBUG(" kern_blob_size = %#x\n",
356 		  preamble->body_signature.data_size);
357 
358 	uint32_t flags = vb2_kernel_get_flags(preamble);
359 	VB2_DEBUG(" flags = %#x\n", flags);
360 
361 	g_preamble = preamble;
362 	g_ondisk_bootloader_addr = g_preamble->bootloader_address;
363 
364 	vb2_kernel_get_vmlinuz_header(preamble,
365 				      &vmlinuz_header_address,
366 				      &vmlinuz_header_size);
367 	if (vmlinuz_header_size) {
368 		VB2_DEBUG(" vmlinuz_header_address = 0x%" PRIx64 "\n",
369 			  vmlinuz_header_address);
370 		VB2_DEBUG(" vmlinuz_header_size = %#x\n", vmlinuz_header_size);
371 		g_ondisk_vmlinuz_header_addr = vmlinuz_header_address;
372 	}
373 
374 	VB2_DEBUG("kernel blob is at offset %#x\n", now);
375 	g_kernel_blob_data = kpart_data + now;
376 	g_kernel_blob_size = preamble->body_signature.data_size;
377 
378 	/* Validity check */
379 	if (kpart_size < now + g_kernel_blob_size) {
380 		fprintf(stderr,
381 			"kernel body size %u exceeds partition end\n",
382 			g_kernel_blob_size);
383 		return NULL;
384 	}
385 
386 	/* Update the blob pointers */
387 	UnpackKernelBlob(g_kernel_blob_data);
388 
389 	if (keyblock_ptr)
390 		*keyblock_ptr = keyblock;
391 	if (preamble_ptr)
392 		*preamble_ptr = preamble;
393 	if (blob_size_ptr)
394 		*blob_size_ptr = g_kernel_blob_size;
395 
396 	return g_kernel_blob_data;
397 }
398 
SignKernelBlob(uint8_t * kernel_blob,uint32_t kernel_size,uint32_t padding,int version,uint64_t kernel_body_load_address,struct vb2_keyblock * keyblock,struct vb2_private_key * signpriv_key,uint32_t flags,uint32_t * vblock_size_ptr)399 uint8_t *SignKernelBlob(uint8_t *kernel_blob,
400 			uint32_t kernel_size,
401 			uint32_t padding,
402 			int version,
403 			uint64_t kernel_body_load_address,
404 			struct vb2_keyblock *keyblock,
405 			struct vb2_private_key *signpriv_key,
406 			uint32_t flags,
407 			uint32_t *vblock_size_ptr)
408 {
409 	/* Make sure the preamble fills up the rest of the required padding */
410 	uint32_t min_size = padding > keyblock->keyblock_size
411 		? padding - keyblock->keyblock_size : 0;
412 
413 	/* Sign the kernel data */
414 	struct vb2_signature *body_sig = vb2_calculate_signature(kernel_blob,
415 								 kernel_size,
416 								 signpriv_key);
417 	if (!body_sig) {
418 		fprintf(stderr, "Error calculating body signature\n");
419 		return NULL;
420 	}
421 
422 	/* Create preamble */
423 	struct vb2_kernel_preamble *preamble =
424 		vb2_create_kernel_preamble(version,
425 					   kernel_body_load_address,
426 					   g_ondisk_bootloader_addr,
427 					   g_bootloader_size,
428 					   body_sig,
429 					   g_ondisk_vmlinuz_header_addr,
430 					   g_vmlinuz_header_size,
431 					   flags,
432 					   min_size,
433 					   signpriv_key);
434 	if (!preamble) {
435 		fprintf(stderr, "Error creating preamble.\n");
436 		return 0;
437 	}
438 
439 	uint32_t outsize = keyblock->keyblock_size + preamble->preamble_size;
440 	void *outbuf = calloc(outsize, 1);
441 	memcpy(outbuf, keyblock, keyblock->keyblock_size);
442 	memcpy(outbuf + keyblock->keyblock_size,
443 	       preamble, preamble->preamble_size);
444 
445 	if (vblock_size_ptr)
446 		*vblock_size_ptr = outsize;
447 	return outbuf;
448 }
449 
450 /* Returns zero on success */
WriteSomeParts(const char * outfile,void * part1_data,uint32_t part1_size,void * part2_data,uint32_t part2_size)451 int WriteSomeParts(const char *outfile,
452 		   void *part1_data, uint32_t part1_size,
453 		   void *part2_data, uint32_t part2_size)
454 {
455 	FILE *f;
456 
457 	/* Write the output file */
458 	VB2_DEBUG("writing %s with %#x, %#x\n",
459 		  outfile, part1_size, part2_size);
460 
461 	f = fopen(outfile, "wb");
462 	if (!f) {
463 		fprintf(stderr, "Can't open output file %s: %s\n",
464 			outfile, strerror(errno));
465 		return -1;
466 	}
467 
468 	if (part1_data && part1_size) {
469 		if (1 != fwrite(part1_data, part1_size, 1, f)) {
470 			fprintf(stderr, "Can't write output file %s: %s\n",
471 				outfile, strerror(errno));
472 			fclose(f);
473 			unlink(outfile);
474 			return -1;
475 		}
476 	}
477 
478 	if (part2_data && part2_size) {
479 		if (1 != fwrite(part2_data, part2_size, 1, f)) {
480 			fprintf(stderr, "Can't write output file %s: %s\n",
481 				outfile, strerror(errno));
482 			fclose(f);
483 			unlink(outfile);
484 			return -1;
485 		}
486 	}
487 
488 	fclose(f);
489 
490 	/* Success */
491 	return 0;
492 }
493 
494 /* Returns 0 on success */
VerifyKernelBlob(uint8_t * kernel_blob,uint32_t kernel_size,struct vb2_packed_key * signpub_key,const char * keyblock_outfile,uint32_t min_version)495 int VerifyKernelBlob(uint8_t *kernel_blob,
496 		     uint32_t kernel_size,
497 		     struct vb2_packed_key *signpub_key,
498 		     const char *keyblock_outfile,
499 		     uint32_t min_version)
500 {
501 	int rv = -1;
502 	uint32_t vmlinuz_header_size = 0;
503 	uint64_t vmlinuz_header_address = 0;
504 
505 	uint8_t workbuf[VB2_KERNEL_WORKBUF_RECOMMENDED_SIZE]
506 		__attribute__((aligned(VB2_WORKBUF_ALIGN)));
507 	struct vb2_workbuf wb;
508 	vb2_workbuf_init(&wb, workbuf, sizeof(workbuf));
509 
510 	if (signpub_key) {
511 		struct vb2_public_key pubkey;
512 		if (VB2_SUCCESS != vb2_unpack_key(&pubkey, signpub_key)) {
513 			fprintf(stderr, "Error unpacking signing key.\n");
514 			goto done;
515 		}
516 		if (VB2_SUCCESS !=
517 		    vb2_verify_keyblock(g_keyblock, g_keyblock->keyblock_size,
518 					&pubkey, &wb)) {
519 			fprintf(stderr, "Error verifying keyblock.\n");
520 			goto done;
521 		}
522 	} else if (VB2_SUCCESS !=
523 		   vb2_verify_keyblock_hash(g_keyblock,
524 					    g_keyblock->keyblock_size,
525 					    &wb)) {
526 		fprintf(stderr, "Error verifying keyblock.\n");
527 		goto done;
528 	}
529 
530 	printf("Keyblock:\n");
531 	struct vb2_packed_key *data_key = &g_keyblock->data_key;
532 	printf("  Signature:           %s\n",
533 	       signpub_key ? "valid" : "ignored");
534 	printf("  Size:                %#x\n", g_keyblock->keyblock_size);
535 	printf("  Flags:               %u ", g_keyblock->keyblock_flags);
536 	if (g_keyblock->keyblock_flags & VB2_KEYBLOCK_FLAG_DEVELOPER_0)
537 		printf(" !DEV");
538 	if (g_keyblock->keyblock_flags & VB2_KEYBLOCK_FLAG_DEVELOPER_1)
539 		printf(" DEV");
540 	if (g_keyblock->keyblock_flags & VB2_KEYBLOCK_FLAG_RECOVERY_0)
541 		printf(" !REC");
542 	if (g_keyblock->keyblock_flags & VB2_KEYBLOCK_FLAG_RECOVERY_1)
543 		printf(" REC");
544 	if (g_keyblock->keyblock_flags & VB2_KEYBLOCK_FLAG_MINIOS_0)
545 		printf(" !MINIOS");
546 	if (g_keyblock->keyblock_flags & VB2_KEYBLOCK_FLAG_MINIOS_1)
547 		printf(" MINIOS");
548 	printf("\n");
549 	printf("  Data key algorithm:  %u %s\n", data_key->algorithm,
550 	       vb2_get_crypto_algorithm_name(data_key->algorithm));
551 	printf("  Data key version:    %u\n", data_key->key_version);
552 	printf("  Data key sha1sum:    %s\n",
553 	       packed_key_sha1_string(data_key));
554 
555 	if (keyblock_outfile) {
556 		FILE *f = NULL;
557 		f = fopen(keyblock_outfile, "wb");
558 		if (!f)  {
559 			fprintf(stderr, "Can't open keyblock file %s: %s\n",
560 				keyblock_outfile, strerror(errno));
561 			goto done;
562 		}
563 		if (1 != fwrite(g_keyblock, g_keyblock->keyblock_size, 1, f)) {
564 			fprintf(stderr, "Can't write keyblock file %s: %s\n",
565 				keyblock_outfile, strerror(errno));
566 			fclose(f);
567 			goto done;
568 		}
569 		fclose(f);
570 	}
571 
572 	if (data_key->key_version < (min_version >> 16)) {
573 		fprintf(stderr, "Data key version %u < minimum %u.\n",
574 			data_key->key_version, (min_version >> 16));
575 		goto done;
576 	}
577 
578 	struct vb2_public_key pubkey;
579 	if (VB2_SUCCESS != vb2_unpack_key(&pubkey, data_key)) {
580 		fprintf(stderr, "Error parsing data key.\n");
581 		goto done;
582 	}
583 
584 	/* Verify preamble */
585 	if (VB2_SUCCESS != vb2_verify_kernel_preamble(
586 			(struct vb2_kernel_preamble *)g_preamble,
587 			g_preamble->preamble_size, &pubkey, &wb)) {
588 		fprintf(stderr, "Error verifying preamble.\n");
589 		goto done;
590 	}
591 
592 	printf("Preamble:\n");
593 	printf("  Size:                %#x\n", g_preamble->preamble_size);
594 	printf("  Header version:      %u.%u\n",
595 	       g_preamble->header_version_major,
596 	       g_preamble->header_version_minor);
597 	printf("  Kernel version:      %u\n", g_preamble->kernel_version);
598 	printf("  Body load address:   0x%" PRIx64 "\n",
599 	       g_preamble->body_load_address);
600 	printf("  Body size:           %#x\n",
601 	       g_preamble->body_signature.data_size);
602 	printf("  Bootloader address:  0x%" PRIx64 "\n",
603 	       g_preamble->bootloader_address);
604 	printf("  Bootloader size:     %#x\n", g_preamble->bootloader_size);
605 
606 	vb2_kernel_get_vmlinuz_header(g_preamble,
607 				      &vmlinuz_header_address,
608 				      &vmlinuz_header_size);
609 	if (vmlinuz_header_size) {
610 		printf("  Vmlinuz header address: 0x%" PRIx64 "\n",
611 		       vmlinuz_header_address);
612 		printf("  Vmlinuz header size:    %#x\n",
613 		       (uint32_t)vmlinuz_header_size);
614 	}
615 
616 	printf("  Flags          :       %#x\n",
617 	       vb2_kernel_get_flags(g_preamble));
618 
619 	if (g_preamble->kernel_version < (min_version & 0xFFFF)) {
620 		fprintf(stderr,
621 			"Kernel version %u is lower than minimum %u.\n",
622 			g_preamble->kernel_version, (min_version & 0xFFFF));
623 		goto done;
624 	}
625 
626 	/* Verify body */
627 	if (VB2_SUCCESS !=
628 	    vb2_verify_data(kernel_blob, kernel_size,
629 			    &g_preamble->body_signature,
630 			    &pubkey, &wb)) {
631 		fprintf(stderr, "Error verifying kernel body.\n");
632 		goto done;
633 	}
634 	printf("Body verification succeeded.\n");
635 
636 	printf("Config:\n%s\n",
637 	       kernel_blob + kernel_cmd_line_offset(g_preamble));
638 
639 	rv = 0;
640 done:
641 	return rv;
642 }
643 
644 
CreateKernelBlob(uint8_t * vmlinuz_buf,uint32_t vmlinuz_size,enum arch_t arch,uint64_t kernel_body_load_address,uint8_t * config_data,uint32_t config_size,uint8_t * bootloader_data,uint32_t bootloader_size,uint32_t * blob_size_ptr)645 uint8_t *CreateKernelBlob(uint8_t *vmlinuz_buf, uint32_t vmlinuz_size,
646 			  enum arch_t arch, uint64_t kernel_body_load_address,
647 			  uint8_t *config_data, uint32_t config_size,
648 			  uint8_t *bootloader_data, uint32_t bootloader_size,
649 			  uint32_t *blob_size_ptr)
650 {
651 	uint32_t now = 0;
652 	int tmp;
653 
654 	/* We have all the parts. How much room do we need? */
655 	tmp = KernelSize(vmlinuz_buf, vmlinuz_size, arch);
656 	if (tmp < 0)
657 		return NULL;
658 
659 	/* If we have an EFI stub, move it into the bootloader section. */
660 	if (KernelHasEfiBootStub(vmlinuz_buf, vmlinuz_size)) {
661 		if (bootloader_size) {
662 			WARN("Ignoring kernel's EFI boot stub because a bootloader file was provided.\n");
663 		} else {
664 			bootloader_data = vmlinuz_buf;
665 			bootloader_size = vmlinuz_size - tmp;
666 		}
667 	}
668 
669 	g_kernel_size = tmp;
670 	g_config_size = CROS_CONFIG_SIZE;
671 	g_param_size = CROS_PARAMS_SIZE;
672 	g_bootloader_size = roundup(bootloader_size, CROS_ALIGN);
673 	g_vmlinuz_header_size = vmlinuz_size-g_kernel_size;
674 	g_kernel_blob_size =
675 		roundup(g_kernel_size, CROS_ALIGN) +
676 		g_config_size                      +
677 		g_param_size                       +
678 		g_bootloader_size                  +
679 		g_vmlinuz_header_size;
680 
681 	/*
682 	 * Round the whole blob up so it's a multiple of sectors, even on 4k
683 	 * devices.
684 	 */
685 	g_kernel_blob_size = roundup(g_kernel_blob_size, CROS_ALIGN);
686 	VB2_DEBUG("g_kernel_blob_size  %#x\n", g_kernel_blob_size);
687 
688 	/* Allocate space for the blob. */
689 	g_kernel_blob_data = malloc(g_kernel_blob_size);
690 	memset(g_kernel_blob_data, 0, g_kernel_blob_size);
691 
692 	/* Assign the sub-pointers */
693 	g_kernel_data = g_kernel_blob_data + now;
694 	VB2_DEBUG("g_kernel_size       %#x ofs %#x\n",
695 		  g_kernel_size, now);
696 	now += roundup(g_kernel_size, CROS_ALIGN);
697 
698 	g_config_data = g_kernel_blob_data + now;
699 	VB2_DEBUG("g_config_size       %#x ofs %#x\n",
700 		  g_config_size, now);
701 	now += g_config_size;
702 
703 	g_param_data = g_kernel_blob_data + now;
704 	VB2_DEBUG("g_param_size        %#x ofs %#x\n",
705 		  g_param_size, now);
706 	now += g_param_size;
707 
708 	g_bootloader_data = g_kernel_blob_data + now;
709 	VB2_DEBUG("g_bootloader_size   %#x ofs %#x\n",
710 		  g_bootloader_size, now);
711 	g_ondisk_bootloader_addr = kernel_body_load_address + now;
712 	VB2_DEBUG("g_ondisk_bootloader_addr   0x%" PRIx64 "\n",
713 		  g_ondisk_bootloader_addr);
714 	now += g_bootloader_size;
715 
716 	if (g_vmlinuz_header_size) {
717 		g_vmlinuz_header_data = g_kernel_blob_data + now;
718 		VB2_DEBUG("g_vmlinuz_header_size %#x ofs %#x\n",
719 			  g_vmlinuz_header_size, now);
720 		g_ondisk_vmlinuz_header_addr = kernel_body_load_address + now;
721 		VB2_DEBUG("g_ondisk_vmlinuz_header_addr   0x%" PRIx64 "\n",
722 			  g_ondisk_vmlinuz_header_addr);
723 	}
724 
725 	VB2_DEBUG("end of kern_blob at kern_blob+%#x\n", now);
726 
727 	/* Copy the kernel and params bits into the correct places */
728 	PickApartVmlinuz(vmlinuz_buf, vmlinuz_size, arch,
729 			 kernel_body_load_address);
730 
731 	/* Copy the other bits too */
732 	memcpy(g_config_data, config_data, config_size);
733 	memcpy(g_bootloader_data, bootloader_data, bootloader_size);
734 	memset(g_bootloader_data + bootloader_size, 0,
735 	       g_bootloader_size - bootloader_size);
736 	if (g_vmlinuz_header_size) {
737 		memcpy(g_vmlinuz_header_data,
738 		       vmlinuz_buf,
739 		       g_vmlinuz_header_size);
740 	}
741 
742 	if (blob_size_ptr)
743 		*blob_size_ptr = g_kernel_blob_size;
744 	return g_kernel_blob_data;
745 }
746 
ft_recognize_vblock1(uint8_t * buf,uint32_t len)747 enum futil_file_type ft_recognize_vblock1(uint8_t *buf, uint32_t len)
748 {
749 	uint8_t workbuf[VB2_KERNEL_WORKBUF_RECOMMENDED_SIZE]
750 		__attribute__((aligned(VB2_WORKBUF_ALIGN)));
751 	struct vb2_workbuf wb;
752 	vb2_workbuf_init(&wb, workbuf, sizeof(workbuf));
753 
754 	/* Vboot 2.0 signature checks destroy the buffer, so make a copy */
755 	uint8_t *buf2 = malloc(len);
756 	memcpy(buf2, buf, len);
757 	struct vb2_keyblock *keyblock = (struct vb2_keyblock *)buf2;
758 	if (VB2_SUCCESS != vb2_verify_keyblock_hash(keyblock, len, &wb)) {
759 		free(buf2);
760 		return FILE_TYPE_UNKNOWN;
761 	}
762 
763 	/* Try unpacking the data key from the keyblock */
764 	struct vb2_public_key data_key;
765 	if (VB2_SUCCESS !=
766 	    vb2_unpack_key(&data_key, &keyblock->data_key)) {
767 		/* It looks like a bad keyblock, but still a keyblock */
768 		free(buf2);
769 		return FILE_TYPE_KEYBLOCK;
770 	}
771 
772 	uint32_t more = keyblock->keyblock_size;
773 
774 	/* Followed by firmware preamble too? */
775 	struct vb2_fw_preamble *pre2 = (struct vb2_fw_preamble *)(buf2 + more);
776 	if (VB2_SUCCESS ==
777 	    vb2_verify_fw_preamble(pre2, len - more, &data_key, &wb)) {
778 		free(buf2);
779 		return FILE_TYPE_FW_PREAMBLE;
780 	}
781 
782 	/* Recopy since firmware preamble check destroyed the buffer */
783 	memcpy(buf2, buf, len);
784 
785 	/* Or maybe kernel preamble? */
786 	struct vb2_kernel_preamble *kern_preamble =
787 		(struct vb2_kernel_preamble *)(buf2 + more);
788 	if (VB2_SUCCESS ==
789 	    vb2_verify_kernel_preamble(kern_preamble, len - more,
790 				       &data_key, &wb)) {
791 		free(buf2);
792 		return FILE_TYPE_KERN_PREAMBLE;
793 	}
794 
795 	free(buf2);
796 
797 	/* No, just keyblock */
798 	return FILE_TYPE_KEYBLOCK;
799 }
800 
ft_recognize_vb1_key(uint8_t * buf,uint32_t len)801 enum futil_file_type ft_recognize_vb1_key(uint8_t *buf, uint32_t len)
802 {
803 	/* Maybe just a packed public key? */
804 	const struct vb2_packed_key *pubkey = (struct vb2_packed_key *)buf;
805 	if (vb2_packed_key_looks_ok(pubkey, len) == VB2_SUCCESS)
806 		return FILE_TYPE_PUBKEY;
807 
808 	/* How about a private key? */
809 	if (len < sizeof(uint64_t))
810 		return FILE_TYPE_UNKNOWN;
811 	const unsigned char *start = buf + sizeof(uint64_t);
812 	struct rsa_st *rsa =
813 		d2i_RSAPrivateKey(NULL, &start, len - sizeof(uint64_t));
814 	if (rsa) {
815 		RSA_free(rsa);
816 		return FILE_TYPE_PRIVKEY;
817 	}
818 
819 	return FILE_TYPE_UNKNOWN;
820 }
821