vboot_kernel.c revision 3f4d8d05ba4e32990c8584bd47cdf082d4604232
1/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2 * Use of this source code is governed by a BSD-style license that can be
3 * found in the LICENSE file.
4 *
5 * Functions for loading a kernel from disk.
6 * (Firmware portion)
7 */
8
9#include "sysincludes.h"
10
11#include "cgptlib.h"
12#include "cgptlib_internal.h"
13#include "region.h"
14#include "gbb_access.h"
15#include "gbb_header.h"
16#include "gpt_misc.h"
17#include "load_kernel_fw.h"
18#include "utility.h"
19#include "vboot_api.h"
20#include "vboot_common.h"
21#include "vboot_kernel.h"
22
23#define KBUF_SIZE 65536  /* Bytes to read at start of kernel partition */
24#define LOWEST_TPM_VERSION 0xffffffff
25
26typedef enum BootMode {
27	kBootRecovery = 0,  /* Recovery firmware, any dev switch position */
28	kBootNormal = 1,    /* Normal boot - kernel must be verified */
29	kBootDev = 2        /* Developer boot - self-signed kernel ok */
30} BootMode;
31
32VbError_t LoadKernel(LoadKernelParams *params, VbCommonParams *cparams)
33{
34	VbSharedDataHeader *shared =
35		(VbSharedDataHeader *)params->shared_data_blob;
36	VbSharedDataKernelCall *shcall = NULL;
37	VbNvContext* vnc = params->nv_context;
38	VbPublicKey* kernel_subkey = NULL;
39	int free_kernel_subkey = 0;
40	GptData gpt;
41	uint64_t part_start, part_size;
42	uint64_t blba;
43	uint64_t kbuf_sectors;
44	uint8_t* kbuf = NULL;
45	int found_partitions = 0;
46	int good_partition = -1;
47	int good_partition_key_block_valid = 0;
48	uint32_t lowest_version = LOWEST_TPM_VERSION;
49	int rec_switch, dev_switch;
50	BootMode boot_mode;
51	uint32_t require_official_os = 0;
52	uint32_t body_toread;
53	uint8_t *body_readptr;
54
55	VbError_t retval = VBERROR_UNKNOWN;
56	int recovery = VBNV_RECOVERY_LK_UNSPECIFIED;
57
58	/* Sanity Checks */
59	if (!params->bytes_per_lba ||
60	    !params->streaming_lba_count) {
61		VBDEBUG(("LoadKernel() called with invalid params\n"));
62		retval = VBERROR_INVALID_PARAMETER;
63		goto LoadKernelExit;
64	}
65
66	/* Clear output params in case we fail */
67	params->partition_number = 0;
68	params->bootloader_address = 0;
69	params->bootloader_size = 0;
70
71	/* Calculate switch positions and boot mode */
72	rec_switch = (BOOT_FLAG_RECOVERY & params->boot_flags ? 1 : 0);
73	dev_switch = (BOOT_FLAG_DEVELOPER & params->boot_flags ? 1 : 0);
74	if (rec_switch) {
75		boot_mode = kBootRecovery;
76	} else if (dev_switch) {
77		boot_mode = kBootDev;
78		VbNvGet(vnc, VBNV_DEV_BOOT_SIGNED_ONLY, &require_official_os);
79	} else {
80		boot_mode = kBootNormal;
81	}
82
83	/*
84	 * Set up tracking for this call.  This wraps around if called many
85	 * times, so we need to initialize the call entry each time.
86	 */
87	shcall = shared->lk_calls + (shared->lk_call_count
88				     & (VBSD_MAX_KERNEL_CALLS - 1));
89	Memset(shcall, 0, sizeof(VbSharedDataKernelCall));
90	shcall->boot_flags = (uint32_t)params->boot_flags;
91	shcall->boot_mode = boot_mode;
92	shcall->sector_size = (uint32_t)params->bytes_per_lba;
93	shcall->sector_count = params->streaming_lba_count;
94	shared->lk_call_count++;
95
96	/* Initialization */
97	blba = params->bytes_per_lba;
98	kbuf_sectors = KBUF_SIZE / blba;
99	if (0 == kbuf_sectors) {
100		VBDEBUG(("LoadKernel() called with sector size > KBUF_SIZE\n"));
101		retval = VBERROR_INVALID_PARAMETER;
102		goto LoadKernelExit;
103	}
104
105	if (kBootRecovery == boot_mode) {
106		/* Use the recovery key to verify the kernel */
107		retval = VbGbbReadRecoveryKey(cparams, &kernel_subkey);
108		if (VBERROR_SUCCESS != retval)
109			goto LoadKernelExit;
110		free_kernel_subkey = 1;
111	} else {
112		/* Use the kernel subkey passed from LoadFirmware(). */
113		kernel_subkey = &shared->kernel_subkey;
114	}
115
116	/* Read GPT data */
117	gpt.sector_bytes = (uint32_t)blba;
118	gpt.streaming_drive_sectors = params->streaming_lba_count;
119	gpt.gpt_drive_sectors = params->gpt_lba_count;
120	gpt.flags = params->boot_flags & BOOT_FLAG_EXTERNAL_GPT
121			? GPT_FLAG_EXTERNAL : 0;
122	if (0 != AllocAndReadGptData(params->disk_handle, &gpt)) {
123		VBDEBUG(("Unable to read GPT data\n"));
124		shcall->check_result = VBSD_LKC_CHECK_GPT_READ_ERROR;
125		goto bad_gpt;
126	}
127
128	/* Initialize GPT library */
129	if (GPT_SUCCESS != GptInit(&gpt)) {
130		VBDEBUG(("Error parsing GPT\n"));
131		shcall->check_result = VBSD_LKC_CHECK_GPT_PARSE_ERROR;
132		goto bad_gpt;
133	}
134
135	/* Allocate kernel header buffers */
136	kbuf = (uint8_t*)VbExMalloc(KBUF_SIZE);
137	if (!kbuf)
138		goto bad_gpt;
139
140        /* Loop over candidate kernel partitions */
141        while (GPT_SUCCESS ==
142	       GptNextKernelEntry(&gpt, &part_start, &part_size)) {
143		VbSharedDataKernelPart *shpart = NULL;
144		VbKeyBlockHeader *key_block;
145		VbKernelPreambleHeader *preamble;
146		RSAPublicKey *data_key = NULL;
147		VbExStream_t stream = NULL;
148		uint64_t key_version;
149		uint32_t combined_version;
150		uint64_t body_offset;
151		int key_block_valid = 1;
152
153		VBDEBUG(("Found kernel entry at %" PRIu64 " size %" PRIu64 "\n",
154			 part_start, part_size));
155
156		/*
157		 * Set up tracking for this partition.  This wraps around if
158		 * called many times, so initialize the partition entry each
159		 * time.
160		 */
161		shpart = shcall->parts + (shcall->kernel_parts_found
162					  & (VBSD_MAX_KERNEL_PARTS - 1));
163		Memset(shpart, 0, sizeof(VbSharedDataKernelPart));
164		shpart->sector_start = part_start;
165		shpart->sector_count = part_size;
166		/*
167		 * TODO: GPT partitions start at 1, but cgptlib starts them at
168		 * 0.  Adjust here, until cgptlib is fixed.
169		 */
170		shpart->gpt_index = (uint8_t)(gpt.current_kernel + 1);
171		shcall->kernel_parts_found++;
172
173		/* Found at least one kernel partition. */
174		found_partitions++;
175
176		/* Set up the stream */
177		if (VbExStreamOpen(params->disk_handle,
178				   part_start, part_size, &stream)) {
179			VBDEBUG(("Partition error getting stream.\n"));
180			shpart->check_result = VBSD_LKP_CHECK_TOO_SMALL;
181			goto bad_kernel;
182		}
183
184		if (0 != VbExStreamRead(stream, KBUF_SIZE, kbuf)) {
185			VBDEBUG(("Unable to read start of partition.\n"));
186			shpart->check_result = VBSD_LKP_CHECK_READ_START;
187			goto bad_kernel;
188		}
189
190		/* Verify the key block. */
191		key_block = (VbKeyBlockHeader*)kbuf;
192		if (0 != KeyBlockVerify(key_block, KBUF_SIZE,
193					kernel_subkey, 0)) {
194			VBDEBUG(("Verifying key block signature failed.\n"));
195			shpart->check_result = VBSD_LKP_CHECK_KEY_BLOCK_SIG;
196			key_block_valid = 0;
197
198			/* If not in developer mode, this kernel is bad. */
199			if (kBootDev != boot_mode)
200				goto bad_kernel;
201
202			/*
203			 * In developer mode, we can explictly disallow
204			 * self-signed kernels
205			 */
206			if (require_official_os) {
207				VBDEBUG(("Self-signed kernels not enabled.\n"));
208				shpart->check_result =
209					VBSD_LKP_CHECK_SELF_SIGNED;
210				goto bad_kernel;
211			}
212
213			/*
214			 * Allow the kernel if the SHA-512 hash of the key
215			 * block is valid.
216			 */
217			if (0 != KeyBlockVerify(key_block, KBUF_SIZE,
218						kernel_subkey, 1)) {
219				VBDEBUG(("Verifying key block hash failed.\n"));
220				shpart->check_result =
221					VBSD_LKP_CHECK_KEY_BLOCK_HASH;
222				goto bad_kernel;
223			}
224		}
225
226		/* Check the key block flags against the current boot mode. */
227		if (!(key_block->key_block_flags &
228		      (dev_switch ? KEY_BLOCK_FLAG_DEVELOPER_1 :
229		       KEY_BLOCK_FLAG_DEVELOPER_0))) {
230			VBDEBUG(("Key block developer flag mismatch.\n"));
231			shpart->check_result = VBSD_LKP_CHECK_DEV_MISMATCH;
232			key_block_valid = 0;
233		}
234		if (!(key_block->key_block_flags &
235		      (rec_switch ? KEY_BLOCK_FLAG_RECOVERY_1 :
236		       KEY_BLOCK_FLAG_RECOVERY_0))) {
237			VBDEBUG(("Key block recovery flag mismatch.\n"));
238			shpart->check_result = VBSD_LKP_CHECK_REC_MISMATCH;
239			key_block_valid = 0;
240		}
241
242		/* Check for rollback of key version except in recovery mode. */
243		key_version = key_block->data_key.key_version;
244		if (kBootRecovery != boot_mode) {
245			if (key_version < (shared->kernel_version_tpm >> 16)) {
246				VBDEBUG(("Key version too old.\n"));
247				shpart->check_result =
248					VBSD_LKP_CHECK_KEY_ROLLBACK;
249				key_block_valid = 0;
250			}
251			if (key_version > 0xFFFF) {
252				/*
253				 * Key version is stored in 16 bits in the TPM,
254				 * so key versions greater than 0xFFFF can't be
255				 * stored properly.
256				 */
257				VBDEBUG(("Key version > 0xFFFF.\n"));
258				shpart->check_result =
259					VBSD_LKP_CHECK_KEY_ROLLBACK;
260				key_block_valid = 0;
261			}
262		}
263
264		/* If not in developer mode, key block required to be valid. */
265		if (kBootDev != boot_mode && !key_block_valid) {
266			VBDEBUG(("Key block is invalid.\n"));
267			goto bad_kernel;
268		}
269
270		/* Get key for preamble/data verification from the key block. */
271		data_key = PublicKeyToRSA(&key_block->data_key);
272		if (!data_key) {
273			VBDEBUG(("Data key bad.\n"));
274			shpart->check_result = VBSD_LKP_CHECK_DATA_KEY_PARSE;
275			goto bad_kernel;
276		}
277
278		/* Verify the preamble, which follows the key block */
279		preamble = (VbKernelPreambleHeader *)
280			(kbuf + key_block->key_block_size);
281		if ((0 != VerifyKernelPreamble(
282					preamble,
283					KBUF_SIZE - key_block->key_block_size,
284					data_key))) {
285			VBDEBUG(("Preamble verification failed.\n"));
286			shpart->check_result = VBSD_LKP_CHECK_VERIFY_PREAMBLE;
287			goto bad_kernel;
288		}
289
290		/*
291		 * If the key block is valid and we're not in recovery mode,
292		 * check for rollback of the kernel version.
293		 */
294		combined_version = (uint32_t)(
295				(key_version << 16) |
296				(preamble->kernel_version & 0xFFFF));
297		shpart->combined_version = combined_version;
298		if (key_block_valid && kBootRecovery != boot_mode) {
299			if (combined_version < shared->kernel_version_tpm) {
300				VBDEBUG(("Kernel version too low.\n"));
301				shpart->check_result =
302					VBSD_LKP_CHECK_KERNEL_ROLLBACK;
303				/*
304				 * If not in developer mode, kernel version
305				 * must be valid.
306				 */
307				if (kBootDev != boot_mode)
308					goto bad_kernel;
309			}
310		}
311
312		VBDEBUG(("Kernel preamble is good.\n"));
313		shpart->check_result = VBSD_LKP_CHECK_PREAMBLE_VALID;
314
315		/* Check for lowest version from a valid header. */
316		if (key_block_valid && lowest_version > combined_version)
317			lowest_version = combined_version;
318		else {
319			VBDEBUG(("Key block valid: %d\n", key_block_valid));
320			VBDEBUG(("Combined version: %u\n",
321				 (unsigned) combined_version));
322		}
323
324		/*
325		 * If we already have a good kernel, no need to read another
326		 * one; we only needed to look at the versions to check for
327		 * rollback.  So skip to the next kernel preamble.
328		 */
329		if (-1 != good_partition) {
330			VbExStreamClose(stream);
331			stream = NULL;
332			continue;
333		}
334
335		body_offset = key_block->key_block_size +
336			preamble->preamble_size;
337
338		/*
339		 * Make sure the kernel starts at or before what we already
340		 * read into kbuf.
341		 *
342		 * We could deal with a larger offset by reading and discarding
343		 * the data in between the vblock and the kernel data.
344		 */
345		if (body_offset > KBUF_SIZE) {
346			shpart->check_result = VBSD_LKP_CHECK_BODY_OFFSET;
347			VBDEBUG(("Kernel body offset is %d > 64KB.\n",
348				 (int)body_offset));
349			goto bad_kernel;
350		}
351
352		if (!params->kernel_buffer) {
353			/* Get kernel load address and size from the header. */
354			params->kernel_buffer =
355				(void *)((long)preamble->body_load_address);
356			params->kernel_buffer_size =
357				preamble->body_signature.data_size;
358		} else if (preamble->body_signature.data_size >
359			   params->kernel_buffer_size) {
360			VBDEBUG(("Kernel body doesn't fit in memory.\n"));
361			shpart->check_result = VBSD_LKP_CHECK_BODY_EXCEEDS_MEM;
362			goto bad_kernel;
363		}
364
365		/*
366		 * Body signature data size is 64 bit and toread is 32 bit so
367		 * this could technically cause us to read less data.  That's
368		 * fine, because a 4 GB kernel is implausible, and if we did
369		 * have one that big, we'd simply read too little data and fail
370		 * to verify it.
371		 */
372		body_toread = preamble->body_signature.data_size;
373		body_readptr = params->kernel_buffer;
374
375		/*
376		 * If we've already read part of the kernel, copy that to the
377		 * beginning of the kernel buffer.
378		 */
379		if (body_offset < KBUF_SIZE) {
380			uint32_t body_copied = KBUF_SIZE - body_offset;
381
382			/* If the kernel is tiny, don't over-copy */
383			if (body_copied > body_toread)
384				body_copied = body_toread;
385
386			Memcpy(body_readptr, kbuf + body_offset, body_copied);
387			body_toread -= body_copied;
388			body_readptr += body_copied;
389		}
390
391		/* Read the kernel data */
392		if (body_toread &&
393		    0 != VbExStreamRead(stream, body_toread, body_readptr)) {
394			VBDEBUG(("Unable to read kernel data.\n"));
395			shpart->check_result = VBSD_LKP_CHECK_READ_DATA;
396			goto bad_kernel;
397		}
398
399		/* Close the stream; we're done with it */
400		VbExStreamClose(stream);
401		stream = NULL;
402
403		/* Verify kernel data */
404		if (0 != VerifyData((const uint8_t *)params->kernel_buffer,
405				    params->kernel_buffer_size,
406				    &preamble->body_signature, data_key)) {
407			VBDEBUG(("Kernel data verification failed.\n"));
408			shpart->check_result = VBSD_LKP_CHECK_VERIFY_DATA;
409			goto bad_kernel;
410		}
411
412		/* Done with the kernel signing key, so can free it now */
413		RSAPublicKeyFree(data_key);
414		data_key = NULL;
415
416		/*
417		 * If we're still here, the kernel is valid.  Save the first
418		 * good partition we find; that's the one we'll boot.
419		 */
420		VBDEBUG(("Partition is good.\n"));
421		shpart->check_result = VBSD_LKP_CHECK_KERNEL_GOOD;
422		if (key_block_valid)
423			shpart->flags |= VBSD_LKP_FLAG_KEY_BLOCK_VALID;
424
425		good_partition_key_block_valid = key_block_valid;
426		/*
427		 * TODO: GPT partitions start at 1, but cgptlib starts them at
428		 * 0.  Adjust here, until cgptlib is fixed.
429		 */
430		good_partition = gpt.current_kernel + 1;
431		params->partition_number = gpt.current_kernel + 1;
432		GetCurrentKernelUniqueGuid(&gpt, &params->partition_guid);
433		/*
434		 * TODO: GetCurrentKernelUniqueGuid() should take a destination
435		 * size, or the dest should be a struct, so we know it's big
436		 * enough.
437		 */
438		params->bootloader_address = preamble->bootloader_address;
439		params->bootloader_size = preamble->bootloader_size;
440
441		/* Update GPT to note this is the kernel we're trying */
442		GptUpdateKernelEntry(&gpt, GPT_UPDATE_ENTRY_TRY);
443
444		/*
445		 * If we're in recovery mode or we're about to boot a
446		 * dev-signed kernel, there's no rollback protection, so we can
447		 * stop at the first valid kernel.
448		 */
449		if (kBootRecovery == boot_mode || !key_block_valid) {
450			VBDEBUG(("In recovery mode or dev-signed kernel\n"));
451			break;
452		}
453
454		/*
455		 * Otherwise, we do care about the key index in the TPM.  If
456		 * the good partition's key version is the same as the tpm,
457		 * then the TPM doesn't need updating; we can stop now.
458		 * Otherwise, we'll check all the other headers to see if they
459		 * contain a newer key.
460		 */
461		if (combined_version == shared->kernel_version_tpm) {
462			VBDEBUG(("Same kernel version\n"));
463			break;
464		}
465
466		/* Continue, so that we skip the error handling code below */
467		continue;
468
469	bad_kernel:
470		/* Handle errors parsing this kernel */
471		if (NULL != stream)
472			VbExStreamClose(stream);
473		if (NULL != data_key)
474			RSAPublicKeyFree(data_key);
475
476		VBDEBUG(("Marking kernel as invalid.\n"));
477		GptUpdateKernelEntry(&gpt, GPT_UPDATE_ENTRY_BAD);
478
479
480        } /* while(GptNextKernelEntry) */
481
482 bad_gpt:
483
484	/* Free kernel buffer */
485	if (kbuf)
486		VbExFree(kbuf);
487
488	/* Write and free GPT data */
489	WriteAndFreeGptData(params->disk_handle, &gpt);
490
491	/* Handle finding a good partition */
492	if (good_partition >= 0) {
493		VBDEBUG(("Good_partition >= 0\n"));
494		shcall->check_result = VBSD_LKC_CHECK_GOOD_PARTITION;
495		shared->kernel_version_lowest = lowest_version;
496		/*
497		 * Sanity check - only store a new TPM version if we found one.
498		 * If lowest_version is still at its initial value, we didn't
499		 * find one; for example, we're in developer mode and just
500		 * didn't look.
501		 */
502		if (lowest_version != LOWEST_TPM_VERSION &&
503		    lowest_version > shared->kernel_version_tpm)
504			shared->kernel_version_tpm = lowest_version;
505
506		/* Success! */
507		retval = VBERROR_SUCCESS;
508	} else if (found_partitions > 0) {
509		shcall->check_result = VBSD_LKC_CHECK_INVALID_PARTITIONS;
510		recovery = VBNV_RECOVERY_RW_INVALID_OS;
511		retval = VBERROR_INVALID_KERNEL_FOUND;
512	} else {
513		shcall->check_result = VBSD_LKC_CHECK_NO_PARTITIONS;
514		recovery = VBNV_RECOVERY_RW_NO_OS;
515		retval = VBERROR_NO_KERNEL_FOUND;
516	}
517
518 LoadKernelExit:
519
520	/* Store recovery request, if any */
521	VbNvSet(vnc, VBNV_RECOVERY_REQUEST, VBERROR_SUCCESS != retval ?
522		recovery : VBNV_RECOVERY_NOT_REQUESTED);
523
524	/*
525	 * If LoadKernel() was called with bad parameters, shcall may not be
526	 * initialized.
527	 */
528	if (shcall)
529		shcall->return_code = (uint8_t)retval;
530
531	/* Save whether the good partition's key block was fully verified */
532	if (good_partition_key_block_valid)
533		shared->flags |= VBSD_KERNEL_KEY_VERIFIED;
534
535	/* Store how much shared data we used, if any */
536	params->shared_data_size = shared->data_used;
537
538	if (free_kernel_subkey)
539		VbExFree(kernel_subkey);
540
541	return retval;
542}
543