vboot2: api-level routines

I'm breaking the last chunk of vboot2 into smaller pieces as I add
tests.  This has the api-level routines actually called by depthcharge.

BUG=chromium:370082
BRANCH=none
TEST=make clean && VBOOT2=1 COV=1 make

Change-Id: Ic7c082fc5faa0b874b2fa5a15ebda7135dcafe0b
Signed-off-by: Randall Spangler <rspangler@chromium.org>
Reviewed-on: https://chromium-review.googlesource.com/200151
Reviewed-by: Bill Richardson <wfrichar@chromium.org>
diff --git a/Makefile b/Makefile
index 326ba47..2acdb98 100644
--- a/Makefile
+++ b/Makefile
@@ -279,6 +279,7 @@
 
 # Firmware library source needed for smaller library 2
 FWLIB2_SRCS = \
+	firmware/2lib/2api.c \
 	firmware/2lib/2common.c \
 	firmware/2lib/2crc8.c \
 	firmware/2lib/2misc.c \
@@ -466,6 +467,12 @@
 	utility/pad_digest_utility \
 	utility/signature_digest_utility \
 	utility/verify_data
+
+ifneq (${VBOOT2},)
+UTIL_NAMES += \
+	utility/vb2_verify_fw
+endif
+
 endif
 
 UTIL_BINS_STATIC := $(addprefix ${BUILD}/,${UTIL_NAMES_STATIC})
@@ -571,6 +578,7 @@
 
 ifneq (${VBOOT2},)
 TEST_NAMES += \
+	tests/vb2_api_tests \
 	tests/vb2_common_tests \
 	tests/vb2_common2_tests \
 	tests/vb2_common3_tests \
@@ -1103,6 +1111,7 @@
 
 .PHONY: run2tests
 run2tests: test_setup
+	${RUNTEST} ${BUILD_RUN}/tests/vb2_api_tests
 	${RUNTEST} ${BUILD_RUN}/tests/vb2_common_tests
 	${RUNTEST} ${BUILD_RUN}/tests/vb2_common2_tests ${TEST_KEYS}
 	${RUNTEST} ${BUILD_RUN}/tests/vb2_common3_tests ${TEST_KEYS}
diff --git a/firmware/2lib/2api.c b/firmware/2lib/2api.c
new file mode 100644
index 0000000..0138669
--- /dev/null
+++ b/firmware/2lib/2api.c
@@ -0,0 +1,295 @@
+/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ *
+ * Externally-callable APIs
+ * (Firmware portion)
+ */
+
+#include "2sysincludes.h"
+#include "2api.h"
+#include "2common.h"
+#include "2misc.h"
+#include "2nvstorage.h"
+#include "2secdata.h"
+#include "2sha.h"
+#include "2rsa.h"
+
+int vb2api_secdata_check(const struct vb2_context *ctx)
+{
+	return vb2_secdata_check_crc(ctx);
+}
+
+int vb2api_secdata_create(struct vb2_context *ctx)
+{
+	return vb2_secdata_create(ctx);
+}
+
+void vb2api_fail(struct vb2_context *ctx, uint8_t reason, uint8_t subcode)
+{
+	/* Initialize the vboot context if it hasn't been yet */
+	vb2_init_context(ctx);
+
+	vb2_fail(ctx, reason, subcode);
+}
+
+int vb2api_fw_phase1(struct vb2_context *ctx)
+{
+	struct vb2_shared_data *sd = vb2_get_sd(ctx);
+	int rv;
+
+	/* Initialize the vboot context if it hasn't been yet */
+	vb2_init_context(ctx);
+
+	/* Initialize NV context */
+	vb2_nv_init(ctx);
+
+	/* Initialize secure data */
+	rv = vb2_secdata_init(ctx);
+	if (rv)
+		sd->recovery_reason = VB2_RECOVERY_SECDATA_INIT;
+
+	/*
+	 * Check for recovery.  Note that this function returns void, since
+	 * any errors result in requesting recovery.
+	 */
+	vb2_check_recovery(ctx);
+
+	/* Return error if recovery is needed */
+	if (ctx->flags & VB2_CONTEXT_RECOVERY_MODE) {
+		/* Always clear RAM when entering recovery mode */
+		ctx->flags |= VB2_CONTEXT_CLEAR_RAM;
+
+		return VB2_ERROR_API_PHASE1_RECOVERY;
+	}
+
+	return VB2_SUCCESS;
+}
+
+int vb2api_fw_phase2(struct vb2_context *ctx)
+{
+	int rv;
+
+	/* Load and parse the GBB header */
+	rv = vb2_fw_parse_gbb(ctx);
+	if (rv) {
+		vb2_fail(ctx, VB2_RECOVERY_GBB_HEADER, rv);
+		return rv;
+	}
+
+	/* Check for dev switch */
+	rv = vb2_check_dev_switch(ctx);
+	if (rv) {
+		vb2_fail(ctx, VB2_RECOVERY_DEV_SWITCH, rv);
+		return rv;
+	}
+
+	/* Always clear RAM when entering developer mode */
+	if (ctx->flags & VB2_CONTEXT_DEVELOPER_MODE)
+		ctx->flags |= VB2_CONTEXT_CLEAR_RAM;
+
+	/* Check for explicit request to clear TPM */
+	rv = vb2_check_tpm_clear(ctx);
+	if (rv) {
+		vb2_fail(ctx, VB2_RECOVERY_TPM_CLEAR_OWNER, rv);
+		return rv;
+	}
+
+	/* Decide which firmware slot to try this boot */
+	rv = vb2_select_fw_slot(ctx);
+	if (rv) {
+		vb2_fail(ctx, VB2_RECOVERY_FW_SLOT, rv);
+		return rv;
+	}
+
+	return VB2_SUCCESS;
+}
+
+int vb2api_fw_phase3(struct vb2_context *ctx)
+{
+	int rv;
+
+	/* Verify firmware keyblock */
+	rv = vb2_verify_fw_keyblock(ctx);
+	if (rv) {
+		vb2_fail(ctx, VB2_RECOVERY_RO_INVALID_RW, rv);
+		return rv;
+	}
+
+	/* Verify firmware preamble */
+	rv = vb2_verify_fw_preamble2(ctx);
+	if (rv) {
+		vb2_fail(ctx, VB2_RECOVERY_RO_INVALID_RW, rv);
+		return rv;
+	}
+
+	return VB2_SUCCESS;
+}
+
+int vb2api_init_hash(struct vb2_context *ctx, uint32_t tag, uint32_t *size)
+{
+	struct vb2_shared_data *sd = vb2_get_sd(ctx);
+	const struct vb2_fw_preamble *pre;
+	struct vb2_digest_context *dc;
+	struct vb2_public_key key;
+	struct vb2_workbuf wb;
+	int rv;
+
+	vb2_workbuf_from_ctx(ctx, &wb);
+
+	if (tag == VB2_HASH_TAG_INVALID)
+		return VB2_ERROR_API_INIT_HASH_TAG;
+
+	/* Get preamble pointer */
+	if (!sd->workbuf_preamble_size)
+		return VB2_ERROR_API_INIT_HASH_PREAMBLE;
+	pre = (const struct vb2_fw_preamble *)
+		(ctx->workbuf + sd->workbuf_preamble_offset);
+
+	/* For now, we only support the firmware body tag */
+	if (tag != VB2_HASH_TAG_FW_BODY)
+		return VB2_ERROR_API_INIT_HASH_TAG;
+
+	/* Allocate workbuf space for the hash */
+	if (sd->workbuf_hash_size) {
+		dc = (struct vb2_digest_context *)
+			(ctx->workbuf + sd->workbuf_hash_offset);
+	} else {
+		uint32_t dig_size = sizeof(*dc);
+
+		dc = vb2_workbuf_alloc(&wb, dig_size);
+		if (!dc)
+			return VB2_ERROR_API_INIT_HASH_WORKBUF;
+
+		sd->workbuf_hash_offset = vb2_offset_of(ctx->workbuf, dc);
+		sd->workbuf_hash_size = dig_size;
+		ctx->workbuf_used = sd->workbuf_hash_offset + dig_size;
+	}
+
+	/*
+	 * Unpack the firmware data key to see which hashing algorithm we
+	 * should use.
+	 *
+	 * TODO: really, the firmware body should be hashed, and not signed,
+	 * because the signature we're checking is already signed as part of
+	 * the firmware preamble.  But until we can change the signing scripts,
+	 * we're stuck with a signature here instead of a hash.
+	 */
+	if (!sd->workbuf_data_key_size)
+		return VB2_ERROR_API_INIT_HASH_DATA_KEY;
+
+	rv = vb2_unpack_key(&key,
+			    ctx->workbuf + sd->workbuf_data_key_offset,
+			    sd->workbuf_data_key_size);
+	if (rv)
+		return rv;
+
+	sd->hash_tag = tag;
+	sd->hash_remaining_size = pre->body_signature.data_size;
+
+	if (size)
+		*size = pre->body_signature.data_size;
+
+	return vb2_digest_init(dc, key.algorithm);
+}
+
+int vb2api_extend_hash(struct vb2_context *ctx,
+		       const void *buf,
+		       uint32_t size)
+{
+	struct vb2_shared_data *sd = vb2_get_sd(ctx);
+	struct vb2_digest_context *dc = (struct vb2_digest_context *)
+		(ctx->workbuf + sd->workbuf_hash_offset);
+
+	/* Must have initialized hash digest work area */
+	if (!sd->workbuf_hash_size)
+		return VB2_ERROR_API_EXTEND_HASH_WORKBUF;
+
+	/* Don't extend past the data we expect to hash */
+	if (!size || size > sd->hash_remaining_size)
+		return VB2_ERROR_API_EXTEND_HASH_SIZE;
+
+	sd->hash_remaining_size -= size;
+
+	return vb2_digest_extend(dc, buf, size);
+}
+
+int vb2api_check_hash(struct vb2_context *ctx)
+{
+	struct vb2_shared_data *sd = vb2_get_sd(ctx);
+	struct vb2_digest_context *dc = (struct vb2_digest_context *)
+		(ctx->workbuf + sd->workbuf_hash_offset);
+	struct vb2_workbuf wb;
+
+	uint8_t *digest;
+	uint32_t digest_size = vb2_digest_size(dc->algorithm);
+
+	struct vb2_fw_preamble *pre;
+	struct vb2_public_key key;
+	int rv;
+
+	vb2_workbuf_from_ctx(ctx, &wb);
+
+	/* Get preamble pointer */
+	if (!sd->workbuf_preamble_size)
+		return VB2_ERROR_API_CHECK_HASH_PREAMBLE;
+	pre = (struct vb2_fw_preamble *)
+		(ctx->workbuf + sd->workbuf_preamble_offset);
+
+	/* Must have initialized hash digest work area */
+	if (!sd->workbuf_hash_size)
+		return VB2_ERROR_API_CHECK_HASH_WORKBUF;
+
+	/* Should have hashed the right amount of data */
+	if (sd->hash_remaining_size)
+		return VB2_ERROR_API_CHECK_HASH_SIZE;
+
+	/* Allocate the digest */
+	digest = vb2_workbuf_alloc(&wb, digest_size);
+	if (!digest)
+		return VB2_ERROR_API_CHECK_HASH_WORKBUF_DIGEST;
+
+	/* Finalize the digest */
+	rv = vb2_digest_finalize(dc, digest, digest_size);
+	if (rv)
+		return rv;
+
+	/* The code below is specific to the body signature */
+	if (sd->hash_tag != VB2_HASH_TAG_FW_BODY)
+		return VB2_ERROR_API_CHECK_HASH_TAG;
+
+	/*
+	 * The body signature is currently a *signature* of the body data, not
+	 * just its hash.  So we need to verify the signature.
+	 */
+
+	/* Unpack the data key */
+	if (!sd->workbuf_data_key_size)
+		return VB2_ERROR_API_CHECK_HASH_DATA_KEY;
+
+	rv = vb2_unpack_key(&key,
+			    ctx->workbuf + sd->workbuf_data_key_offset,
+			    sd->workbuf_data_key_size);
+	if (rv)
+		return rv;
+
+	/* Make sure body signature is the right size */
+	if (pre->body_signature.sig_size != vb2_rsa_sig_size(key.algorithm)) {
+		VB2_DEBUG("Wrong data signature size for algorithm, "
+			  "sig_size=%d, expected %d for algorithm %d.\n",
+			 (int)pre->body_signature.sig_size,
+			  vb2_rsa_sig_size(key.algorithm),
+			  key.algorithm);
+		return VB2_ERROR_API_CHECK_HASH_SIG_SIZE;
+	}
+
+	/*
+	 * Check digest vs. signature.  Note that this destroys the signature.
+	 * That's ok, because we only check each signature once per boot.
+	 */
+	rv = vb2_verify_digest(&key,
+			       vb2_signature_data(&pre->body_signature),
+			       digest,
+			       &wb);
+	return rv;
+}
diff --git a/firmware/2lib/include/2api.h b/firmware/2lib/include/2api.h
index 3a4772b..7e95d24 100644
--- a/firmware/2lib/include/2api.h
+++ b/firmware/2lib/include/2api.h
@@ -156,6 +156,195 @@
 	VB2_RES_FW_VBLOCK,
 };
 
+/******************************************************************************
+ * APIs provided by verified boot.
+ *
+ * At a high level, call functions in the order described below.  After each
+ * call, examine vb2_context.flags to determine whether nvdata or secdata
+ * needs to be written.
+ *
+ * If you need to cause the boot process to fail at any point, call
+ * vb2api_fail().  Then check vb2_context.flags to see what data needs to be
+ * written.  Then reboot.
+ *
+ *	Load nvdata from wherever you keep it.
+ *
+ *	Load secdata from wherever you keep it.
+ *
+ *      	If it wasn't there at all (for example, this is the first boot
+ *		of a new system in the factory), call vb2api_secdata_create()
+ *		to initialize the data.
+ *
+ *		If access to your storage is unreliable (reads/writes may
+ *		contain corrupt data), you may call vb2api_secdata_check() to
+ *		determine if the data was valid, and retry reading if it
+ *		wasn't.  (In that case, you should also read back and check the
+ *		data after any time you write it, to make sure it was written
+ *		correctly.)
+ *
+ *	Call vb2api_fw_phase1().  At present, this nominally decides whether
+ *	recovery mode is needed this boot.
+ *
+ *	Call vb2api_fw_phase2().  At present, this nominally decides which
+ *	firmware slot will be attempted (A or B).
+ *
+ *	Call vb2api_fw_phase3().  At present, this nominally verifies the
+ *	firmware keyblock and preamble.
+ *
+ *	Lock down wherever you keep secdata.  It should no longer be writable
+ *	this boot.
+ *
+ *	Verify the hash of each section of code/data you need to boot the RW
+ *	firmware.  For each section:
+ *
+ *		Call vb2_init_hash() to see if the hash exists.
+ *
+ *		Load the data for the section.  Call vb2_extend_hash() on the
+ *		data as you load it.  You can load it all at once and make one
+ *		call, or load and hash-extend a block at a time.
+ *
+ *		Call vb2_check_hash() to see if the hash is valid.
+ *
+ *			If it is valid, you may use the data and/or execute
+ *			code from that section.
+ *
+ *			If the hash was invalid, you must reboot.
+ *
+ * At this point, firmware verification is done, and vb2_context contains the
+ * kernel key needed to verify the kernel.  That context should be preserved
+ * and passed on to kernel selection.  For now, that requires translating it
+ * into the old VbSharedData format (via a func which does not yet exist...)
+ */
+
+/**
+ * Sanity-check the contents of the secure storage context.
+ *
+ * Use this if reading from secure storage may be flaky, and you want to retry
+ * reading it several times.
+ *
+ * This may be called before vb2api_phase1().
+ *
+ * @param ctx		Context pointer
+ * @return VB2_SUCCESS, or non-zero error code if error.
+ */
+int vb2api_secdata_check(const struct vb2_context *ctx);
+
+/**
+ * Create fresh data in the secure storage context.
+ *
+ * Use this only when initializing the secure storage context on a new machine
+ * the first time it boots.  Do NOT simply use this if vb2api_secdata_check()
+ * (or any other API in this library) fails; that could allow the secure data
+ * to be rolled back to an insecure state.
+ *
+ * This may be called before vb2api_phase1().
+ *
+ * @param ctx		Context pointer
+ * @return VB2_SUCCESS, or non-zero error code if error.
+ */
+int vb2api_secdata_create(struct vb2_context *ctx);
+
+/**
+ * Report firmware failure to vboot.
+ *
+ * This may be called before vb2api_phase1() to indicate errors in the boot
+ * process prior to the start of vboot.
+ *
+ * If this is called after vb2api_phase1(), on return, the calling firmware
+ * should check for updates to secdata and/or nvdata, then reboot.
+ *
+ * @param reason	Recovery reason
+ * @param subcode	Recovery subcode
+ */
+void vb2api_fail(struct vb2_context *ctx, uint8_t reason, uint8_t subcode);
+
+/**
+ * Firmware selection, phase 1.
+ *
+ * On error, the calling firmware should jump directly to recovery-mode
+ * firmware without rebooting.
+ *
+ * @param ctx		Vboot context
+ * @return VB2_SUCCESS, or error code on error.
+ */
+int vb2api_fw_phase1(struct vb2_context *ctx);
+
+/**
+ * Firmware selection, phase 2.
+ *
+ * On error, the calling firmware should check for updates to secdata and/or
+ * nvdata, then reboot.
+ *
+ * @param ctx		Vboot context
+ * @return VB2_SUCCESS, or error code on error.
+ */
+int vb2api_fw_phase2(struct vb2_context *ctx);
+
+/**
+ * Firmware selection, phase 3.
+ *
+ * On error, the calling firmware should check for updates to secdata and/or
+ * nvdata, then reboot.
+ *
+ * On success, the calling firmware should lock down secdata before continuing
+ * with the boot process.
+ *
+ * @param ctx		Vboot context
+ * @return VB2_SUCCESS, or error code on error.
+ */
+int vb2api_fw_phase3(struct vb2_context *ctx);
+
+/*
+ * Tags for types of hashable data.
+ *
+ * TODO: These are the ones that vboot specifically knows about given the
+ * current data structures.  In the future, I'd really like the vboot preamble
+ * to contain an arbitrary list of tags and their hashes, so that we can hash
+ * ram init, main RW body, EC-RW for software sync, etc. all separately.
+ */
+enum vb2api_hash_tag {
+	/* Invalid hash tag; never present in table */
+	VB2_HASH_TAG_INVALID = 0,
+
+	/* Firmware body */
+	VB2_HASH_TAG_FW_BODY,
+};
+
+/**
+ * Initialize hashing data for the specified tag.
+ *
+ * @param ctx		Vboot context
+ * @param tag		Tag to start hashing
+ * @param size		If non-null, expected size of data for tag will be
+ *			stored here on output.
+ * @return VB2_SUCCESS, or error code on error.
+ */
+int vb2api_init_hash(struct vb2_context *ctx, uint32_t tag, uint32_t *size);
+
+/**
+ * Extend the hash started by vb2api_init_hash() with additional data.
+ *
+ * @param ctx		Vboot context
+ * @param buf		Data to hash
+ * @param size		Size of data in bytes
+ * @return VB2_SUCCESS, or error code on error.
+ */
+int vb2api_extend_hash(struct vb2_context *ctx,
+		       const void *buf,
+		       uint32_t size);
+
+/**
+ * Check the hash value started by vb2api_init_hash().
+ *
+ * @param ctx		Vboot context
+ * @return VB2_SUCCESS, or error code on error.
+ */
+int vb2api_check_hash(struct vb2_context *ctx);
+
+int vb2api_get_kernel_subkey(struct vb2_context *ctx,
+			     uint8_t *buf,
+			     uint32_t *size);
+
 /*****************************************************************************/
 /* APIs provided by the caller to verified boot */
 
diff --git a/firmware/2lib/include/2return_codes.h b/firmware/2lib/include/2return_codes.h
index 7c61a49..fb00936 100644
--- a/firmware/2lib/include/2return_codes.h
+++ b/firmware/2lib/include/2return_codes.h
@@ -25,6 +25,9 @@
 	/* Unknown / unspecified error */
 	VB2_ERROR_UNKNOWN = VB2_ERROR_BASE + 1,
 
+	/* Mock error for testing */
+	VB2_ERROR_MOCK,
+
         /**********************************************************************
 	 * SHA errors
 	 */
@@ -307,9 +310,12 @@
 	/* Uninitialized work area in vb2api_check_hash() */
 	VB2_ERROR_API_CHECK_HASH_WORKBUF,
 
-	/* Wrong amount of data hashed in vb2api_extend_hash() */
+	/* Wrong amount of data hashed in vb2api_check_hash() */
 	VB2_ERROR_API_CHECK_HASH_SIZE,
 
+	/* Work buffer too small in vb2api_check_hash() */
+	VB2_ERROR_API_CHECK_HASH_WORKBUF_DIGEST,
+
 	/* Bag tag in vb2api_check_hash() */
 	VB2_ERROR_API_CHECK_HASH_TAG,
 
@@ -319,12 +325,6 @@
 	/* Siganature size mismatch in vb2api_check_hash() */
 	VB2_ERROR_API_CHECK_HASH_SIG_SIZE,
 
-	/* Preamble not present in vb2api_get_kernel_subkey() */
-	VB2_ERROR_API_KERNEL_SUBKEY_PREAMBLE,
-
-	/* Destination buffer too small in vb2api_get_kernel_subkey() */
-	VB2_ERROR_API_KERNEL_SUBKEY_DEST_SIZE,
-
 	/* Phase one needs recovery mode */
 	VB2_ERROR_API_PHASE1_RECOVERY,
 
diff --git a/tests/vb2_api_tests.c b/tests/vb2_api_tests.c
new file mode 100644
index 0000000..8a0cece
--- /dev/null
+++ b/tests/vb2_api_tests.c
@@ -0,0 +1,448 @@
+/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ *
+ * Tests for misc library
+ */
+
+#include <stdio.h>
+
+#include "2sysincludes.h"
+#include "2api.h"
+#include "2common.h"
+#include "2misc.h"
+#include "2nvstorage.h"
+#include "2rsa.h"
+#include "2secdata.h"
+
+#include "test_common.h"
+
+/* Common context for tests */
+static uint8_t workbuf[VB2_WORKBUF_RECOMMENDED_SIZE]
+	__attribute__ ((aligned (16)));
+static struct vb2_context cc;
+static struct vb2_shared_data *sd;
+
+const char mock_body[320] = "Mock body";
+const int mock_body_size = sizeof(mock_body);
+const int mock_algorithm = VB2_ALG_RSA2048_SHA256;
+const int mock_sig_size = 64;
+
+/* Mocked function data */
+
+static int retval_vb2_fw_parse_gbb;
+static int retval_vb2_check_dev_switch;
+static int retval_vb2_check_tpm_clear;
+static int retval_vb2_select_fw_slot;
+static int retval_vb2_verify_fw_keyblock;
+static int retval_vb2_verify_fw_preamble2;
+static int retval_vb2_digest_finalize;
+static int retval_vb2_verify_digest;
+
+/* Type of test to reset for */
+enum reset_type {
+	FOR_MISC,
+	FOR_EXTEND_HASH,
+	FOR_CHECK_HASH,
+};
+
+static void reset_common_data(enum reset_type t)
+{
+	struct vb2_fw_preamble *pre;
+	struct vb2_packed_key *k;
+
+	memset(workbuf, 0xaa, sizeof(workbuf));
+
+	memset(&cc, 0, sizeof(cc));
+	cc.workbuf = workbuf;
+	cc.workbuf_size = sizeof(workbuf);
+
+	vb2_init_context(&cc);
+	sd = vb2_get_sd(&cc);
+
+	vb2_nv_init(&cc);
+
+	vb2_secdata_create(&cc);
+	vb2_secdata_init(&cc);
+
+	retval_vb2_fw_parse_gbb = VB2_SUCCESS;
+	retval_vb2_check_dev_switch = VB2_SUCCESS;
+	retval_vb2_check_tpm_clear = VB2_SUCCESS;
+	retval_vb2_select_fw_slot = VB2_SUCCESS;
+	retval_vb2_verify_fw_keyblock = VB2_SUCCESS;
+	retval_vb2_verify_fw_preamble2 = VB2_SUCCESS;
+	retval_vb2_digest_finalize = VB2_SUCCESS;
+	retval_vb2_verify_digest = VB2_SUCCESS;
+
+	sd->workbuf_preamble_offset = 8;
+	sd->workbuf_preamble_size = sizeof(*pre);
+	cc.workbuf_used = sd->workbuf_preamble_offset
+		+ sd->workbuf_preamble_size;
+	pre = (struct vb2_fw_preamble *)
+		(cc.workbuf + sd->workbuf_preamble_offset);
+	pre->body_signature.data_size = mock_body_size;
+	pre->body_signature.sig_size = mock_sig_size;
+
+	sd->workbuf_data_key_offset = cc.workbuf_used;
+	sd->workbuf_data_key_size = sizeof(*k) + 8;
+	cc.workbuf_used = sd->workbuf_data_key_offset +
+		sd->workbuf_data_key_size;
+	k = (struct vb2_packed_key *)
+		(cc.workbuf + sd->workbuf_data_key_offset);
+	k->algorithm = mock_algorithm;
+
+	if (t == FOR_EXTEND_HASH || t == FOR_CHECK_HASH)
+		vb2api_init_hash(&cc, VB2_HASH_TAG_FW_BODY, NULL);
+
+	if (t == FOR_CHECK_HASH)
+		vb2api_extend_hash(&cc, mock_body, mock_body_size);
+};
+
+/* Mocked functions */
+
+int vb2_fw_parse_gbb(struct vb2_context *ctx)
+{
+	return retval_vb2_fw_parse_gbb;
+}
+
+int vb2_check_dev_switch(struct vb2_context *ctx)
+{
+	return retval_vb2_check_dev_switch;
+}
+
+int vb2_check_tpm_clear(struct vb2_context *ctx)
+{
+	return retval_vb2_check_tpm_clear;
+}
+
+int vb2_select_fw_slot(struct vb2_context *ctx)
+{
+	return retval_vb2_select_fw_slot;
+}
+
+int vb2_verify_fw_keyblock(struct vb2_context *ctx)
+{
+	return retval_vb2_verify_fw_keyblock;
+}
+
+int vb2_verify_fw_preamble2(struct vb2_context *ctx)
+{
+	return retval_vb2_verify_fw_preamble2;
+}
+
+int vb2_unpack_key(struct vb2_public_key *key,
+		   const uint8_t *buf,
+		   uint32_t size)
+{
+	struct vb2_packed_key *k = (struct vb2_packed_key *)buf;
+
+	if (size != sizeof(*k) + 8)
+		return VB2_ERROR_UNPACK_KEY_SIZE;
+
+	key->algorithm = k->algorithm;
+
+	return VB2_SUCCESS;
+}
+
+int vb2_digest_init(struct vb2_digest_context *dc, uint32_t algorithm)
+{
+	if (algorithm != mock_algorithm)
+		return VB2_ERROR_SHA_INIT_ALGORITHM;
+
+	dc->algorithm = algorithm;
+
+	return VB2_SUCCESS;
+}
+
+int vb2_digest_extend(struct vb2_digest_context *dc,
+		      const uint8_t *buf,
+		      uint32_t size)
+{
+	if (dc->algorithm != mock_algorithm)
+		return VB2_ERROR_SHA_EXTEND_ALGORITHM;
+
+	return VB2_SUCCESS;
+}
+
+int vb2_digest_finalize(struct vb2_digest_context *dc,
+			uint8_t *digest,
+			uint32_t digest_size)
+{
+	return retval_vb2_digest_finalize;
+}
+
+uint32_t vb2_rsa_sig_size(uint32_t algorithm)
+{
+	return mock_sig_size;
+}
+
+int vb2_verify_digest(const struct vb2_public_key *key,
+		      uint8_t *sig,
+		      const uint8_t *digest,
+		      struct vb2_workbuf *wb)
+{
+	return retval_vb2_verify_digest;
+}
+
+/* Tests */
+
+static void misc_tests(void)
+{
+	/* Test secdata passthru functions */
+	reset_common_data(FOR_MISC);
+	/* Corrupt secdata so initial check will fail */
+	cc.secdata[0] ^= 0x42;
+	TEST_EQ(vb2api_secdata_check(&cc), VB2_ERROR_SECDATA_CRC,
+		"secdata check");
+	TEST_SUCC(vb2api_secdata_create(&cc), "secdata create");
+	TEST_SUCC(vb2api_secdata_check(&cc), "secdata check 2");
+
+	/* Test fail passthru */
+	reset_common_data(FOR_MISC);
+	vb2api_fail(&cc, 12, 34);
+	TEST_EQ(vb2_nv_get(&cc, VB2_NV_RECOVERY_REQUEST),
+		12, "vb2api_fail request");
+	TEST_EQ(vb2_nv_get(&cc, VB2_NV_RECOVERY_SUBCODE),
+		34, "vb2api_fail subcode");
+}
+
+static void phase1_tests(void)
+{
+	reset_common_data(FOR_MISC);
+	TEST_SUCC(vb2api_fw_phase1(&cc), "phase1 good");
+	TEST_EQ(sd->recovery_reason, 0, "  not recovery");
+	TEST_EQ(cc.flags & VB2_CONTEXT_RECOVERY_MODE, 0, "  recovery flag");
+	TEST_EQ(cc.flags & VB2_CONTEXT_CLEAR_RAM, 0, "  clear ram flag");
+
+	reset_common_data(FOR_MISC);
+	cc.secdata[0] ^= 0x42;
+	TEST_EQ(vb2api_fw_phase1(&cc),
+		VB2_ERROR_API_PHASE1_RECOVERY, "phase1 secdata");
+	TEST_EQ(sd->recovery_reason, VB2_RECOVERY_SECDATA_INIT, "  recovery");
+	TEST_NEQ(cc.flags & VB2_CONTEXT_RECOVERY_MODE, 0, "  recovery flag");
+	TEST_NEQ(cc.flags & VB2_CONTEXT_CLEAR_RAM, 0, "  clear ram flag");
+}
+
+static void phase2_tests(void)
+{
+	reset_common_data(FOR_MISC);
+	TEST_SUCC(vb2api_fw_phase2(&cc), "phase2 good");
+	TEST_EQ(cc.flags & VB2_CONTEXT_CLEAR_RAM, 0, "  clear ram flag");
+
+	reset_common_data(FOR_MISC);
+	retval_vb2_fw_parse_gbb = VB2_ERROR_GBB_MAGIC;
+	TEST_EQ(vb2api_fw_phase2(&cc), VB2_ERROR_GBB_MAGIC, "phase2 gbb");
+	TEST_EQ(vb2_nv_get(&cc, VB2_NV_RECOVERY_REQUEST),
+		VB2_RECOVERY_GBB_HEADER, "  recovery reason");
+
+	reset_common_data(FOR_MISC);
+	retval_vb2_check_dev_switch = VB2_ERROR_MOCK;
+	TEST_EQ(vb2api_fw_phase2(&cc), VB2_ERROR_MOCK, "phase2 dev switch");
+	TEST_EQ(vb2_nv_get(&cc, VB2_NV_RECOVERY_REQUEST),
+		VB2_RECOVERY_DEV_SWITCH, "  recovery reason");
+
+	reset_common_data(FOR_MISC);
+	cc.flags |= VB2_CONTEXT_DEVELOPER_MODE;
+	TEST_SUCC(vb2api_fw_phase2(&cc), "phase1 dev");
+	TEST_NEQ(cc.flags & VB2_CONTEXT_CLEAR_RAM, 0, "  clear ram flag");
+
+	reset_common_data(FOR_MISC);
+	retval_vb2_check_tpm_clear = VB2_ERROR_MOCK;
+	TEST_EQ(vb2api_fw_phase2(&cc), VB2_ERROR_MOCK, "phase2 tpm clear");
+	TEST_EQ(vb2_nv_get(&cc, VB2_NV_RECOVERY_REQUEST),
+		VB2_RECOVERY_TPM_CLEAR_OWNER, "  recovery reason");
+
+	reset_common_data(FOR_MISC);
+	retval_vb2_select_fw_slot = VB2_ERROR_MOCK;
+	TEST_EQ(vb2api_fw_phase2(&cc), VB2_ERROR_MOCK, "phase2 slot");
+	TEST_EQ(vb2_nv_get(&cc, VB2_NV_RECOVERY_REQUEST),
+		VB2_RECOVERY_FW_SLOT, "  recovery reason");
+}
+
+static void phase3_tests(void)
+{
+	reset_common_data(FOR_MISC);
+	TEST_SUCC(vb2api_fw_phase3(&cc), "phase3 good");
+
+	reset_common_data(FOR_MISC);
+	retval_vb2_verify_fw_keyblock = VB2_ERROR_MOCK;
+	TEST_EQ(vb2api_fw_phase3(&cc), VB2_ERROR_MOCK, "phase3 keyblock");
+	TEST_EQ(vb2_nv_get(&cc, VB2_NV_RECOVERY_REQUEST),
+		VB2_RECOVERY_RO_INVALID_RW, "  recovery reason");
+
+	reset_common_data(FOR_MISC);
+	retval_vb2_verify_fw_preamble2 = VB2_ERROR_MOCK;
+	TEST_EQ(vb2api_fw_phase3(&cc), VB2_ERROR_MOCK, "phase3 keyblock");
+	TEST_EQ(vb2_nv_get(&cc, VB2_NV_RECOVERY_REQUEST),
+		VB2_RECOVERY_RO_INVALID_RW, "  recovery reason");
+}
+
+static void init_hash_tests(void)
+{
+	struct vb2_packed_key *k;
+	int wb_used_before;
+	uint32_t size;
+
+	/* For now, all we support is body signature hash */
+	reset_common_data(FOR_MISC);
+	wb_used_before = cc.workbuf_used;
+	TEST_SUCC(vb2api_init_hash(&cc, VB2_HASH_TAG_FW_BODY, &size),
+		  "init hash good");
+	TEST_EQ(sd->workbuf_hash_offset,
+		(wb_used_before + (VB2_WORKBUF_ALIGN - 1)) &
+		~(VB2_WORKBUF_ALIGN - 1),
+		"hash context offset");
+	TEST_EQ(sd->workbuf_hash_size, sizeof(struct vb2_digest_context),
+		"hash context size");
+	TEST_EQ(cc.workbuf_used,
+		sd->workbuf_hash_offset + sd->workbuf_hash_size,
+		"hash uses workbuf");
+	TEST_EQ(sd->hash_tag, VB2_HASH_TAG_FW_BODY, "hash tag");
+	TEST_EQ(sd->hash_remaining_size, mock_body_size, "hash remaining");
+
+	wb_used_before = cc.workbuf_used;
+	TEST_SUCC(vb2api_init_hash(&cc, VB2_HASH_TAG_FW_BODY, NULL),
+		  "init hash again");
+	TEST_EQ(cc.workbuf_used, wb_used_before, "init hash reuses context");
+
+	reset_common_data(FOR_MISC);
+	TEST_EQ(vb2api_init_hash(&cc, VB2_HASH_TAG_INVALID, &size),
+		VB2_ERROR_API_INIT_HASH_TAG, "init hash invalid tag");
+
+	reset_common_data(FOR_MISC);
+	sd->workbuf_preamble_size = 0;
+	TEST_EQ(vb2api_init_hash(&cc, VB2_HASH_TAG_FW_BODY, &size),
+		VB2_ERROR_API_INIT_HASH_PREAMBLE, "init hash preamble");
+
+	reset_common_data(FOR_MISC);
+	TEST_EQ(vb2api_init_hash(&cc, VB2_HASH_TAG_FW_BODY + 1, &size),
+		VB2_ERROR_API_INIT_HASH_TAG, "init hash unknown tag");
+
+	reset_common_data(FOR_MISC);
+	cc.workbuf_used =
+		cc.workbuf_size - sizeof(struct vb2_digest_context) + 8;
+	TEST_EQ(vb2api_init_hash(&cc, VB2_HASH_TAG_FW_BODY, &size),
+		VB2_ERROR_API_INIT_HASH_WORKBUF, "init hash workbuf");
+
+	reset_common_data(FOR_MISC);
+	sd->workbuf_data_key_size = 0;
+	TEST_EQ(vb2api_init_hash(&cc, VB2_HASH_TAG_FW_BODY, &size),
+		VB2_ERROR_API_INIT_HASH_DATA_KEY, "init hash data key");
+
+	reset_common_data(FOR_MISC);
+	sd->workbuf_data_key_size--;
+	TEST_EQ(vb2api_init_hash(&cc, VB2_HASH_TAG_FW_BODY, &size),
+		VB2_ERROR_UNPACK_KEY_SIZE, "init hash data key size");
+
+	reset_common_data(FOR_MISC);
+	k = (struct vb2_packed_key *)(cc.workbuf + sd->workbuf_data_key_offset);
+	k->algorithm--;
+	TEST_EQ(vb2api_init_hash(&cc, VB2_HASH_TAG_FW_BODY, &size),
+		VB2_ERROR_SHA_INIT_ALGORITHM, "init hash algorithm");
+}
+
+static void extend_hash_tests(void)
+{
+	struct vb2_digest_context *dc;
+
+	reset_common_data(FOR_EXTEND_HASH);
+	TEST_SUCC(vb2api_extend_hash(&cc, mock_body, 32),
+		"hash extend good");
+	TEST_EQ(sd->hash_remaining_size, mock_body_size - 32,
+		"hash extend remaining");
+	TEST_SUCC(vb2api_extend_hash(&cc, mock_body, mock_body_size - 32),
+		"hash extend again");
+	TEST_EQ(sd->hash_remaining_size, 0, "hash extend remaining 2");
+
+	reset_common_data(FOR_EXTEND_HASH);
+	sd->workbuf_hash_size = 0;
+	TEST_EQ(vb2api_extend_hash(&cc, mock_body, mock_body_size),
+		VB2_ERROR_API_EXTEND_HASH_WORKBUF, "hash extend no workbuf");
+
+	reset_common_data(FOR_EXTEND_HASH);
+	TEST_EQ(vb2api_extend_hash(&cc, mock_body, mock_body_size + 1),
+		VB2_ERROR_API_EXTEND_HASH_SIZE, "hash extend too much");
+
+	reset_common_data(FOR_EXTEND_HASH);
+	TEST_EQ(vb2api_extend_hash(&cc, mock_body, 0),
+		VB2_ERROR_API_EXTEND_HASH_SIZE, "hash extend empty");
+
+	reset_common_data(FOR_EXTEND_HASH);
+	dc = (struct vb2_digest_context *)
+		(cc.workbuf + sd->workbuf_hash_offset);
+	dc->algorithm++;
+	TEST_EQ(vb2api_extend_hash(&cc, mock_body, mock_body_size),
+		VB2_ERROR_SHA_EXTEND_ALGORITHM, "hash extend fail");
+}
+
+static void check_hash_tests(void)
+{
+	struct vb2_fw_preamble *pre;
+
+	reset_common_data(FOR_CHECK_HASH);
+	TEST_SUCC(vb2api_check_hash(&cc), "check hash good");
+
+	reset_common_data(FOR_CHECK_HASH);
+	sd->workbuf_preamble_size = 0;
+	TEST_EQ(vb2api_check_hash(&cc),
+		VB2_ERROR_API_CHECK_HASH_PREAMBLE, "check hash preamble");
+
+	reset_common_data(FOR_CHECK_HASH);
+	sd->workbuf_hash_size = 0;
+	TEST_EQ(vb2api_check_hash(&cc),
+		VB2_ERROR_API_CHECK_HASH_WORKBUF, "check hash no workbuf");
+
+	reset_common_data(FOR_CHECK_HASH);
+	sd->hash_remaining_size = 1;
+	TEST_EQ(vb2api_check_hash(&cc),
+		VB2_ERROR_API_CHECK_HASH_SIZE, "check hash size");
+
+	reset_common_data(FOR_CHECK_HASH);
+	cc.workbuf_used = cc.workbuf_size;
+	TEST_EQ(vb2api_check_hash(&cc),
+		VB2_ERROR_API_CHECK_HASH_WORKBUF_DIGEST, "check hash workbuf");
+
+	reset_common_data(FOR_CHECK_HASH);
+	retval_vb2_digest_finalize = VB2_ERROR_MOCK;
+	TEST_EQ(vb2api_check_hash(&cc),	VB2_ERROR_MOCK, "check hash finalize");
+
+	reset_common_data(FOR_CHECK_HASH);
+	sd->hash_tag = VB2_HASH_TAG_INVALID;
+	TEST_EQ(vb2api_check_hash(&cc),
+		VB2_ERROR_API_CHECK_HASH_TAG, "check hash tag");
+
+	reset_common_data(FOR_CHECK_HASH);
+	sd->workbuf_data_key_size = 0;
+	TEST_EQ(vb2api_check_hash(&cc),
+		VB2_ERROR_API_CHECK_HASH_DATA_KEY, "check hash data key");
+
+	reset_common_data(FOR_CHECK_HASH);
+	sd->workbuf_data_key_size--;
+	TEST_EQ(vb2api_check_hash(&cc),
+		VB2_ERROR_UNPACK_KEY_SIZE, "check hash data key size");
+
+	reset_common_data(FOR_CHECK_HASH);
+	pre = (struct vb2_fw_preamble *)
+		(cc.workbuf + sd->workbuf_preamble_offset);
+	pre->body_signature.sig_size++;
+	TEST_EQ(vb2api_check_hash(&cc),
+		VB2_ERROR_API_CHECK_HASH_SIG_SIZE, "check hash sig size");
+
+	reset_common_data(FOR_CHECK_HASH);
+	retval_vb2_digest_finalize = VB2_ERROR_RSA_VERIFY_DIGEST;
+	TEST_EQ(vb2api_check_hash(&cc),
+		VB2_ERROR_RSA_VERIFY_DIGEST, "check hash finalize");
+}
+
+int main(int argc, char* argv[])
+{
+	misc_tests();
+	phase1_tests();
+	phase2_tests();
+	phase3_tests();
+	init_hash_tests();
+	extend_hash_tests();
+	check_hash_tests();
+
+	return gTestSuccess ? 0 : 255;
+}
diff --git a/utility/vb2_verify_fw.c b/utility/vb2_verify_fw.c
new file mode 100644
index 0000000..2d662de
--- /dev/null
+++ b/utility/vb2_verify_fw.c
@@ -0,0 +1,209 @@
+/* Copyright (c) 2011 The Chromium OS Authors. All rights reserved.
+ * Use of this source code is governed by a BSD-style license that can be
+ * found in the LICENSE file.
+ *
+ * Routines for verifying a firmware image's signature.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "2sysincludes.h"
+#include "2api.h"
+
+const char *progname = "vb2_verify_fw";
+
+const char *gbb_fname;
+const char *vblock_fname;
+const char *body_fname;
+
+/**
+ * Local implementation which reads resources from individual files.  Could be
+ * more elegant and read from bios.bin, if we understood the fmap.
+ */
+int vb2ex_read_resource(struct vb2_context *ctx,
+			enum vb2_resource_index index,
+			uint32_t offset,
+			void *buf,
+			uint32_t size)
+{
+	const char *fname;
+	FILE *f;
+	int got_size;
+
+	/* Get the filename for the resource */
+	switch(index) {
+	case VB2_RES_GBB:
+		fname = gbb_fname;
+		break;
+	case VB2_RES_FW_VBLOCK:
+		fname = vblock_fname;
+		break;
+	default:
+		return VB2_ERROR_UNKNOWN;
+	}
+
+	/* Open file and seek to the requested offset */
+	f = fopen(fname, "rb");
+	if (!f)
+		return VB2_ERROR_UNKNOWN;
+
+	if (fseek(f, offset, SEEK_SET)) {
+		fclose(f);
+		return VB2_ERROR_UNKNOWN;
+	}
+
+	/* Read data and close file */
+	got_size = fread(buf, 1, size, f);
+	fclose(f);
+
+	/* Return success if we read everything */
+	return got_size == size ? VB2_SUCCESS : VB2_ERROR_UNKNOWN;
+}
+
+int vb2ex_tpm_clear_owner(struct vb2_context *ctx)
+{
+	// TODO: implement
+	return VB2_SUCCESS;
+}
+
+/**
+ * Save non-volatile and/or secure data if needed.
+ */
+void save_if_needed(struct vb2_context *ctx)
+{
+
+	if (ctx->flags & VB2_CONTEXT_NVDATA_CHANGED) {
+		// TODO: implement
+		ctx->flags &= ~VB2_CONTEXT_NVDATA_CHANGED;
+	}
+
+	if (ctx->flags & VB2_CONTEXT_SECDATA_CHANGED) {
+		// TODO: implement
+		ctx->flags &= ~VB2_CONTEXT_SECDATA_CHANGED;
+	}
+}
+
+/**
+ * Verify firmware body
+ */
+int hash_body(struct vb2_context *ctx)
+{
+	uint32_t expect_size;
+	uint8_t block[8192];
+	uint32_t size;
+	FILE *f;
+	int rv;
+
+	/* Open the body data */
+	f = fopen(body_fname, "rb");
+
+	/* Start the body hash */
+	rv = vb2api_init_hash(ctx, VB2_HASH_TAG_FW_BODY, &expect_size);
+	if (rv)
+		return rv;
+
+	printf("Expect %d bytes of body...\n", expect_size);
+
+	/* Extend over the body */
+	while (expect_size) {
+		size = sizeof(block);
+		if (size > expect_size)
+			size = expect_size;
+
+		/* Read next body block */
+		size = fread(block, 1, size, f);
+		if (size <= 0)
+			break;
+
+		/* Hash it */
+		rv = vb2api_extend_hash(ctx, block, size);
+		if (rv)
+			return rv;
+
+		expect_size -= size;
+	}
+
+	/* Check the result */
+	rv = vb2api_check_hash(ctx);
+	if (rv)
+		return rv;
+
+	return VB2_SUCCESS;
+}
+
+int main(int argc, char *argv[])
+{
+	struct vb2_context ctx;
+	uint8_t workbuf[16384];
+	int rv;
+
+	if (argc < 4) {
+		fprintf(stderr,
+			"usage: %s <gbb> <vblock> <body>\n", progname);
+		return 1;
+	}
+
+	/* Save filenames */
+	gbb_fname = argv[1];
+	vblock_fname = argv[2];
+	body_fname = argv[3];
+
+	/* Set up context */
+	memset(&ctx, 0, sizeof(ctx));
+	ctx.workbuf = workbuf;
+	ctx.workbuf_size = sizeof(workbuf);
+
+	/* Initialize secure context */
+	rv = vb2api_secdata_create(&ctx);
+	if (rv) {
+		fprintf(stderr,
+			"error: vb2api_secdata_create() failed (%d)\n", rv);
+		return 1;
+	}
+
+	// TODO: optional args to set contents for nvdata, secdata?
+
+	/* Do early init */
+	printf("Phase 1...\n");
+	rv = vb2api_fw_phase1(&ctx);
+	if (rv) {
+		printf("Phase 1 wants recovery mode.\n");
+		save_if_needed(&ctx);
+		return 0;
+	}
+
+	/* Determine which firmware slot to boot */
+	printf("Phase 2...\n");
+	rv = vb2api_fw_phase2(&ctx);
+	if (rv) {
+		printf("Phase 2 wants reboot.\n");
+		save_if_needed(&ctx);
+		return 0;
+	}
+
+	/* Try that slot */
+	printf("Phase 3...\n");
+	rv = vb2api_fw_phase3(&ctx);
+	if (rv) {
+		printf("Phase 3 wants reboot.\n");
+		save_if_needed(&ctx);
+		return 0;
+	}
+
+	/* Verify body */
+	printf("Hash body...\n");
+	rv = hash_body(&ctx);
+	save_if_needed(&ctx);
+	if (rv) {
+		printf("Phase 4 wants reboot.\n");
+		return 0;
+	}
+
+	printf("Yaay!\n");
+
+	printf("Workbuf used = %d bytes\n", ctx.workbuf_used);
+
+	return 0;
+}